367 lines
18KB

  1. <?php
  2. namespace Lc\ShopBundle\Services\Order;
  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\OrderReductionCreditInterface;
  9. use Lc\ShopBundle\Context\OrderShopInterface;
  10. use Lc\ShopBundle\Context\OrderStatusHistoryInterface;
  11. use Lc\ShopBundle\Context\PriceUtilsInterface;
  12. use Lc\ShopBundle\Context\ProductFamilyUtilsInterface;
  13. use Lc\ShopBundle\Context\ReductionCreditInterface;
  14. use Lc\ShopBundle\Model\ProductFamily;
  15. use Lc\ShopBundle\Services\CreditUtils;
  16. use Lc\ShopBundle\Services\DocumentUtils;
  17. use Lc\ShopBundle\Services\UserUtils;
  18. use Lc\ShopBundle\Services\Utils;
  19. use Symfony\Component\Routing\RouterInterface;
  20. use Symfony\Component\Security\Core\Security;
  21. class OrderUtils
  22. {
  23. use OrderUtilsReductionTrait;
  24. use OrderUtilsStockTrait;
  25. use OrderUtilsPaymentTrait;
  26. use OrderUtilsDocumentTrait;
  27. use OrderUtilsCartTrait;
  28. protected $em;
  29. protected $security;
  30. protected $userUtils;
  31. protected $merchantUtils;
  32. protected $orderShopRepo;
  33. protected $reductionCreditRepo ;
  34. protected $orderReductionCreditRepo ;
  35. protected $documentRepo ;
  36. protected $priceUtils;
  37. protected $productFamilyUtils;
  38. protected $documentUtils;
  39. protected $utils;
  40. protected $creditUtils;
  41. protected $router;
  42. public function __construct(EntityManagerInterface $em, Security $security, RouterInterface $router, UserUtils $userUtils,
  43. MerchantUtilsInterface $merchantUtils, PriceUtilsInterface $priceUtils, ProductFamilyUtilsInterface $productFamilyUtils,
  44. DocumentUtils $documentUtils, Utils $utils, CreditUtils $creditUtils)
  45. {
  46. $this->em = $em;
  47. $this->security = $security;
  48. $this->userUtils = $userUtils;
  49. $this->merchantUtils = $merchantUtils;
  50. $this->orderShopRepo = $this->em->getRepository($this->em->getClassMetadata(OrderShopInterface::class)->getName());
  51. $this->reductionCreditRepo = $this->em->getRepository($this->em->getClassMetadata(ReductionCreditInterface::class)->getName());
  52. $this->orderReductionCreditRepo = $this->em->getRepository($this->em->getClassMetadata(OrderReductionCreditInterface::class)->getName());
  53. $this->documentRepo = $this->em->getRepository($this->em->getClassMetadata(DocumentInterface::class)->getName());
  54. $this->priceUtils = $priceUtils;
  55. $this->productFamilyUtils = $productFamilyUtils;
  56. $this->documentUtils = $documentUtils;
  57. $this->utils = $utils;
  58. $this->creditUtils = $creditUtils;
  59. $this->router = $router;
  60. }
  61. public function createOrderShop($params)
  62. {
  63. //TODO vérifier que l'utilisateur n'a pas déjà une commande en cours
  64. $orderShop = new OrderShop();
  65. $orderShopBelongTo = false;
  66. if (isset($params['user']) && $params['user']) {
  67. $orderShopBelongTo = true;
  68. $orderShop->setUser($params['user']);
  69. }
  70. if (isset($params['visitor']) && $params['visitor'] && !$orderShop->getUser()) {
  71. $orderShopBelongTo = true;
  72. $orderShop->setVisitor($params['visitor']);
  73. }
  74. if (!$orderShopBelongTo) {
  75. throw new \ErrorException('La commande doit être liée à un utilisateur ou à un visiteur.');
  76. }
  77. if (isset($params['merchant']) && $params['merchant']) {
  78. $orderShop->setMerchant($params['merchant']);
  79. } else {
  80. throw new \ErrorException('La commande doit être liée à un merchant.');
  81. }
  82. $orderShop = $this->changeOrderStatus('cart', $orderShop);
  83. return $orderShop;
  84. }
  85. public function addOrderProduct($orderShop, $orderProductAdd, $persist = true)
  86. {
  87. $return = false;
  88. $user = $this->security->getUser();
  89. $visitor = $this->userUtils->getVisitorCurrent();
  90. if (!$orderShop) {
  91. $orderShop = $this->createOrderShop([
  92. 'user' => $user,
  93. 'visitor' => $visitor,
  94. 'merchant' => $this->merchantUtils->getMerchantCurrent()
  95. ]);
  96. }
  97. if($this->isOrderProductAvailableAddCart($orderProductAdd, $orderShop)) {
  98. if ($orderProductAdd->getQuantityOrder() > 0) {
  99. $updated = false;
  100. $orderProductAdd->setTitle($orderProductAdd->getTitleOrderShop());
  101. $orderProductAdd->setPrice($this->priceUtils->getPrice($orderProductAdd->getProduct()));
  102. $orderProductAdd->setBuyingPrice($this->priceUtils->getBuyingPrice($orderProductAdd->getProduct()));
  103. $orderProductAdd->setUnit($orderProductAdd->getProduct()->getUnitInherited());
  104. $orderProductAdd->setTaxRate($orderProductAdd->getProduct()->getTaxRateInherited());
  105. $orderProductAdd->setQuantityProduct($orderProductAdd->getProduct()->getQuantityInherited());
  106. $productFamily = $this->productFamilyUtils->getProductFamilyBySlug($orderProductAdd->getProduct()->getProductFamily()->getSlug());
  107. $reductionCatalog = $productFamily->getReductionCatalog();
  108. if ($reductionCatalog) {
  109. $orderProductReductionCatalog = new OrderProductReductionCatalog();
  110. $orderProductReductionCatalog->setTitle($reductionCatalog->getTitle());
  111. $orderProductReductionCatalog->setValue($reductionCatalog->getValue());
  112. $orderProductReductionCatalog->setUnit($reductionCatalog->getUnit());
  113. $orderProductReductionCatalog->setBehaviorTaxRate($reductionCatalog->getBehaviorTaxRate());
  114. $orderProductAdd->setOrderProductReductionCatalog($orderProductReductionCatalog);
  115. }
  116. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  117. if ($orderProduct->getProduct()->getId() == $orderProductAdd->getProduct()->getId()
  118. && $orderProduct->getRedelivery() == $orderProductAdd->getRedelivery()
  119. && (string) $this->priceUtils->getPrice($orderProduct) == (string) $this->priceUtils->getPrice($orderProductAdd)
  120. && $this->compareOrderProductReductionCatalog($orderProduct->getOrderProductReductionCatalog(), $orderProductAdd->getOrderProductReductionCatalog())) {
  121. $orderProduct->setQuantityOrder($orderProduct->getQuantityOrder() + $orderProductAdd->getQuantityOrder());
  122. if ($persist) {
  123. $this->em->persist($orderProduct);
  124. }
  125. $updated = true;
  126. $return = true;
  127. break;
  128. }
  129. }
  130. if (!$updated) {
  131. $orderShop->addOrderProduct($orderProductAdd);
  132. if ($persist) {
  133. if (isset($orderProductReductionCatalog)) {
  134. $this->em->persist($orderProductReductionCatalog);
  135. }
  136. $this->em->persist($orderProductAdd);
  137. $this->em->persist($orderShop);
  138. }
  139. $return = true;
  140. }
  141. if ($persist) {
  142. $this->em->flush();
  143. }
  144. $this->eventOrderShopChangeQuantity($orderShop) ;
  145. }
  146. }
  147. else {
  148. $availableQuantity = $orderProductAdd->getProduct()->getAvailableQuantityInherited() ;
  149. $textError = "Le produit <strong>".$orderProductAdd->getTitleOrderShop()."</strong> n'est pas disponible" ;
  150. if($availableQuantity !== false && $availableQuantity > 0) {
  151. $unit = '' ;
  152. if($orderProductAdd->getProduct()->getProductFamily()->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE) {
  153. $unit = $orderProductAdd->getProduct()->getUnitInherited()->getUnitReference()->getUnit() ;
  154. }
  155. $textError .= ' dans cette quantité ' ;
  156. $user = $this->security->getUser() ;
  157. if($user && $user->hasRole('ROLE_USER')) {
  158. $textError .= '<br />'.$availableQuantity.$unit.' disponible(s) dont '.$this->getQuantityOrderByProduct($orderShop, $orderProductAdd->getProduct()).$unit.' déjà dans votre panier.' ;
  159. }
  160. }
  161. $this->utils->addFlash('error', $textError);
  162. }
  163. return $return ;
  164. }
  165. public function countQuantities($orderShop)
  166. {
  167. return $this->countQuantitiesByOrderProducts($orderShop->getOrderProducts());
  168. }
  169. public function countQuantitiesByOrderProducts($orderProducts = [])
  170. {
  171. $count = 0;
  172. foreach ($orderProducts as $orderProduct) {
  173. $count += $orderProduct->getQuantityOrder();
  174. }
  175. return $count;
  176. }
  177. public function getOrderProductsByParentCategory($orderShop = null)
  178. {
  179. $categoriesArray = [];
  180. if ($orderShop) {
  181. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  182. $productCategories = $orderProduct->getProduct()->getProductFamily()->getProductCategories();
  183. $category = $productCategories[0]->getParentCategory();
  184. $labelCategory = $category->getTitle();
  185. if (!isset($categoriesArray[$labelCategory])) {
  186. $categoriesArray[$labelCategory] = [];
  187. }
  188. $categoriesArray[$labelCategory][] = $orderProduct;
  189. }
  190. }
  191. return $categoriesArray;
  192. }
  193. public function getOrderDatas($order = null)
  194. {
  195. $data = [];
  196. if (!$order) {
  197. $order = $this->getCartCurrent();
  198. }
  199. $data['order'] = $order;
  200. if ($order) {
  201. $data['count'] = $this->countQuantities($order);
  202. $data['total_with_tax'] = $this->priceUtils->getTotalWithTax($order);
  203. $data['order_products_by_category'] = $this->getOrderProductsByParentCategory($order);
  204. }
  205. return $data;
  206. }
  207. public function getOrderAsJsonObject(OrderShopInterface $order)
  208. {
  209. $data['id'] = $order->getId();
  210. $data['user'] = $order->getUser()->getSummary();
  211. $data['orderStatus'] = $order->getOrderStatus()->__tosString();
  212. $data['deliveryAddress'] = $order->getDeliveryAddress()->getSummary();
  213. $data['invoiceAddress'] = $order->getInvoiceAddress()->getSummary();
  214. $data['total'] = $this->priceUtils->getTotal($order);
  215. $data['totalWithTax'] = $this->priceUtils->getTotalWithTax($order);
  216. $data['totalWithTaxAndReduction'] = $this->priceUtils->getTotalWithTax($order);
  217. $i = 0;
  218. foreach ($this->getOrderProductsByParentCategory($order) as $labelCategory => $orderProducts) {
  219. foreach ($orderProducts as $orderProduct) {
  220. $data['orderProducts'][$i]['id'] = $orderProduct->getId();
  221. $data['orderProducts'][$i]['product'] = $orderProduct->getProduct()->getId();
  222. $data['orderProducts'][$i]['quantityOrder'] = $orderProduct->getQuantityOrder();
  223. $data['orderProducts'][$i]['labelCategory'] = $labelCategory;
  224. $data['orderProducts'][$i]['title'] = $orderProduct->getTitle();
  225. $data['orderProducts'][$i]['price'] = $this->priceUtils->getPrice($orderProduct);
  226. $data['orderProducts'][$i]['priceWithTax'] = $this->priceUtils->getPriceWithTax($orderProduct);
  227. $data['orderProducts'][$i]['priceWithTaxAndReduction'] = $this->priceUtils->getPriceWithTaxAndReduction($orderProduct);
  228. $data['orderProducts'][$i]['quantity'] = $orderProduct->getQuantityOrder();
  229. $data['orderProducts'][$i]['totalWithTaxAndReduction'] = $this->priceUtils->getTotalOrderProductsWithTaxAndReduction(array($orderProduct));
  230. $i++;
  231. }
  232. }
  233. return $data;
  234. }
  235. public function newOrderStatusHistory($order, $status, $origin = 'user')
  236. {
  237. $orderStatusHistoryClass = $this->em->getClassMetadata(OrderStatusHistoryInterface::class);
  238. $orderStatusHistory = new $orderStatusHistoryClass->name;
  239. $orderStatusHistory->setOrderShop($order);
  240. $orderStatusHistory->setOrderStatus($status);
  241. $orderStatusHistory->setOrigin($origin);
  242. $this->em->persist($orderStatusHistory);
  243. }
  244. public function mergeOrderShops($orderShop1, $orderShop2, $persist = true)
  245. {
  246. if ($orderShop1 && $orderShop2) {
  247. foreach ($orderShop2->getOrderProducts() as $orderProduct) {
  248. $orderProductAlreadyInCart = $this->hasOrderProductAlreadyInCart($orderShop1, $orderProduct) ;
  249. if($orderProductAlreadyInCart) {
  250. if($orderProduct->getQuantityOrder() > $orderProductAlreadyInCart->getQuantityOrder()) {
  251. $orderShop1->removeOrderProduct($orderProductAlreadyInCart) ;
  252. $this->addOrderProduct($orderShop1, $orderProduct);
  253. }
  254. }
  255. else {
  256. $this->addOrderProduct($orderShop1, $orderProduct);
  257. }
  258. if($persist) {
  259. $this->em->remove($orderProduct);
  260. }
  261. }
  262. if($persist) {
  263. $this->em->remove($orderShop2);
  264. $this->em->persist($orderShop1);
  265. $this->em->flush();
  266. }
  267. return $orderShop1;
  268. }
  269. }
  270. public function hasOrderProductAlreadyInCart($orderShop, $orderProductTest)
  271. {
  272. foreach($orderShop->getOrderProducts() as $orderProduct) {
  273. if($orderProduct->getProduct() == $orderProductTest->getProduct()) {
  274. return $orderProduct ;
  275. }
  276. }
  277. return false ;
  278. }
  279. public function groupOrderProductsByProductFamily($orderProducts)
  280. {
  281. $orderProductsByProductFamily = [];
  282. foreach ($orderProducts as $orderProduct) {
  283. if ($orderProduct->getProduct() && $orderProduct->getProduct()->getProductFamily()) {
  284. $productFamily = $orderProduct->getProduct()->getProductFamily();
  285. if (!isset($orderProductsByProductFamily[$productFamily->getId()])) {
  286. $orderProductsByProductFamily[$productFamily->getId()] = [
  287. 'order_products' => [],
  288. 'total_quantity_weight' => 0,
  289. ];
  290. }
  291. $orderProductsByProductFamily[$productFamily->getId()]['order_products'][] = $orderProduct;
  292. $orderProductsByProductFamily[$productFamily->getId()]['total_quantity_weight'] += ($orderProduct->getQuantityProduct() / $orderProduct->getUnit()->getCoefficient()) * $orderProduct->getQuantityOrder();
  293. }
  294. }
  295. return $orderProductsByProductFamily;
  296. }
  297. public function isOrderShopPositiveAmount(OrderShopInterface $orderShop)
  298. {
  299. return $this->priceUtils->getTotalWithTax($orderShop) >= 0 ;
  300. }
  301. public function eventOrderShopChangeQuantity(OrderShopInterface $orderShop)
  302. {
  303. }
  304. }