<?php
namespace EADPlataforma\Controller\Website;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Cache;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\HttpFoundation\RedirectResponse;
use EADPlataforma\Entity\Cart;
use EADPlataforma\Entity\Product;
use EADPlataforma\Entity\ProductCharge;
use EADPlataforma\Entity\ProductOffer;
use EADPlataforma\Entity\ProductCoupon;
use EADPlataforma\Entity\ProductOpportunity;
use EADPlataforma\Entity\ProductSuggestion;
use EADPlataforma\Entity\Whishlist;
use EADPlataforma\Entity\Transaction;
use EADPlataforma\Entity\TransactionItem;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\Country;
use EADPlataforma\Entity\State;
use EADPlataforma\Entity\City;
use EADPlataforma\Entity\UserCard;
use EADPlataforma\Entity\UserCheckoutInfo;
use EADPlataforma\Entity\UserSubscription;
use EADPlataforma\Entity\UserCustomField;
use EADPlataforma\Entity\Course;
use EADPlataforma\DataTransferObject\UserDTO;
use EADPlataforma\Enum\CartEnum;
use EADPlataforma\Enum\ProductEnum;
use EADPlataforma\Enum\ProductChargeEnum;
use EADPlataforma\Enum\GeoDataEnum;
use EADPlataforma\Enum\ReceiverEnum;
use EADPlataforma\Enum\TransactionEnum;
use EADPlataforma\Enum\TransactionItemEnum;
use EADPlataforma\Enum\ProductOfferEnum;
use EADPlataforma\Enum\ProductCouponEnum;
use EADPlataforma\Enum\ProductSuggestionEnum;
use EADPlataforma\Enum\ProductOpportunityEnum;
use EADPlataforma\Enum\TagsMarketingEnum;
use EADPlataforma\Enum\UserEnum;
use EADPlataforma\Enum\UserCardEnum;
use EADPlataforma\Enum\UserCheckoutInfoEnum;
use EADPlataforma\Enum\UserSubscriptionEnum;
use EADPlataforma\Enum\WhishlistEnum;
use EADPlataforma\Enum\EnrollmentEnum;
use EADPlataforma\Enum\NotificationEnum;
use EADPlataforma\Enum\WebhookEnum;
use EADPlataforma\Enum\UserCustomFieldEnum;
use EADPlataforma\Enum\CourseEnum;
use EADPlataforma\Enum\TrashEnum;
use EADPlataforma\Enum\ErrorEnum;
/**
* @Route(
* schemes = {"http|https"}
* )
* @Cache(
* maxage = "0",
* smaxage = "0",
* expires = "now",
* public = false
* )
*/
class CartController extends AbstractWebsiteController {
/**
* @Route(
* path = "/installment/interest",
* name = "getInstallmentInterest",
* methods = {"GET"}
* )
*/
public function getInstallmentInterest(Request $request) {
$this->requestUtil->setRequest($request)->setData();
$numberUtil = $this->generalService->getUtil('NumberUtil');
$installments = (int)$this->requestUtil->getField('installments');
$freeInstallments = (int)$this->requestUtil->getField('freeInstallments');
$amount = (float)$this->requestUtil->getField('amount');
$productOfferIds = $this->requestUtil->getField('productIds');
$productOfferIds = json_decode($productOfferIds);
$poRepository = $this->em->getRepository(ProductOffer::class);
if(empty($freeInstallments)){
$freeInstallments = CartEnum::YES;
}
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$paymentConfig = $this->configuration->getPaymentConfig();
$parcelItems = [];
if(!empty($productOfferIds)){
foreach ($productOfferIds as $key => $offerId) {
$productOffer = $poRepository->find($offerId);
$parcels = (array) $pagarMeTransaction->calculateInstallments([
'amount' => $numberUtil->numberToCents($productOffer->getPriceReal()),
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
foreach ($parcels as $key => $value) {
$value->amount = $numberUtil->centsToNumber($value->amount);
$value->installment_amount = $numberUtil->centsToNumber(
$value->installment_amount
);
$parcels[$key] = $value;
}
$parcelItems[$offerId] = $parcels;
}
}
$installmentsOptions = (array) $pagarMeTransaction->calculateInstallments([
'amount' => $numberUtil->numberToCents($amount),
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
if(empty($installmentsOptions[$installments])){
return $this->eadResponse([
"parcelItems" => $parcelItems,
"installmentsOptions" => [
"1" => [
"installment" => 1,
"amount" => $amount,
"installment_amount" => $amount,
]
],
"amountTotal" => $amount,
"amountParcel" => $amount
]);
}
foreach ($installmentsOptions as $key => $value) {
$value->amount = $numberUtil->centsToNumber($value->amount);
$value->installment_amount = $numberUtil->centsToNumber(
$value->installment_amount
);
$installmentsOptions[$key] = $value;
}
return $this->eadResponse([
"parcelItems" => $parcelItems,
"installmentsOptions" => $installmentsOptions,
"amountTotal" => $installmentsOptions[$installments]->amount,
"amountParcel" => $installmentsOptions[$installments]->installment_amount
]);
}
/**
* @Route(
* path = "/charge/payment/{hash}",
* name = "getChargePage",
* methods = {"GET"}
* )
*/
public function getChargePage(Request $request) {
if(!$this->configuration->isModuleActive("product_charge_module")){
return $this->redirectToRoute('notFound');
}
$hash = $request->get('hash');
$debug = (int)$request->get('debug');
$productCharge = $this->em->getRepository(ProductCharge::class)->findOneBy([
"chargeKey" => $hash,
"deleted" => ProductChargeEnum::ITEM_NO_DELETED
]);
if (!$productCharge) {
return $this->redirectToRoute('notFound');
}
if($productCharge->getPublish() == ProductChargeEnum::NO){
return $this->redirectToRoute('notFound');
}
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$user = $productCharge->getUser();
$numberUserCheckoutInfo = $userCheckoutInfoRepository->count([
"user" => $user->getId(),
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED
]);
if(empty($numberUserCheckoutInfo)){
$userCheckoutInfo = new UserCheckoutInfo();
$userCheckoutInfo->setName($user->getName());
$userCheckoutInfo->setEmail($user->getEmail());
$userCheckoutInfo->setDocument($user->getDocument());
$userCheckoutInfo->setPhone($user->getPhone());
$userCheckoutInfo->setZipCode($user->getZipCode());
$userCheckoutInfo->setAddress($user->getAddress());
$userCheckoutInfo->setAddressNumber($user->getAddressNumber());
$userCheckoutInfo->setAddressComplement($user->getAddressComplement());
$userCheckoutInfo->setAddressNeighborhood($user->getAddressNeighborhood());
$userCheckoutInfo->setCity($user->getCity());
$userCheckoutInfo->setState($user->getState());
$userCheckoutInfo->setCountry($user->getCountry());
$userCheckoutInfo->setUser($user);
$userCheckoutInfo->setReceiveEmail(UserCheckoutInfoEnum::NO);
$userCheckoutInfo->setDefault(UserCheckoutInfoEnum::YES);
$this->em->persist($userCheckoutInfo);
}
if($productCharge->getStatus() == ProductChargeEnum::WAITING){
$today = strtotime(date('Y-m-d'));
$dateExpire = strtotime($productCharge->getDateExpire());
if($today > $dateExpire){
$productCharge->setStatus(ProductChargeEnum::EXPIRED_PAYMENT);
}
}
$this->em->flush();
$userCheckoutInfos = $userCheckoutInfoRepository->findBy([
"user" => $user->getId(),
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED
]);
$userCardRepository = $this->em->getRepository(UserCard::class);
$userCards = null;
if($this->user && $this->user->getId() == $user->getId()){
$userCards = $userCardRepository->getValidUserCard();
}
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$paymentConfig = $this->configuration->getPaymentConfig();
$this->data['installmentsOptions'] = (array) $pagarMeTransaction->calculateInstallments([
'amount' => $productCharge->getAmount(true),
'free_installments' => $productCharge->getInstallmentNumberInterest(),
'max_installments' => $productCharge->getInstallmentNumberMax(),
'interest_rate' => $paymentConfig->installmentInterest
]);
$this->data['productCharge'] = $productCharge;
$this->data['userCheckoutInfos'] = $userCheckoutInfos;
$this->data['userCards'] = $userCards;
$this->data['debug'] = $debug;
return $this->renderEAD('cart/charge/charge.html.twig');
}
/**
* @Route(
* path = "/cart/opportunity/{hash}",
* name = "getCartOpportunity",
* methods = {"GET"}
* )
*/
public function getCartOpportunity(Request $request) {
$hash = $request->get('hash');
$cartRepository = $this->em->getRepository(Cart::class);
$userRepository = $this->em->getRepository(User::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productOpportunityRepository = $this->em->getRepository(ProductOpportunity::class);
$op = (object)$productOpportunityRepository->getDetailProductOpportunityByHash(
$hash
);
$user = $userRepository->findOneBy([
"id" => $op->user->userId,
"deleted" => UserEnum::ITEM_NO_DELETED,
]);
if($user){
$this->generalService->setCookie('hashcartoff', $user->getHashIdentify());
if($this->user && $this->user->getId() != $user->getId()){
return $this->redirectToRoute('notFound');
}
}
$this->requestUtil->setRequest($request)->setData();
$data = $this->requestUtil->getData();
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$utmsUrl = json_encode($dataUtml);
foreach ($op->order as $key => $value){
$productOffer = $productOfferRepository->findOneBy([
"id" => $value->offerId,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED,
]);
if($productOffer){
$cartRepository->addCartByProductOffer(
$productOffer,
$user,
null,
null,
$utmsUrl
);
}
}
return $this->redirectToRoute('cart');
}
/**
* @Route(
* path = "/cart/items/menu",
* name = "getCartItemsMenu",
* methods = {"GET"}
* )
*/
public function getCartItemsMenu(Request $request) {
$itemsNumber = (int)$request->get('itemsNumber');
$this->data['itemsNumber'] = $itemsNumber;
return $this->renderEAD('includes/submenu-cart-items.html.twig');
}
/**
* @Route(
* path = "/cart/initiate/checkout",
* name = "cartInitiateCheckout",
* methods = {"GET"}
* )
*/
public function cartInitiateCheckout(Request $request){
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$pixelService->sendConversion('InitiateCheckout');
return $this->eadResponse([ "message" => "Success" ]);
}
/**
* @Route(
* path = "/checkout/{type}/{productId}/{couponKey}/{productSuggestionId}",
* name = "checkoutOldCart",
* methods = {"GET"},
* defaults = { "couponKey" = 0, "productSuggestionId" = 0 },
* requirements = { "productId" = "\d+" }
* )
*/
public function getCheckoutOldCart(Request $request) {
$couponKey = $request->get('couponKey');
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$product = $this->em->getRepository(Product::class)->findOneBy([
"id" => (int)$request->get('productId')
]);
if(!$product){
return $this->redirectToRoute('notFound');
}
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productOffer = $productOfferRepository->getProductOfferDefaultByProduct(
$product
);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
$productCoupon = null;
if(!empty($couponKey)){
$productCouponRepository = $this->em->getRepository(ProductCoupon::class);
$productCoupon = $productCouponRepository->findValidProductCouponByProductOffer(
$couponKey,
$productOffer
);
}
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
(
$product->getType() != ProductEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductOfferEnum::YES
)
){
if($productOffer->getAllowTrial() == ProductOfferEnum::YES){
$params = [
"poHash" => $productOffer->getOfferLink(),
"pcKey" => $couponKey,
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartIndividual', $params);
}
}
$params = [
"poID" => $productOffer->getId(),
"pcID" => ( $productCoupon ? $productCoupon->getId() : 0 ),
"psID" => $request->get('productSuggestionId'),
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartAdd', $params);
}
/**
* @Route(
* path = "/checkout/offer/{type}/{productId}/{offerLink}/{courseId}",
* name = "checkoutNewCart",
* methods = {"GET"},
* defaults = { "courseId" = 0 },
* requirements = { "productId" = "\d+", "courseId" = "\d+" }
* )
*/
public function getCheckoutNewCart(Request $request) {
$offerLink = $request->get('offerLink');
$courseId = (int)$request->get('courseId');
$product = $this->em->getRepository(Product::class)->findOneBy([
"id" => $request->get('productId')
]);
if(!$product){
return $this->redirectToRoute('notFound');
}
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productOffer = $productOfferRepository->getProductOfferDefaultByProduct(
$product,
$offerLink
);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
(
$product->getType() != ProductEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductOfferEnum::YES
)
){
if($productOffer->getAllowTrial() == ProductOfferEnum::YES){
$params = [
"poHash" => $productOffer->getOfferLink(),
"pcKey" => null,
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartIndividual', $params);
}
}
$params = [
"poID" => $productOffer->getId(),
"courseId" => $courseId,
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartAdd', $params);
}
/**
* @Route(
* path = "/checkout/coupon/{type}/{productId}/{productCouponId}",
* name = "checkoutCartWithCoupon",
* methods = {"GET"},
* requirements = { "productId" = "\d+", "productCouponId" = "\d+" }
* )
*/
public function getCheckoutCartWithCoupon(Request $request) {
$product = $this->em->getRepository(Product::class)->findOneBy([
"id" => (int)$request->get('productId')
]);
if(!$product){
return $this->redirectToRoute('notFound');
}
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productOffer = $productOfferRepository->getProductOfferDefaultByProduct(
$product
);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
(
$product->getType() != ProductEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductOfferEnum::YES
)
){
if($productOffer->getAllowTrial() == ProductOfferEnum::YES){
$params = [
"poHash" => $productOffer->getOfferLink(),
"pcKey" => null,
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartIndividual', $params);
}
}
$params = [
"poID" => $productOffer->getId(),
"pcID" => (int)$request->get('productCouponId'),
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartAdd', $params);
}
/**
* @Route(
* path = "/cart/add/{poID}/{psID}/{pcID}/{isAjaxRequest}/{courseId}",
* name = "cartAdd",
* methods = {"GET"},
* defaults = {
* "psID" = 0,
* "pcID" = 0,
* "isAjaxRequest" = 0,
* "courseId" = 0
* }
* )
*/
public function registerCart(Request $request) {
$cartRepository = $this->em->getRepository(Cart::class);
$productOfferId = (int)$request->get('poID');
$productSuggestionId = (int)$request->get('psID');
$productCouponId = (int)$request->get('pcID');
$isAjaxRequest = (int)$request->get('isAjaxRequest');
$courseId = (int)$request->get('courseId');
$hash = base64_encode($request->getUri());
$this->requestUtil->setRequest($request)->setData();
$data = $this->requestUtil->getData();
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$utmsUrl = json_encode($dataUtml);
$course = $this->em->getRepository(Course::class)->findOneBy([
"id" => $courseId,
"status" => CourseEnum::PUBLISHED,
"deleted" => CourseEnum::ITEM_NO_DELETED
]);
$productOffer = $this->em->getRepository(ProductOffer::class)->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
if(!$productOffer){
if($isAjaxRequest == CartEnum::YES){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
return $this->redirectToRoute('notFound');
}
$hasModule = $this->configuration->isModuleActive("product_coupon_module");
$enrollmentService = $this->generalService->getService('EnrollmentService');
$pcRepository = $this->em->getRepository(ProductCoupon::class);
$psRepository = $this->em->getRepository(ProductSuggestion::class);
$productSuggestion = null;
if(!empty($productSuggestionId)){
$productSuggestion = $psRepository->findOneBy([
"id" => $productSuggestionId,
"status" => ProductSuggestionEnum::PUBLISHED,
"deleted" => ProductSuggestionEnum::ITEM_NO_DELETED
]);
}
$productCoupon = null;
$product = $productOffer->getProduct();
if($hasModule){
$productCoupon = $pcRepository->findValidProductCouponByIdAndProductOffer(
$productCouponId,
$productOffer
);
if($productCoupon && $this->user){
if($pcRepository->checkApplyCoupon($productCoupon, $productOffer)){
$price = $pcRepository->applyDiscount(
$productCoupon,
$productOffer->getPriceReal()
);
if(empty($price)){
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($productCoupon->getKey());
$enrollmentService->enrollUserByProduct(
$this->user,
$product,
($product->isTypeResource() ? $course : null)
);
return $this->redirectToRoute('resume');
}
}
}
}
if($productOffer->getSaleChannel() == ProductOfferEnum::EXTERNAL){
$externalCheckoutLink = $productOffer->getExternalCheckoutLink();
if(!empty($externalCheckoutLink)){
return $this->redirect($externalCheckoutLink, 301);
}
}
$cartRepository->addCartByProductOffer(
$productOffer,
$this->user,
$productSuggestion,
$productCoupon,
$utmsUrl,
($course ? [ $course ] : null)
);
$allowSuggestion = (
!$product->isTypeResource() ||
($course && $product->isTypeResource())
);
$psRedirect = null;
if($allowSuggestion){
$psRedirect = $psRepository->getProductSuggestionRedirectByProductOffer(
$productOffer,
ProductSuggestionEnum::EXECUTE_ON_ADD_CART
);
}
if($isAjaxRequest == CartEnum::YES){
return $this->eadResponse([
"cartItemsQuantity" => $cartRepository->countUserOnCart(),
"urlRedirect" => ( $psRedirect ? $psRedirect->getLinkRedirect() : null ),
"success" => CartEnum::YES
]);
}
if($psRedirect){
return $this->redirect($psRedirect->getLinkRedirect());
}
$productOfferSuggestions = null;
if($allowSuggestion){
$productOfferSuggestions = $psRepository->getProductSuggestionsByOfferOrigin(
$productOffer,
ProductSuggestionEnum::EXECUTE_ON_ADD_CART
);
}
if(!empty($productOfferSuggestions)){
if($productCoupon && $hasModule){
foreach ($productOfferSuggestions as $key => $offerSuggestion) {
$pcSuggestion = $pcRepository->findValidProductCouponByIdAndProductOffer(
$productCoupon->getId(),
$offerSuggestion,
true
);
if($pcSuggestion){
$amount = $offerSuggestion->getPriceReal();
if($pcRepository->checkApplyCoupon($pcSuggestion, $offerSuggestion)){
$amount = $pcRepository->applyDiscount($pcSuggestion, $amount);
}
if(!empty($amount)){
$offerSuggestion->setPriceRealCopy($amount);
$productOfferSuggestions[$key] = $offerSuggestion;
}else{
if($this->user){
$pcSuggestion->setUsageNumber(
$pcSuggestion->getUsageNumber() + 1
);
$this->em->flush();
$offerProd = $offerSuggestion->getProduct();
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($couponKey);
$enrollmentService->enrollUserByProduct(
$this->user,
$offerProd,
($offerProd->isTypeResource() ? $course : null)
);
unset($productOfferSuggestions[$key]);
}
}
}
}
}
$this->data['productOfferId'] = $productOfferId;
$this->data['productCoupon'] = $productCoupon;
$this->data['productOfferSuggestions'] = $productOfferSuggestions;
return $this->renderEAD('cart/suggestions.html.twig');
}
if($productCoupon){
return $this->redirectToRoute('cart', [
"coupon" => $productCoupon->getKey()
]);
}
return $this->redirectToRoute('cart');
}
/**
* @Route(
* path = "/cart/add/suggestion/{productOfferId}/{productCouponId}",
* name = "cartAddSuggestion",
* methods = {"POST"},
* defaults = { "productCouponId" = 0 }
* )
*/
public function registerCartBySuggestion(Request $request) {
$this->requestUtil->setRequest($request)->setData();
$cartRepository = $this->em->getRepository(Cart::class);
$productSuggestions = json_decode(
$this->requestUtil->getField('productSuggestions')
);
if(empty($productSuggestions)){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$productCouponId = (int)$request->get('productCouponId');
$productOfferId = (int)$request->get('productOfferId');
$hasModule = $this->configuration->isModuleActive("product_coupon_module");
$enrollmentService = $this->generalService->getService('EnrollmentService');
$pcRepository = $this->em->getRepository(ProductCoupon::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productOffer = $productOfferRepository->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
if(!$productOffer){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
if($productOffer->getSaleChannel() == ProductOfferEnum::EXTERNAL){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$product = $productOffer->getProduct();
$productCouponOffer = null;
$course = null;
if(
$product->getType() == ProductEnum::COURSE ||
$product->getType() == ProductEnum::COMBO
){
$courseRepository = $this->em->getRepository(Course::class);
$courses = $courseRepository->getCoursesByProduct($product->getId());
}
if($hasModule){
$productCouponOffer = $pcRepository->findValidProductCouponByIdAndProductOffer(
$productCouponId,
$productOffer
);
if($productCouponOffer && $this->user){
if($pcRepository->checkApplyCoupon($productCouponOffer, $productOffer)){
$priceOffer = $pcRepository->applyDiscount(
$productCouponOffer,
$priceOffer
);
if(empty($priceOffer)){
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($productCouponOffer->getKey());
$enrollmentService->enrollUserByProduct(
$this->user,
$product,
null,
($product->isTypeResource() ? $courses : null)
);
}
}
}
}
$cartRepository->addCartByProductOffer(
$productOffer,
$this->user,
null,
$productCouponOffer,
null,
($product->isTypeResource() ? $courses : null)
);
$psRepository = $this->em->getRepository(ProductSuggestion::class);
foreach ($productSuggestions as $key => $productSuggestionId) {
$productSuggestion = $psRepository->findOneBy([
"id" => $productSuggestionId,
"status" => ProductSuggestionEnum::PUBLISHED,
"deleted" => ProductSuggestionEnum::ITEM_NO_DELETED
]);
if($productSuggestion){
$offerSuggestion = $productSuggestion->getProductOffer();
$pcSuggestion = null;
$priceOfferSuggestion = $offerSuggestion->getPriceReal();
$offerProd = $offerSuggestion->getProduct();
if($hasModule){
$pcSuggestion = $pcRepository->findValidProductCouponByIdAndProductOffer(
$productCouponId,
$offerSuggestion,
true
);
if($pcSuggestion && $this->user){
if($pcRepository->checkApplyCoupon($pcSuggestion, $offerSuggestion)){
$priceOfferSuggestion = $pcRepository->applyDiscount(
$pcSuggestion,
$priceOfferSuggestion
);
if(empty($priceOfferSuggestion)){
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($pcSuggestion->getKey());
$enrollmentService->enrollUserByProduct(
$this->user,
$offerProd,
($offerProd->isTypeResource() ? $courses : null)
);
}
}
}
}
$cartRepository->addCartByProductOffer(
$offerSuggestion,
$this->user,
$productSuggestion,
$pcSuggestion,
null,
($offerProd->isTypeResource() ? $courses : null)
);
}
}
return $this->eadResponse([
"cartItemsQuantity" => $cartRepository->countUserOnCart(),
"success" => CartEnum::YES
]);
}
/**
* @Route(
* path = "/cart/enroll/{productOfferId}",
* name = "cartCreateEnroll",
* methods = {"GET"}
* )
*/
public function cartCreateEnroll(Request $request){
$this->checkUserSession($request);
$productOfferId = $request->get('productOfferId');
$productOffer = $this->em->getRepository(ProductOffer::class)->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
$product = $productOffer->getProduct();
if($product->isDisable()){
return $this->redirectToRoute('notFound');
}
if($productOffer->getSaleOption() != ProductOfferEnum::FREE){
return $this->redirectToRoute('notFound');
}
$enrollmentService = $this->generalService->getService('EnrollmentService');
$enrollmentService->setNotification(true);
$enrollmentService->enrollUserByProduct($this->user, $product);
return $this->redirectToRoute('resume');
}
/**
* @Route(
* path = "/whishlist/add/{productId}",
* name = "addProductWhishlist",
* methods = {"GET"}
* )
*/
public function addProductWhishlist(Request $request){
$this->checkUserSession($request);
$productId = $request->get('productId');
$product = $this->em->getRepository(Product::class)->findOneBy([
"id" => $productId,
"status" => ProductEnum::PUBLISHED,
"deleted" => ProductEnum::ITEM_NO_DELETED
]);
if(!$product){
return $this->redirectToRoute('notFound');
}
if($product->isDisable()){
return $this->redirectToRoute('notFound');
}
$productOfferId = $request->get('productOfferId');
$productOffer = $this->em->getRepository(ProductOffer::class)->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
$whishlist = new Whishlist();
$whishlistSave = $this->em->getRepository(Whishlist::class)->findOneBy([
"product" => $productId,
"user" => $this->user->getId(),
]);
if($whishlistSave){
$whishlist = $whishlistSave;
}
$whishlist->setUser($this->user);
$whishlist->setProduct($product);
if($productOffer){
$whishlist->setProductOffer($productOffer);
}
$errors = $this->validateEntity($whishlist);
if($errors){
return $this->redirectToRoute('notFound');
}
if(!$whishlistSave) {
$this->em->persist($whishlist);
}
$this->em->flush();
return $this->redirectToRoute('resume');
}
/**
* @Route(
* path = "/apply",
* name = "applyCartCoupon",
* methods = {"POST"},
* )
*/
public function applyProductCoupon(Request $request) {
if(!$this->configuration->isModuleActive("product_coupon_module")){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$this->requestUtil->setRequest($request)->setData();
$couponKey = $this->requestUtil->getField('couponKey');
$cookieName = 'hashcartoff';
$hashId = $this->generalService->getCookie($cookieName);
$cartRepository = $this->em->getRepository(Cart::class);
$return = $cartRepository->applyCouponUserCart($couponKey, $this->user, $hashId);
return $this->eadResponse([ "success" => ( $return ? 1 : 0 ) ]);
}
/**
* @Route(
* path = "/apply/offer",
* name = "applyProductCouponOnOffer",
* methods = {"POST"},
* )
*/
public function applyProductCouponOnOffer(Request $request) {
if(!$this->configuration->isModuleActive("product_coupon_module")){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$this->requestUtil->setRequest($request)->setData();
$couponKey = $this->requestUtil->getField('couponKey');
$productOfferIds = $this->requestUtil->getField('productIds');
$cartIds = $this->requestUtil->getField('cartIds');
if(empty($couponKey)){
return $this->eadResponse([ "couponKey" ], ErrorEnum::FIELD_EMPTY);
}
$cartIds = json_decode($cartIds);
$productOfferIds = json_decode($productOfferIds);
if(empty($productOfferIds) || !is_array($productOfferIds)){
return $this->eadResponse([ "productIds" ], ErrorEnum::FIELD_EMPTY);
}
$poRepository = $this->em->getRepository(ProductOffer::class);
$pcRepository = $this->em->getRepository(ProductCoupon::class);
$items = [];
$total = 0;
$totalWithDiscount = 0;
$find = false;
foreach ($productOfferIds as $key => $offerId) {
$productOffer = $poRepository->find($offerId);
$productCoupon = $pcRepository->findValidProductCouponByProductOffer(
$couponKey,
$productOffer
);
$amountDisplay = (float)$productOffer->getPriceDisplay();
$amount = (float)$productOffer->getPriceReal();
if(in_array($offerId, $cartIds)){
$total = $total + (!empty($amountDisplay) ? $amountDisplay : $amount);
}
if($productCoupon){
$find = true;
$amount = $pcRepository->applyDiscount($productCoupon, $amount);
}
if(in_array($offerId, $cartIds)){
$totalWithDiscount = $totalWithDiscount + $amount;
}
$items[] = (object)[
"id" => $offerId,
"amount" => $amount,
];
}
if(!$find){
return $this->eadResponse([
"message" => "Invalid Coupon"
], ErrorEnum::ACTION_INVALID);
}
$data = [
"total" => $total,
"totalDiscount" => $total - $totalWithDiscount,
"totalWithDiscount" => $totalWithDiscount,
"items" => $items,
];
return $this->eadResponse($data);
}
/**
* @Route(
* path = "/cart",
* name = "cart",
* methods = {"GET"}
* )
*/
public function cartPage(Request $request) {
$cookieName = 'hashcartoff';
$hashId = $this->generalService->getCookie($cookieName);
$cartRepository = $this->em->getRepository(Cart::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$pcRepository = $this->em->getRepository(ProductCoupon::class);
$cartRepository->updateCartsWithProductCouponExpired(
($this->user ? $this->user->getId() : null),
$hashId
);
$couponKey = $request->get('coupon');
$this->data['couponKeyValid'] = false;
if(!empty($couponKey)){
$this->data['couponKeyValid'] = $cartRepository->applyCouponUserCart(
$couponKey,
$this->user,
$hashId
);
}
$this->data['formName'] = "formRegisterUserCart";
$this->data['carts'] = null;
$this->data['cartSubtotal'] = 0;
$this->data['cartDisplaySubtotal'] = 0;
$this->data['couponKey'] = $couponKey;
$this->data['showInfoStep'] = true;
$cartRepository = $this->em->getRepository(Cart::class);
$customCart = false;
$displayTotal = 0;
$cartSubtotal = 0;
$paymentConfig = $this->configuration->getPaymentConfig();
if($this->user){
$userCheckoutInfoRepository = $this->em->getRepository(
UserCheckoutInfo::class
);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"user" => $this->user->getId(),
"default" => UserCheckoutInfoEnum::YES,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED
]);
if($userCheckoutInfo){
$this->data['showInfoStep'] = false;
}
$userId = $this->user->getId();
$carts = $cartRepository->getUserValidCarts($userId);
$userCards = $this->em->getRepository(UserCard::class)->getValidUserCard();
$customCart = (
$cartRepository->countCustomCheckout($userId) > 0 ? true : false
);
$hasOnlyCourseInCart = $cartRepository->hasOnlyCourseInCart($userId);
$cartSubtotal = $cartRepository->getUserSubTotal($userId);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$numberUtil = $this->generalService->getUtil('NumberUtil');
$methods = [
ProductOfferEnum::CARD,
ProductOfferEnum::BILL,
ProductOfferEnum::PIX,
];
$cardOptions = [
ProductOfferEnum::ALL_METHODS,
ProductOfferEnum::CARD,
ProductOfferEnum::CARD_PIX,
ProductOfferEnum::CARD_BILL,
];
$pixOptions = [
ProductOfferEnum::ALL_METHODS,
ProductOfferEnum::PIX,
ProductOfferEnum::CARD_PIX,
ProductOfferEnum::BILL_PIX,
];
$billOptions = [
ProductOfferEnum::ALL_METHODS,
ProductOfferEnum::BILL,
ProductOfferEnum::CARD_BILL,
ProductOfferEnum::BILL_PIX,
];
$getPaymentOption = function(ProductOffer $productOffer) use (
$productOfferRepository,
$cardOptions,
$pixOptions,
$billOptions
){
$billTypeExpire = ProductOfferEnum::BILL_PERIOD;
$billPeriodExpire = 7;
$billDateExpire = null;
$pixTypeExpire = ProductOfferEnum::PIX_PERIOD;
$pixPeriodExpire = 7;
$pixDateExpire = null;
$installmentNumberMax = 12;
$installmentNumberInterest = 1;
$freeInstallments = 1;
$paymentMethodOption = $productOffer->getPaymentMethod();
if(in_array($paymentMethodOption, $cardOptions)){
$installmentNumberMax = $productOffer->getInstallmentNumberMax();
$installmentNumberInterest = $productOffer->getInstallmentNumberInterest();
$freeInstallments = $productOfferRepository->getFreeInstallment(
$productOffer
);
}else if(in_array($paymentMethodOption, $pixOptions)){
$pixTypeExpire = $productOffer->getPixTypeExpire();
$pixPeriodExpire = $productOffer->getPixPeriodExpire();
$pixDateExpire = $productOffer->getPixDateExpire();
}else if(in_array($paymentMethodOption, $billOptions)){
$billTypeExpire = $productOffer->getBillTypeExpire();
$billPeriodExpire = $productOffer->getBillPeriodExpire();
$billDateExpire = $productOffer->getBillDateExpire();
}
return (object)[
"typeCheckout" => $productOffer->getTypeCheckout(),
"saleOption" => $productOffer->getSaleOption(),
"paymentMethod" => $paymentMethodOption,
"billTypeExpire" => $billTypeExpire,
"billPeriodExpire" => $billPeriodExpire,
"billDateExpire" => $billDateExpire,
"pixTypeExpire" => $pixTypeExpire,
"pixPeriodExpire" => $pixPeriodExpire,
"pixDateExpire" => $pixDateExpire,
"installmentNumberMax" => $installmentNumberMax,
"installmentNumberInterest" => $installmentNumberInterest,
"freeInstallments" => $freeInstallments,
"items" => [],
];
};
$offerPaymentOptions = [];
$internalOptions = [
ProductOfferEnum::INTERNAL_EAD,
ProductOfferEnum::INTERNAL_PAYPAL,
ProductOfferEnum::INTERNAL_PAGSEGURO,
ProductOfferEnum::INTERNAL_MERCADOPAGO,
];
foreach ($carts as $key => $cart) {
$productOffer = $cart->getProductOffer();
$offerInternalOptions = json_decode($productOffer->getSaleOptionInternal());
if(is_array($offerInternalOptions)){
$internalOptions = array_intersect(
$internalOptions,
$offerInternalOptions
);
}
$productOfferCouponTotal = $pcRepository->countPublicCouponByProductOffer(
$productOffer
);
$cart->offerPaymentOptions = null;
if($customCart){
$cart->offerPaymentOptions = $getPaymentOption($productOffer);
$offerPaymentOptions[] = $cart->offerPaymentOptions;
}
$cart->productOfferCouponTotal = $productOfferCouponTotal;
$carts[$key] = $cart;
}
$customCartSame = true;
$optionCustomDefault = null;
if(count($offerPaymentOptions) == count($carts)){
foreach ($offerPaymentOptions as $key => $option) {
if(empty($optionCustomDefault)){
$optionCustomDefault = $option;
}
if($optionCustomDefault != $option){
$customCartSame = false;
break;
}
}
}
$this->data['use_card'] = $this->configuration->get('use_card');
$this->data['use_pix'] = $this->configuration->get('use_pix');
$this->data['use_bill'] = $this->configuration->get('use_bill');
$this->data['use_paypal'] = CartEnum::NO;
$this->data['use_pagseguro'] = CartEnum::NO;
$this->data['use_mercadopago'] = CartEnum::NO;
if(is_array($internalOptions)){
$this->data['use_paypal'] = (
in_array(ProductOfferEnum::INTERNAL_PAYPAL, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
$this->data['use_pagseguro'] = (
in_array(ProductOfferEnum::INTERNAL_PAGSEGURO, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
$this->data['use_mercadopago'] = (
in_array(ProductOfferEnum::INTERNAL_MERCADOPAGO, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
}
$this->data['isOneMethod'] = CartEnum::NO;
$this->data['isOneMethodType'] = null;
if($customCartSame && $optionCustomDefault){
$customCart = false;
$methodsInUse = [];
$this->data['use_card'] = CartEnum::NO;
$this->data['use_pix'] = CartEnum::NO;
$this->data['use_bill'] = CartEnum::NO;
if(in_array($optionCustomDefault->paymentMethod, $cardOptions)){
$this->data['use_card'] = CartEnum::YES;
$methodsInUse[] = CartEnum::PAYMENT_CARD;
}
if(in_array($optionCustomDefault->paymentMethod, $pixOptions)){
$this->data['use_pix'] = CartEnum::YES;
$methodsInUse[] = CartEnum::PAYMENT_PIX;
}
if(in_array($optionCustomDefault->paymentMethod, $billOptions)){
$this->data['use_bill'] = CartEnum::YES;
$methodsInUse[] = CartEnum::PAYMENT_BILL;
}
if(count($methodsInUse) == CartEnum::YES){
$this->data['isOneMethod'] = CartEnum::YES;
$this->data['isOneMethodType'] = end($methodsInUse);
}
$freeInstallments = $optionCustomDefault->installmentNumberInterest;
/*if($paymentConfig->assumeInstallmentInterest == ProductOfferEnum::YES){
$freeInstallments = 12;
}*/
$parcelInfo = $numberUtil->getNumberMaxParcel(
$cartSubtotal * 100,
$optionCustomDefault->installmentNumberMax,
$freeInstallments,
ProductOfferEnum::EAD,
ProductOfferEnum::CHECKOUT_CUSTOM
);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $numberUtil->numberToCents($cartSubtotal),
'free_installments' => $freeInstallments,
'max_installments' => $parcelInfo->maxInstallments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$this->data['installmentsOptions'] = (array)$installmentsOptions;
}else if($customCart){
$steps = [];
$auxOption = [];
foreach ($offerPaymentOptions as $key => $value) {
if(!in_array($value, $auxOption)){
$auxOption[] = $value;
}
}
$offerPaymentOptions = $auxOption;
$defaultObj = (object)[
"amountStep" => 0,
"amountStepCent" => 0,
"items" => [],
"installmentsOptions" => null,
"freeInstallments" => 1,
"useCard" => $this->configuration->get('use_card'),
"usePix" => $this->configuration->get('use_pix'),
"useBill" => $this->configuration->get('use_bill'),
"installmentNumberMax" => $paymentConfig->installmentNumberMax,
"assumeInstallmentInterest" => $paymentConfig->assumeInstallmentInterest,
"installmentNumberInterest" => $paymentConfig->installmentNumberInterest,
"default" => true,
];
$defaultSubtotalCent = 0;
$defaultInstallmentsOptions = null;
foreach ($carts as $key => $cart) {
$cart->setAble(CartEnum::YES);
$productOffer = $cart->getProductOffer();
if($productOffer->getTypeCheckout() == ProductOfferEnum::CHECKOUT_DEFAULT){
$price = $cart->getPrice() + $cart->getMembershipFee();
$priceCents = $cart->getPrice(true) + $cart->getMembershipFee(true);
$defaultObj->amountStep = $defaultObj->amountStep + $price;
$defaultObj->amountStepCent = $defaultObj->amountStepCent + $priceCents;
$defaultObj->items[] = $cart;
}else{
$indexOptions = array_search(
$cart->offerPaymentOptions,
$offerPaymentOptions
);
if(isset($offerPaymentOptions[$indexOptions])){
$offerPaymentOptions[$indexOptions]->items[] = $cart;
}
}
}
foreach ($offerPaymentOptions as $key => $option) {
if(count($option->items)){
$option->useCard = in_array($option->paymentMethod, $cardOptions);
$option->usePix = in_array($option->paymentMethod, $pixOptions);
$option->useBill = in_array($option->paymentMethod, $billOptions);
$amountOption = 0;
$amountOptionCents = 0;
foreach ($option->items as $keyItem => $item) {
$productOffer = $item->getProductOffer();
$amountOption = $amountOption + $item->getPrice() + $item->getMembershipFee();
$amountOptionCents = $amountOptionCents + $item->getPrice(true) + $item->getMembershipFee(true);
}
$installmentsOptions = null;
if($option->useCard){
$parcelInfo = $numberUtil->getNumberMaxParcel(
$amountOptionCents,
$option->installmentNumberMax,
$option->freeInstallments,
$option->saleOption,
$option->typeCheckout
);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $amountOptionCents,
'free_installments' => $option->freeInstallments,
'max_installments' => $parcelInfo->maxInstallments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$installmentsOptions = (array)$installmentsOptions;
}
$newStep = (object)[
'amountStep' => $amountOption,
'amountStepCent' => $amountOptionCents,
"items" => $option->items,
"installmentsOptions" => $installmentsOptions,
"freeInstallments" => 1,
"useCard" => $option->useCard,
"usePix" => $option->usePix,
"useBill" => $option->useBill,
"installmentNumberMax" => $option->installmentNumberMax,
"assumeInstallmentInterest" => ProductOfferEnum::NO,
"installmentNumberInterest" => $option->installmentNumberInterest,
"default" => false
];
if($option->useCard){
$this->data['use_card'] = CartEnum::YES;
}
if($option->usePix){
$this->data['use_pix'] = CartEnum::YES;
}
if($option->useBill){
$this->data['use_bill'] = CartEnum::YES;
}
$steps[] = $newStep;
}
}
if(count($defaultObj->items)){
$defaultObj->freeInstallments = $paymentConfig->installmentNumberInterest;
if($paymentConfig->assumeInstallmentInterest == ProductOfferEnum::YES){
$defaultObj->freeInstallments = 12;
}
$parcelInfo = $numberUtil->getNumberMaxParcel(
$defaultObj->amountStepCent,
$paymentConfig->installmentNumberMax,
$defaultObj->freeInstallments,
ProductOfferEnum::EAD,
ProductOfferEnum::CHECKOUT_DEFAULT
);
$defaultOptions = (array)$pagarMeTransaction->calculateInstallments([
'amount' => $defaultObj->amountStepCent,
'free_installments' => $defaultObj->freeInstallments,
'max_installments' => $parcelInfo->maxInstallments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$defaultObj->installmentsOptions = $defaultOptions;
array_unshift($steps, $defaultObj);
}
$this->data['steps'] = $steps;
}else{
$freeInstallments = $paymentConfig->installmentNumberInterest;
if($paymentConfig->assumeInstallmentInterest == ProductOfferEnum::YES){
$freeInstallments = 12;
}
$parcelInfo = $numberUtil->getNumberMaxParcel(
$cartSubtotal * 100,
$paymentConfig->installmentNumberMax,
$freeInstallments,
ProductOfferEnum::EAD,
ProductOfferEnum::CHECKOUT_DEFAULT
);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $numberUtil->numberToCents($cartSubtotal),
'free_installments' => $freeInstallments,
'max_installments' => $parcelInfo->maxInstallments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$this->data['installmentsOptions'] = (array)$installmentsOptions;
}
$receiverSchoolEad = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
$receiverSchoolPayPal = $this->configuration->getReceiverSchool(
ReceiverEnum::PAYPAL
);
$receiverSchoolPagSeguro = $this->configuration->getReceiverSchool(
ReceiverEnum::PAGSEGURO
);
$receiverSchoolMercadoPago = $this->configuration->getReceiverSchool(
ReceiverEnum::MERCADO_PAGO
);
$displayTotal = $cartRepository->getUserDisplaySubTotal($userId);
$this->data['receiverSchoolEad'] = $receiverSchoolEad;
$this->data['receiverSchoolPayPal'] = $receiverSchoolPayPal;
$this->data['receiverSchoolPagSeguro'] = $receiverSchoolPagSeguro;
$this->data['receiverSchoolMercadoPago'] = $receiverSchoolMercadoPago;
$this->data['cartSubtotal'] = $cartSubtotal;
$this->data['cartDisplaySubtotal'] = $displayTotal;
$this->data['userCards'] = $userCards;
$this->data['hasOnlyCourseInCart'] = $hasOnlyCourseInCart;
$this->data['carts'] = $carts;
}else if(!empty($hashId)){
$cartInfo = $cartRepository->getHashValidCartsInfo($hashId);
$customCart = ($cartInfo->totalCustom > 0 ? true : false);
$carts = $cartInfo->data;
foreach ($carts as $key => $cart) {
$cart->setAble(CartEnum::YES);
$productOffer = $cart->getProductOffer();
$productOfferCouponTotal = $pcRepository->countPublicCouponByProductOffer(
$productOffer
);
$cart->productOfferCouponTotal = $productOfferCouponTotal;
$carts[$key] = $cart;
}
$this->data['carts'] = $carts;
$this->data['cartSubtotal'] = $cartInfo->totalPrice;
$this->data['cartDisplaySubtotal'] = $cartInfo->totalDisplay;
}
$this->data['keyCaptcha'] = $this->createCaptchaKey($request);
$this->data['customCart'] = $customCart;
$this->data['cartSubtotalDiff'] = $displayTotal - $cartSubtotal;
$this->data['isCart'] = true;
$this->data['urlPost'] = $this->generalService->generateUrl("cartCheckoutDefault");
$this->data['urlConclusion'] = $this->generalService->generateUrl("cartConclusion");
$this->em->flush();
if(empty($this->data['carts'])){
$this->data['carts'] = [];
}
return $this->renderEAD('cart/cart.html.twig');
}
/**
* @Route(
* path = "/cart/indvidual/{poHash}/{pcKey}",
* name = "cartIndividual",
* methods = {"GET"},
* defaults = { "pcKey" = "" }
* )
*/
public function cartPageIndvidual(Request $request) {
$cartRepository = $this->em->getRepository(Cart::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productCouponRepository = $this->em->getRepository(ProductCoupon::class);
$productRepository = $this->em->getRepository(Product::class);
$offerHash = $request->get('poHash');
$productOffer = $productOfferRepository->getProductByOfferLink($offerHash);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
$product = $productOffer->getProduct();
if($productOffer->getAllowTrial() == ProductOfferEnum::NO){
return $this->redirectToRoute('notFound');
}
$productPage = $productOffer->getProductPage();
if(!$productPage){
return $this->redirectToRoute('notFound');
}
if($productOffer->getSaleChannel() == ProductOfferEnum::EXTERNAL){
$externalCheckoutLink = $productOffer->getExternalCheckoutLink();
return $this->redirect($externalCheckoutLink, 301);
}
$externalPage = $productPage->getExternalPage();
$externalPageLink = $productPage->getExternalPageLink();
if($externalPage == ProductEnum::YES && !empty($externalPageLink)){
//return $this->redirect($externalPageLink, 301);
}
$productCoupon = null;
$couponKey = $request->get('pcKey');
$couponKeyValid = false;
if(!empty($couponKey)){
$productCoupon = $productCouponRepository->findValidProductCouponByProductOffer(
$couponKey,
$productOffer
);
if($productCoupon){
$amount = $productOffer->getPriceReal();
if(
$productCouponRepository->checkApplyCoupon($productCoupon, $productOffer)
){
$amount = $productCouponRepository->applyDiscount(
$productCoupon,
$amount
);
$couponKeyValid = true;
}
if(!empty($amount)){
$productOffer->setPriceRealCopy($amount);
}
}
}
if(
$this->user &&
(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
)
){
$userSubscriptionRepository = $this->em->getRepository(UserSubscription::class);
$userSubscription = $userSubscriptionRepository->findOneBy([
"user" => $this->user->getId(),
"product" => $product->getId(),
"deleted" => UserSubscriptionEnum::ITEM_NO_DELETED,
]);
if($userSubscription){
if(
$userSubscription->getStatus() == UserSubscriptionEnum::STATUS_COMPLETED ||
$userSubscription->getStatus() == UserSubscriptionEnum::STATUS_CANCELED
){
$params = [
"poID" => $productOffer->getId(),
"pcID" => ( $productCoupon ? $productCoupon->getId() : 0 ),
];
return $this->redirectToRoute('cartAdd', $params);
}
return $this->redirectToRoute('notFound');
}
}
$this->data['couponKey'] = $couponKey;
$this->data['couponKeyValid'] = $couponKeyValid;
$this->data['showInfoStep'] = true;
$customCart = false;
$displayTotal = $productOffer->getPriceDisplay();
$cartSubtotal = $productOffer->getPriceRealCopy();
$hasOnlyCourseInCart = true;
$paymentConfig = $this->configuration->getPaymentConfig();
$userCards = [];
if($this->user){
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"user" => $this->user->getId(),
"default" => UserCheckoutInfoEnum::YES,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED
]);
if($userCheckoutInfo){
$this->data['showInfoStep'] = false;
}
$userCards = $this->em->getRepository(UserCard::class)->getValidUserCard();
}
$pagarMeTransaction = $this->generalService->getService('PagarMe\\PagarMeTransaction');
$numberUtil = $this->generalService->getUtil('NumberUtil');
$useCard = $productOfferRepository->produtOfferAllowCard($productOffer);
$useBill = $productOfferRepository->produtOfferAllowBill($productOffer);
$usePix = $productOfferRepository->produtOfferAllowPix($productOffer);
$internalOptions = json_decode($productOffer->getSaleOptionInternal());
$this->data['use_paypal'] = CartEnum::NO;
$this->data['use_pagseguro'] = CartEnum::NO;
$this->data['use_mercadopago'] = CartEnum::NO;
if(is_array($internalOptions)){
$this->data['use_paypal'] = (
in_array(ProductOfferEnum::INTERNAL_PAYPAL, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
$this->data['use_pagseguro'] = (
in_array(ProductOfferEnum::INTERNAL_PAGSEGURO, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
$this->data['use_mercadopago'] = (
in_array(ProductOfferEnum::INTERNAL_MERCADOPAGO, $internalOptions) ?
CartEnum::YES :
CartEnum::NO
);
}
$hasTrue = [
$useCard == CartEnum::YES && $useBill == CartEnum::NO && $usePix == CartEnum::NO,
$useCard == CartEnum::NO && $useBill == CartEnum::YES && $usePix == CartEnum::NO,
$useCard == CartEnum::NO && $useBill == CartEnum::NO && $usePix == CartEnum::YES,
];
$paymentMethod = [
CartEnum::PAYMENT_CARD,
CartEnum::PAYMENT_BILL,
CartEnum::PAYMENT_PIX,
];
$this->data['use_card'] = $useCard;
$this->data['use_bill'] = $useBill;
$this->data['use_pix'] = $usePix;
$key = array_search(true, $hasTrue);
$this->data['isOneMethod'] = (!empty($key) ? CartEnum::YES : CartEnum::NO);
$this->data['isOneMethodType'] = (!empty($key) ? $paymentMethod[$key] : null);
$freeInstallments = $productOfferRepository->getFreeInstallment($productOffer);
$maxInstallments = $productOfferRepository->getInstallmentNumberMax($productOffer);
$parcelInfo = $numberUtil->getNumberMaxParcel(
$cartSubtotal * 100,
$maxInstallments,
$freeInstallments,
ProductOfferEnum::EAD,
$productOffer->getTypeCheckout()
);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $numberUtil->numberToCents($cartSubtotal),
'free_installments' => $freeInstallments,
'max_installments' => $parcelInfo->maxInstallments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$this->data['installmentsOptions'] = (array)$installmentsOptions;
$receiverSchoolEad = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
$receiverSchoolPayPal = $this->configuration->getReceiverSchool(
ReceiverEnum::PAYPAL
);
$receiverSchoolPagSeguro = $this->configuration->getReceiverSchool(
ReceiverEnum::PAGSEGURO
);
$receiverSchoolMercadoPago = $this->configuration->getReceiverSchool(
ReceiverEnum::MERCADO_PAGO
);
$this->data['receiverSchoolEad'] = $receiverSchoolEad;
$this->data['receiverSchoolPayPal'] = $receiverSchoolPayPal;
$this->data['receiverSchoolPagSeguro'] = $receiverSchoolPagSeguro;
$this->data['receiverSchoolMercadoPago'] = $receiverSchoolMercadoPago;
$this->data['cartSubtotal'] = CartEnum::NO;//$cartSubtotal;
$this->data['cartDisplaySubtotal'] = CartEnum::NO;//$displayTotal;
$this->data['cartSubtotalDiff'] = CartEnum::NO;//$displayTotal - $cartSubtotal;
$this->data['userCards'] = $userCards;
$this->data['hasOnlyCourseInCart'] = $hasOnlyCourseInCart;
$cart = new Cart();
$hashIdentify = $this->generalService->getCookieHashIdentify();
$cart->setProductOffer($productOffer);
$cart->setProduct($product);
if($productCoupon && $couponKeyValid){
$cart->setProductCoupon($productCoupon);
}
if($this->user){
$cart->setUser($this->user);
$cart->setHashIdentify($this->user->getHashIdentify());
}else if(!empty($hashIdentify)){
$cart->setHashIdentify($hashIdentify);
}
$cart->setPrice($productOffer->getPriceRealCopy());
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
){
$cart->setMembershipFee($productOffer->getMembershipFeeCopy());
}
$cart->setProductType($product->getType());
$productOfferCouponTotal = $productCouponRepository->countPublicCouponByProductOffer(
$productOffer
);
$cart->offerPaymentOptions = null;
$cart->productOfferCouponTotal = $productOfferCouponTotal;
$this->data['carts'] = [
$cart
];
$this->data['keyCaptcha'] = $this->createCaptchaKey($request);
$this->data['customCart'] = $customCart;
$this->data['isCart'] = false;
$this->data['urlPost'] = $this->generalService->generateUrl(
"cartCheckoutPlanTrial",
[
"poID" => $productOffer->getId(),
"pcID" => ($productCoupon ? $productCoupon->getId() : null),
]
);
$this->data['urlRedirect'] = $this->generalService->generateUrl(
"cartIndividual",
[
"poHash" => $offerHash,
"pcKey" => ($couponKey ? $couponKey : null),
]
) . "#cart-step-info";
$this->data['urlConclusion'] = $this->generalService->generateUrl("cartConclusion");
$this->em->flush();
if(empty($this->data['carts'])){
$this->data['carts'] = [];
}
return $this->renderEAD('cart/cart.html.twig');
}
/**
* @Route(
* path = "/admin/cart/user/valid",
* name = "getUserValidCarts",
* methods = {"GET"}
* )
*/
public function getUserValidCarts(Request $request){
if (!$this->user) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$cartRepository = $this->em->getRepository(Cart::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$userId = $this->user->getId();
$carts = $cartRepository->getUserValidCarts($userId);
$paymentConfig = $this->configuration->getPaymentConfig();
$fileService = $this->generalService->getService('FileService');
$data = [];
foreach ($carts as $key => $cart) {
$productOffer = $cart->getProductOffer();
$billDateExpire = $productOfferRepository->getDateExpireBill($productOffer);
$pixDateExpire = $productOfferRepository->getDateExpirePix($productOffer);
$photo = $fileService->getFilePathComplete(
$cart->getProductOffer()->getProductPage()->getPhoto(),
ProductEnum::PATH_PRODUCT_PHOTO,
true,
false,
'product-photo',
true
);
$onErrorPhoto = $fileService->getFilePathComplete(
$cart->getProductOffer()->getProductPage()->getPhoto(),
ProductEnum::PATH_PRODUCT_PHOTO,
true,
false,
'product-photo',
false
);
$price = (float)($cart->getPrice() + $cart->getMembershipFee());
$membershipFee = (float)$productOffer->getMembershipFee();
$priceReal = (float)($productOffer->getPriceReal() + $membershipFee);
$priceDiscount = (float)$price - $priceReal;
$priceDisplay = (float)$productOffer->getPriceDisplay();
if(!empty($priceDisplay)){
$priceDisplay = (float)($priceDisplay + $membershipFee);
$priceDiscount = $price - $priceDisplay;
}
$recurrency = (
$cart->getProduct()->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
)? true : false;
$item = (object)[
"id" => $cart->getId(),
"title" => $cart->getProduct()->getTitle(),
"photo" => $photo,
"onErrorPhoto" => $onErrorPhoto,
"able" => ($cart->getAble() == CartEnum::YES),
"priceOrigin" => (float)$cart->getPrice(),
"membershipFeeOrigin" => (float)$productOffer->getMembershipFee(),
"membershipFeeReal" => (float)$cart->getMembershipFee(),
"priceReal" => $priceReal,
"price" => (float)$price,
"priceReal" => $priceReal,
"priceDisplay" => (float)$priceDisplay,
"priceDiscount" => (float)$priceDiscount,
"couponKey" => (
$cart->getProductCoupon() ? $cart->getProductCoupon()->getKey() : null
),
"couponMembershipFee" => (int)(
$cart->getProductCoupon() ?
$cart->getProductCoupon()->getApplyMembershipFee() :
ProductEnum::NO
),
"billDateExpire" => $billDateExpire,
"pixDateExpire" => $pixDateExpire,
"interestFee" => $paymentConfig->installmentInterest,
"currencySymbol" => $productOffer->getCurrencySymbol(),
"paymentCycle" => $productOffer->getPlanCycle(),
"recurrency" => $recurrency,
];
$data[] = $item;
}
return $this->eadResponse($data);
}
/**
* @Route(
* path = "/admin/cart/change/status",
* name = "cartChangeStatus",
* methods = {"PUT"}
* )
*/
public function updateCartStatus(Request $request){
if (!$this->user) {
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$this->requestUtil->setRequest($request)->setData();
$cartId = $this->requestUtil->getField('cart');
$able = $this->requestUtil->getField('able');
$cartRepository = $this->em->getRepository(Cart::class);
$userId = $this->user->getId();
$cart = $cartRepository->findOneBy([
"id" => $cartId,
"user" => $userId,
"deleted" => CartEnum::ITEM_NO_DELETED,
]);
if(!$cart){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$cart->setAble($able);
$this->em->flush();
return $this->eadResponse([ "success" => 1 ]);
}
/**
* @Route(
* path = "/cart/checkout/paypal",
* name = "cartCheckoutPaypal",
* methods = {"GET"}
* )
*/
public function checkoutPayPal(Request $request){
$this->checkUserSession($request);
$receiverSchool = $this->configuration->getReceiverSchool(ReceiverEnum::PAYPAL);
if(!$receiverSchool){
return $this->redirectToRoute('notFound');
}
$this->requestUtil->setRequest($request)->setData();
$cartRepository = $this->em->getRepository(Cart::class);
$hasOnlyCourseInCart = $cartRepository->hasOnlyCourseInCart($this->user->getId());
if(!$hasOnlyCourseInCart){
return $this->redirectToRoute('notFound');
}
$currencyCode = $this->configuration->get('currency_code');
$userCheckoutInfoId = $this->requestUtil->getField('userCheckoutInfoId');
$transactionData = [
"cmd" => "_cart",
"business" => $receiverSchool->getEmail(),
"upload" => 1,
"currency_code" => ( $currencyCode ? $currencyCode : "BRL" ),
"charset" => "UTF-8",
];
$dataCustom = [];
$carts = $cartRepository->getUserValidCarts($this->user->getId());
if(empty($carts)){
return $this->redirectToRoute('notFound');
}
foreach ($carts as $key => $cart) {
$index = $key + 1;
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$title = $this->stringUtil->shortTextClean($product->getTitle(), 30);
$title = $this->stringUtil->cleanString2($title);
$transactionData["item_number_{$index}"] = $product->getId();
$transactionData["item_name_{$index}"] = $title;
$transactionData["amount_{$index}"] = $cart->getPrice();
$transactionData["quantity_{$index}"] = 1;
$dataCustom["cart_{$index}"] = $cart->getId();
$dataCustom["amount_{$index}"] = $cart->getPrice();
$dataCustom["offer_{$index}"] = $productOffer->getId();
$productCoupon = $cart->getProductCoupon();
if($productCoupon){
$dataCustom["coupon_{$index}"] = $productCoupon->getId();
}
}
$dataCustom["new"] = CartEnum::YES;
$dataCustom["userId"] = $this->user->getId();
$dataCustom["numberItens"] = count($carts);
$dataCustom["userCheckoutInfoId"] = $userCheckoutInfoId;
$transactionData["custom"] = json_encode($dataCustom);
$transactionData["return"] = "https://{$this->eadDomain}/resume/";
$transactionData["notify_url"] = "https://{$this->eadDomain}/paypal/";
$transactionData = http_build_query($transactionData);
$payPal = $this->generalService->getService('PayPal\\PayPal');
$url = "{$payPal->getPayPalAddress()}?{$transactionData}";
return $this->redirect($url, 301);
}
/**
* @Route(
* path = "/cart/checkout/pagseguro",
* name = "cartCheckoutPagseguro",
* methods = {"GET"}
* )
*/
public function checkoutPagSeguro(Request $request){
$this->checkUserSession($request);
$receiverSchool = $this->configuration->getReceiverSchool(ReceiverEnum::PAGSEGURO);
if(!$receiverSchool){
return $this->redirectToRoute('notFound');
}
$this->requestUtil->setRequest($request)->setData();
$cartRepository = $this->em->getRepository(Cart::class);
$hasOnlyCourseInCart = $cartRepository->hasOnlyCourseInCart($this->user->getId());
if(!$hasOnlyCourseInCart){
return $this->redirectToRoute('notFound');
}
$userCheckoutInfoId = $this->requestUtil->getField('userCheckoutInfoId');
$transactionData = [
"cmd" => "_cart",
"business" => $receiverSchool->getEmail(),
//"upload" => 1,
"currency" => "BRL",
"charset" => "ISO-8859-1",
];
$dataCustom = [];
$carts = $cartRepository->getUserValidCarts($this->user->getId());
if(empty($carts)){
return $this->redirectToRoute('notFound');
}
foreach ($carts as $key => $cart) {
$index = $key + 1;
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$title = $this->stringUtil->shortTextClean($product->getTitle(), 30);
$title = $this->stringUtil->cleanString2($title);
$transactionData["itemId{$index}"] = $productOffer->getId();
$transactionData["itemDescription{$index}"] = $title;
$transactionData["itemAmount{$index}"] = $cart->getPrice();
$transactionData["itemQuantity{$index}"] = 1;
$dataCustom["cart_{$index}"] = $cart->getId();
$dataCustom["amount_{$index}"] = $cart->getPrice();
$dataCustom["offer_{$index}"] = $productOffer->getId();
$productCoupon = $cart->getProductCoupon();
if($productCoupon){
$dataCustom["coupon_{$index}"] = $productCoupon->getId();
}
}
$dataCustom["userId"] = $this->user->getId();
$dataCustom["numberItens"] = count($carts);
$dataCustom["userCheckoutInfoId"] = $userCheckoutInfoId;
$transactionData["reference"] = $this->user->getId();
$transactionData["custom"] = json_encode($dataCustom);
$transactionData["redirectURL"] = "https://{$this->eadDomain}/resume/";
$transactionData["notificationURL"] = "https://{$this->eadDomain}/pagseguro/";
$pagSeguro = $this->generalService->getService('PagSeguro\\PagSeguro');
$url = $pagSeguro->getCheckoutPagseguro($transactionData);
return $this->redirect($url, 301);
}
/**
* @Route(
* path = "/cart/checkout/mercadopago",
* name = "cartCheckoutMercadopago",
* methods = {"GET"}
* )
*/
public function checkoutMercadopago(Request $request) {
$this->checkUserSession($request);
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::MERCADO_PAGO
);
if(!$receiverSchool){
return $this->redirectToRoute('notFound');
}
$this->requestUtil->setRequest($request)->setData();
$cartRepository = $this->em->getRepository(Cart::class);
$hasOnlyCourseInCart = $cartRepository->hasOnlyCourseInCart($this->user->getId());
if(!$hasOnlyCourseInCart){
return $this->redirectToRoute('notFound');
}
$carts = $cartRepository->getUserValidCarts($this->user->getId());
if(empty($carts)){
return $this->redirectToRoute('notFound');
}
foreach ($carts as $key => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$title = $this->stringUtil->shortTextClean($product->getTitle(), 30);
$title = $this->stringUtil->cleanString2($title);
$description = $this->stringUtil->shortTextClean($product->getDescription(), 30);
$description = $this->stringUtil->cleanString2($description);
$items[] = [
"id" => $productOffer->getId(),
"title" => $title,
"description" => $description,
"quantity" => 1,
"unit_price" => $cart->getPrice()
];
}
$transactionData["items"] = $items;
$transactionData["back_urls"] = [
"success" => "https://{$this->eadDomain}/resume/",
"failure" => "https://{$this->eadDomain}/cart#mercadopago/",
"pending" => "https://{$this->eadDomain}/cart#mercadopago/"
];
$transactionData["external_reference"] = $this->user->getId();
$transactionData["notification_url"] = "https://{$this->eadDomain}/mercadopago?debug=1";
$data = json_encode($transactionData);
$mercadoPago = $this->generalService->getService('MercadoPago\\MercadoPago');
$url = $mercadoPago->getCheckoutMercadoPago($data);
return $this->redirect($url, 301);
}
/**
* @Route(
* path = "/admin/cart/checkout/charge",
* name = "cartCheckoutCharge",
* methods = {"POST"}
* )
*/
public function checkoutCharge(Request $request){
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->eadResponse(
[ "message" => "Receiver not found "],
ErrorEnum::ACTION_INVALID
);
}
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$this->requestUtil->setRequest($request)->setData();
$productChargeId = (int)$this->requestUtil->getField('productChargeId');
$userCheckoutInfoId = (int)$this->requestUtil->getField('userCheckoutInfoId');
$paymentMethod = (int)$this->requestUtil->getField('paymentMethod');
$installments = (int)$this->requestUtil->getField('installments');
$debug = (int)$request->get('debug');
$productCharge = $this->em->getRepository(ProductCharge::class)->findOneBy([
"id" => $productChargeId,
"deleted" => ProductChargeEnum::ITEM_NO_DELETED
]);
if (!$productCharge) {
return $this->eadResponse(
[ "message" => "Charge not found "],
ErrorEnum::ACTION_INVALID
);
}
if ($productCharge->getPublish() == ProductChargeEnum::NO) {
return $this->eadResponse(
[ "message" => "Charge is not publish "],
ErrorEnum::ACTION_INVALID
);
}
$userCardRepository = $this->em->getRepository(UserCard::class);
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"id" => $userCheckoutInfoId,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
if(!$userCheckoutInfo){
return $this->eadResponse([
"message" => "UserCheckoutInfo is empty"
], ErrorEnum::ACTION_INVALID);
}
$paymentConfig = $this->configuration->getPaymentConfig();
$product = $productCharge->getProduct();
$productOffer = $productCharge->getProductOffer();
$items = [
(object)[
"courseId" => null,
"productOfferId" => $productOffer->getId(),
"productId" => $product->getId(),
"amount" => $productCharge->getAmount(),
"cartId" => null,
"productCouponId" => null,
]
];
$userCard = null;
$amount = $productCharge->getAmount(true);
$dateExpire = $productCharge->getDateExpire();
if(empty($paymentMethod)){
return $this->eadResponse([ 'paymentMethod' ], ErrorEnum::FIELD_EMPTY);
}
if($paymentMethod == CartEnum::PAYMENT_CARD){ // get user card
if(empty($installments)){
return $this->eadResponse([ 'installments' ], ErrorEnum::FIELD_EMPTY);
}
$userCardId = $this->requestUtil->getField('userCardId');
if(empty($userCardId)){
return $this->eadResponse([ 'userCardId' ], ErrorEnum::FIELD_EMPTY);
}
if($userCardId > 0){
$userCard = $userCardRepository->findOneBy([
"id" => $userCardId,
"user" => $this->user->getId(),
"deleted" => CartEnum::ITEM_NO_DELETED
]);
}
}
if($paymentMethod == CartEnum::PAYMENT_CARD && !$userCard){
return $this->eadResponse(
[ "message" => "Card not found "],
ErrorEnum::ACTION_INVALID
);
}
$freeInstallments = $productCharge->getInstallmentNumberInterest();
if($paymentMethod == CartEnum::PAYMENT_CARD){
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $amount,
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$amount = $installmentsOptions->{$installments}->amount;
}
if($amount < $this->configuration->getMinValueProduct()){
return $this->eadResponse([ "message" => "Amount invalid "], ErrorEnum::ACTION_INVALID);
}
if($this->user && $this->user->getId() == CartEnum::YES){
$transactionService->setDebug(true);
}
if($debug == CartEnum::YES){
$transactionService->setDebug(true);
}
$transactionOrigin = TransactionEnum::ORIGIN_CHARGE;
$data = $transactionService->createTransactionEAD(
$productCharge->getUser(),
$userCheckoutInfo,
$amount,
$paymentMethod,
$installments,
$items,
$userCard,
$dateExpire,
null,
$productChargeId,
(!empty($freeInstallments) ? (int)$freeInstallments : null),
$transactionOrigin
);
if(!empty($data['errorMessage'])){
$productCharge->setErrorMessage($data['errorMessage']);
$this->em->flush();
return $this->eadResponse([
"message" => $data['errorMessage']
], ErrorEnum::ACTION_INVALID);
}
return $this->eadResponse($data);
}
/**
* @Route(
* path = "/cart/checkout/clean",
* name = "checkoutClean",
* methods = {"POST"}
* )
*/
public function checkoutClean(Request $request){
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$pixelService->sendConversion('InitiateCheckout');
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$this->requestUtil->setRequest($request)->setData();
$data = $this->requestUtil->getData();
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$utmsUrl = json_encode($dataUtml);
$cartRepository = $this->em->getRepository(Cart::class);
$courseRepository = $this->em->getRepository(Course::class);
$userCardRepository = $this->em->getRepository(UserCard::class);
$userRepository = $this->em->getRepository(User::class);
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$poRepository = $this->em->getRepository(ProductOffer::class);
$pcRepository = $this->em->getRepository(ProductCoupon::class);
//user
$name = $this->requestUtil->getField('name');
$email = $this->requestUtil->getField('email');
$document = $this->requestUtil->getField('document');
$phone = $this->requestUtil->getField('phone');
$zipCode = $this->requestUtil->getField('zipCode');
$stateId = (int)$this->requestUtil->getField('state');
$cityId = (int)$this->requestUtil->getField('city');
$address = $this->requestUtil->getField('address');
$addressNeighborhood = $this->requestUtil->getField('addressNeighborhood');
$addressNumber = $this->requestUtil->getField('addressNumber');
$addressComplement = $this->requestUtil->getField('addressComplement');
$foreigner = (int)$this->requestUtil->getField('foreigner');
//userCheckoutInfo
$checkoutName = $this->requestUtil->getField('checkout-name');
$checkoutEmail = $this->requestUtil->getField('checkout-email');
$checkoutDocument = $this->requestUtil->getField('checkout-document');
$checkoutPhone = $this->requestUtil->getField('checkout-phone');
$checkoutZipCode = $this->requestUtil->getField('checkout-zipCode');
$checkoutStateId = (int)$this->requestUtil->getField('checkout-state');
$checkoutCityId = (int)$this->requestUtil->getField('checkout-city');
$checkoutAddress = $this->requestUtil->getField('checkout-address');
$checkoutAddressNeighborhood = $this->requestUtil->getField(
'checkout-addressNeighborhood'
);
$checkoutAddressNumber = $this->requestUtil->getField('checkout-addressNumber');
$checkoutAddressComplement = $this->requestUtil->getField(
'checkout-addressComplement'
);
$checkoutNotify = (int)$this->requestUtil->getField('checkout-notify');
$checkoutForeigner = (int)$this->requestUtil->getField('checkout-foreigner');
$checkoutNew = (int)$this->requestUtil->getField('checkout-new');
$cardNew = (int)$this->requestUtil->getField('card-new');
$userNew = (int)$this->requestUtil->getField('user-new');
$installments = (int)$this->requestUtil->getField('installments');
$paymentMethod = (int)$this->requestUtil->getField('payment-method');
$cardId = (int)$this->requestUtil->getField('card-id');
$cardHash = $this->requestUtil->getField('card-hash');
$userId = (int)$this->requestUtil->getField('user-id');
$userCheckoutInfoId = (int)$this->requestUtil->getField('checkout-id');
$offerDefaultId = (int)$this->requestUtil->getField('offer-default');
$offers = $this->requestUtil->getField('added-ids');
$offers = explode(",", $offers);
if(empty($offers)){
return $this->eadResponse([ 'added-ids' ], ErrorEnum::FIELD_EMPTY);
}
if(empty($paymentMethod)){
return $this->eadResponse([ 'paymentMethod' ], ErrorEnum::FIELD_EMPTY);
}
$couponKey = $this->requestUtil->getField('couponKey');
$user = null;
$userCheckoutInfo = null;
$userCard = null;
if(!empty($userId)){
$user = $userRepository->findOneBy([
"id" => $userId,
]);
//update user data ???
}else if($userNew == UserEnum::YES){
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$pixelService->sendConversion('Lead');
//check user exist
$user = $userRepository->findOneBy([
"email" => $email,
], [ "id" => "DESC" ]);
if(!$user || ($user && $user->isDeleted())){
$dataUser = [
"name" => $name,
"email" => $email,
"password" => null,
"phone" => $phone,
"notify" => UserEnum::YES,
"invited" => UserEnum::YES
];
$userDTO = new UserDTO($dataUser);
$data = $userRepository->newUser($userDTO, UserEnum::YES);
if($data->errors){
return $this->eadResponse($data->errors, ErrorEnum::FIELD_EMPTY);
}
$user = $data->user;
}
$user->setDocument($document);
$user->setPhone($phone);
$user->setZipCode($zipCode);
if($foreigner == UserCheckoutInfoEnum::NO){
$country = $this->em->getRepository(Country::class)->findOneBy([
"deleted" => GeoDataEnum::ITEM_NO_DELETED ,
"id" => GeoDataEnum::YES,
]);
if($country){
$user->setCountry($country);
}
}
if(!empty($stateId)){
$state = $this->em->getRepository(State::class)->findOneBy([
"id" => $stateId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if($state){
$user->setState($state);
}
}
if(!empty($cityId)){
$city = $this->em->getRepository(City::class)->findOneBy([
"id" => $cityId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if($city){
$user->setCity($city);
}
}
$user->setAddress($address);
$user->setAddressNeighborhood($addressNeighborhood);
$user->setAddressNumber($addressNumber);
$user->setAddressComplement($addressComplement);
$user->restore();
}
if(!$user){
return $this->eadResponse([ 'user' ], ErrorEnum::FIELD_EMPTY);
}
if($checkoutNew == CartEnum::NO && empty($userCheckoutInfoId)){
$userCheckoutInfo = new UserCheckoutInfo();
$userCheckoutInfo->setName($user->getName());
$userCheckoutInfo->setEmail($user->getEmail());
$userCheckoutInfo->setDocument($user->getDocument());
$userCheckoutInfo->setPhone($user->getPhone());
$userCheckoutInfo->setZipCode($user->getZipCode());
$userCheckoutInfo->setAddress($user->getAddress());
$userCheckoutInfo->setAddressNumber($user->getAddressNumber());
$userCheckoutInfo->setAddressComplement($user->getAddressComplement());
$userCheckoutInfo->setAddressNeighborhood($user->getAddressNeighborhood());
$userCheckoutInfo->setCity($user->getCity());
$userCheckoutInfo->setState($user->getState());
$userCheckoutInfo->setCountry($user->getCountry());
$userCheckoutInfo->setUser($user);
$userCheckoutInfo->setReceiveEmail(UserCheckoutInfoEnum::NO);
$userCheckoutInfo->setDefault(UserCheckoutInfoEnum::YES);
$this->em->persist($userCheckoutInfo);
}else if($checkoutNew == CartEnum::NO && !empty($userCheckoutInfoId)){
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"id" => $userCheckoutInfoId,
"user" => $user->getId(),
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
}else if($checkoutNew == CartEnum::YES){
$userCheckoutInfo = new UserCheckoutInfo();
$userCheckoutInfo->setName($checkoutName);
$userCheckoutInfo->setEmail($checkoutEmail);
$userCheckoutInfo->setDocument($checkoutDocument);
$userCheckoutInfo->setPhone($checkoutPhone);
$userCheckoutInfo->setZipCode($checkoutZipCode);
$userCheckoutInfo->setAddress($checkoutAddress);
$userCheckoutInfo->setAddressNumber($checkoutAddressNumber);
$userCheckoutInfo->setAddressComplement($checkoutAddressComplement);
$userCheckoutInfo->setAddressNeighborhood($checkoutAddressNeighborhood);
if($checkoutForeigner == UserCheckoutInfoEnum::NO){
$country = $this->em->getRepository(Country::class)->findOneBy([
"deleted" => GeoDataEnum::ITEM_NO_DELETED ,
"id" => GeoDataEnum::YES,
]);
if($country){
$userCheckoutInfo->setCountry($country);
}
}
if(!empty($checkoutStateId)){
$state = $this->em->getRepository(State::class)->findOneBy([
"id" => $checkoutStateId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if($state){
$userCheckoutInfo->setState($state);
}
}
if(!empty($checkoutCityId)){
$city = $this->em->getRepository(City::class)->findOneBy([
"id" => $checkoutCityId,
"deleted" => UserEnum::ITEM_NO_DELETED
]);
if($city){
$userCheckoutInfo->setCity($city);
}
}
$userCheckoutInfo->setUser($user);
$userCheckoutInfo->setReceiveEmail($checkoutNotify);
$userCheckoutInfo->setDefault(UserCheckoutInfoEnum::YES);
$this->em->persist($userCheckoutInfo);
}
if(!$userCheckoutInfo){
return $this->eadResponse([ 'userCheckoutInfo' ], ErrorEnum::FIELD_EMPTY);
}
if($paymentMethod == CartEnum::PAYMENT_CARD){
if($cardNew == CartEnum::NO && !empty($cardId)){
$userCard = $userCardRepository->findOneBy([
"id" => $cardId,
"user" => $user->getId(),
"deleted" => CartEnum::ITEM_NO_DELETED
]);
}else if($cardNew == CartEnum::YES){
if(empty($cardHash)){
return $this->eadResponse([ 'cardHash' ], ErrorEnum::FIELD_EMPTY);
}
$userCard = $userCardRepository->createByHash($cardHash, $user);
}
if(!$userCard){
return $this->eadResponse([ 'userCard' ], ErrorEnum::FIELD_EMPTY);
}
if(empty($installments)){
return $this->eadResponse([ 'installments' ], ErrorEnum::FIELD_EMPTY);
}
}
$productOfferDefault = null;
$amount = null;
$items = [];
$courses = null;
$coursesAux = [];
foreach ($offers as $key => $offerId) {
$productOffer = $poRepository->findOneBy([
"id" => $offerId,
]);
if($productOffer){
$product = $productOffer->getProduct();
if($offerId == $offerDefaultId){
$productOfferDefault = $productOffer;
if(
$product->getType() == ProductEnum::COURSE ||
$product->getType() == ProductEnum::COMBO
){
$courses = $courseRepository->getCoursesByProduct(
$product->getId()
);
foreach ($courses as $key => $course) {
$coursesAux[] = $course->getId();
}
}
}
if(!empty($couponKey)){
$productCoupon = $pcRepository->findValidProductCouponByProductOffer(
$couponKey,
$productOffer
);
}
$cart = $cartRepository->addCartByProductOffer(
$productOffer,
$user,
null,
$productCoupon,
$utmsUrl,
($productOffer->getProduct()->isTypeResource() ? $courses : null)
);
if($cart){
$items[] = (object)[
"courses" => $coursesAux,
"productOfferId" => $productOffer->getId(),
"productId" => $product->getId(),
"amount" => $cart->getPrice() + $cart->getMembershipFee(),
"cartId" => $cart->getId(),
"productCouponId" => (
$productCoupon ? $productCoupon->getId() : null
),
];
$amount = $amount + $cart->getPrice(true) + $cart->getMembershipFee(true);
}
}
}
if(count($items) != count($offers)){
return $this->eadResponse([ "added-ids" ], ErrorEnum::FIELD_EMPTY);
}
if(!$productOfferDefault){
return $this->eadResponse([ "offer-default" ], ErrorEnum::FIELD_EMPTY);
}
$this->em->flush();
$paymentConfig = $this->configuration->getPaymentConfig();
$dateExpire = null;
if($paymentMethod == CartEnum::PAYMENT_CARD){
$freeInstallments = $poRepository->getFreeInstallment($productOfferDefault);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $amount,
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$amount = $installmentsOptions->{$installments}->amount;
}else if($paymentMethod == CartEnum::PAYMENT_BILL){
$dateExpire = $poRepository->getDateExpireBill($productOffer);
}else if($paymentMethod == CartEnum::PAYMENT_PIX){
$dateExpire = $poRepository->getDateExpirePix($productOffer);
}
if($amount < $this->configuration->getMinValueProduct()){
return $this->eadResponse([
"message" => "Min Value"
], ErrorEnum::ACTION_INVALID);
}
if($user && $user->getId() == CartEnum::YES){
$transactionService->setDebug(true);
}
$transactionOrigin = TransactionEnum::ORIGIN_CHECKOUT_PAGE;
$data = $transactionService->createTransactionEAD(
$user,
$userCheckoutInfo,
$amount,
$paymentMethod,
$installments,
$items,
$userCard,
$dateExpire,
null,
null,
null,
$transactionOrigin
);
if(!empty($data['errorMessage'])){
foreach ($offers as $key => $offerId) {
$productOffer = $poRepository->findOneBy([
"id" => $offerId,
]);
if($productOffer){
if($cart){
$cart->setErrorMessage($data['errorMessage']);
}
}
}
$this->em->flush();
return $this->eadResponse([
"message" => $data['errorMessage']
], ErrorEnum::ACTION_INVALID);
}
return $this->eadResponse($data);
}
/**
* @Route(
* path = "/admin/cart/checkout/default",
* name = "cartCheckoutDefault",
* methods = {"POST"}
* )
*/
public function checkoutDefault(Request $request){
if(!$this->user){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$this->requestUtil->setRequest($request)->setData();
$userCheckoutInfoId = $this->requestUtil->getField('userCheckoutInfoId');
$paymentMethod = $this->requestUtil->getField('paymentMethod');
$installments = $this->requestUtil->getField('installments');
$cartRepository = $this->em->getRepository(Cart::class);
$productRepository = $this->em->getRepository(Product::class);
$userCardRepository = $this->em->getRepository(UserCard::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"id" => $userCheckoutInfoId,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
if(!$userCheckoutInfo){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$paymentConfig = $this->configuration->getPaymentConfig();
$items = [];
$amount = 0;
$userCard = null;
$dateExpire = null;
if(empty($paymentMethod)){
return $this->eadResponse([ 'paymentMethod' ], ErrorEnum::FIELD_EMPTY);
}
if($paymentMethod == CartEnum::PAYMENT_CARD){ // get user card
if(empty($installments)){
return $this->eadResponse([ 'installments' ], ErrorEnum::FIELD_EMPTY);
}
$userCardId = $this->requestUtil->getField('userCardId');
if(empty($userCardId)){
return $this->eadResponse([ 'userCardId' ], ErrorEnum::FIELD_EMPTY);
}
if($userCardId > 0){
$userCard = $userCardRepository->findOneBy([
"id" => $userCardId,
"user" => $this->user->getId(),
"deleted" => CartEnum::ITEM_NO_DELETED
]);
}
}
if($paymentMethod == CartEnum::PAYMENT_CARD && !$userCard){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$carts = $cartRepository->getUserValidCarts($this->user->getId());
if(empty($carts)){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$freeInstallments = $paymentConfig->installmentNumberInterest;
if($paymentConfig->assumeInstallmentInterest == CartEnum::YES){
$freeInstallments = 12;
}
$billDateExpire = null;
$pixDateExpire = null;
$hasOneItem = (count($carts) == CartEnum::YES);
foreach ($carts as $key => $cart) {
$productOffer = $cart->getProductOffer();
$product = $cart->getProduct();
if($hasOneItem){
$billDateExpire = $productOfferRepository->getDateExpireBill($productOffer);
$pixDateExpire = $productOfferRepository->getDateExpirePix($productOffer);
$freeInstallments = $productOfferRepository->getFreeInstallment(
$productOffer
);
}
$productCoupon = $cart->getProductCoupon();
$items[] = (object)[
"courses" => $cart->getCourse(),
"productOfferId" => $productOffer->getId(),
"productId" => $product->getId(),
"amount" => $cart->getPrice() + $cart->getMembershipFee(),
"cartId" => $cart->getId(),
"productCouponId" => ($productCoupon ? $productCoupon->getId() : null),
];
$amount = $amount + $cart->getPrice(true) + $cart->getMembershipFee(true);
}
if($paymentMethod == CartEnum::PAYMENT_BILL){
$dateExpire = $billDateExpire;
if(empty($dateExpire)){
$period = (int)$this->configuration->get('bill_period_expire') + 1;
if($period == 1){
$period = 8;
}
$dateExpire = date("Y-m-d", strtotime("+ {$period} day"));
}
}else if($paymentMethod == CartEnum::PAYMENT_PIX){
$dateExpire = $pixDateExpire;
if(empty($dateExpire)){
$period = (int)$this->configuration->get('pix_period_expire') + 1;
if($period == 1){
$period = 8;
}
$dateExpire = date("Y-m-d", strtotime("+ {$period} day"));
}
}else if($paymentMethod == CartEnum::PAYMENT_CARD){
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $amount,
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$amount = $installmentsOptions->{$installments}->amount;
}
if($amount < $this->configuration->getMinValueProduct()){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
if($this->user && $this->user->getId() == CartEnum::YES){
$transactionService->setDebug(true);
}
$transactionOrigin = TransactionEnum::ORIGIN_CHECKOUT_DEFAULT;
$data = $transactionService->createTransactionEAD(
$this->user,
$userCheckoutInfo,
$amount,
$paymentMethod,
$installments,
$items,
$userCard,
$dateExpire,
null,
null,
(!empty($freeInstallments) ? (int)$freeInstallments : null),
$transactionOrigin
);
if(!empty($data['errorMessage'])){
foreach ($carts as $key => $cart) {
$cart->setErrorMessage($data['errorMessage']);
}
$this->em->flush();
return $this->eadResponse([
"message" => $data['errorMessage']
], ErrorEnum::ACTION_INVALID);
}
return $this->eadResponse($data);
}
/**
* @Route(
* path = "/admin/cart/checkout/custom",
* name = "cartCheckoutCustom",
* methods = {"POST"}
* )
*/
public function cartCheckoutCustom(Request $request){
if(!$this->user){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$this->requestUtil->setRequest($request)->setData();
$items = json_decode($this->requestUtil->getField('items'));
$userCardId = $this->requestUtil->getField('userCardId');
$userCheckoutInfoId = $this->requestUtil->getField('userCheckoutInfoId');
if(count($items) == CartEnum::NO){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$cartRepository = $this->em->getRepository(Cart::class);
$productRepository = $this->em->getRepository(Product::class);
$userCardRepository = $this->em->getRepository(UserCard::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$carts = $cartRepository->getUserValidCarts($this->user->getId());
if(empty($carts)){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"id" => $userCheckoutInfoId,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
if(!$userCheckoutInfo){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$groupedItems = [];
$ref = null;
$group = [];
foreach ($items as $key => $item) {
if(empty($ref)){
$ref = $item->parentRef;
}
if($ref != $item->parentRef){
if(!empty($group)){
$groupedItems[] = $group;
}
$ref = $item->parentRef;
$group = [];
}
$group[] = $item;
if(($key + 1) == count($items)){
if(!empty($group)){
$groupedItems[] = $group;
}
}
}
$userCard = null;
if($userCardId > 0){
$userCard = $userCardRepository->findOneBy([
"id" => $userCardId,
"user" => $this->user->getId(),
"deleted" => CartEnum::ITEM_NO_DELETED
]);
}
$hashReference = md5(
date('Y-m-d H:i:s') . $this->user->getId() . $this->client->getClientId()
);
$paymentConfig = $this->configuration->getPaymentConfig();
foreach ($groupedItems as $key => $group) {
$items = [];
$paymentMethod = null;
$installments = 1;
$dateExpire = null;
$amount = 0;
foreach ($group as $key => $itemReq) {
$itemReq = (object)$itemReq;
if($itemReq->able){
$cart = $cartRepository->findOneBy([
"id" => $itemReq->id,
"deleted" => CartEnum::ITEM_NO_DELETED
]);
$productOffer = $cart->getProductOffer();
$product = $cart->getProduct();
$productCoupon = $cart->getProductCoupon();
$items[] = (object)[
"courses" => $cart->getCourse(),
"productOfferId" => $productOffer->getId(),
"productId" => $product->getId(),
"amount" => $cart->getPrice() + $productOffer->getMembershipFee(),
"cartId" => $cart->getId(),
"productCouponId" => (
$productCoupon ? $productCoupon->getId() : null
),
];
$paymentMethod = $itemReq->paymentMethod;
$installments = $itemReq->installment;
if($paymentMethod == CartEnum::PAYMENT_BILL){
$dateExpire = $itemReq->billDateExpire;
}else if($paymentMethod == CartEnum::PAYMENT_PIX){
$dateExpire = $itemReq->pixDateExpire;
}
$amountItem = $cart->getPrice(true) + $productOffer->getMembershipFee(
true
);
if($paymentMethod == CartEnum::PAYMENT_CARD){
$freeInstallments = $productOfferRepository->getFreeInstallment(
$productOffer
);
$installmentsOptions = $pagarMeTransaction->calculateInstallments([
'amount' => $amountItem,
'free_installments' => $freeInstallments,
'max_installments' => $installments,
'interest_rate' => $paymentConfig->installmentInterest
]);
$amountItem = $installmentsOptions->{$installments}->amount;
}
$amount = $amount + $amountItem;
}
}
if($amount < $this->configuration->getMinValueProduct()){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
if($this->user && $this->user->getId() == CartEnum::YES){
$transactionService->setDebug(true);
}
$transactionOrigin = TransactionEnum::ORIGIN_CHECKOUT_CUSTOM;
$data = $transactionService->createTransactionEAD(
$this->user,
$userCheckoutInfo,
$amount,
$paymentMethod,
$installments,
$items,
$userCard,
$dateExpire,
$hashReference,
null,
null,
$transactionOrigin
);
if(!empty($data['errorMessage'])){
foreach ($group as $key => $itemReq) {
if($itemReq->able){
$cart = $cartRepository->findOneBy([
"id" => $itemReq->id,
"deleted" => CartEnum::ITEM_NO_DELETED
]);
$cart->setErrorMessage($data['errorMessage']);
}
}
$this->em->flush();
return $this->eadResponse([
"message" => $data['errorMessage']
], ErrorEnum::ACTION_INVALID);
}
}
$dataFinal = [
"hashReference" => $hashReference,
];
return $this->eadResponse($dataFinal);
}
/**
* @Route(
* path = "/cart/buy/one/click/{productOfferId}/{courseId}",
* name = "cartOneClickBuy",
* methods = {"GET"},
* defaults = { "courseId" = 0 }
* )
*/
public function cartOneClickBuy(Request $request){
$this->requestUtil->setRequest($request)->setData();
$productOfferId = $request->get('productOfferId');
$courseId = (int)$request->get('courseId');
$dataUtml = [
"utm_source" => $request->get('utm_source'),
"utm_medium" => $request->get('utm_medium'),
"utm_campaign" => $request->get('utm_campaign'),
"utm_term" => $request->get('utm_term'),
"utm_content" => $request->get('utm_content'),
];
$utmsUrl = json_encode($dataUtml);
$params = [
"poID" => $productOfferId,
"courseId" => $courseId,
];
$params = array_merge($params, $dataUtml);
$cartRepository = $this->em->getRepository(Cart::class);
$productOffer = $this->em->getRepository(ProductOffer::class)->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
if(!$productOffer){
return $this->redirectToRoute('notFound');
}
$product = $productOffer->getProduct();
if($product->isTypeResource() && empty($courseId)){
return $this->redirectToRoute('notFound');
}
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
(
$product->getType() != ProductEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductOfferEnum::YES
)
){
if($productOffer->getAllowTrial() == ProductOfferEnum::YES){
$params = [
"poHash" => $productOffer->getOfferLink(),
"pcKey" => null,
];
$params = array_merge($params, $dataUtml);
return $this->redirectToRoute('cartIndividual', $params);
}
}
if(!$this->user){
return $this->redirectToRoute('cartAdd', $params);
}
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->redirectToRoute('cartAdd', $params);
}
if($this->user->getAllowOneClickBuy() == UserEnum::NO){
return $this->redirectToRoute('cartAdd', $params);
}
$userCardRepository = $this->em->getRepository(UserCard::class);
$userCardDefault = $userCardRepository->getDefaultValidUserCard();
if(!$userCardDefault){
return $this->redirectToRoute('cartAdd', $params);
}
if($productOffer->getSaleChannel() == ProductOfferEnum::EXTERNAL){
$externalCheckoutLink = $productOffer->getExternalCheckoutLink();
return $this->redirect($externalCheckoutLink, 301);
}
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"user" => $this->user->getId(),
"default" => UserCheckoutInfoEnum::YES,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
if(!$userCheckoutInfo){
return $this->redirectToRoute('cartAdd', $params);
}
$productSuggestion = null;
if(!empty($productSuggestionId)){
$productSuggestion = $psRepository->findOneBy([
"id" => $productSuggestionId,
"status" => ProductSuggestionEnum::PUBLISHED,
"deleted" => ProductSuggestionEnum::ITEM_NO_DELETED
]);
}
$course = null;
$courseRepository = $this->em->getRepository(Course::class);
if(!empty($courseId)){
$course = $courseRepository->findOneBy([
"id" => $courseId,
"deleted" => CourseEnum::ITEM_NO_DELETED,
]);
}
$cart = $cartRepository->addCartByProductOffer(
$productOffer,
$this->user,
$productSuggestion,
null,
$utmsUrl,
($course ? [ $course ] : null)
);
if(!$cart){
return $this->redirectToRoute('cartAdd', $params);
}
$productCoupon = $cart->getProductCoupon();
$items = [
(object)[
"courseId" => ($course ? $course->getId() : null),
"productOfferId" => $productOffer->getId(),
"productId" => $productOffer->getProduct()->getId(),
"amount" => $cart->getPrice() + $cart->getMembershipFee(),
"cartId" => $cart->getId(),
"productCouponId" => ($productCoupon ? $productCoupon->getId() : null),
]
];
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
if($this->user && $this->user->getId() == CartEnum::YES){
$transactionService->setDebug(true);
}
$transactionOrigin = TransactionEnum::ORIGIN_ONE_CLICK;
$data = (object)$transactionService->createTransactionEAD(
$this->user,
$userCheckoutInfo,
$cart->getPrice(true) + $cart->getMembershipFee(true),
CartEnum::PAYMENT_CARD,
1,
$items,
$userCardDefault,
null,
null,
null,
null,
$transactionOrigin
);
if(!empty($data->errorMessage)){
$cart->setErrorMessage($data->errorMessage);
$this->em->flush();
//return $this->eadResponse([
// "message" => $data->errorMessage
//], ErrorEnum::ACTION_INVALID);
return $this->redirectToRoute('cart');
}
$paramsConclusion = [
"hashReference" => $data->hashReference,
];
return $this->redirectToRoute('cartConclusion', $paramsConclusion);
}
/**
* @Route(
* path = "/admin/cart/checkout/plan/trial/{poID}/{pcID}",
* name = "cartCheckoutPlanTrial",
* methods = {"POST"},
* defaults = { "pcID" = 0 }
* )
*/
public function cartCheckoutPlanTrial(Request $request){
if(!$this->user){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT
);
if(!$receiverSchool){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$productOfferId = (int)$request->get('poID');
$productCouponId = (int)$request->get('pcID');
$this->requestUtil->setRequest($request)->setData();
$userCheckoutInfoId = $this->requestUtil->getField('userCheckoutInfoId');
$paymentMethod = $this->requestUtil->getField('paymentMethod');
$installments = $this->requestUtil->getField('installments');
$userCardRepository = $this->em->getRepository(UserCard::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productCouponRepository = $this->em->getRepository(ProductCoupon::class);
$userCheckoutInfoRepository = $this->em->getRepository(UserCheckoutInfo::class);
$productOffer = $productOfferRepository->findOneBy([
"id" => $productOfferId,
"status" => ProductOfferEnum::PUBLISHED,
"deleted" => ProductOfferEnum::ITEM_NO_DELETED
]);
if(!$productOffer){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
if($productOffer->getAllowTrial() == ProductOfferEnum::NO){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$product = $productOffer->getProduct();
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$userCheckoutInfo = $userCheckoutInfoRepository->findOneBy([
"id" => $userCheckoutInfoId,
"deleted" => UserCheckoutInfoEnum::ITEM_NO_DELETED,
]);
if(!$userCheckoutInfo){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$paymentConfig = $this->configuration->getPaymentConfig();
$userCard = null;
if(empty($paymentMethod)){
return $this->eadResponse([ 'paymentMethod' ], ErrorEnum::FIELD_EMPTY);
}
if($paymentMethod == CartEnum::PAYMENT_CARD){ // get user card
if(empty($installments)){
return $this->eadResponse([ 'installments' ], ErrorEnum::FIELD_EMPTY);
}
$userCardId = $this->requestUtil->getField('userCardId');
if(empty($userCardId)){
return $this->eadResponse([ 'userCardId' ], ErrorEnum::FIELD_EMPTY);
}
if($userCardId > 0){
$userCard = $userCardRepository->findOneBy([
"id" => $userCardId,
"user" => $this->user->getId(),
"deleted" => CartEnum::ITEM_NO_DELETED
]);
}
}
if($paymentMethod == CartEnum::PAYMENT_CARD && !$userCard){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$productCoupon = null;
$amount = $productOffer->getPriceReal();
if(!empty($productCouponId)){
$productCoupon = $productCouponRepository->findOneBy([
"deleted" => ProductCouponEnum::ITEM_NO_DELETED,
"status" => ProductCouponEnum::PUBLISHED,
"id" => $productCouponId,
]);
if($productCoupon){
if($productCouponRepository->checkApplyCoupon($productCoupon, $productOffer)){
$amount = $productCouponRepository->applyDiscount(
$productCoupon,
$amount
);
}
}
}
if($amount < $this->configuration->getMinValueProduct()){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
$userSubscriptionRepository = $this->em->getRepository(UserSubscription::class);
$userSubscription = $userSubscriptionRepository->findOneBy([
"user" => $this->user->getId(),
"product" => $product->getId()
]);
if($userSubscription && $userSubscription->isLive()){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
if(!$userSubscription){
$userSubscription = new UserSubscription();
}else{
$userSubscriptionRepository->restore($userSubscription, TrashEnum::USER_SUBSCRIPTION);
}
$userSubscription->setStatus(UserSubscriptionEnum::STATUS_TRIAL);
$userSubscription->setDateStart(date('Y-m-d H:i:s'));
$userSubscription->setAutomaticRenewal($productOffer->getPlanRenew());
$userSubscription->setLifetime($productOffer->getPlanLifetime());
$userSubscription->setPrice($productOffer->getPriceReal());
$userSubscription->setCycle($productOffer->getPlanCycle());
$userSubscription->setChargeNumberMax($productOffer->getPlanChargeNumberMax());
$userSubscription->setMembershipFee($productOffer->getMembershipFee());
$userSubscription->setProduct($product);
$userSubscription->setProductOffer($productOffer);
$userSubscription->setUser($this->user);
$userSubscription->setUsedTrial(UserSubscriptionEnum::YES);
if($productCoupon){
$userSubscription->setProductCoupon($productCoupon);
$userSubscription->setCouponKey($productCoupon->getKey());
$userSubscription->setCouponType($productCoupon->getDiscountType());
$userSubscription->setCouponApplyMembershipFee(
$productCoupon->getApplyMembershipFee()
);
$userSubscription->setCouponLifetime($productCoupon->getPlanLifetime());
$userSubscription->setCouponNumberCharges($productCoupon->getPlanCharges());
$userSubscription->setCouponDiscount($productCoupon->getDiscount());
}
$userSubscription->setPaymentMethod($paymentMethod);
$monthCycles = [
UserSubscriptionEnum::CYCLE_MONTHLY,
UserSubscriptionEnum::CYCLE_WEEKLY,
UserSubscriptionEnum::CYCLE_BIWEEKLY,
];
if(!in_array($userSubscription->getCycle(), $monthCycles)){
$freeInstallmentNumber = $productOfferRepository->getFreeInstallment(
$productOffer
);
$userSubscription->setInstallments($installments);
$userSubscription->setInstallmentsFree($freeInstallmentNumber);
}
//define date renew
if(
$userSubscription->getLifetime() == UserSubscriptionEnum::NO &&
$userSubscription->getAutomaticRenewal() == UserSubscriptionEnum::YES
){
$periodRenew = $userSubscriptionRepository->getPlanCycle(
$userSubscription->getCycle(),
$userSubscription->getChargeNumberMax()
);
$userSubscription->setDateRenew(date('Y-m-d', strtotime($periodRenew)));
}
$days = $productOffer->getTrialPeriod();
$dateNextPayment = date('Y-m-d', strtotime("+ {$days} day"));
$dateAccess = date('Y-m-d H:i:s', strtotime("+ {$days} day"));
$userSubscription->setDateNextPayment($dateNextPayment);
$userSubscription->setDateExpiration($dateNextPayment);
$userSubscription->setUserCard($userCard);
$userSubscription->setUserCard($userCard);
$userSubscription->setTrialDateEnd($dateAccess);
$this->em->persist($userSubscription);
$this->userLogService->logInsert(
"user_subscription",
$userSubscription->getId(),
$userSubscription->toReturn()
);
$enrollmentService = $this->generalService->getService('EnrollmentService');
$enrollmentService->setNotification(true);
$enrollmentService->setEmail(false);
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_SUBSCRIPTION);
if($userSubscription->getPaymentMethod() == UserSubscriptionEnum::PAYMENT_BILL){
$dateAccess = date('Y-m-d H:i:s', strtotime("{$dateAccess} + 3 days"));
}
$enrollmentService->setAccessDate($dateAccess);
$enrollmentService->setSupportDate($dateAccess);
$enrollmentService->setUserSubscription($userSubscription);
$enrollmentService->enrollUserByProduct(
$userSubscription->getUser(),
$userSubscription->getProduct()
);
$marketingService = $this->generalService->getService('Marketing\MarketingService');
$marketingService->setTag(TagsMarketingEnum::TAG_START_SUBSCRIPTION);
$marketingService->setTextComplement($product->getTitle());
$marketingService->setUser($this->user);
$marketingService->send();
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$pixelService->sendConversion('StartTrial', (object)[
"value" => $userSubscription->getPrice(),
"currency" => $productOffer->getCurrencyCode(),
"contents" => [
(object)[
"id" => $product->getId(),
"quantity" => 1,
"item_price" => $userSubscription->getPrice(),
//"name" => $product->getTitle(),
//"type" => $product->getType()
]
],
"num_items" => 1,
"content_type" => "product",
"transaction_id" => $userSubscription->getId(),
]);
$this->em->flush();
if($userSubscription->getUser() && $userSubscription->getProduct()->getUser()){
sleep(1);
if($userSubscription->getId()){
$notificationService = $this->generalService->getService('NotificationService');
$notificationService->create(
$userSubscription->getUser(),
$userSubscription->getProduct()->getUser(),
NotificationEnum::ORIGIN_USER_SUBSCRIPTION_NEW,
$userSubscription->getId()
);
$notificationService->create(
$userSubscription->getProduct()->getUser(),
$userSubscription->getUser(),
NotificationEnum::ORIGIN_USER_SUBSCRIPTION_NEW,
$userSubscription->getId()
);
}
}
$userWebhook = $this->em->getRepository(User::class)->getToWebhook(
$userSubscription->getUser()
);
//webhook
$dataObj = (object)[
"user" => $userWebhook,
"subscription" => $userSubscription->toWebhook(),
"product" => (object)[
"id" => (string)$userSubscription->getProduct()->getId(),
"name" => $userSubscription->getProduct()->getTitle(),
"offer" => (object)[
"id" => (string)$userSubscription->getProductOffer()->getId(),
"name" => $userSubscription->getProductOffer()->getTitle(),
"price" => (string)$userSubscription->getProductOffer()->getPriceReal(),
"membership"=> (string)$userSubscription->getMembershipFee(),
],
],
];
$webhookService = $this->generalService->getService('WebhookService');
$webhookService->addItemList(WebhookEnum::SUBSCRIPTION, $dataObj);
return $this->eadResponse([
"billLink" => null,
"pixCode" => null,
"userId" => $this->user->getId(),
"transactionHash" => "success",
"hashReference" => "success",
]);
}
/**
* @Route(
* path = "/cart/checkout/new/try/{transactionHash}",
* name = "cartCheckoutNewTry",
* methods = {"GET"}
* )
*/
public function cartCheckoutNewTry(Request $request){
$this->checkUserSession($request);
$transactionHash = $request->get('transactionHash');
$cartRepository = $this->em->getRepository(Cart::class);
$transactionRepository = $this->em->getRepository(Transaction::class);
$transactionItemRepository = $this->em->getRepository(TransactionItem::class);
$transaction = $transactionRepository->findOneBy([
"hash" => $transactionHash,
"status" => TransactionEnum::CANCELED,
"deleted" => TransactionEnum::ITEM_NO_DELETED
]);
if(!$transaction){
return $this->redirectToRoute('notFound');
}
$transactionItems = $transactionItemRepository->findBy([
"transaction" => $transaction->getId(),
"deleted" => TransactionItemEnum::ITEM_NO_DELETED
]);
if(empty($transactionItems)){
return $this->redirectToRoute('notFound');
}
foreach ($transactionItems as $key => $transactionItem) {
$courses = [];
foreach ($transactionItem->getCourse() as $keyC => $course) {
$courses[] = $course;
}
$cartRepository->addCartByProductOffer(
$transactionItem->getProductOffer(),
$transaction->getUser(),
null,
$transactionItem->getProductCoupon(),
$transactionItem->getUtmsUrl(),
$courses
);
}
$this->em->flush();
return $this->redirectToRoute('cart');
}
/**
* @Route(
* path = "/cart/conclusion/{hashReference}",
* name = "cartConclusion",
* methods = {"GET"},
* defaults = { "hashReference" = null }
* )
* @Route(
* path = "/cart/conclusao/{hashReference}",
* name = "cartConclusionOld",
* methods = {"GET"},
* defaults = { "hashReference" = null }
* )
*/
public function cartConclusionPage(Request $request) {
$cartRepository = $this->em->getRepository(Cart::class);
$productRepository = $this->em->getRepository(Product::class);
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$transactionRepository = $this->em->getRepository(Transaction::class);
$ti = $this->em->getRepository(TransactionItem::class);
$psRepository = $this->em->getRepository(ProductSuggestion::class);
$hashReference = $request->get('hashReference');
$this->data['hashReference'] = $hashReference;
$this->data['transactionsCard'] = null;
$this->data['transactionsPix'] = null;
$this->data['transactionsBill'] = null;
$this->data['productOfferSuggestions'] = null;
$this->data['hasWaiting'] = true;
$this->data['hasApproved'] = false;
$this->data['hasCanceled'] = false;
$this->data['showInfoStep'] = true;
$this->data['hasContracts'] = true;
$this->data['sOffers'] = [];
$this->data['showSteps'] = true;
if(!empty($hashReference)){
$isCheckoutPage = $transactionRepository->existByReferenceAndOrigin(
$hashReference,
TransactionEnum::ORIGIN_CHECKOUT_PAGE
);
if($isCheckoutPage){
$this->data['showSteps'] = false;
}
$hasWaiting = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::WAITING
);
$hasApproved = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::APPROVED
);
$hasCanceled = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::CANCELED
);
$hasWaitingCard = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::WAITING,
TransactionEnum::PAYMENT_CARD
);
$hasApprovedCard = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::APPROVED,
TransactionEnum::PAYMENT_CARD
);
$hasCanceledCard = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::CANCELED,
TransactionEnum::PAYMENT_CARD
);
$hasWaitingBill = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::WAITING,
TransactionEnum::PAYMENT_BILL
);
$hasApprovedBill = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::APPROVED,
TransactionEnum::PAYMENT_BILL
);
$hasCanceledBill = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::CANCELED,
TransactionEnum::PAYMENT_BILL
);
$hasWaitingPix = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::WAITING,
TransactionEnum::PAYMENT_PIX
);
$hasApprovedPix = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::APPROVED,
TransactionEnum::PAYMENT_PIX
);
$hasCanceledPix = $transactionRepository->existByReferenceAndStatus(
$hashReference,
TransactionEnum::CANCELED,
TransactionEnum::PAYMENT_PIX
);
$transactionsCard = $transactionRepository->getToCartConclusion(
$hashReference,
TransactionEnum::PAYMENT_CARD
);
$transactionsPix = $transactionRepository->getToCartConclusion(
$hashReference,
TransactionEnum::PAYMENT_PIX
);
$transactionsBill = $transactionRepository->getToCartConclusion(
$hashReference,
TransactionEnum::PAYMENT_BILL
);
$transactionOffers = $productOfferRepository->getByTransactionHashReference(
$hashReference
);
if(count($transactionOffers) == TransactionEnum::YES){
$offer = $transactionOffers[0];
$productPage = $offer->getProductPage();
$externalPageLink = $productPage->getExternalConclusionLink();
if(
$productPage->getAllowExternalConclusion() &&
!empty($externalPageLink) &&
$hasApproved
){
return $this->redirect($externalPageLink, 301);
}
}
$sOffers = [];
foreach ($transactionOffers as $keyOffer => $offer) {
$productOfferSuggestions = $psRepository->getByOfferOriginSimply(
$offer,
ProductSuggestionEnum::EXECUTE_IN_CONCLUSION_PAGE
);
foreach ($productOfferSuggestions as $key => $productSuggestion) {
$productOffer = $productSuggestion->getProductOffer();
$product = $productOffer->getProduct();
if($this->user && !$productRepository->userHasProduct($this->user, $product)){
$productOffer->productSuggestionId = $productSuggestion->getId();
$productOffer->productSuggestionItem = $productSuggestion;
if($productOffer->getAllowSaleLimit() == ProductOfferEnum::YES){
$saleNumber = $ti->countSalesApprovedByProductOffer(
$productOffer
);
if($productOffer->getSaleNumberLimit() > $saleNumber){
$sOffers[$productOffer->getId()] = $productOffer;
}
}else{
$sOffers[$productOffer->getId()] = $productOffer;
}
}
}
$cartRepository->sendConclusionConversion($hashReference);
}
try{
$transactions = array_merge(
$transactionsCard,
$transactionsPix,
$transactionsBill
);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
foreach ($transactions as $key => $tr) {
if($tr->getGateway() == TransactionEnum::EAD_CHECKOUT){
if($tr->getPaymentMethod() == TransactionEnum::PAYMENT_BILL){
$transactionPagarme = $pagarMeTransaction->get($tr->getHash());
$dateExpire = date(
'Y-m-d',
strtotime($transactionPagarme->boleto_expiration_date)
);
$tr->setBillCode($transactionPagarme->boleto_barcode);
$tr->setBillLink($transactionPagarme->boleto_url);
$tr->setDateExpire($dateExpire);
}else if($tr->getPaymentMethod() == TransactionEnum::PAYMENT_PIX){
$transactionPagarme = $pagarMeTransaction->get($tr->getHash());
$dateExpire = date(
'Y-m-d',
strtotime($transactionPagarme->pix_expiration_date)
);
$tr->setPixCode($transactionPagarme->pix_qr_code);
$tr->setDateExpire($dateExpire);
}
}
}
$this->em->flush();
}catch(Exception $e){
}
$this->data['hasWaiting'] = $hasWaiting;
$this->data['hasApproved'] = $hasApproved;
$this->data['hasCanceled'] = $hasCanceled;
$this->data['hasWaitingCard'] = $hasWaitingCard;
$this->data['hasApprovedCard'] = $hasApprovedCard;
$this->data['hasCanceledCard'] = $hasCanceledCard;
$this->data['hasWaitingBill'] = $hasWaitingBill;
$this->data['hasApprovedBill'] = $hasApprovedBill;
$this->data['hasCanceledBill'] = $hasCanceledBill;
$this->data['hasWaitingPix'] = $hasWaitingPix;
$this->data['hasApprovedPix'] = $hasApprovedPix;
$this->data['hasCanceledPix'] = $hasCanceledPix;
$this->data['transactionsCard'] = $transactionsCard;
$this->data['transactionsPix'] = $transactionsPix;
$this->data['transactionsBill'] = $transactionsBill;
$this->data['productOfferSuggestions'] = $sOffers;
}
$this->data['customCart'] = true;
$this->data['cartConclusion'] = true;
return $this->renderEAD('cart/cart-conclusion.html.twig');
}
/**
* @Route(
* path = "/cart/conclusion/status/{hashReference}/{charge}",
* name = "cartConclusionCheckStatus",
* methods = {"GET"},
* defaults = { "hashReference" = null, "charge" = 0 }
* )
*/
public function cartConclusionCheckStatus(Request $request) {
$cartRepository = $this->em->getRepository(Cart::class);
$transactionRepository = $this->em->getRepository(Transaction::class);
$transactionItemRepository = $this->em->getRepository(TransactionItem::class);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$processEad = $this->generalService->getService('Transaction\\ProcessEad');
$charge = $request->get('charge');
$hashReference = $request->get('hashReference');
if(empty($hashReference)){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
$transactions = $transactionRepository->findBy([
"hashReference" => $hashReference,
"deleted" => TransactionEnum::ITEM_NO_DELETED
]);
$refresh = [];
foreach ($transactions as $key => $transaction) {
$transactionPagarme = $pagarMeTransaction->get($transaction->getHash());
$newStatus = $pagarMeTransaction->getTransactionStatus(
$transactionPagarme->status
);
if(
$newStatus == TransactionEnum::APPROVED ||
$charge == TransactionEnum::YES && (
!empty($transactionPagarme->boleto_barcode) ||
!empty($transactionPagarme->pix_expiration_date)
)
){
$refresh[] = true;
}
}
$this->em->flush();
$data = [
"refresh" => (count($refresh) == count($transactions))
];
return $this->eadResponse($data, ErrorEnum::SUCCESS);
}
/**
* @Route(
* path = "/cart/remove/coupon/{id}",
* name = "cartCouponRemove",
* methods = {"GET"},
* requirements = { "id" = "\d+"}
* )
*/
public function removeCouponProduct(Request $request) {
$cartId = $request->get('id');
$cartRepository = $this->em->getRepository(Cart::class);
$cart = $cartRepository->findOneBy([
"id" => $cartId,
"deleted" => CartEnum::ITEM_NO_DELETED
]);
if(!$cart){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
if($this->user){
if($this->user->getId() != $cart->getUser()->getId()){
return $this->eadResponse(null, ErrorEnum::ACTION_INVALID);
}
}
if($cart->getProductCoupon()){
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$cart->setPrice($productOffer->getPriceReal());
$cart->setMembershipFee(ProductEnum::NO);
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
){
$cart->setMembershipFee($productOffer->getMembershipFee());
}
$cart->setProductCoupon(null);
}
$this->em->flush();
// return $this->eadResponse($cart->toReturn(), ErrorEnum::SUCCESS);
return $this->redirectToRoute('cart');
}
/**
* @Route(
* path = "/delete/{id}/{isAjaxRequest}",
* name = "cartDelete",
* methods = {"GET"},
* requirements = { "id" = "\d+" },
* defaults = { "isAjaxRequest" = 0 }
* )
*/
public function deleteCart(Request $request) {
$isAjaxRequest = (int)$request->get('isAjaxRequest');
$cartId = $request->get('id');
$cartRepository = $this->em->getRepository(Cart::class);
$cart = $cartRepository->findOneBy([
"id" => $cartId,
"deleted" => CartEnum::ITEM_NO_DELETED
]);
if(!$cart){
if($isAjaxRequest == CartEnum::YES){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
return $this->redirectToRoute('notFound');
}
if($this->user){
if($this->user->getId() != $cart->getUser()->getId()){
if($isAjaxRequest == CartEnum::YES){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
return $this->redirectToRoute('notFound');
}
}else{
$cookieName = 'hashcartoff';
$hashId = $this->generalService->getCookie($cookieName);
if(empty($hashId) || $hashId != $cart->getHashIdentify()){
if($isAjaxRequest == CartEnum::YES){
return $this->eadResponse(null, ErrorEnum::NOT_FOUND);
}
return $this->redirectToRoute('notFound');
}
}
$cartRepository->updateCartProductSuggestion($cart);
if($this->user){
$whishlistIsActive = $this->em->getRepository(Whishlist::class)->findOneBy([
"product" => $cart->getProduct()->getId(),
"user" => $cart->getUser()->getId(),
"deleted" => WhishlistEnum::ITEM_NO_DELETED
]);
$crmService = $this->generalService->getService('CRM\\CrmService');
$dealId = $cart->getPipedriveDeal();
$crmService->deleteDeal($dealId);
if($whishlistIsActive){
$backWhishlist = $crmService->saveDeal(
$dealId,
$cart->getUser(),
$cart->getProduct(),
'open',
$this->configuration->get("pipedrive_wishlist"),
$cart->getPrice(),
$cart->getProductOffer()->getCurrencyCode()
);
}
}
$cart->setUtmsUrl(null);
$cart->setProductCoupon(null);
$cart->delete();
$this->em->flush();
$mkgService = $this->generalService->getService('Marketing\\MarketingService');
$mkgService->setTag(TagsMarketingEnum::TAG_REMOVE_CART);
$mkgService->setTextComplement($cart->getProduct()->getTitle());
$mkgService->setUser($this->user);
$mkgService->send();
// AJAX
// if($isAjaxRequest == CartEnum::YES){
// return $this->redirectToRoute('cart');
// }
// NAVBAR
return $this->redirectToRoute('cart');
}
}