350 lines
17KB

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