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.

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