<?php
namespace EADPlataforma\Repository;
use EADPlataforma\Entity\Eadmin\Plan;
use EADPlataforma\Entity\Cart;
use EADPlataforma\Entity\Course;
use EADPlataforma\Entity\Product;
use EADPlataforma\Entity\ProductOffer;
use EADPlataforma\Entity\ProductTeam;
use EADPlataforma\Entity\ProductCoupon;
use EADPlataforma\Entity\Receiver;
use EADPlataforma\Entity\TransactionItem;
use EADPlataforma\Entity\Transaction;
use EADPlataforma\Entity\User;
use EADPlataforma\Entity\UserCard;
use EADPlataforma\Entity\ProductSuggestion;
use EADPlataforma\Entity\Whishlist;
use EADPlataforma\Enum\CartEnum;
use EADPlataforma\Enum\ProductEnum;
use EADPlataforma\Enum\ProductTeamEnum;
use EADPlataforma\Enum\ProductOfferEnum;
use EADPlataforma\Enum\ProductCouponEnum;
use EADPlataforma\Enum\ReceiverEnum;
use EADPlataforma\Enum\TagsMarketingEnum;
use EADPlataforma\Enum\TransactionEnum;
use EADPlataforma\Enum\TransactionItemEnum;
use EADPlataforma\Enum\ProductSuggestionEnum;
use EADPlataforma\Enum\UserEnum;
use EADPlataforma\Enum\ProductOpportunityEnum;
use EADPlataforma\Enum\EnrollmentEnum;
use EADPlataforma\Enum\WebhookEnum;
use EADPlataforma\Enum\CourseEnum;
/**
* @method Cart|null find($id, $lockMode = null, $lockVersion = null)
* @method Cart|null findOneBy(array $criteria, array $orderBy = null)
* @method Cart[] findAll()
* @method Cart[] findBy(array $criteria, array $orderBy = null, $limit = null, $offset = null)
*/
class CartRepository extends AbstractRepository
{
public function getEntityClass(){
return Cart::class;
}
public function getConnectionName(){
return "school";
}
public function sendConclusionConversion(string $hashReference){
$transactionRepository = $this->em->getRepository(Transaction::class);
$transactions = $transactionRepository->findBy([
"deleted" => TransactionEnum::ITEM_NO_DELETED,
"hashReference" => $hashReference
]);
foreach ($transactions as $key => $transaction) {
$this->sendConversionTransaction($transaction);
}
}
public function sendConversionTransaction(Transaction $transaction)
{
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$contents = [];
$transactionItemRepository = $this->em->getRepository(TransactionItem::class);
$items = $transactionItemRepository->findBy([
"deleted" => TransactionItemEnum::ITEM_NO_DELETED,
"transaction" => $transaction->getId(),
]);
$tStatus = $transaction->getStatus();
$tPayment = $transaction->getPaymentMethod();
$statusValid = [
TransactionEnum::WAITING,
TransactionEnum::APPROVED,
TransactionEnum::CANCELED,
];
if(!in_array($tStatus, $statusValid)){
return;
}
$checkFunction = function ($value){
return (TransactionEnum::YES == $value);
};
$paymentMethodCheck = [
TransactionEnum::PAYMENT_CARD => $checkFunction,
TransactionEnum::PAYMENT_BILL => $checkFunction,
TransactionEnum::PAYMENT_PIX => $checkFunction
];
$statusCheck = [
TransactionEnum::WAITING => $checkFunction,
TransactionEnum::APPROVED => $checkFunction,
TransactionEnum::CANCELED => $checkFunction
];
foreach ($items as $key => $item) {
$product = $item->getProduct();
if($checkFunction($product->getExecuteScriptTypeNative())){
$valueCheckPaymentMethod = [
TransactionEnum::PAYMENT_CARD => $product->getExecuteScriptCard(),
TransactionEnum::PAYMENT_BILL => $product->getExecuteScriptBill(),
TransactionEnum::PAYMENT_PIX => $product->getExecuteScriptPix()
];
$valueCheckStatus = [
TransactionEnum::WAITING => $product->getExecuteScriptStatusApproved(),
TransactionEnum::APPROVED => $product->getExecuteScriptStatusWaiting(),
TransactionEnum::CANCELED => $product->getExecuteScriptStatusCanceled(),
];
if($paymentMethodCheck[$tPayment]($valueCheckPaymentMethod[$tPayment])){
if($statusCheck[$tStatus]($valueCheckStatus[$tStatus])){
$contents[] = (object)[
"id" => $product->getId(),
"quantity" => 1,
"item_price" => $item->getAmount(),
//"item_name" => $product->getTitle(),
//"type" => $product->getType()
];
}
}
}
if($product->getType() == ProductEnum::SUBSCRIPTION){
$pixelService->sendConversion('Subscribe', (object)[
"value" => (float)$item->getAmount(),
"currency" => $transaction->getCurrencyCode(),
"contents" => [
(object)[
"id" => $product->getId(),
"quantity" => 1,
"item_price" => $item->getAmount(),
//"name" => $product->getTitle(),
//"type" => $product->getType()
]
],
"num_items" => 1,
"content_type" => "product",
"transaction_id" => $transaction->getId(),
]);
}
}
if(empty($contents)){
return;
}
$data = (object)[
"value" => (float)$transaction->getAmount(),
"currency" => $transaction->getCurrencyCode(),
"contents" => $contents,
"num_items" => count($contents),
"content_type" => "product",
"transaction_id" => $transaction->getId(),
];
$pixelService->sendConversion('Purchase', $data);
}
public function addCartByProductOffer(
ProductOffer $productOffer,
?User $user = null,
?ProductSuggestion $productSuggestion = null,
?ProductCoupon $productCoupon = null,
?string $utmsUrl = null,
?array $courses = null
)
{
$product = $productOffer->getProduct();
if($product->isDisable()){
return false;
}
if($productOffer->getNotForSale() == ProductOfferEnum::YES){
return false;
}
$transactionItemRepository = $this->em->getRepository(TransactionItem::class);
$saleNumber = $transactionItemRepository->countSalesApprovedByProductOffer(
$productOffer
);
$poRepository = $this->em->getRepository(ProductOffer::class);
if(!$poRepository->checkProductOfferIsOnSale($productOffer)){
return false;
}
if($user){
$productRepository = $this->em->getRepository(Product::class);
if($productRepository->userHasProduct($user, $product)){
return false;
}
}
if(empty($courses) && $product->isTypeResource()){
return false;
}
$hashIdentify = $this->generalService->getCookieHashIdentify();
$filter = [
"product" => $product->getId()
];
if($user){
$filter["user"] = $user->getId();
} else if(!empty($hashIdentify)){
$filter["hashIdentify"] = $hashIdentify;
}
$new = false;
$cart = $this->findOneBy($filter);
if (!$cart) {
$new = true;
$cart = new Cart();
}
if(!$new){
if($cart->getProductOffer()->getId() != $productOffer->getId()){
if($utmsUrl){
$cart->setUtmsUrl($utmsUrl);
}
$this->updateCartProductSuggestion($cart);
}
}
if($utmsUrl){
$cart->setUtmsUrl($utmsUrl);
}
if($courses){
foreach ($courses as $key => $course) {
$cart->addCourse($course);
}
}
$cart->setProductOffer($productOffer);
$cart->setProduct($product);
if($productSuggestion){
$cart->setProductSuggestion($productSuggestion);
}
if($user){
$cart->setUser($user);
$cart->setHashIdentify($user->getHashIdentify());
}else if(!empty($hashIdentify)){
$cart->setHashIdentify($hashIdentify);
}
$price = $productOffer->getPriceReal();
$membershipFee = $productOffer->getMembershipFee();
if($productCoupon){
$productCouponRepository = $this->em->getRepository(ProductCoupon::class);
if($productCoupon->getApplyMembershipFee() == ProductCouponEnum::YES){
$membershipFee = $productCouponRepository->applyDiscount(
$productCoupon,
$membershipFee
);
}else{
$price = $productCouponRepository->applyDiscount(
$productCoupon,
$price
);
if(
!$productCouponRepository->checkApplyCoupon(
$productCoupon,
$productOffer
)
){
return;
}
}
$cart->setProductCoupon($productCoupon);
}
$cart->setPrice($productOffer->getPriceReal());
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
){
$cart->setMembershipFee($membershipFee);
}
if($cart->getProduct()){
$cart->setProductType($cart->getProduct()->getType());
}
$entityUtil = $this->generalService->getUtil('EntityUtil');
$errors = $entityUtil->setEntity($cart)->validateEntity();
if($errors){
return false;
}
if(!empty($price) || $productCoupon){
$cart->setPrice($price);
}
$cart->restore();
if($new){
$this->em->persist($cart);
}
$this->em->flush();
$this->processAddCart($cart, $new);
return $cart;
}
public function processAddCart(Cart $cart, ?bool $new = false)
{
$crmService = $this->generalService->getService('CRM\\CrmService');
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$user = $cart->getUser();
if(!$product->getPipedriveProduct()){
$crmService->saveProduct($product);
}
if($user){
$pipedriveDealId = null;
if(!$user->getPipedrivePerson()){
$crmService->savePerson($user);
}
$whishlist = $this->em->getRepository(Whishlist::class)->findOneBy([
"product" => $product->getId(),
"user" => $user->getId()
]);
if(!$whishlist){
$pipedriveDealId = $crmService->saveDeal(
$cart->getPipedriveDeal(),
$user,
$product,
'open',
$this->configuration->get("pipedrive_cart"),
$cart->getPrice(),
$productOffer->getCurrencyCode()
);
$cart->setPipedriveDeal($pipedriveDealId);
}else{
$pipedriveDeal = $cart->getPipedriveDeal();
$price = $cart->getPrice();
if(empty($pipedriveDeal)){
$pipedriveDeal = $whishlist->getPipedriveDeal();
$price = $productOffer->getPriceReal();
}
$pipedriveDealId = $crmService->saveDeal(
$pipedriveDeal,
$user,
$product,
'open',
$this->configuration->get("pipedrive_cart"),
$price,
$productOffer->getCurrencyCode()
);
$whishlist->setPipedriveDeal($pipedriveDealId);
$cart->setPipedriveDeal($pipedriveDealId);
}
$this->em->flush();
//tags
$mkgService = $this->generalService->getService('Marketing\\MarketingService');
$mkgService->setTag(TagsMarketingEnum::TAG_ADD_CART);
$mkgService->setTextComplement($product->getTitle());
$mkgService->setUser($user);
$mkgService->setProductOffer($productOffer);
$mkgService->setOpportunity(ProductOpportunityEnum::TAG_ADD_CART);
$mkgService->send();
}
//pixel
$pixelService = $this->generalService->getService('Marketing\\PixelService');
$pixelService->sendConversion('AddToCart', (object)[
"content_ids" => [ $productOffer->getId() ],
"content_name" => $productOffer->getTitle(),
"currency" => $productOffer->getCurrencyCode(),
"value" => $productOffer->getPriceReal(),
]);
return;
}
public function updateCartHashToUser(User $user)
{
$crmService = $this->generalService->getService('CRM\\CrmService');
$productRepository = $this->em->getRepository(Product::class);
$cookieName = 'hashcartoff';
$hashIdentify = $this->generalService->getCookie($cookieName);
if(empty($hashIdentify)){
return;
}
//if($hashIdentify != $user->getHashIdentify()){
//return;
//}
$enrollmentService = $this->generalService->getService('EnrollmentService');
$carts = $this->getHashValidCarts($hashIdentify);
$cartsNumber = count($carts);
$free = 0;
foreach ($carts as $key => $cart) {
$product = $cart->getProduct();
$userCart = $cart->getUser();
$cartSave = $this->findOneBy([
"user" => $user->getId(),
"product" => $product->getId(),
]);
$productCoupon = $cart->getProductCoupon();
$price = (float)$cart->getPrice();
if(empty($price) && $productCoupon){
$free = $free + 1;
$productCoupon->setUsageNumber($productCoupon->getUsageNumber() + 1);
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($productCoupon->getKey());
$enrollmentService->enrollUserByProduct(
$user,
$cart->getProduct(),
($cart->getProduct()->isTypeResource() ? $cart->getCourse() : null)
);
$this->em->remove($cart);
}else{
if($userCart){
if($userCart->getId() == $user->getId()){
if($productRepository->userHasProduct($user, $product)){
$this->em->remove($cart);
$free = $free + 1;
}else if($cartSave && $cartSave->getId() != $cart->getId()){
$this->em->remove($cartSave);
}
}else{
if($cartSave){
$pipedriveDealId = $cartSave->getPipedriveDeal();
$this->em->remove($cartSave);
}
$newCart = clone $cart;
$newCart->setUser($user);
$newCart->setHashIdentify($user->getHashIdentify());
$pipedriveDealId = $crmService->saveDeal(
(!empty($pipedriveDealId) ? $pipedriveDealId : null),
$user,
$product,
'open',
$this->configuration->get("pipedrive_cart"),
$newCart->getPrice(),
$newCart->getProductOffer()->getCurrencyCode()
);
$newCart->setPipedriveDeal($pipedriveDealId);
$this->em->persist($newCart);
}
}else{
$pipedriveDealId = null;
if($cartSave){
$pipedriveDealId = $cartSave->getPipedriveDeal();
$this->em->remove($cartSave);
}
$cart->setUser($user);
$cart->setHashIdentify($user->getHashIdentify());
$pipedriveDealId = $crmService->saveDeal(
(!empty($pipedriveDealId) ? $pipedriveDealId : $cart->getPipedriveDeal()),
$user,
$product,
'open',
$this->configuration->get("pipedrive_cart"),
$cart->getPrice(),
$cart->getProductOffer()->getCurrencyCode()
);
$cart->setPipedriveDeal($pipedriveDealId);
}
}
}
$this->em->flush();
$this->generalService->setCookie($cookieName, $user->getHashIdentify());
return ($cartsNumber == $free);
}
public function updateCartProductSuggestion(Cart $cart)
{
$poRepository = $this->em->getRepository(ProductOffer::class);
$user = $cart->getUser();
$query = $this->createQueryBuilder('c');
$query->innerJoin(
'EADPlataforma:ProductSuggestion',
'ps',
'WITH',
'ps.id = c.productSuggestion'
);
$query->andWhere('c.id != :cartDeleted');
$query->andWhere('ps.productOrigin = :productOrigin');
$query->andWhere(':productOfferOrigin MEMBER OF ps.productOfferOrigin');
$query->andWhere('c.deleted = :deleted');
if($user){
$query->andWhere('c.user = :userId');
$query->setParameter('userId', $cart->getUser()->getId());
}else{
$query->andWhere('c.hashIdentify = :hashIdentify');
$query->setParameter('hashIdentify', $cart->getHashIdentify());
}
$query->setParameter('cartDeleted', $cart->getId());
$query->setParameter('productOrigin', $cart->getProduct()->getId());
$query->setParameter('productOfferOrigin', $cart->getProductOffer()->getId());
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$cartsWithSuggestion = $query->getQuery()->execute();
foreach ($cartsWithSuggestion as $key => $cartWithSuggestion) {
$cartWithSuggestion->setProductSuggestion(null);
$product = $cartWithSuggestion->getProduct();
$productOfferDefault = $poRepository->getProductOfferDefaultByProduct($product);
if($productOfferDefault){
$cartWithSuggestion->setProductOffer($productOfferDefault);
$cartWithSuggestion->setPrice($productOfferDefault->getPriceReal());
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOfferDefault->getAllowRecurrency() == ProductEnum::YES
){
$cartWithSuggestion->setMembershipFee(
$productOfferDefault->getMembershipFee()
);
}
}else{
$cartsWithSuggestion->delete();
}
}
$this->em->flush();
return;
}
public function countUserOnCart()
{
if($this->getUser()){
return $this->countUserValidCarts($this->getUser()->getId());
}else{
$hashIdentify = $this->generalService->getCookie('hashcartoff');
if(!empty($hashIdentify)){
return $this->countHashValidCarts($hashIdentify);
}
}
return 0;
}
public function countCustomCheckout(int $userId)
{
$query = $this->createQueryBuilder('c');
$query->select('COUNT(c.id) AS total');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = 0
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->andWhere('po.typeCheckout = :customCheckout');
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('customCheckout', ProductOfferEnum::CHECKOUT_CUSTOM);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function hasOnlyCourseInCart(int $userId)
{
$query = $this->createQueryBuilder('c');
$query->select('COUNT(c.id) AS total');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = :saleDateType
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->andWhere('(
(p.type != :typeCourse AND p.type != :typeCombo)
OR
po.allowRecurrency = :allowRecurrency
)');
$query->setParameter('allowRecurrency', ProductOfferEnum::YES);
$query->setParameter('saleDateType', ProductOfferEnum::SALE_OPEN);
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('typeCourse', ProductEnum::COURSE);
$query->setParameter('typeCombo', ProductEnum::COMBO);
$result = (object)$query->getQuery()->getOneOrNullResult();
return ($result->total > 0 ? false : true);
}
public function getUserValidCarts(int $userId, ?int $productId = null,
?int $limit = null)
{
$query = $this->createQueryBuilder('c');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = :saleDateType
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('saleDateType', ProductOfferEnum::SALE_OPEN);
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
if($productId > 0){
$query->andWhere('c.product = :productId');
$query->setParameter('productId', $productId);
}
if(!empty($limit)){
$query->setMaxResults($limit);
}
return $query->getQuery()->execute();
}
public function countUserValidCarts(int $userId)
{
$query = $this->createQueryBuilder('c');
$query->select('COUNT(c.id) AS total');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = 0
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function countHashValidCarts(string $hash)
{
$query = $this->createQueryBuilder('c');
$query->select('COUNT(c.id) AS total');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = 0
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.hashIdentify = :hash');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('hash', $hash);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->total;
}
public function getUserDisplaySubTotal(int $userId)
{
$query = $this->createQueryBuilder('c');
$query->select('
SUM(
CASE
WHEN po.priceDisplay > po.priceReal
THEN po.priceDisplay + po.membershipFee
ELSE po.priceReal + po.membershipFee
END
) AS subtotal
');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = :no
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('no', ProductOfferEnum::NO);
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return $result->subtotal;
}
public function getUserSubTotal(int $userId)
{
$query = $this->createQueryBuilder('c');
$query->select('SUM(c.price + c.membershipFee) AS subtotal');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = 0
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->andWhere('c.user = :userId');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('userId', $userId);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$result = (object)$query->getQuery()->getOneOrNullResult();
return (!empty($result->subtotal) ? $result->subtotal : 0 );
}
public function isValidCart(Cart $cart)
{
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
if($product->isDisable()){
return false;
}
if($productOffer->getStatus() != ProductOfferEnum::PUBLISHED){
return false;
}
if($productOffer->getNotForSale() == ProductOfferEnum::YES){
return false;
}
if(!$productOffer->getSaleIsOpen()){
return false;
}
return true;
}
public function getHashValidCartsInfo(string $hash)
{
$filter = [
"hashIdentify" => $hash,
"deleted" => CartEnum::ITEM_NO_DELETED,
];
$carts = $this->findBy($filter);
$total = 0;
$totalCustom = 0;
$totalPrice = 0;
$totalDisplay = 0;
$data = [];
foreach ($carts as $key => $cart) {
if(!$this->isValidCart($cart)){
continue;
}
$productOffer = $cart->getProductOffer();
$price = (
$productOffer->getPriceDisplay() > $productOffer->getPriceReal() ?
$productOffer->getPriceDisplay() :
$productOffer->getPriceReal()
);
$total = $total + 1;
if($productOffer->getTypeCheckout() == ProductOfferEnum::CHECKOUT_CUSTOM){
$totalCustom = $totalCustom + 1;
}
$totalPrice = $totalPrice + $cart->getPrice() + $cart->getMembershipFee();
$totalDisplay = $totalDisplay + $price + $productOffer->getMembershipFee();
$data[] = $cart;
}
return (object)[
"total" => $total,
"totalCustom" => $totalCustom,
"totalPrice" => $totalPrice,
"totalDisplay" => $totalDisplay,
"data" => $data,
];
}
public function countCustomCheckoutHash(string $hash)
{
$carts = $this->findBy([
"hashIdentify" => $hash,
"deleted" => CartEnum::ITEM_NO_DELETED,
]);
$total = 0;
foreach ($carts as $key => $cart) {
if(!$this->isValidCart($cart)){
continue;
}
$total = $total + 1;
}
return $total;
}
public function getHashValidCarts(string $hash, ?int $productId = null,
?int $limit = null)
{
$filter = [
"hashIdentify" => $hash,
"deleted" => CartEnum::ITEM_NO_DELETED,
];
if($productId > 0){
$filter["product"] = $productId;
}
$carts = $this->findBy($filter, null, $limit);
$data = [];
foreach ($carts as $key => $cart) {
if(!$this->isValidCart($cart)){
continue;
}
$data[] = $cart;
}
return $data;
}
public function getHashDisplaySubTotal(string $hash)
{
$filter = [
"hashIdentify" => $hash,
"deleted" => CartEnum::ITEM_NO_DELETED,
];
$carts = $this->findBy($filter);
$total = 0;
foreach ($carts as $key => $cart) {
if(!$this->isValidCart($cart)){
continue;
}
$productOffer = $cart->getProductOffer();
$price = (
$productOffer->getPriceDisplay() > $productOffer->getPriceReal() ?
$productOffer->getPriceDisplay() :
$productOffer->getPriceReal()
);
$total = $total + $price + $productOffer->getMembershipFee();
}
return $total;
}
public function getHashSubTotal(string $hash)
{
$filter = [
"hashIdentify" => $hash,
"deleted" => CartEnum::ITEM_NO_DELETED,
];
$carts = $this->findBy($filter);
$total = 0;
foreach ($carts as $key => $cart) {
if(!$this->isValidCart($cart)){
continue;
}
$total = $total + $cart->getPrice() + $cart->getMembershipFee();
}
return $total;
}
public function getAbandonedCarts(int $type)
{
$query = $this->createQueryBuilder('c');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin('EADPlataforma:User', 'u', 'WITH', 'u.id = c.user');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer AND po.product = p.id'
);
$query->andWhere('(
po.saleDateType = 0
OR (:today BETWEEN po.saleDateStart AND po.saleDateClose)
)');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('u.status != 2');
$query->andWhere('c.type = :type');
$query->andWhere('c.deleted = :deleted');
$query->andWhere('p.status != :statusDraftProduct');
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('p.deleted = :deletedProduct');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('type', $type);
$query->setParameter('today', date('Y-m-d H:i:s'));
$query->setParameter('statusDraftProduct', ProductEnum::DRAFT);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->setParameter('deleted', CartEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProduct', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
return $query->getQuery()->execute();
}
public function getSplitRules(
array $products, User
$user,
$amount,
int $installments,
int $paymentMethod,
?UserCard $userCard = null,
?int $freeInstallments = null,
?bool $debug = false
)
{
$paymentConfig = $this->configuration->getPaymentConfig();
$installmentNumberInterest = $paymentConfig->installmentNumberInterest;
$productOfferRepository = $this->em->getRepository(ProductOffer::class);
$productTeamRepository = $this->em->getRepository(ProductTeam::class);
$receiverRepository = $this->em->getRepository(Receiver::class);
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$receiverIdEAD = $pagarMeTransaction->getReceiverIdEAD();
$numberItems = count($products);
$splits = [];
$splitsUser = [];
$amountTotal = $amount / 100;
$amountOrigin = $amount / 100;
$transactionService = $this->generalService->getService(
'Transaction\\TransactionService'
);
$checkoutAmountsEAD = $transactionService->getEADCheckoutAmount(
$amountTotal,
$paymentMethod,
$installments,
false,
$userCard
);
$rate = $checkoutAmountsEAD->rate;
$fee = $checkoutAmountsEAD->fee;
$amountTotal = $checkoutAmountsEAD->amountTotalCents;
$amountEAD = $checkoutAmountsEAD->amountEADCents;
if($rate > 0 && $numberItems > 0){
$rate = round( $rate / $numberItems, 2);
}
$splitEAD = (object)[
"recipient_id" => $receiverIdEAD,
"charge_processing_fee" => false,
"liable" => true,
"percentage" => null,
"amount" => (int)round($amountEAD),
"date_created" => date('Y-m-d H:i:s'),
"date_updated" => date('Y-m-d H:i:s')
];
$discordService = $this->generalService->getService('DiscordService');
$discordService->setChannel('debug');
foreach ($products as $key => $item) {
if(!empty($item->cartId)){
$cart = $this->find($item->cartId);
}
$productTeams = $productTeamRepository->findBy([
"product" => $item->productId,
"commission" => ProductTeamEnum::YES,
"deleted" => ProductTeamEnum::ITEM_NO_DELETED
]);
$productOffer = $productOfferRepository->find($item->productOfferId);
$productAmount = $item->amount;
if(empty($productAmount)){
$productOffer->getPriceReal();
}
if(empty($freeInstallments)){
$freeInstallments = $productOfferRepository->getFreeInstallment(
$productOffer
);
}
if($paymentMethod != CartEnum::PAYMENT_CARD){
$freeInstallments = 12;
$installments = 1;
}
$pagarMeTransaction = $this->generalService->getService(
'PagarMe\\PagarMeTransaction'
);
$productAmount = $pagarMeTransaction->calculateInterest(
$productAmount,
(int)$installments,
(int)$freeInstallments
);
$feeAmount = $productAmount * ($fee / 100) + $rate;
$productAmount = ($productAmount - $feeAmount);
$productAmount = round($productAmount, 2);
foreach ($productTeams as $teamKey => $productTeam) {
if($productTeam->getCommission() == ProductTeamEnum::YES){
$receiver = $receiverRepository->findOneBy([
"user" => $productTeam->getUser()->getId(),
"accountType" => ReceiverEnum::EAD_CHECKOUT,
"status" => ReceiverEnum::ACTIVE,
"type" => ReceiverEnum::EMPLOYEE,
"deleted" => ReceiverEnum::ITEM_NO_DELETED
]);
if($receiver){
$teamAmount = $productAmount * ( $productTeam->getPercent() / 100 );
$teamAmount = round($teamAmount, 2);
$teamAmountCents = ceil($teamAmount * 100);
$splitTeam = (object)[
"recipient_id" => $receiver->getReceiverHash(),
"charge_processing_fee" => false,
"liable" => true,
"percentage" => null,
"amount" => (int)$teamAmountCents,
"date_created" => date('Y-m-d H:i:s'),
"date_updated" => date('Y-m-d H:i:s')
];
$amountTotal = $amountTotal - $teamAmountCents;
$splitsUser[] = $splitTeam;
}
}
}
}
//remover iguais
$ignore = [];
foreach ($splitsUser as $splitsKey => $split) {
foreach ($splitsUser as $splitsKey2 => $split2) {
if(
$split->recipient_id == $split2->recipient_id &&
$splitsKey != $splitsKey2
){
$split->amount = $split->amount + $split2->amount;
}
}
if(!in_array($split->recipient_id, $ignore)){
$splits[] = $split;
$ignore[] = $split->recipient_id;
}
}
$receiverSchool = $this->configuration->getReceiverSchool(
ReceiverEnum::EAD_CHECKOUT,
$debug
);
if(!$receiverSchool){
if($debug){
$discordService->setMessage("Not found receiver");
$discordService->sendDiscord();
}
return [];
}
$splitAdmin = (object)[
"recipient_id" => $receiverSchool->getReceiverHash(),
"charge_processing_fee" => true,
"liable" => true,
"percentage" => null,
"amount" => (int)round($amountTotal),
"date_created" => date('Y-m-d H:i:s'),
"date_updated" => date('Y-m-d H:i:s')
];
$splits[] = $splitEAD;
$splits[] = $splitAdmin;
if($debug){
$discordService->setMessage(json_encode($splits));
$discordService->sendDiscord();
}
return $splits;
}
public function applyCouponUserCart($couponKey, ?User $user = null,
?string $hashIdentify = null)
{
if(empty($user) && empty($hashIdentify)){
return false;
}
$productRepository = $this->em->getRepository(Product::class);
$productCouponRepository = $this->em->getRepository(ProductCoupon::class);
$productCoupons = $productCouponRepository->findValidProductCoupon($couponKey);
if(empty($productCoupons)){
return false;
}
$enrollmentService = $this->generalService->getService('EnrollmentService');
$filter = [
"deleted" => ProductCouponEnum::ITEM_NO_DELETED
];
if($user){
$filter["user"] = $user;
}else if(!empty($hashIdentify)){
$filter["hashIdentify"] = $hashIdentify;
}
$carts = $this->findBy($filter);
$apply = false;
foreach ($productCoupons as $key => $productCoupon) {
$couponType = $productCoupon->getType();
$all = $productCoupon->getAll();
$discountType = $productCoupon->getDiscountType();
$discount = $productCoupon->getDiscount();
$applyOfferType = $productCoupon->getApplyOfferType();
$public = $productCoupon->getPublic();
if($public == ProductCouponEnum::YES){
$applyOfferType = ProductCouponEnum::OFFER_DEFAULT;
}
$is100 = ($discountType == ProductCouponEnum::PERCENTAGE && $discount >= 100);
$usageNumber = $productCoupon->getUsageNumber();
if($productCoupon->getApplyMembershipFee() == ProductCouponEnum::YES){
if(!empty($carts)){
foreach ($carts as $keyCart => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$default = $productOffer->getDefault();
$amount = $productOffer->getMembershipFee();
$amount = $productCouponRepository->applyDiscount(
$productCoupon,
$amount
);
if($couponType == ProductCouponEnum::CATEGORY){
if($default == ProductCouponEnum::YES){
$hasCategory = $product->getCategory()->contains(
$productCoupon->getCategory()
);
if($hasCategory){
$apply = true;
$cart->setMembershipFee($amount);
$cart->setPrice($productOffer->getPriceReal());
$cart->setProductCoupon($productCoupon);
}
}
}else if(
$couponType == $product->getType() &&
(
$all == ProductCouponEnum::YES ||
(
$productCoupon->getProduct() &&
$product->getId() == $productCoupon->getProduct()->getId()
)
)
){
if(
$applyOfferType == ProductCouponEnum::OFFER_ALL ||
(
$applyOfferType == ProductCouponEnum::OFFER_DEFAULT &&
$default == ProductCouponEnum::YES
) ||
(
$applyOfferType == ProductCouponEnum::OFFER_CUSTOM &&
$productCoupon->getProductOffer()->contains($productOffer)
)
){
$apply = true;
$cart->setMembershipFee($amount);
$cart->setPrice($productOffer->getPriceReal());
$cart->setProductCoupon($productCoupon);
}
}
}
}
}else{
if($all == ProductCouponEnum::YES && $is100 && $user){
if($couponType != ProductCouponEnum::SUBSCRIPTION){
$apply = true;
$usageNumber = $usageNumber + 1;
$products = $productRepository->getAllPublicByType($couponType);
foreach ($products as $keyProduct => $product){
$enrollmentService->setOrigin(EnrollmentEnum::ORIGIN_COUPOM);
$enrollmentService->setCouponKey($couponKey);
$enrollmentService->enrollUserByProduct(
$user,
$product
);
}
}
}else if(!empty($carts)){
foreach ($carts as $keyCart => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$default = $productOffer->getDefault();
if($couponType == ProductCouponEnum::CATEGORY){
if($default == ProductCouponEnum::YES){
$hasCategory = $product->getCategory()->contains(
$productCoupon->getCategory()
);
if ($hasCategory){
$amount = $productOffer->getPriceReal();
$amount = $productCouponRepository->applyDiscount(
$productCoupon,
$amount
);
if($amount > 0){
$apply = true;
$cart->setPrice($amount);
$cart->setProductCoupon($productCoupon);
}else if(
$product->getType() != ProductCouponEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductEnum::NO
){
if($user){
$apply = true;
$usageNumber = $usageNumber + 1;
$enrollmentService->setOrigin(
EnrollmentEnum::ORIGIN_COUPOM
);
$enrollmentService->setCouponKey($couponKey);
$enrollmentService->enrollUserByProduct(
$user,
$product,
(
$product->isTypeResource() ?
$cart->getCourse() :
null
)
);
}else{
$apply = true;
$cart->setPrice($amount);
$cart->setProductCoupon($productCoupon);
}
}
}
}
}else if(
$couponType == $product->getType() &&
(
$all == ProductCouponEnum::YES ||
(
$productCoupon->getProduct() &&
$product->getId() == $productCoupon->getProduct()->getId()
)
)
){
if(
$applyOfferType == ProductCouponEnum::OFFER_ALL ||
(
$applyOfferType == ProductCouponEnum::OFFER_DEFAULT &&
$default == ProductCouponEnum::YES
) ||
(
$applyOfferType == ProductCouponEnum::OFFER_CUSTOM &&
$productCoupon->getProductOffer()->contains($productOffer)
)
){
$amount = $productOffer->getPriceReal();
$amount = $productCouponRepository->applyDiscount(
$productCoupon,
$amount
);
if($amount > 0){
$apply = true;
$cart->setPrice($amount);
$cart->setProductCoupon($productCoupon);
}else if(
$couponType != ProductCouponEnum::SUBSCRIPTION &&
$productOffer->getAllowRecurrency() == ProductEnum::NO
){
if($user){
$apply = true;
$usageNumber = $usageNumber + 1;
$enrollmentService->setOrigin(
EnrollmentEnum::ORIGIN_COUPOM
);
$enrollmentService->setCouponKey($couponKey);
$enrollmentService->enrollUserByProduct(
$user,
$product,
(
$product->isTypeResource() ?
$cart->getCourse() :
null
)
);
}else{
$apply = true;
$cart->setPrice($amount);
$cart->setProductCoupon($productCoupon);
}
}
}
}
}
}
}
$productCoupon->setUsageNumber($usageNumber);
}
$this->em->flush();
return $apply;
}
public function resetCartsByProductOffer(ProductOffer $productOffer)
{
$carts = $this->findBy([ "productOffer" => $productOffer->getId() ]);
foreach ($carts as $key => $cart) {
$cart->setProductCoupon(null);
$cart->setProductSuggestion(null);
$cart->setPrice($productOffer->getPriceReal());
}
$this->em->flush();
}
public function getCartsWithProductCoupon(?int $userId = null,
?string $hashIdentify = null)
{
$query = $this->createQueryBuilder('c');
$query->innerJoin(
'EADPlataforma:ProductCoupon',
'pc',
'WITH',
'pc.id = c.productCoupon'
);
if(!empty($userId)){
$query->andWhere('c.user = :userId');
$query->setParameter('userId', $userId);
}else if(!empty($hashIdentify)){
$query->andWhere('c.hashIdentify = :hashIdentify');
$query->setParameter('hashIdentify', $hashIdentify);
}
return $query->getQuery()->execute();
}
public function updateCartsWithProductCouponExpired(?int $userId = null,
?string $hashIdentify = null)
{
$carts = $this->getCartsWithProductCoupon($userId, $hashIdentify);
$today = strtotime("now");
foreach ($carts as $key => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$productCoupon = $cart->getProductCoupon();
$update = false;
if($productCoupon){
$dateStart = strtotime($productCoupon->getDateStart());
$dateEnd = strtotime($productCoupon->getDateEnd());
if($productCoupon->getUsageNumber() >= $productCoupon->getQuantity()){
$update = true;
}else if($today > $dateEnd || $today < $dateStart){
$update = true;
}
}
if($update){
$cart->setProductCoupon(null);
$cart->setProductSuggestion(null);
$cart->setPrice($productOffer->getPriceReal());
if(
$product->getType() == ProductEnum::SUBSCRIPTION ||
$productOffer->getAllowRecurrency() == ProductEnum::YES
){
$cart->setMembershipFee($productOffer->getMembershipFee());
}
}
}
$this->em->flush();
}
public function getCartsWait($type)
{
$query = $this->createQueryBuilder('c');
$query->innerJoin('EADPlataforma:Product', 'p', 'WITH', 'p.id = c.product');
$query->innerJoin(
'EADPlataforma:ProductOffer',
'po',
'WITH',
'po.id = c.productOffer'
);
$query->innerJoin('EADPlataforma:User', 'u', 'WITH', 'u.id = c.user');
$query->andWhere('po.notForSale = :no');
$query->setParameter('no', ProductOfferEnum::NO);
$query->andWhere('po.status = :statusPublicProductOffer');
$query->andWhere('po.deleted = :deletedProductOffer');
$query->setParameter('deletedProductOffer', ProductEnum::ITEM_NO_DELETED);
$query->setParameter('statusPublicProductOffer', ProductOfferEnum::PUBLISHED);
$query->andWhere('u.deleted = :deleted');
$query->andWhere('u.status != :status');
$query->andWhere('u.allowNotifyCart = :notify');
$query->andWhere('c.type = :type');
$query->setParameter('deleted', UserEnum::ITEM_NO_DELETED);
$query->setParameter('status', UserEnum::BLOCK);
$query->setParameter('notify', UserEnum::YES);
$query->setParameter('type', $type);
$query->addOrderBy('c.user', 'ASC');
return $query->getQuery()->execute();
}
public function alertCheckoutWait(){
$emailService = $this->generalService->getService('EmailService');
$numberUtil = $this->generalService->getUtil('NumberUtil');
$webhookService = $this->generalService->getService('WebhookService');
$client = $this->configuration->getClient();
$carts = $this->getCartsWait(CartEnum::CHECKOUT);
$today = date('Y-m-d');
$auxId = null;
$auxValue = null;
$auxEmail = null;
$auxName = null;
$itemsHtml = '';
$auxLinkCheckout = '';
foreach ($carts as $key => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$user = $cart->getUser();
if(!$emailService->checkUserToSend($user)){
continue;
}
if(!$productOffer){
continue;
}
if(!$product){
continue;
}
if($product->getStatus() == ProductEnum::DRAFT){
continue;
}
$oneDay = date('Y-m-d', strtotime($cart->getDate() . ' + 1 day '));
$threeDay = date('Y-m-d', strtotime($cart->getDate() . ' + 3 day '));
$sevenDay = date('Y-m-d', strtotime($cart->getDate() . ' + 7 day '));
if($oneDay != $today && $threeDay != $today && $sevenDay != $today){
continue;
}
$auxId = $user->getId();
$auxValue = $auxValue + $cart->getPrice();
$auxEmail = $user->getEmail();
$auxName = $user->getName();
$domainClient = $client->getDomainPrimary();
$domainClient = "https://{$domainClient}";
$linkCheckout = "{$domainClient}/cart/add/{$productOffer->getId()}";
$linkStop = "{$domainClient}/stopNotification/{$user->getHashIdentify()}";
if($user->getId() != $auxId && $auxId > 0){
//$auxValue = number_format($auxValue, 2, ',', '.');
$auxValue = $numberUtil->currencyFormat($auxValue);
$emailService->setToEmail($auxEmail);
$emailService->setToName($auxName);
$subText = $this->configuration->getLanguage(
'remember_cart.subject', 'email'
);
$subject = "{$subText}{$client->getBrand()}?";
$emailService->setSubject($subject);
$emailService->setData([
"userName" => $auxName,
"text2" => "{$subText}?",
"status" => '',
"code" => '',
"moeda" => "R$",
"itens" => $itemsHtml,
"value" => $auxValue,
"btnLink" => $linkCheckout,
"urlDisableNot" => $linkStop,
"year" => date('Y')
]);
$emailService->setTemplateBody("remember_cart");
$emailService->send();
$itemsHtml = '';
$auxValue = null;
}
$todayTime = strtotime(date('Y-m-d H:i:s'));
$dateStart = strtotime($productOffer->getSaleDateStart());
$dateClose = strtotime($productOffer->getSaleDateClose());
if($todayTime > $dateClose || $todayTime < $dateStart){
continue;
}
$itemName = $product->getTitle();
if(!empty($itemName)){
$itemName = htmlentities($itemName);
$itemsHtml .= "
<tr style='margin:0px;border:1px solid rgb(238,238,238)'>
<td style='padding:5px 0px 5px 15px;border:1px solid rgb(238,238,238)'>
<p style='margin:0px;font-size:0.9em;color:rgb(102,102,102);line-height:1.2em'>{$itemName}</p>
</td>
</tr>";
}
#last
if(($key + 1) == count($carts)){
$auxValue = $numberUtil->currencyFormat($auxValue);
$emailService->setToEmail($auxEmail);
$emailService->setToName($auxName);
$subText = $this->configuration->getLanguage(
'remember_cart.subject', 'email'
);
$subject = "{$subText}{$client->getBrand()}?";
$emailService->setSubject($subject);
$emailService->setData([
"userName" => $auxName,
"text2" => "{$subText}?",
"status" => '',
"code" => '',
"moeda" => "R$",
"itens" => $itemsHtml,
"value" => $auxValue,
"btnLink" => $linkCheckout,
"urlDisableNot" => $linkStop,
"year" => date('Y')
]);
$emailService->setTemplateBody("remember_cart");
$emailService->send();
$itemsHtml = '';
}
$userWebhook = $this->em->getRepository(User::class)->getToWebhook($user);
//webhook
$dataObj = (object)[
"customer" => $userWebhook,
"products" => [
[
"id" => $product->getId(),
"offer_id" => $productOffer->getId(),
"name" => $product->getTitle(),
"original_price" => $productOffer->getPriceReal(),
"price" => $productOffer->getPriceDisplay(),
"coupon" => null,
"type" => $product->getType(),
"nfe" => "0"
]
],
];
$webhookService->addItemList(WebhookEnum::CART, $dataObj);
}
return;
}
public function alertCartWait(){
$emailService = $this->generalService->getService('EmailService');
$numberUtil = $this->generalService->getUtil('NumberUtil');
$webhookService = $this->generalService->getService('WebhookService');
$client = $this->configuration->getClient();
$carts = $this->getCartsWait(CartEnum::CART);
$today = date('Y-m-d');
$auxId = null;
$auxValue = null;
$auxEmail = null;
$auxName = null;
$itemsHtml = '';
$auxLinkCheckout = '';
foreach ($carts as $key => $cart) {
$product = $cart->getProduct();
$productOffer = $cart->getProductOffer();
$user = $cart->getUser();
if(!$emailService->checkUserToSend($user)){
continue;
}
if(!$productOffer){
continue;
}
if(!$product){
continue;
}
if($product->getStatus() == ProductEnum::DRAFT){
continue;
}
$oneDay = date('Y-m-d', strtotime($cart->getDate() . ' + 1 day '));
$threeDay = date('Y-m-d', strtotime($cart->getDate() . ' + 3 day '));
$sevenDay = date('Y-m-d', strtotime($cart->getDate() . ' + 7 day '));
if($oneDay != $today && $threeDay != $today && $sevenDay != $today){
continue;
}
$auxId = $user->getId();
$auxValue = $auxValue + $cart->getPrice();
$auxEmail = $user->getEmail();
$auxName = $user->getName();
$domainClient = $client->getDomainPrimary();
$domainClient = "https://{$domainClient}";
$linkCheckout = "{$domainClient}/cart/add/{$productOffer->getId()}";
$linkStop = "{$domainClient}/stopNotification/{$user->getHashIdentify()}";
if($user->getId() != $auxId && $auxId > 0){
//$auxValue = number_format($auxValue, 2, ',', '.');
$auxValue = $numberUtil->currencyFormat($auxValue);
$emailService->setToEmail($auxEmail);
$emailService->setToName($auxName);
$subText = $this->configuration->getLanguage(
'remember_cart.subject', 'email'
);
$subject = "{$subText}{$client->getBrand()}?";
$emailService->setSubject($subject);
$emailService->setData([
"userName" => $auxName,
"text2" => "{$subText}?",
"status" => '',
"code" => '',
"moeda" => "R$",
"itens" => $itemsHtml,
"value" => $auxValue,
"btnLink" => $linkCheckout,
"urlDisableNot" => $linkStop,
"year" => date('Y')
]);
$emailService->setTemplateBody("remember_cart");
$emailService->send();
$itemsHtml = '';
$auxValue = null;
}
$todayTime = strtotime(date('Y-m-d H:i:s'));
$dateStart = strtotime($productOffer->getSaleDateStart());
$dateClose = strtotime($productOffer->getSaleDateClose());
if($todayTime > $dateClose || $todayTime < $dateStart){
continue;
}
$itemName = $product->getTitle();
if(!empty($itemName)){
$itemName = htmlentities($itemName);
$itemsHtml .= "
<tr style='margin:0px;border:1px solid rgb(238,238,238)'>
<td style='padding:5px 0px 5px 15px;border:1px solid rgb(238,238,238)'>
<p style='margin:0px;font-size:0.9em;color:rgb(102,102,102);line-height:1.2em'>{$itemName}</p>
</td>
</tr>";
}
#last
if(($key + 1) == count($carts)){
$auxValue = $numberUtil->currencyFormat($auxValue);
$emailService->setToEmail($auxEmail);
$emailService->setToName($auxName);
$subText = $this->configuration->getLanguage(
'remember_cart.subject', 'email'
);
$subject = "{$subText}{$client->getBrand()}?";
$emailService->setSubject($subject);
$emailService->setData([
"userName" => $auxName,
"text2" => "{$subText}?",
"status" => '',
"code" => '',
"moeda" => "R$",
"itens" => $itemsHtml,
"value" => $auxValue,
"btnLink" => $linkCheckout,
"urlDisableNot" => $linkStop,
"year" => date('Y')
]);
$emailService->setTemplateBody("remember_cart");
$emailService->send();
$itemsHtml = '';
}
$userWebhook = $this->em->getRepository(User::class)->getToWebhook($user);
//webhook
$dataObj = (object)[
"customer" => $userWebhook,
"products" => [
[
"id" => $product->getId(),
"offer_id" => $productOffer->getId(),
"name" => $product->getTitle(),
"original_price" => $productOffer->getPriceReal(),
"price" => $productOffer->getPriceDisplay(),
"coupon" => null,
"type" => $product->getType(),
"nfe" => "0"
]
],
];
$webhookService->addItemList(WebhookEnum::CART, $dataObj);
}
return;
}
public function deleteByUser(int $userId, $deleted)
{
$sql = "UPDATE EADPlataforma:Cart AS c
SET c.deleted = :deleted WHERE c.user = :userId";
$query = $this->em->createQuery($sql);
$query->setParameter('userId', $userId);
$query->setParameter('deleted', $deleted);
$query->execute();
return true;
}
}