<?php
namespace App\Entity;
use App\Service\TrackPodAPIService;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Mapping as ORM;
use SpecShaper\EncryptBundle\Annotations\Encrypted;
use App\Entity\FinancialTax;
use App\Entity\PickupLocations;
use App\Entity\CartProduct;
use App\Entity\City;
/**
* @ORM\Entity
* @ORM\Entity(repositoryClass="App\Repository\CartRepository")
*/
class Cart
{
/**
* @ORM\Id()
* @ORM\GeneratedValue()
* @ORM\Column(type="integer")
*/
private $id;
/**
* @ORM\Column(type="datetime")
*/
private $dateCreated;
/**
* @ORM\OneToMany(targetEntity="App\Entity\CartProduct", mappedBy="cart", orphanRemoval=true, cascade={"remove", "persist"})
*/
private $products;
/**
* @ORM\OneToMany(targetEntity="App\Entity\FinancialLog", mappedBy="cart", cascade={"remove"})
*/
private $financialLogs;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\UserShippingLocation", inversedBy="cartsShipped",cascade={"persist"})
* @ORM\JoinColumn(nullable=true)
*/
private $shippingAddress;
/**
* @ORM\Column(type="string", length=255, nullable=true)
* @Encrypted
*/
private $stripeToken;
/**
* @ORM\Column(type="text", nullable=true)
* @Encrypted
*/
private $stripeResponse;
/**
* @ORM\Column(type="boolean")
*/
private $isPaid = false;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="carts")
* @ORM\JoinColumn(nullable=true)
*/
private $user;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $solexOrderId;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $datePayment;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $shippingEstimationRaw;
/**
* @ORM\Column(type="float", nullable=true)
*/
private $shippingMaturinCost;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $shippingMaturinCarrierName;
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $shippingMaturinServiceName;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $shippingMaturinEstimatedDate;
/**
* @ORM\Column(type="float")
*/
private $pickingAndPackingFee = 0;
/**
* @ORM\Column(type="float")
*/
private $paymentFee = 0;
/**
* @ORM\Column(type="float")
*/
private $maturinFee = 0;
/**
* @ORM\Column(type="float")
*/
private $taxesProducts = 0;
/**
* @ORM\Column(type="float")
*/
private $taxesMaturin = 0;
/**
* @ORM\Column(type="float")
*/
private $taxesShippingMaturin = 0;
/**
* @ORM\Column(type="float")
*/
private $taxesShippingCompany = 0;
/**
* @ORM\Column(type="float")
*/
private $taxesPacking = 0;
/**
* @ORM\Column(type="string", length=50, nullable=true)
*/
private $shippingMaturinServiceId;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $solexOrderRaw;
/**
* @ORM\Column(type="array", nullable=true)
*/
private $maturinTrackingInfo = [];
/**
* @ORM\Column(type="string", length=255, nullable=true)
*/
private $orderNo;
/**
* @ORM\OneToMany(targetEntity="App\Entity\CustomOrder", mappedBy="fromCart")
*/
private $customOrders;
/**
* @ORM\OneToMany(targetEntity="App\Entity\MaturinOrder", mappedBy="fromCart")
*/
private $maturinOrders;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\CartCoupon", inversedBy="carts")
*/
private $usedCoupon;
/**
* @ORM\Column(type="boolean")
*/
private $isOnHold = false;
/**
* @ORM\Column(type="boolean")
*/
private $justInTimeEmailSent = false;
/**
* @ORM\Column(type="boolean")
*/
private $reminderSent = false;
/**
* @ORM\Column(type="object", nullable=true)
*/
private $rawDistributorBilling;
/**
* @ORM\OneToMany(targetEntity="App\Entity\RecurringOrder", mappedBy="cart",cascade={"persist"})
*/
private $recurringOrders;
/**
* @ORM\Column(type="array", nullable=true)
*/
private $taxesProductsCalculations = [];
/**
* @ORM\Column(type="array", nullable=true)
*/
private $taxesShippingMaturinCalculations = [];
/**
* @ORM\Column(type="array", nullable=true)
*/
private $taxesShippingCompanyCalculations = [];
/**
* @ORM\Column(type="array", nullable=true)
*/
private $taxesPackingCalculations = [];
/**
* @ORM\Column(type="float")
*/
private $amountSavedByCoupon = 0;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Invoice", inversedBy="carts")
*/
private $logisticInvoice;
/**
* @ORM\Column(type="boolean")
*/
private $shippingSignatureRequired = false;
/**
* @ORM\OneToMany(targetEntity="App\Entity\Subscription", mappedBy="fromCart")
*/
private $subscriptions;
/**
* @ORM\Column(type="boolean")
*/
private $signatureMandatory = false;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Subscription", inversedBy="mergeWithCarts")
*/
private $sendWithSubscription;
/**
* @ORM\Column(type="integer")
*/
private $extraPriorityPoints = 0;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $warehouseGroupId;
/**
* @ORM\ManyToOne(targetEntity="App\Entity\Subscription", inversedBy="renewalCarts")
*/
private $fromSubscription;
/**
* @ORM\Column(type="boolean")
*/
private $isRefunded = false;
/**
* @ORM\Column(type="object", nullable=true)
*/
private $refundStripeResponse;
/**
* @ORM\Column(type="text", nullable=true)
*/
private $noteFromBuyer;
/**
* @ORM\Column(type="boolean", nullable=true)
*/
private $isBulkOrder = false;
/**
* @ORM\Column(type="text",nullable=true)
*/
private $trackLink;
/**
* @ORM\Column(type="integer", nullable=true)
*/
private $trackPodStatusId;
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $deliveryChoiceDate;
/**
* @ORM\Column(type="boolean")
*/
private $preOrder;
/**
* @ORM\Column(type="boolean")
*/
private $preOrderNow;
protected $em;
public function __construct()
{
$this->products = new ArrayCollection();
$this->dateCreated = new \dateTime();
$this->financialLogs = new ArrayCollection();
$this->customOrders = new ArrayCollection();
$this->maturinOrders = new ArrayCollection();
$this->recurringOrders = new ArrayCollection();
$this->subscriptions = new ArrayCollection();
}
/**
* @ORM\PostLoad
* @ORM\PostPersist
*/
public function fetchEntityManager(LifecycleEventArgs $args)
{
$this->em = $args->getEntityManager();
}
public function setEntityManager($em)
{
$this->em = $em;
}
public function getId(): ?int
{
return $this->id;
}
public function setId(?int $id)
{
$this->id = $id;
return $this;
}
public function getDateCreated(): ?\DateTimeInterface
{
return $this->dateCreated;
}
public function setDateCreated(\DateTimeInterface $dateCreated): self
{
$this->dateCreated = $dateCreated;
return $this;
}
/*
* New format for total Product
*/
public function getTotalProducts($applyCoupon = true, $applyFees = true)
{
return $this->getSubTotalToPay($applyCoupon, $applyFees);
}
public function getTotalProductsMaturinDeliveryOnly($applyCoupon = true, $applyFees = true)
{
return $this->getSubTotalToPay($applyCoupon, $applyFees, true);
}
public function getTotalProductsWithoutHiddenCost()
{
$total = $this->getTotalProducts(false, false);
return $total - $this->newRebateEstimate();
}
public function getTotalProductsWithoutCouponOrFee()
{
return $this->getTotalProducts(false, false);
}
public function getTotalProductsTaxable(): ?float
{
$total = 0;
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->isTaxable()) {
$total += $p->getTotal();
}
}
return $total;
}
public function getHasMaturinDeliveryProducts() {
foreach ($this->getProducts() as $p) {
$product = $p->getProduct();
if ($product->getDeliveryType() == 0) {
return true;
}
}
return false;
}
/*
* Return the subtotal of the cart
*/
public function getSubTotalToPay($applyCoupon = true, $applyFees = true, $ignoreNotMaturinDelivery = false)
{
$total = 0;
foreach ($this->getProducts() as $p) {
if ($ignoreNotMaturinDelivery) {
$product = $p->getProduct();
if ($product->getDeliveryType() != 0) {
continue;
}
}
$total += $p->getTotal($applyCoupon);
}
if ($applyFees)
$total += $this->getExtraShippingFeesTotal();
return round($total, 2);
}
/**
* @return Collection|CartProduct[]
*/
public function getProducts(): Collection
{
return $this->products;
}
public function addProduct(CartProduct $product): self
{
if (!$this->products->contains($product)) {
//As Interaction with cart was done, we can send reminder again
$this->setReminderSent(false);
//Reset the calculations
$this->resetCalculations();
$this->products[] = $product;
$product->setCart($this);
}
return $this;
}
public function removeProduct(CartProduct $product): self
{
if ($this->products->contains($product)) {
//Put the reminder back on
$this->setReminderSent(false);
//Reset the calculations
$this->resetCalculations();
$this->products->removeElement($product);
// set the owning side to null (unless already changed)
if ($product->getCart() === $this) {
//As Interaction with cart was done, we can send reminder again
$product->setCart(null);
}
}
return $this;
}
/**
* @return Collection|FinancialLog[]
*/
public function getFinancialLogs(): Collection
{
return $this->financialLogs;
}
public function addFinancialLog(FinancialLog $financialLog): self
{
if (!$this->financialLogs->contains($financialLog)) {
$this->financialLogs[] = $financialLog;
$financialLog->setCart($this);
}
return $this;
}
public function removeFinancialLog(FinancialLog $financialLog): self
{
if ($this->financialLogs->contains($financialLog)) {
$this->financialLogs->removeElement($financialLog);
// set the owning side to null (unless already changed)
if ($financialLog->getCart() === $this) {
$financialLog->setCart(null);
}
}
return $this;
}
public function __toString()
{
if ($this->getOrderNo())
return $this->getOrderNo();
else
return 'Cart Id' . $this->getId();
}
public function getShippingAddress(): ?UserShippingLocation
{
return $this->shippingAddress;
}
public function setShippingAddress(?UserShippingLocation $shippingAddress): self
{
$this->shippingAddress = $shippingAddress;
return $this;
}
public function getStripeToken(): ?string
{
return $this->stripeToken;
}
public function setStripeToken(?string $stripeToken): self
{
$this->stripeToken = $stripeToken;
return $this;
}
public function getStripeResponse(): ?string
{
return $this->stripeResponse;
}
public function setStripeResponse(?string $stripeResponse): self
{
$this->stripeResponse = $stripeResponse;
return $this;
}
public function isPaid(): ?bool
{
return $this->isPaid;
}
public function getIsPaid(): ?bool
{
return $this->isPaid;
}
public function setIsPaid(bool $isPaid): self
{
$this->isPaid = $isPaid;
return $this;
}
public function hasCombinedShipping()
{
$maturin = false;
$company = false;
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->isShippedByMaturin())
$maturin = true;
else
$company = true;
}
if ($maturin == $company)
return true;
else
return false;
}
public function hasCompanyShipping()
{
foreach ($this->getProducts() as $p) {
if (!$p->getProduct()->isShippedByMaturin())
return true;
}
return false;
}
public function hasMaturinShipping()
{
foreach ($this->getProducts() as $p) {
if (!$p->getIsAPickup() && $p->getProduct()->isShippedByMaturin()) {
return true;
}
}
return false;
}
public function hasJIT()
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getIsJustInTime())
return true;
}
return false;
}
public function hasPickup()
{
foreach ($this->getProducts() as $p) {
if ($p->getIsAPickup())
return true;
}
return false;
}
public function getPickupLocationId()
{
foreach ($this->getProducts() as $p) {
if ($p->getPickupLocationId()) {
return $p->getPickupLocationId();
}
}
return false;
}
public function hasPackup()
{
foreach ($this->getProducts() as $p) {
if ($p->getIsAPickup() && $p->getCompanyDeliveryMethod() && $p->getCompanyDeliveryMethod()->getWithPacking())
return true;
}
return false;
}
public function getTotalShipping(): ?float
{
// + $this->getExtraShippingFeesTotal()
return $this->getShippingMaturinCost() + $this->getShippingCompanyCost();
}
public function getUser(): ?User
{
return $this->user;
}
public function setUser(?User $user): self
{
$this->user = $user;
return $this;
}
public function isShipped(): ?float
{
foreach ($this->getProducts() as $p) {
if (!$p->getIsShipped())
return false;
}
return true;
}
public function getIsShippedOrValidated()
{
foreach ($this->getProducts() as $p) {
if (!$p->getIsShippedOrEmpty())
return false;
}
return true;
}
public function getSolexOrderId(): ?string
{
return $this->solexOrderId;
}
public function setSolexOrderId(?string $solexOrderId): self
{
$this->solexOrderId = $solexOrderId;
return $this;
}
public function getDatePayment(): ?\DateTimeInterface
{
return $this->datePayment;
}
public function setDatePayment(?\DateTimeInterface $datePayment): self
{
$this->datePayment = $datePayment;
return $this;
}
public function getShippingEstimationRaw(): ?string
{
return $this->shippingEstimationRaw;
}
public function setShippingEstimationRaw(?string $shippingEstimationRaw): self
{
$this->shippingEstimationRaw = $shippingEstimationRaw;
return $this;
}
/*
* This one is a little tricky with a few hacks
* Main reasons is some order get free delivery reaching a certain point
* Creating those issues
*/
public function getShippingCompanyCost($companyId = false): ?float
{
$companyShippingCost = array();
$companyProductTotal = array();
foreach ($this->getProducts() as $p) {
$cId = $p->getProduct()->getCompany()->getId();
if (empty($companyShippingCost[$cId])) {
$companyShippingCost[$cId] = $p->getShippingCompanyCost();
$companyProductTotal[$cId] = $p->getTotal(false);
} else {
$companyProductTotal[$cId] += $p->getTotal(false);
$test = $p->getShippingCompanyCost(true, $companyProductTotal[$cId]);
if ($test >= 0) {
$companyShippingCost[$cId] += $test;
} else {
$companyShippingCost[$cId] = 0;
}
}
}
$total = 0;
foreach ($companyShippingCost as $c) {
$total += $c;
}
if ($total < 0)
return 0;
if ($companyId && isset($companyShippingCost[$companyId]))
return $companyShippingCost[$companyId];
else
return $total;
}
public function getShippingMaturinCostWithoutRebateOrFee()
{
return $this->shippingMaturinCost;
}
public function getShippingMaturinCost($forceZero = true)
{
$user = $this->getUser();
// $cost = $this->shippingMaturinCost - $this->newRebateEstimate();
$cost = $this->shippingMaturinCost;
if ($this->newRebateEstimate() > 0){
$cost -= $this->newRebateEstimate();
}
else{
$cost += $this->newRebateEstimate();
}
$route = $this->getRoutes();
if(!empty($route) && strpos($route,"Puro Frais") !== false){
}else{
// if($user->getUserSubscriptionMaturin() == true){
// $cost = 0;
// }
$cost += $this->getExtraShippingFeesTotal();
}
if ($cost < 1 && $forceZero)
$cost = 0;
return $cost;
}
public function setShippingMaturinCost(?float $shippingMaturinCost): self
{
$this->shippingMaturinCost = $shippingMaturinCost;
return $this;
}
public function getShippingMaturinCarrierName(): ?string
{
return $this->shippingMaturinCarrierName;
}
public function setShippingMaturinCarrierName(?string $shippingMaturinCarrierName): self
{
$this->shippingMaturinCarrierName = $shippingMaturinCarrierName;
return $this;
}
public function getShippingMaturinServiceName(): ?string
{
return $this->shippingMaturinServiceName;
}
public function setShippingMaturinServiceName(?string $shippingMaturinServiceName): self
{
$this->shippingMaturinServiceName = $shippingMaturinServiceName;
return $this;
}
public function getShippingMaturinEstimatedDate(): ?\DateTimeInterface
{
return $this->shippingMaturinEstimatedDate;
}
public function setShippingMaturinEstimatedDate(?\DateTimeInterface $shippingMaturinEstimatedDate): self
{
$this->shippingMaturinEstimatedDate = $shippingMaturinEstimatedDate;
return $this;
}
public function getPickingAndPackingFee(): ?float
{
return $this->pickingAndPackingFee;
}
public function setPickingAndPackingFee(float $pickingAndPackingFee): self
{
$this->pickingAndPackingFee = $pickingAndPackingFee;
return $this;
}
public function getPaymentFee(): ?float
{
return $this->paymentFee;
}
public function setPaymentFee(float $paymentFee): self
{
$this->paymentFee = $paymentFee;
return $this;
}
public function getMaturinFee(): ?float
{
return $this->maturinFee;
}
public function setMaturinFee(float $maturinFee): self
{
$this->maturinFee = $maturinFee;
return $this;
}
public function getTaxesProducts(): ?float
{
return $this->taxesProducts;
}
public function setTaxesProducts(float $taxesProducts): self
{
$this->taxesProducts = $taxesProducts;
return $this;
}
public function getTaxesMaturin(): ?float
{
return $this->taxesMaturin;
}
public function setTaxesMaturin(float $taxesMaturin): self
{
$this->taxesMaturin = $taxesMaturin;
return $this;
}
public function getTaxesShipping(): ?float
{
return $this->getTaxesShippingMaturin() + $this->getTaxesShippingCompany();
}
public function getTaxes()
{
return round($this->getTaxesShipping() + $this->getTaxesProducts() + $this->getTaxesPacking(), 2);
}
public function getTaxesShippingMaturin(): ?float
{
return $this->taxesShippingMaturin;
}
public function setTaxesShippingMaturin(float $taxesShippingMaturin): self
{
$this->taxesShippingMaturin = $taxesShippingMaturin;
return $this;
}
public function getTaxesPacking(): ?float
{
return $this->taxesPacking;
}
public function setTaxesPacking(float $taxesPacking): self
{
$this->taxesPacking = $taxesPacking;
return $this;
}
public function getTaxesShippingCompany(): ?float
{
return $this->taxesShippingCompany;
}
public function setTaxesShippingCompany(float $taxesShippingCompany): self
{
$this->taxesShippingCompany = $taxesShippingCompany;
return $this;
}
public function getConsignedCost()
{
$cost = 0;
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->isConsigned()) {
$cost += (($p->getProduct()->getConsignedCost() * $p->getProduct()->getQtyPerUnit()) * $p->getQuantity());
}
}
return $cost;
}
public function getCouponSavings()
{
$total = 0;
if ($this->getUsedCoupon()) {
if ($this->getUsedCoupon()->getIsGiftCertificate()) {
if ($this->getTotal(false) > $this->getUsedCoupon()->getAmount())
return $this->getUsedCoupon()->getAmount();
else
return $this->getTotal(false);
} else {
foreach ($this->getProducts() as $p) {
$total += $p->getCouponSavings();
}
}
}
return $total;
}
public function setTotal($total)
{
// todo ???
}
/**
* Compute total packing fee for this cart
* TODO unit test
* @return float total fee
*/
public function getPackingCost($packing = true): float
{
$totalPackingFee = 0.0;
// apply fixed packing fee for each associations
$fixedFeedAppliedOnAssociations = [];
foreach ($this->getProducts() as $cartProduct) {
// apply fee for pickup product purchased while browsing an association
if (
$cartProduct->getIsAPickup()
&& ($association = $cartProduct->getAddedWhenBeingInAssociation()) !== null
&& (($packing && $cartProduct->isWithPacking() || !$packing))
) {
// association's fixed packing fee has to be applyed only once (per association)
if (!in_array($association->getId(), $fixedFeedAppliedOnAssociations)) {
$fixedFeedAppliedOnAssociations[] = $association->getId();
// check if asso has a fixed packing fee
$fee = $association->getVariableValueByCodeName('orders.packingFixedFee');
if ($fee !== null) {
// apply fee
$totalPackingFee += floatval($fee);
}
}
}
}
return $totalPackingFee;
}
public function getTotal($applyCoupon = true)
{
$total =
//($this->getTotalProducts() - $this->getCouponSavings())+
$this->getTotalProducts() +
$this->getConsignedCost() +
$this->getTotalShipping() +
$this->getPickingAndPackingFee() +
$this->getTaxes();
if ($applyCoupon && !empty($this->getUsedCoupon()) && $this->getUsedCoupon()->getIsGiftCertificate()) {
//For Archive
if ($this->getAmountSavedByCoupon() > 0)
$total = $total - $this->getAmountSavedByCoupon();
else {
if ($this->getTotal(false) > $this->getUsedCoupon()->getAmount()) {
$total = $total - $this->getUsedCoupon()->getAmount();
} else {
$total = 0;
}
}
}
return round($total, 2);
}
public function getRebateOnMaturinShipping()
{
$total = 0;
foreach ($this->getProducts() as $p) {
$total += $p->getRebateOnMaturinShipping();
}
return $total;
}
public function getShippingMaturinServiceId(): ?string
{
return $this->shippingMaturinServiceId;
}
public function setShippingMaturinServiceId(?string $shippingMaturinServiceId): self
{
$this->shippingMaturinServiceId = $shippingMaturinServiceId;
return $this;
}
public function getSolexOrderRaw(): ?string
{
return $this->solexOrderRaw;
}
public function setSolexOrderRaw(?string $solexOrderRaw): self
{
$this->solexOrderRaw = $solexOrderRaw;
return $this;
}
public function findInvoicingOnlyProductById($productId) {
$cartProduct = $this->em->getRepository(CartProduct::class)->findOneBy([
"product"=>$productId,
"invoicingCart"=>$this->id,
"forInvoicingOnly"=>1
]);
if ($cartProduct) {
return $cartProduct;
} else {
return false;
}
}
public function findProductById($productId)
{
foreach ($this->getProducts() as $p) {
//@FIX this is ugly, a work around for Kit product
//But we assume if it's one of the kit, it should be the kit
//It's called from Distributor to update tracking and price mainly
if ($p->getProduct()->getIsBoxOfProducts()) {
foreach ($p->getProduct()->getProductsInBox() as $mp) {
if ($mp->getProduct()->getId() == $productId)
return $p;
}
} else {
if ($p->getProduct()->getId() == $productId)
return $p;
}
}
return false;
}
public function findProductByDistributorId($productId)
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getSolexId() == $productId)
return $p;
}
return false;
}
public function getMaturinTrackingInfo(): ?array
{
return $this->maturinTrackingInfo;
}
public function setMaturinTrackingInfo(?array $maturinTrackingInfo): self
{
$this->maturinTrackingInfo = $maturinTrackingInfo;
return $this;
}
public function getOrderNo(): ?string
{
if (!empty($this->orderNo))
return strToUpper($this->orderNo);
else
return $this->orderNo;
}
public function setOrderNo(?string $orderNo): self
{
$this->orderNo = $orderNo;
return $this;
}
public function getAllTrackings()
{
$done = array();
$t = array();
foreach ($this->getMaturinOrders() as $p) {
if (!empty($p->getCarrierTrackings())) {
if (empty($done[$p->getCarrierTrackings()])) {
$t[] = array(
'carrier' => $p->getCarrierName(),
'tracking' => $p->getCarrierTrackings()
);
$done[$p->getCarrierTrackings()] = true;
}
}
}
foreach ($this->getCustomOrders() as $p) {
if (!empty($p->getCarrierTrackings())) {
if (empty($done[$p->getCarrierTrackings()])) {
$t[] = array(
'carrier' => $p->getCarrierName(),
'tracking' => $p->getCarrierTrackings()
);
$done[$p->getCarrierTrackings()] = true;
}
}
}
return $t;
}
public function getExtraShippingFeesTotal(): float
{
$total = 0;
// $user = $this->getUser();
// if($user && $user->getUserSubscriptionMaturin() != true){
foreach ($this->getExtraShippingFeesDetails() as $f) {
$total += $f['fee'];
}
// }else{
// $total = 0;
// }
return $total;
}
public function getExtraShippingFeesDetails()
{
$fees = array();
if ($this->hasMaturinShipping() && !$this->hasPromotionalProduct()) {
//Add 2.5 if order between 25 and 50
$subTotal = $this->getTotalProducts(false, false);
if ($subTotal < 50) {
$fees[] = array(
'label' => "Frais d'emballage sur commande de moins de 50$",
'fee' => 2.5
);
}
}
$route = $this->getRoutes();
if($this->hasMaturinShipping()){
if(!empty($route) && strpos($route,"Puro Frais") !== false){
$fee = array(
'label' => "Frais d'emballage sur commande avec livraison puro frais",
'fee' => 2.5
);
array_push($fees,$fee);
}
}
// no extra fees for HRI orders
$user = $this->getUser();
if ($user) {
if ($user->getIsHri()) {
return array();
}
}
return $fees;
}
/**
* @return Collection|CustomOrder[]
*/
public function getCustomOrders(): Collection
{
return $this->customOrders;
}
public function addCustomOrder(CustomOrder $customOrder): self
{
if (!$this->customOrders->contains($customOrder)) {
$this->customOrders[] = $customOrder;
$customOrder->setFromCart($this);
}
return $this;
}
public function removeCustomOrder(CustomOrder $customOrder): self
{
if ($this->customOrders->contains($customOrder)) {
$this->customOrders->removeElement($customOrder);
// set the owning side to null (unless already changed)
if ($customOrder->getFromCart() === $this) {
$customOrder->setFromCart(null);
}
}
return $this;
}
/**
* @return Collection|MaturinOrder[]
*/
public function getMaturinOrders(): Collection
{
return $this->maturinOrders;
}
public function addMaturinOrder(MaturinOrder $maturinOrder): self
{
if (!$this->maturinOrders->contains($maturinOrder)) {
$this->maturinOrders[] = $maturinOrder;
$maturinOrder->setFromCart($this);
}
return $this;
}
public function removeMaturinOrder(MaturinOrder $maturinOrder): self
{
if ($this->maturinOrders->contains($maturinOrder)) {
$this->maturinOrders->removeElement($maturinOrder);
// set the owning side to null (unless already changed)
if ($maturinOrder->getFromCart() === $this) {
$maturinOrder->setFromCart(null);
}
}
return $this;
}
public function getUsedCoupon(): ?CartCoupon
{
return $this->usedCoupon;
}
public function setUsedCoupon(?CartCoupon $usedCoupon): self
{
$this->usedCoupon = $usedCoupon;
return $this;
}
public function getIsOnHold(): ?bool
{
return $this->isOnHold;
}
public function setIsOnHold(bool $isOnHold): self
{
$this->isOnHold = $isOnHold;
return $this;
}
public function containJustInTimeProduct(): ?bool
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getIsJustInTime() && !$this->getIsAPickup()) {
return true;
}
}
return false;
}
public function getJustInTimeEmailSent(): ?bool
{
return $this->justInTimeEmailSent;
}
public function setJustInTimeEmailSent(bool $justInTimeEmailSent): self
{
$this->justInTimeEmailSent = $justInTimeEmailSent;
return $this;
}
public function getReminderSent(): ?bool
{
return $this->reminderSent;
}
public function setReminderSent(bool $reminderSent): self
{
$this->reminderSent = $reminderSent;
return $this;
}
/*
* Reset all the calculations variables from the cart and products
*/
public function resetCalculations(): self
{
$this->setIsPaid(false);
$this->setOrderNo(null);
$this->setStripeToken(null);
$this->setStripeResponse(null);
$this->setOrderNo(null);
$this->setMaturinFee(0);
$this->setPaymentFee(0);
$this->setTaxesProducts(0);
$this->setTaxesMaturin(0);
$this->setPickingAndPackingFee($this->getPackingCost());
$this->setShippingMaturinCost(0);
$this->setShippingEstimationRaw('');
$this->setShippingMaturinCarrierName(null);
$this->setShippingMaturinServiceName(null);
$this->setShippingMaturinServiceId(null);
$this->setTaxesShippingMaturin(0);
$this->setTaxesShippingCompany(0);
foreach ($this->getProducts() as $p) {
$p->setPricePaidProduct(null);
}
return $this;
}
public function setRawDistributorBillingInJson($raw)
{
}
public function getRawDistributorBillingInJson(): ?string
{
return json_encode($this->rawDistributorBilling);
}
public function getRawDistributorBilling()
{
return $this->rawDistributorBilling;
}
public function setRawDistributorBilling($rawDistributorBilling): self
{
$this->rawDistributorBilling = $rawDistributorBilling;
return $this;
}
public function getTotalShippingFeesFor($companyId): float
{
$total = 0;
if (empty($this->getRawDistributorBilling()))
return 0;
foreach ($this->getRawDistributorBilling()->costSplit as $b) {
if (preg_replace("/[^0-9]/", "", $b->vendorIdentifier) == $companyId) {
foreach ($b->processingFees as $f) {
$total += $f->qtyFee * $f->amountFee;
}
break;
}
}
return round($total, 2);
}
public function __clone()
{
if ($this->id) {
$this->setId(null);
$this->setUsedCoupon(null);
$this->resetCalculations();
$this->products = clone $this->products;
}
}
/*
* Return true if all item in the cart has Maturin Free Shipping
* used mostly for the Shipping Estimate
*/
public function getIsFreeMaturinShipping()
{
foreach ($this->getProducts() as $p) {
if (!$p->getProduct()->getHasFreeMaturinShipping())
return false;
}
return true;
}
/**
* @return Collection|RecurringOrder[]
*/
public function getRecurringOrders(): Collection
{
return $this->recurringOrders;
}
public function addRecurringOrder(RecurringOrder $recurringOrder): self
{
if (!$this->recurringOrders->contains($recurringOrder)) {
$this->recurringOrders[] = $recurringOrder;
$recurringOrder->setCart($this);
}
return $this;
}
public function removeRecurringOrder(RecurringOrder $recurringOrder): self
{
if ($this->recurringOrders->contains($recurringOrder)) {
$this->recurringOrders->removeElement($recurringOrder);
// set the owning side to null (unless already changed)
if ($recurringOrder->getCart() === $this) {
$recurringOrder->setCart(null);
}
}
return $this;
}
/*
* Tell if contain a promotional product
*/
public function hasPromotionalProduct()
{
//We rely on multiple product for now
//as only Maturin promotional have this for now
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getHasMultipleProducts())
return true;
}
return false;
}
/*
* For Admin export only
*/
public function getExportProducts()
{
$products = array();
foreach ($this->getProducts() as $p) {
$products[] = $p->getQuantity() . 'x ' . $p->getProduct()->getNameWithDetails();
}
return implode(', ', $products);
}
public function getIsSentToWarehouse(): bool
{
if (!empty($this->getSolexOrderRaw()))
return true;
return false;
}
public function getTaxesProductsCalculations(): ?array
{
return $this->taxesProductsCalculations;
}
public function setTaxesProductsCalculations(?array $taxesProductsCalculations): self
{
$this->taxesProductsCalculations = $taxesProductsCalculations;
return $this;
}
public function getTaxesShippingMaturinCalculations(): ?array
{
return $this->taxesShippingMaturinCalculations;
}
public function setTaxesShippingMaturinCalculations(array $taxesShippingMaturinCalculations): self
{
$this->taxesShippingMaturinCalculations = $taxesShippingMaturinCalculations;
return $this;
}
public function getTaxesShippingCompanyCalculations(): ?array
{
return $this->taxesShippingCompanyCalculations;
}
public function setTaxesShippingCompanyCalculations(?array $taxesShippingCompanyCalculations): self
{
$this->taxesShippingCompanyCalculations = $taxesShippingCompanyCalculations;
return $this;
}
public function getTaxesPackingCalculations(): ?array
{
return $this->taxesPackingCalculations;
}
public function setTaxesPackingCalculations(?array $taxesPackingCalculations): self
{
$this->taxesPackingCalculations = $taxesPackingCalculations;
return $this;
}
public function getAllTaxes(): ?array
{
$taxes = array();
$raw = $this->getTaxesProductsCalculations();
if (!empty($raw)) {
if (isset($raw['details'])) {
foreach ($raw['details'] as $d) {
if (!empty($taxes[$d['taxName']]))
$taxes[$d['taxName']] += $d['amount'];
else
$taxes[$d['taxName']] = $d['amount'];
}
}
}
$raw = $this->getTaxesShippingMaturinCalculations();
if (!empty($raw)) {
if (isset($raw['details'])) {
foreach ($raw['details'] as $d) {
if (!empty($taxes[$d['taxName']]))
$taxes[$d['taxName']] += $d['amount'];
else
$taxes[$d['taxName']] = $d['amount'];
}
}
}
$raw = $this->getTaxesShippingCompanyCalculations();
if (!empty($raw)) {
if (isset($raw['details'])) {
foreach ($raw['details'] as $d) {
if (!empty($taxes[$d['taxName']]))
$taxes[$d['taxName']] += $d['amount'];
else
$taxes[$d['taxName']] = $d['amount'];
}
}
}
$raw = $this->getTaxesPackingCalculations();
if (!empty($raw)) {
if (isset($raw['details'])) {
foreach ($raw['details'] as $d) {
if (!empty($taxes[$d['taxName']]))
$taxes[$d['taxName']] += $d['amount'];
else
$taxes[$d['taxName']] = $d['amount'];
}
}
}
$return = array();
foreach ($taxes as $k => $t) {
$return[] = [
'name' => $k,
'total' => $t
];
}
return $return;
}
/*
* For export mainly
*/
function getFirstTaxProductName()
{
try {
if ($this->getTaxesProductsCalculations()) {
$first = current($this->getTaxesProductsCalculations()['details']);
if (isset($first['taxName'])) {
return $first['taxName'];
}
}
} catch (\Exception $e) {
// pass
}
return '';
}
function getFirstTaxProductAmount()
{
try {
if ($this->getTaxesProductsCalculations()) {
$first = current($this->getTaxesProductsCalculations()['details']);
if (isset($first['amount'])) {
return $first['amount'];
}
}
} catch (\Exception $e) {
// pass
}
return '';
}
function getSecondTaxProductName()
{
try {
if ($this->getTaxesProductsCalculations()) {
$first = end($this->getTaxesProductsCalculations()['details']);
if (isset($first['taxName'])) {
return $first['taxName'];
}
}
} catch (\Exception $e) {
// pass
}
return '';
}
function getSecondTaxProductAmount()
{
try {
if ($this->getTaxesProductsCalculations()) {
$first = end($this->getTaxesProductsCalculations()['details']);
if (isset($first['amount'])) {
return $first['amount'];
}
}
} catch (\Exception $e) {
// pass
}
return '';
}
function getFirstTaxServiceName()
{
try {
if ($this->getTaxesShippingMaturinCalculations()) {
$first = current($this->getTaxesShippingMaturinCalculations()['details']);
if (isset($first['taxName'])) {
return $first['taxName'];
}
}
} catch (\Exception $e) {
// pass
}
return '';
}
//this is for export
function getHasJit(): ?bool
{
if ($this->getProducts()) {
foreach ($this->getProducts() as $p) {
if (strpos($p, 'JIT') != false) {
return true;
}
}
}
return false;
}
function getRoutes()
{
$shippingAddress = $this->shippingAddress;
$routesToSend = "";
if ($shippingAddress) {
$routesToSend = $shippingAddress->getRoutes();
}
$routesToSend= $this->parseRoute($routesToSend);
return $routesToSend;
}
/*Return a string without charSequence "Puro Sec"*/
public function parseRoute($routeToSend){
$stringToRemove= "Puro Sec";
$newStr =str_replace ($stringToRemove,"",$routeToSend);
return $newStr;
}
function getFirstTaxServiceAmount()
{
try {
if ($this->getTaxesShippingMaturinCalculations()) {
$first = current($this->getTaxesShippingMaturinCalculations()['details']);
if (isset($first['amount'])) {
return $first['amount'];
}
}
} catch (\Exception $e) {
}
return '';
}
function getSecondTaxServiceName()
{
try {
if ($this->getTaxesShippingMaturinCalculations()) {
$first = end($this->getTaxesShippingMaturinCalculations()['details']);
if (isset($first['taxName'])) {
return $first['taxName'];
}
}
} catch (\Exception $e) {
}
return '';
}
function getSecondTaxServiceAmount()
{
try {
if ($this->getTaxesShippingMaturinCalculations()) {
$first = end($this->getTaxesShippingMaturinCalculations()['details']);
if (isset($first['amount'])) {
return $first['amount'];
}
}
} catch (\Exception $e) {
}
return '';
}
public function getAmountSavedByCoupon(): ?float
{
return $this->amountSavedByCoupon;
}
public function setAmountSavedByCoupon(float $amountSavedByCoupon): self
{
$this->amountSavedByCoupon = $amountSavedByCoupon;
return $this;
}
public function getLogisticInvoice(): ?Invoice
{
return $this->logisticInvoice;
}
public function setLogisticInvoice(?Invoice $logisticInvoice): self
{
$this->logisticInvoice = $logisticInvoice;
return $this;
}
public function getTotalLogisticFees()
{
$total = 0;
$fees = $this->getRawDistributorBilling();
if ($fees) {
$total += $fees->processingAmount;
}
$total += $this->getShippingMaturinCostWithoutRebateOrFee();
return $total;
}
public function getDateShippedFormated($returnObject = false)
{
if ($this->getShippingEstimationRaw()) {
$s = json_decode($this->getShippingEstimationRaw());
$estimates = $s->estimates;
$rawDate = current($estimates);
$date = new \DateTime($rawDate->estimatedDate);
} else {
$date = $this->getDatePayment();
}
if ($returnObject)
return $date;
else
return $date->format('d/m/Y');
}
public function getShippingSignatureRequired(): ?bool
{
return $this->shippingSignatureRequired;
}
public function setShippingSignatureRequired(bool $shippingSignatureRequired): self
{
$this->shippingSignatureRequired = $shippingSignatureRequired;
return $this;
}
/*
* Return the total of different shipment that will occur with this cart
*/
public function getTotalOfShipment()
{
$box = 0;
$maturinBox = 0;
$producer = array();
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->isShippedByMaturin())
$maturinBox = 1;
else {
$cId = $p->getProduct()->getCompany()->getId();
if (empty($producer[$cId])) {
$box++;
$producer[$cId] = $box;
}
}
}
return $box + $maturinBox;
}
/*
* Return boolean if contain maturin's product
*/
public function getHasMaturinShipping()
{
return $this->hasMaturinShipping();
}
/*
* return boolean if contain Custom product
*/
public function getHasCustomShipping()
{
foreach ($this->getProducts() as $p) {
if (!$p->getIsAPickup() && !$p->getProduct()->isShippedByMaturin())
return true;
}
return false;
}
/*
* Used in the invoicing to help find the product inside a multiple product deal one
*/
public function findDealWithProduct($product)
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getIsBoxOfProducts()) {
foreach ($p->getProduct()->getProductsInBox() as $b) {
if ($b->getProduct() == $product) {
return $b;
}
}
}
}
}
/**
* @return Collection|Subscription[]
*/
public function getSubscriptions(): Collection
{
return $this->subscriptions;
}
public function addSubscription(Subscription $subscription): self
{
if (!$this->subscriptions->contains($subscription)) {
$this->subscriptions[] = $subscription;
$subscription->setFromCart($this);
}
return $this;
}
public function removeSubscription(Subscription $subscription): self
{
if ($this->subscriptions->contains($subscription)) {
$this->subscriptions->removeElement($subscription);
// set the owning side to null (unless already changed)
if ($subscription->getFromCart() === $this) {
$subscription->setFromCart(null);
}
}
return $this;
}
public function getSignatureMandatory(): ?bool
{
return $this->signatureMandatory;
}
public function setSignatureMandatory(bool $signatureMandatory): self
{
$this->signatureMandatory = $signatureMandatory;
return $this;
}
public function getSendWithSubscription(): ?Subscription
{
return $this->sendWithSubscription;
}
public function setSendWithSubscription(?Subscription $sendWithSubscription): self
{
$this->sendWithSubscription = $sendWithSubscription;
return $this;
}
public function hasFreshProduct()
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getConservation() && $p->getProduct()->getConservation()->getId() == 5)
return true;
}
return false;
}
public function hasFroozenProduct()
{
foreach ($this->getProducts() as $p) {
if ($p->getProduct()->getConservation() && $p->getProduct()->getConservation()->getId() == 6)
return true;
}
return false;
}
public function getPriority(): int
{
$pts = 0;
if ($this->hasFreshProduct())
$pts += 10;
if ($this->hasFroozenProduct())
$pts += 10;
if ($this->getSubscriptions()->count() > 0)
$pts += 10;
if ($this->getExtraPriorityPoints())
$pts += $this->getExtraPriorityPoints();
if ($this->getShippingAddress()) {
$validZipCode = ['H1A', 'H1B', 'H1C', 'H1E', 'H1G', 'H1H', 'H1J', 'H1K', 'H1L', 'H1M', 'H1N', 'H1P', 'H1R', 'H1S', 'H1T', 'H1V', 'H1W', 'H1X', 'H1Y', 'H1Z', 'H2A', 'H2B', 'H2C', 'H2E', 'H2G', 'H2H', 'H2J', 'H2K', 'H2L', 'H2M', 'H2N', 'H2P', 'H2R', 'H2S', 'H2T', 'H2V', 'H2W', 'H2X', 'H2Y', 'H2Z', 'H3A', 'H3B', 'H3C', 'H3E', 'H3G', 'H3H', 'H3J', 'H3K', 'H3L', 'H3M', 'H3N', 'H3P', 'H3R', 'H3S', 'H3T', 'H3V', 'H3W', 'H3X', 'H3Y', 'H3Z', 'H4A', 'H4B', 'H4C', 'H4E', 'H4G', 'H4H', 'H4J', 'H4K', 'H4L', 'H4M', 'H4N', 'H4P', 'H4R', 'H4S', 'H4T', 'H4V', 'H4W', 'H4X', 'H4Y', 'H4Z', 'H5A', 'H5B', 'H7A', 'H7B', 'H7C', 'H7E', 'H7G', 'H7H', 'H7K', 'H7L', 'H7M', 'H7N', 'H7P', 'H7R', 'H7S', 'H7T', 'H7V', 'H7W', 'H7X', 'H7Y', 'H8N', 'H8P', 'H8R', 'H8S', 'H8T', 'H8Y', 'H8Z', 'H9A', 'H9B', 'H9C', 'H9E', 'H9G', 'H9H', 'H9J', 'H9K', 'H9P', 'H9R', 'H9S', 'H9W', 'J3Y', 'J3Z', 'J4B', 'J4G', 'J4H', 'J4J', 'J4K', 'J4L', 'J4M', 'J4N', 'J4P', 'J4R', 'J4S', 'J4T', 'J4V', 'J4W', 'J4X', 'J4Y', 'J4Z'];
$currentZip = strtoupper(substr($this->getShippingAddress()->getZipCode(), 0, 3));
//Not courrier plus hurry!
if (!in_array($currentZip, $validZipCode)) {
$pts += 10;
} else {
if ($pts > 0)
$pts = 1;
}
}
return $pts;
}
public function getExtraPriorityPoints(): ?int
{
return $this->extraPriorityPoints;
}
public function setExtraPriorityPoints(int $extraPriorityPoints): self
{
$this->extraPriorityPoints = $extraPriorityPoints;
return $this;
}
public function getWarehouseGroupId(): ?int
{
return $this->warehouseGroupId;
}
public function setWarehouseGroupId(?int $warehouseGroupId): self
{
$this->warehouseGroupId = $warehouseGroupId;
return $this;
}
public function getWarehouseStatusLink()
{
if ($this->getSolexOrderId()) {
return 'https://solexis.solutionextreme.com/orders.php?orderno=' . $this->getOrderNo() . '&destination=&customerinvoiceno=&dateFrom=2019-03-12&dateTo=2030-04-11&lg=en&s=ca&cmdSearch=';
}
}
public function getFromSubscription(): ?Subscription
{
return $this->fromSubscription;
}
public function setFromSubscription(?Subscription $subscription): self
{
$this->fromSubscription = $subscription;
return $this;
}
public function getIsRefunded(): ?bool
{
return $this->isRefunded;
}
public function setIsRefunded(bool $isRefunded): self
{
$this->isRefunded = $isRefunded;
return $this;
}
public function getIsBulkOrder(): ?bool
{
return $this->isBulkOrder;
}
public function setIsBulkOrder(bool $isBulkOrder): self
{
$this->isBulkOrder = $isBulkOrder;
return $this;
}
public function getRefundStripeResponse()
{
return $this->refundStripeResponse;
}
public function setRefundStripeResponse($refundStripeResponse): self
{
$this->refundStripeResponse = $refundStripeResponse;
return $this;
}
public function showRefundButtonToUser()
{
$now = new \DateTime();
$limitRange = new \DateTime('-6 hours');
if (
$this->getIsPaid() &&
$this->getDatePayment() > $limitRange &&
$this->hasMaturinShipping() &&
!$this->hasCompanyShipping() &&
$this->getDatePayment()->format('W') == $now->format('W')
) {
return true;
}
return false;
}
public function isAPickup(): ?bool
{
return $this->getIsAPickup();
}
public function getIsAPickup(): ?bool
{
foreach ($this->getProducts() as $p) {
if (!$p->getIsAPickup())
return false;
}
return true;
}
public function getNoteFromBuyer(): ?string
{
return $this->noteFromBuyer;
}
public function setNoteFromBuyer(?string $noteFromBuyer): self
{
$this->noteFromBuyer = $noteFromBuyer;
return $this;
}
public function getAllPickupSchedules(): array
{
return CartProduct::getAllPickupSchedules($this->getProducts());
}
public function getPickUpAddress() {
if($this->isMaturinPickUp()){
$products = $this->getProducts();
foreach($products as $p) {
$pickupLocationId = $p->getPickupLocationId();
$pickupLocation = $this->em->getRepository(PickupLocations::class)->findOneBy(["id"=>$pickupLocationId]);
if ($pickupLocation) {
return $pickupLocation->getLocationAddressWithName();
}
}
}else{
return CartProduct::getPickUpAddress($this->getProducts());
}
return "";
}
public function getIsPickupOmeloView()
{
foreach ($this->getProducts() as $p) {
if ($p->getIsAPickup())
return "Oui";
}
return "Non";
}
/*Return first element of schedules array*/
public function getPickUpSchedule(){
if(!empty($this->getAllPickupSchedules())){
return $this->getAllPickupSchedules()[0];
}
return false;
}
/**Return the date; Which is first occurence of the schedules array */
public function getPickupDate(){
$pickupSchedule = $this->getPickUpSchedule();
if(!empty($pickupSchedule)){
$dateArray = explode(" ",$pickupSchedule);
if (count($dateArray) < 2){
$date = explode(" ",$pickupSchedule)[0];
}else{
$dateArray = explode(" ",$pickupSchedule);
$date = $dateArray[0] . ' ' . $dateArray[1] . ' ' . $dateArray[2];
}
return $date;
}
return false;
}
/**Return the time; Which is second occurence of the schedules array */
public function getPickupTime(){
$pickupSchedule = $this->getPickUpSchedule();
if(!empty($pickupSchedule)){
$date = explode(" ",$pickupSchedule)[4];
return $date;
}
return false;
}
public function getDeliveryRoutesArray()
{
$arrayOfRoutes = $this->shippingAddress->getArrayOfDeliveryRoutes();
return !empty($arrayOfRoutes) ? $arrayOfRoutes : null;
}
public function isMaturinPickUp()
{
$cartProducts = $this->getProducts();
foreach ($cartProducts as $cartProduct) {
if($cartProduct->isMaturinPickUp() && $cartProduct->getProduct()->isShippedByMaturin()){
return true;
}
}
return false;
}
public function newRebateEstimate()
{
// We include the coupon
if ($this->getUsedCoupon()) {
$total = $this->getSubTotalToPay(true);
// if ($this->getUsedCoupon()->getIsGiftCertificate()) {
// $saving = $this->getUsedCoupon()->calculateSavings($total);
// $total = $total - $saving;
// }
return round($total * 0.08, 2);
}
return $this->getRebateOnMaturinShipping();
}
public function containReusableBox(){
foreach ($this->getProducts() as $cartProduct) {
if($cartProduct->getProduct()->getId()==6472){
return true;
}
}
return false;
}
public function getMaturinPickUpInfo(){
$info = "";
if($this->isMaturinPickup()){
$info = $this->getPickUpSchedule();
return $info;
}
return $info;
}
public function isShippedByGoColis(){
return $this->containMaturinRoute();
}
public function containMaturinRoute()
{
$shippingAddress = $this->getShippingAddress();
$maturin_type_route_found = false;
if ($shippingAddress) {
$cityName = $shippingAddress->getCity();
$province = $shippingAddress->getProvince();
$city = $this->em->getRepository(City::class)->findLikeNameAndProvince($cityName,$province);
if (empty($city)) {
$maturin_type_route_found = true;
} else {
$city = $city[0];
}
if ($city) {
$routes = $city->getDeliveryRoutes();
foreach ($routes as $route) {
if (
$route->getType() == "maturin" && $route->getName() != "Pas de frais"
) {
$maturin_type_route_found = true;
}
}
}
}
return $maturin_type_route_found;
}
public function getTrackLink(): ?string
{
return $this->trackLink;
}
public function setTrackLink(string $trackLink): self
{
$this->trackLink = $trackLink;
return $this;
}
/*To avoid setting past orders to "Livree" before 2021-03-10*/
public function isShippedLegacy(): ?float
{
$legacyDate = new \DateTime('10 march 2021 00:00:00');
$dateToCompare = $this->getDateCreated();
if($legacyDate > $dateToCompare)
return $this->isShipped();
return false;
}
/*
aide => trackpod renvoi les id suivant en fonction du status de la commande on peut l'utiliser pour savoir si la commande est livré ou non
1-> In progress
2-> Not Delivered (Waypoint issues)
3-> Delivered
4-> Partially
5-> Not Delivered(order issues)
*/
public function getTrackPodStatusId(): ?int
{
return $this->trackPodStatusId;
}
public function setTrackPodStatusId(?int $trackPodStatusId): self
{
$this->trackPodStatusId = $trackPodStatusId;
return $this;
}
public function preOrder(): ?bool
{
return $this->preOrder;
}
public function getPreOrder(): ?bool
{
return $this->preOrder;
}
public function setPreOrder(bool $preOrder): self
{
$this->preOrder = $preOrder;
return $this;
}
public function preOrderNow(): ?bool
{
return $this->preOrderNow;
}
public function getPreOrderNow(): ?bool
{
return $this->preOrderNow;
}
public function setPreOrderNow(bool $preOrderNow): self
{
$this->preOrderNow = $preOrderNow;
return $this;
}
public function calculateTaxes($price, $province, $returnTaxOnly=false){
$taxes = [];
try {
if ($this->em) {
$taxes = $this->em->getRepository(FinancialTax::class)->findTaxes($province);
}
} catch (\Exception $e) {
// ignore
}
if (empty($taxes)) {
if ($returnTaxOnly) {
return 0;
} else {
return ['totalTax'=>0];
}
}
$return = array();
$total = $price;
$totalTax = 0;
foreach($taxes as $tax){
$ratio = $tax->getPourcentage() / 100;
if($tax->getTaxOnTax())
$p = $total * $ratio;
else
$p = $price * $ratio;
$total += $p;
$totalTax += $p;
$return[]=array(
'amount' => $p,
'taxId' => $tax->getId(),
'taxName' => $tax->getName(),
'taxPourcentage' => $tax->getPourcentage(),
'taxOnTax' => $tax->getTaxOnTax(),
);
}
if($returnTaxOnly)
return $totalTax;
else {
return array(
'totalTax' => $totalTax,
'totalPrice' => $total,
'details' => $return
);
}
}
public function calculateMaturinFees() {
$totalFees = 0.00;
foreach ($this->getProducts() as $p) {
$product = $p->getProduct();
if ($product->getDeliveryType() != 0) {
continue;
}
$maturinFeePc = $product->getMaturinFeePc();
// $pricing = $product->getPricings()->first();
// $productTotal = $pricing->getPrice();
$productTotal = $p->getSellerTotal();
$totalFees += ( $productTotal * $maturinFeePc );
}
$totalFees = round($totalFees, 2);
return $totalFees;
}
public function calculateFees() {
//Ok let's start with the Maturin Fees and taxes
$this->setMaturinFee($this->calculateMaturinFees());
$this->setTaxesMaturin($this->calculateTaxes($this->getMaturinFee(), $this->getShippingAddress()->getProvince(), true));
foreach($this->getProducts() as $item){
$item->setPricePaidProduct($item->getTotal(false));
}
//Coupon is included by default see CartProduct.php method getTotal
$taxes = $this->calculateTaxes($this->getTotalProductsTaxable(), $this->getShippingAddress()->getProvince());
$this->setTaxesProductsCalculations($taxes);
$this->setTaxesProducts($taxes['totalTax']);
//Taxes shipping if by solex
$taxes = $this->calculateTaxes($this->getShippingMaturinCost(), $this->getShippingAddress()->getProvince());
$this->setTaxesShippingMaturinCalculations($taxes);
$this->setTaxesShippingMaturin($taxes['totalTax']);
//@TODO Calculate Shipping Company
$taxes = $this->calculateTaxes($this->getShippingCompanyCost(), $this->getShippingAddress()->getProvince());
$this->setTaxesShippingCompanyCalculations($taxes);
$this->setTaxesShippingCompany($taxes['totalTax']);
// taxes packing
$taxes = $this->calculateTaxes($this->getPackingCost(), $this->getShippingAddress()->getProvince());
$this->setTaxesPackingCalculations($taxes);
$this->setTaxesPacking($taxes['totalTax']);
//Estimating Payment Cost
}
public function getDeliveryChoiceDate(): ?\DateTimeInterface
{
return $this->deliveryChoiceDate;
}
public function setDeliveryChoiceDate(?\DateTimeInterface $deliveryChoiceDate = null): self
{
$this->deliveryChoiceDate = $deliveryChoiceDate;
return $this;
}
public function getPreOrderDateFormatted() {
$preorderDate = $this->deliveryChoiceDate;
$estimatedDate = $this->getShippingMaturinEstimatedDate();
$PreOrderDateFormatted = "";
if ($preorderDate != null){
$PreOrderDateFormatted = $preorderDate->format("Y-m-d");
}else{
if ($estimatedDate != null){
$PreOrderDateFormatted = $estimatedDate->format("Y-m-d");
}
}
return $PreOrderDateFormatted;
}
public function getStatusComand() {
$statusCommande = $this->getAllTrackings();
$messagelivraison = "";
if (!empty($statusCommande)){
$messagelivraison = "Livré";
}
return $messagelivraison;
}
public function getQuantityToOrder($p) {
$listproducts = $this->getProducts();
foreach($listproducts as $products){
if ($p->getId() == $products->getProduct()->getId()){
return $products->getQuantity();
}
}
}
}