You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OrderUtils.php 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. <?php
  2. namespace Lc\ShopBundle\Services;
  3. use App\Entity\OrderProductReductionCatalog;
  4. use App\Entity\OrderShop;
  5. use Doctrine\ORM\EntityManagerInterface;
  6. use Lc\ShopBundle\Context\DocumentInterface;
  7. use Lc\ShopBundle\Context\MerchantUtilsInterface;
  8. use Lc\ShopBundle\Context\OrderPaymentInterface;
  9. use Lc\ShopBundle\Context\OrderReductionCartInterface;
  10. use Lc\ShopBundle\Context\OrderProductInterface;
  11. use Lc\ShopBundle\Context\OrderReductionCreditInterface;
  12. use Lc\ShopBundle\Context\OrderShopInterface;
  13. use Lc\ShopBundle\Context\OrderStatusHistoryInterface;
  14. use Lc\ShopBundle\Context\OrderStatusInterface;
  15. use Lc\ShopBundle\Context\ProductFamilyUtilsInterface;
  16. use Lc\ShopBundle\Context\ReductionCartInterface;
  17. use Lc\ShopBundle\Context\ReductionCreditInterface;
  18. use Lc\ShopBundle\Context\UserInterface;
  19. use Lc\ShopBundle\Model\Document;
  20. use Lc\ShopBundle\Form\Backend\Order\OrderReductionCreditType;
  21. use Lc\ShopBundle\Model\Product;
  22. use Lc\ShopBundle\Model\ProductFamily;
  23. use Lc\ShopBundle\Services\Price\OrderShopPriceUtils;
  24. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  25. use Symfony\Component\Security\Core\Security;
  26. class OrderUtils
  27. {
  28. use OrderUtilsReductionTrait;
  29. protected $em;
  30. protected $security;
  31. protected $userUtils;
  32. protected $merchantUtils;
  33. protected $orderShopRepo;
  34. protected $reductionCreditRepo ;
  35. protected $orderReductionCreditRepo ;
  36. protected $orderShopPriceUtils;
  37. protected $productFamilyUtils;
  38. protected $documentUtils;
  39. protected $session;
  40. public function __construct(EntityManagerInterface $em, Security $security, UserUtils $userUtils,
  41. MerchantUtilsInterface $merchantUtils, OrderShopPriceUtils $orderShopPriceUtils, ProductFamilyUtilsInterface $productFamilyUtils,
  42. DocumentUtils $documentUtils, SessionInterface $session)
  43. {
  44. $this->em = $em;
  45. $this->security = $security;
  46. $this->userUtils = $userUtils;
  47. $this->merchantUtils = $merchantUtils;
  48. $this->orderShopRepo = $this->em->getRepository($this->em->getClassMetadata(OrderShopInterface::class)->getName());
  49. $this->reductionCreditRepo = $this->em->getRepository($this->em->getClassMetadata(ReductionCreditInterface::class)->getName());
  50. $this->orderReductionCreditRepo = $this->em->getRepository($this->em->getClassMetadata(OrderReductionCreditInterface::class)->getName());
  51. $this->orderShopPriceUtils = $orderShopPriceUtils;
  52. $this->productFamilyUtils = $productFamilyUtils;
  53. $this->documentUtils = $documentUtils;
  54. $this->session = $session;
  55. }
  56. public function getCartCurrent()
  57. {
  58. $paramsSearchOrderShop = [];
  59. $user = $this->security->getUser();
  60. $visitor = $this->userUtils->getVisitorCurrent();
  61. $orderShop = null;
  62. $orderShopUser = null;
  63. $orderShopVisitor = null;
  64. if ($user) {
  65. $orderShopUser = $this->orderShopRepo->findCartCurrent([
  66. 'user' => $user
  67. ]);
  68. }
  69. if ($visitor) {
  70. $orderShopVisitor = $this->orderShopRepo->findCartCurrent([
  71. 'visitor' => $visitor
  72. ]);
  73. }
  74. if ($orderShopUser || $orderShopVisitor) {
  75. // merge
  76. if ($orderShopUser && $orderShopVisitor && $orderShopUser != $orderShopVisitor
  77. && $orderShopVisitor->getOrderProducts() && count($orderShopVisitor->getOrderProducts())) {
  78. $orderShop = $this->mergeOrderShops($orderShopUser, $orderShopVisitor);
  79. $this->session->getFlashBag()->add('success', "Votre panier visiteur vient d'être fusionné avec votre panier client.");
  80. } else {
  81. $orderShop = ($orderShopUser) ? $orderShopUser : $orderShopVisitor;
  82. }
  83. // set user
  84. if ($orderShop && $user && !$orderShop->getUser()) {
  85. $orderShop->setUser($user);
  86. $this->em->persist($orderShop);
  87. $this->em->flush();
  88. }
  89. }
  90. return $orderShop;
  91. }
  92. public function createOrderShop($params)
  93. {
  94. $orderShop = new OrderShop();
  95. $orderShopBelongTo = false;
  96. if (isset($params['user']) && $params['user']) {
  97. $orderShopBelongTo = true;
  98. $orderShop->setUser($params['user']);
  99. }
  100. if (isset($params['visitor']) && $params['visitor']) {
  101. $orderShopBelongTo = true;
  102. $orderShop->setVisitor($params['visitor']);
  103. }
  104. if (!$orderShopBelongTo) {
  105. throw new \ErrorException('La commande doit être liée à un utilisateur ou à un visiteur.');
  106. }
  107. if (isset($params['merchant']) && $params['merchant']) {
  108. $orderShop->setMerchant($params['merchant']);
  109. } else {
  110. throw new \ErrorException('La commande doit être liée à un merchant.');
  111. }
  112. $orderShop = $this->changeOrderStatus('cart', $orderShop);
  113. return $orderShop;
  114. }
  115. public function addOrderProduct($orderShop, $orderProductAdd, $persist = true)
  116. {
  117. $return = false;
  118. $user = $this->security->getUser();
  119. $visitor = $this->userUtils->getVisitorCurrent();
  120. if (!$orderShop) {
  121. $orderShop = $this->createOrderShop([
  122. 'user' => $user,
  123. 'visitor' => $visitor,
  124. 'merchant' => $this->merchantUtils->getMerchantCurrent()
  125. ]);
  126. }
  127. if ($orderProductAdd->getQuantityOrder() > 0) {
  128. $updated = false;
  129. $orderProductAdd->setTitle($orderProductAdd->getTitleOrderShop());
  130. $orderProductAdd->setPrice($this->priceUtils->getPrice($orderProductAdd->getProduct()));
  131. $orderProductAdd->setUnit($orderProductAdd->getProduct()->getUnitInherited());
  132. $orderProductAdd->setTaxRate($orderProductAdd->getProduct()->getTaxRateInherited());
  133. $orderProductAdd->setQuantityProduct($orderProductAdd->getProduct()->getQuantityInherited());
  134. $productFamily = $this->productFamilyUtils->getProductFamilyBySlug($orderProductAdd->getProduct()->getProductFamily()->getSlug());
  135. $reductionCatalog = $productFamily->getReductionCatalog();
  136. if ($reductionCatalog) {
  137. $orderProductReductionCatalog = new OrderProductReductionCatalog();
  138. $orderProductReductionCatalog->setTitle($reductionCatalog->getTitle());
  139. $orderProductReductionCatalog->setValue($reductionCatalog->getValue());
  140. $orderProductReductionCatalog->setUnit($reductionCatalog->getUnit());
  141. $orderProductReductionCatalog->setBehaviorTaxRate($reductionCatalog->getBehaviorTaxRate());
  142. $orderProductAdd->setOrderProductReductionCatalog($orderProductReductionCatalog);
  143. }
  144. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  145. if ($orderProduct->getProduct()->getId() == $orderProductAdd->getProduct()->getId()
  146. && (string)$this->priceUtils->getPrice($orderProduct) == (string)$this->priceUtils->getPrice($orderProductAdd)
  147. && $this->compareOrderProductReductionCatalog($orderProduct->getOrderProductReductionCatalog(), $orderProductAdd->getOrderProductReductionCatalog())) {
  148. $orderProduct->setQuantityOrder($orderProduct->getQuantityOrder() + $orderProductAdd->getQuantityOrder());
  149. if ($persist) {
  150. $this->em->persist($orderProduct);
  151. }
  152. $updated = true;
  153. $return = true;
  154. break;
  155. }
  156. }
  157. if (!$updated) {
  158. $orderShop->addOrderProduct($orderProductAdd);
  159. if (isset($orderProductReductionCatalog)) {
  160. $this->em->persist($orderProductReductionCatalog);
  161. if ($persist) {
  162. if (isset($orderProductReductionCatalog)) {
  163. $this->em->persist($orderProductReductionCatalog);
  164. }
  165. $this->em->persist($orderProductAdd);
  166. $this->em->persist($orderShop);
  167. }
  168. }
  169. if ($persist) {
  170. $this->em->flush();
  171. }
  172. $return = true;
  173. }
  174. }
  175. return $return;
  176. }
  177. public function countQuantities($orderShop)
  178. {
  179. return $this->countQuantitiesByOrderProducts($orderShop->getOrderProducts());
  180. }
  181. public function countQuantitiesByOrderProducts($orderProducts = [])
  182. {
  183. $count = 0;
  184. foreach ($orderProducts as $orderProduct) {
  185. $count += $orderProduct->getQuantityOrder();
  186. }
  187. return $count;
  188. }
  189. public function getOrderProductsByParentCategory($orderShop = null)
  190. {
  191. $categoriesArray = [];
  192. if ($orderShop) {
  193. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  194. $productCategories = $orderProduct->getProduct()->getProductFamily()->getProductCategories();
  195. $category = $productCategories[0]->getParentCategory();
  196. $labelCategory = $category->getTitle();
  197. if (!isset($categoriesArray[$labelCategory])) {
  198. $categoriesArray[$labelCategory] = [];
  199. }
  200. $categoriesArray[$labelCategory][] = $orderProduct;
  201. }
  202. }
  203. return $categoriesArray;
  204. }
  205. public function getOrderDatas($order = null)
  206. {
  207. $data = [];
  208. if (!$order) {
  209. $order = $this->getCartCurrent();
  210. }
  211. $data['order'] = $order;
  212. if ($order) {
  213. $data['count'] = $this->countQuantities($order);
  214. $data['total_with_tax'] = $this->priceUtils->getTotalWithTaxAndReduction($order);
  215. $data['order_products_by_category'] = $this->getOrderProductsByParentCategory($order);
  216. }
  217. return $data;
  218. }
  219. public function getOrderAsJsonObject(OrderShopInterface $order)
  220. {
  221. $data['id'] = $order->getId();
  222. $data['user'] = $order->getUser()->getSummary();
  223. $data['orderStatus'] = $order->getOrderStatus()->__tosString();
  224. $data['deliveryAddress'] = $order->getDeliveryAddress()->getSummary();
  225. $data['invoiceAddress'] = $order->getInvoiceAddress()->getSummary();
  226. $data['total'] = $this->priceUtils->getTotal($order);
  227. $data['totalWithTax'] = $this->priceUtils->getTotalWithTax($order);
  228. $data['totalWithTaxAndReduction'] = $this->priceUtils->getTotalWithTax($order);
  229. $i = 0;
  230. foreach ($this->getOrderProductsByParentCategory($order) as $labelCategory => $orderProducts) {
  231. foreach ($orderProducts as $orderProduct) {
  232. $data['orderProducts'][$i]['id'] = $orderProduct->getId();
  233. $data['orderProducts'][$i]['product'] = $orderProduct->getProduct()->getId();
  234. $data['orderProducts'][$i]['quantityOrder'] = $orderProduct->getQuantityOrder();
  235. $data['orderProducts'][$i]['labelCategory'] = $labelCategory;
  236. $data['orderProducts'][$i]['title'] = $orderProduct->getTitle();
  237. $data['orderProducts'][$i]['price'] = $this->priceUtils->getPrice($orderProduct);
  238. $data['orderProducts'][$i]['priceWithTax'] = $this->priceUtils->getPriceWithTax($orderProduct);
  239. $data['orderProducts'][$i]['priceWithTaxAndReduction'] = $this->priceUtils->getPriceWithTaxAndReduction($orderProduct);
  240. $data['orderProducts'][$i]['quantity'] = $orderProduct->getQuantityOrder();
  241. $data['orderProducts'][$i]['totalWithTaxAndReduction'] = $this->priceUtils->getTotalOrderProductsWithTaxAndReduction(array($orderProduct));
  242. $i++;
  243. }
  244. }
  245. return $data;
  246. }
  247. public function newOrderStatusHistory($order, $status, $origin = 'user')
  248. {
  249. $orderStatusHistoryClass = $this->em->getClassMetadata(OrderStatusHistoryInterface::class);
  250. $orderStatusHistory = new $orderStatusHistoryClass->name;
  251. $orderStatusHistory->setOrderShop($order);
  252. $orderStatusHistory->setOrderStatus($status);
  253. $orderStatusHistory->setOrigin($origin);
  254. $this->em->persist($orderStatusHistory);
  255. }
  256. public function mergeOrderShops($orderShop1, $orderShop2)
  257. {
  258. if ($orderShop1 && $orderShop2) {
  259. foreach ($orderShop2->getOrderProducts() as $orderProduct) {
  260. $this->addOrderProduct($orderShop1, $orderProduct);
  261. $this->em->remove($orderProduct);
  262. }
  263. $this->em->remove($orderShop2);
  264. $this->em->persist($orderShop1);
  265. $this->em->flush();
  266. return $orderShop1;
  267. }
  268. }
  269. public function createDocumentInvoice(OrderShopInterface $orderShop)
  270. {
  271. $merchantAddress = $orderShop->getMerchant()->getAddress();
  272. $buyerAddress = $orderShop->getInvoiceAddress();
  273. $document = $this->documentUtils->createDocument([
  274. 'type' => Document::TYPE_INVOICE,
  275. 'title' => '',
  276. 'status' => 1,
  277. 'order_shops' => [$orderShop],
  278. 'merchant_address' => $merchantAddress,
  279. 'buyer_address' => $buyerAddress,
  280. 'created_by' => $orderShop->getUser()
  281. ]);
  282. return $document;
  283. }
  284. public function groupOrderProductsByProductFamily($orderProducts)
  285. {
  286. $orderProductsByProductFamily = [];
  287. foreach ($orderProducts as $orderProduct) {
  288. if ($orderProduct->getProduct() && $orderProduct->getProduct()->getProductFamily()) {
  289. $productFamily = $orderProduct->getProduct()->getProductFamily();
  290. if (!isset($orderProductsByProductFamily[$productFamily->getId()])) {
  291. $orderProductsByProductFamily[$productFamily->getId()] = [
  292. 'order_products' => [],
  293. 'total_quantity_weight' => 0,
  294. ];
  295. }
  296. $orderProductsByProductFamily[$productFamily->getId()]['order_products'][] = $orderProduct;
  297. $orderProductsByProductFamily[$productFamily->getId()]['total_quantity_weight'] += ($orderProduct->getQuantityProduct() / $orderProduct->getUnit()->getCoefficient()) * $orderProduct->getQuantityOrder();
  298. }
  299. }
  300. return $orderProductsByProductFamily;
  301. }
  302. public function createOrderPayment($orderShop, $type, $amount, $reference = null, $comment = null, $paidAt = null)
  303. {
  304. $classOrderPayment = $this->em->getClassMetadata(OrderPaymentInterface::class)->getName();
  305. $orderPayment = new $classOrderPayment;
  306. $orderPayment->setOrderShop($orderShop);
  307. $orderPayment->setType($type);
  308. $orderPayment->setAmount($amount);
  309. $orderPayment->setReference($reference);
  310. $orderPayment->setComment($comment);
  311. if ($paidAt) {
  312. $orderPayment->setPaidAt($paidAt);
  313. } else {
  314. $orderPayment->setPaidAt(new \DateTime('now'));
  315. }
  316. $this->em->persist($orderPayment);
  317. $this->em->flush();
  318. }
  319. public function isOrderPaid($order)
  320. {
  321. if ($this->getTotalOrderPayments($order) >= $this->priceUtils->getTotalWithTaxAndReduction($order)) {
  322. return true;
  323. } else {
  324. $order->editError[] = 'field.error.orderStatus.noPayment';
  325. return false;
  326. }
  327. }
  328. public function getTotalOrderPayments($order): float
  329. {
  330. $totalAmount = floatval(0);
  331. foreach ($order->getOrderPayments() as $orderPayment) {
  332. $totalAmount = $orderPayment->getAmount() + $totalAmount;
  333. }
  334. return $totalAmount;
  335. }
  336. public function deductAvailabilityProduct(\Lc\ShopBundle\Model\OrderShop $orderShop)
  337. {
  338. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  339. switch ($orderProduct->getProduct()->getProductFamily()->getBehaviorCountStock()) {
  340. case ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE :
  341. //Disponibilité par unité de référence
  342. $oldAvailability = $orderProduct->getProduct()->getAvailableQuantityInherited();
  343. $newAvailability = $oldAvailability - ($orderProduct->getQuantityProduct() / $orderProduct->getUnit()->getCoefficient());
  344. $orderProduct->getProduct()->getProductFamily()->setAvailableQuantity($newAvailability);
  345. $this->em->persist($orderProduct->getProduct()->getProductFamily());
  346. break;
  347. case ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT_FAMILY :
  348. $oldAvailability = $orderProduct->getProduct()->getAvailableQuantityInherited();
  349. $newAvailability = $oldAvailability - $orderProduct->getQuantityOrder();
  350. $orderProduct->getProduct()->getProductFamily()->setAvailableQuantity($newAvailability);
  351. $this->em->persist($orderProduct->getProduct()->getProductFamily());
  352. break;
  353. case ProductFamily::BEHAVIOR_COUNT_STOCK_BY_PRODUCT :
  354. $oldAvailability = $orderProduct->getProduct()->getAvailableQuantityInherited();
  355. $newAvailability = $oldAvailability - $orderProduct->getQuantityOrder();
  356. $orderProduct->getProduct()->setAvailableQuantity($newAvailability);
  357. $this->em->persist($orderProduct->getProduct());
  358. break;
  359. }
  360. $this->em->flush();
  361. }
  362. }
  363. public function isProductAvailable(Product $product, $quanityOrder)
  364. {
  365. $quanityAsked = $quanityOrder;
  366. if($product->getProductFamily()->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE) {
  367. $quanityAsked = ($product->getQuantityInherited() / $product->getUnitInherited()->getCoefficient()) * $quanityOrder;
  368. }
  369. if ($product->getAvailableQuantityInherited() >= $quanityAsked || $product->getProductFamily()->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_UNLIMITED) {
  370. return true;
  371. } else {
  372. return false;
  373. }
  374. }
  375. public function isCartAllowToBeOrder($order){
  376. return true;
  377. }
  378. public function getReductionCreditsAvailableByUser($user)
  379. {
  380. $reductionCredits = $this->reductionCreditRepo->findReductionCreditsByUser($user) ;
  381. $reductionCreditsArray = [] ;
  382. foreach($reductionCredits as $reductionCredit) {
  383. if(!$this->orderShopRepo->countValidOrderWithReductionCredit($reductionCredit, $user)) {
  384. $reductionCreditsArray[] = $reductionCredit ;
  385. }
  386. }
  387. return $reductionCreditsArray ;
  388. }
  389. public function isReductionCreditAddedToOrder($orderShop, $reductionCredit)
  390. {
  391. foreach($orderShop->getOrderReductionCredits() as $orderReductionCredit) {
  392. if($orderReductionCredit->getReductionCredit() == $reductionCredit) {
  393. return true ;
  394. }
  395. }
  396. return false ;
  397. }
  398. }