Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

489 rindas
23KB

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