Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

437 lines
21KB

  1. <?php
  2. namespace Lc\ShopBundle\Services\Order;
  3. use App\Entity\OrderProductReductionCatalog;
  4. use App\Entity\OrderShop;
  5. use App\Entity\OrderStatus;
  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\Context\SectionInterface;
  15. use Lc\ShopBundle\Context\SectionUtilsInterface;
  16. use Lc\ShopBundle\Context\UserUtilsInterface;
  17. use Lc\ShopBundle\Manager\EntityManager;
  18. use Lc\ShopBundle\Model\ProductFamily;
  19. use Lc\ShopBundle\Services\CreditUtils;
  20. use Lc\ShopBundle\Services\DocumentUtils;
  21. use Lc\ShopBundle\Services\UserUtils;
  22. use Lc\ShopBundle\Services\Utils;
  23. use Lc\ShopBundle\Services\UtilsManager;
  24. use Symfony\Component\Routing\RouterInterface;
  25. use Symfony\Component\Security\Core\Security;
  26. class OrderUtils
  27. {
  28. use OrderUtilsReductionTrait;
  29. use OrderUtilsStockTrait;
  30. use OrderUtilsPaymentTrait;
  31. use OrderUtilsDocumentTrait;
  32. use OrderUtilsCartTrait;
  33. protected $em;
  34. protected $security;
  35. protected $userUtils;
  36. protected $merchantUtils;
  37. protected $orderShopRepo;
  38. protected $reductionCreditRepo ;
  39. protected $orderReductionCreditRepo ;
  40. protected $documentRepo ;
  41. protected $priceUtils;
  42. protected $productFamilyUtils;
  43. protected $documentUtils;
  44. protected $utils;
  45. protected $creditUtils;
  46. protected $router;
  47. protected $sectionUtils ;
  48. public function __construct(
  49. EntityManager $em,
  50. Security $security,
  51. RouterInterface $router,
  52. UserUtilsInterface $userUtils,
  53. MerchantUtilsInterface $merchantUtils,
  54. PriceUtilsInterface $priceUtils,
  55. ProductFamilyUtilsInterface $productFamilyUtils,
  56. DocumentUtils $documentUtils,
  57. Utils $utils,
  58. CreditUtils $creditUtils,
  59. SectionUtilsInterface $sectionUtils
  60. )
  61. {
  62. $this->em = $em;
  63. $this->security = $security;
  64. $this->userUtils = $userUtils;
  65. $this->merchantUtils = $merchantUtils;
  66. $this->orderShopRepo = $this->em->getRepository($this->em->getEntityName(OrderShopInterface::class));
  67. $this->reductionCreditRepo = $this->em->getRepository($this->em->getEntityName(ReductionCreditInterface::class));
  68. $this->orderReductionCreditRepo = $this->em->getRepository($this->em->getEntityName(OrderReductionCreditInterface::class));
  69. $this->documentRepo = $this->em->getRepository($this->em->getEntityName(DocumentInterface::class));
  70. $this->priceUtils = $priceUtils;
  71. $this->productFamilyUtils = $productFamilyUtils;
  72. $this->documentUtils = $documentUtils;
  73. $this->utils = $utils;
  74. $this->creditUtils = $creditUtils;
  75. $this->router = $router;
  76. $this->sectionUtils = $sectionUtils ;
  77. }
  78. public function createOrderShop($params)
  79. {
  80. //TODO vérifier que l'utilisateur n'a pas déjà une commande en cours
  81. $orderShop = new OrderShop();
  82. $orderShopBelongTo = false;
  83. if (isset($params['user']) && $params['user']) {
  84. $orderShopBelongTo = true;
  85. $orderShop->setUser($params['user']);
  86. }
  87. if (isset($params['visitor']) && $params['visitor'] && !$orderShop->getUser()) {
  88. $orderShopBelongTo = true;
  89. $orderShop->setVisitor($params['visitor']);
  90. }
  91. if (!$orderShopBelongTo) {
  92. throw new \ErrorException('La commande doit être liée à un utilisateur ou à un visiteur.');
  93. }
  94. if (isset($params['merchant']) && $params['merchant']) {
  95. $orderShop->setMerchant($params['merchant']);
  96. } else {
  97. throw new \ErrorException('La commande doit être liée à un merchant.');
  98. }
  99. // pour le moment, à la création, on lie simplement la commande à la section "Marché"
  100. $section = $this->sectionUtils->getSectionMarket() ;
  101. if($section) {
  102. $orderShop->setSection($section) ;
  103. }
  104. else {
  105. throw new \ErrorException('La commande doit être liée à une section.');
  106. }
  107. $orderShop = $this->changeOrderStatus('cart', $orderShop);
  108. return $orderShop;
  109. }
  110. public function addOrderProduct($orderShop, $orderProductAdd, $persist = true)
  111. {
  112. $return = false;
  113. if (!$orderShop) {
  114. $user = $this->security->getUser();
  115. $visitor = $this->userUtils->getVisitorCurrent();
  116. $orderShop = $this->createOrderShop([
  117. 'user' => $user,
  118. 'visitor' => $visitor,
  119. 'merchant' => $this->merchantUtils->getMerchantCurrent(),
  120. ]);
  121. }
  122. if($this->isOrderProductAvailableAddCart($orderProductAdd, $orderShop)) {
  123. if ($orderProductAdd->getQuantityOrder() > 0) {
  124. $updated = false;
  125. $orderProductAdd->setTitle($orderProductAdd->getTitleOrderShop());
  126. $orderProductAdd->setPrice($this->priceUtils->getPrice($orderProductAdd->getProduct()));
  127. $orderProductAdd->setBuyingPrice($this->priceUtils->getBuyingPrice($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. if($productFamily) {
  133. $reductionCatalog = $productFamily->getReductionCatalog();
  134. if ($reductionCatalog) {
  135. $orderProductReductionCatalog = new OrderProductReductionCatalog();
  136. $orderProductReductionCatalog->setTitle($reductionCatalog->getTitle());
  137. $orderProductReductionCatalog->setValue($reductionCatalog->getValue());
  138. $orderProductReductionCatalog->setUnit($reductionCatalog->getUnit());
  139. $orderProductReductionCatalog->setBehaviorTaxRate($reductionCatalog->getBehaviorTaxRate());
  140. $orderProductAdd->setOrderProductReductionCatalog($orderProductReductionCatalog);
  141. }
  142. }
  143. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  144. if ($orderProduct->getProduct()->getId() == $orderProductAdd->getProduct()->getId()
  145. && $orderProduct->getRedelivery() == $orderProductAdd->getRedelivery()
  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 ($persist) {
  160. if (isset($orderProductReductionCatalog)) {
  161. $this->em->persist($orderProductReductionCatalog);
  162. }
  163. $this->em->persist($orderProductAdd);
  164. $this->em->persist($orderShop);
  165. }
  166. $return = true;
  167. }
  168. if ($persist) {
  169. $this->em->flush();
  170. }
  171. $this->eventCartChange($orderShop) ;
  172. }
  173. }
  174. else {
  175. $availableQuantity = $orderProductAdd->getProduct()->getAvailableQuantityInherited() ;
  176. $textError = "Le produit <strong>".$orderProductAdd->getTitleOrderShop()."</strong> n'est pas disponible" ;
  177. if($availableQuantity !== false && $availableQuantity > 0) {
  178. $unit = '' ;
  179. if($orderProductAdd->getProduct()->getProductFamily()->getBehaviorCountStock() == ProductFamily::BEHAVIOR_COUNT_STOCK_BY_MEASURE) {
  180. $unit = $orderProductAdd->getProduct()->getUnitInherited()->getUnitReference()->getUnit() ;
  181. }
  182. $textError .= ' dans cette quantité ' ;
  183. $user = $this->security->getUser() ;
  184. if($user && $user->hasRole('ROLE_USER')) {
  185. $textError .= '<br />'.$availableQuantity.$unit.' disponible(s) dont '.$this->getQuantityOrderByProduct($orderShop, $orderProductAdd->getProduct()).$unit.' déjà dans votre panier.' ;
  186. }
  187. }
  188. $this->utils->addFlash('error', $textError);
  189. }
  190. return $return ;
  191. }
  192. public function countQuantities($orderShop)
  193. {
  194. return $this->countQuantitiesByOrderProducts($orderShop->getOrderProducts());
  195. }
  196. public function countQuantitiesByOrderProducts($orderProducts = [])
  197. {
  198. $count = 0;
  199. foreach ($orderProducts as $orderProduct) {
  200. $count += $orderProduct->getQuantityOrder();
  201. }
  202. return $count;
  203. }
  204. public function getOrderProductsByParentCategory($orderShop = null)
  205. {
  206. $categoriesArray = [];
  207. if ($orderShop) {
  208. foreach ($orderShop->getOrderProducts() as $orderProduct) {
  209. $productCategories = $orderProduct->getProduct()->getProductFamily()->getProductCategories();
  210. $category = $productCategories[0]->getParentCategory();
  211. $labelCategory = $category->getTitle();
  212. if (!isset($categoriesArray[$labelCategory])) {
  213. $categoriesArray[$labelCategory] = [];
  214. }
  215. $categoriesArray[$labelCategory][] = $orderProduct;
  216. }
  217. }
  218. return $categoriesArray;
  219. }
  220. public function getOrderDatas($order = null)
  221. {
  222. $data = [];
  223. if (!$order) {
  224. $order = $this->getCartCurrent();
  225. }
  226. $data['order'] = $order;
  227. if ($order) {
  228. $data['count'] = $this->countQuantities($order);
  229. $data['total_with_tax'] = $this->priceUtils->getTotalWithTax($order);
  230. $data['order_products_by_category'] = $this->getOrderProductsByParentCategory($order);
  231. $data['total_remaining_to_be_paid'] = $this->getTotalRemainingToBePaid($order) ;
  232. }
  233. return $data;
  234. }
  235. public function getOrderAsJsonObject(OrderShopInterface $order)
  236. {
  237. $data['id'] = $order->getId();
  238. $data['user'] = $order->getUser()->getSummary();
  239. $data['orderStatus'] = $order->getOrderStatus()->__toString();
  240. $data['deliveryAddress'] = $order->getDeliveryAddress()->getSummary();
  241. $data['invoiceAddress'] = $order->getInvoiceAddress()->getSummary();
  242. $data['total'] = $this->priceUtils->getTotal($order);
  243. $data['totalWithTax'] = $this->priceUtils->getTotalWithTax($order);
  244. $data['totalWithTaxAndReduction'] = $this->priceUtils->getTotalWithTax($order);
  245. $i = 0;
  246. foreach ($this->getOrderProductsByParentCategory($order) as $labelCategory => $orderProducts) {
  247. foreach ($orderProducts as $orderProduct) {
  248. $data['orderProducts'][$i]['id'] = $orderProduct->getId();
  249. $data['orderProducts'][$i]['product'] = $orderProduct->getProduct()->getId();
  250. $data['orderProducts'][$i]['quantityOrder'] = $orderProduct->getQuantityOrder();
  251. $data['orderProducts'][$i]['labelCategory'] = $labelCategory;
  252. $data['orderProducts'][$i]['title'] = $orderProduct->getTitle();
  253. $data['orderProducts'][$i]['price'] = $this->priceUtils->getPrice($orderProduct);
  254. $data['orderProducts'][$i]['priceWithTax'] = $this->priceUtils->getPriceWithTax($orderProduct);
  255. $data['orderProducts'][$i]['priceWithTaxAndReduction'] = $this->priceUtils->getPriceWithTaxAndReduction($orderProduct);
  256. $data['orderProducts'][$i]['quantity'] = $orderProduct->getQuantityOrder();
  257. $data['orderProducts'][$i]['totalWithTaxAndReduction'] = $this->priceUtils->getTotalOrderProductsWithTaxAndReduction(array($orderProduct));
  258. $i++;
  259. }
  260. }
  261. return $data;
  262. }
  263. public function newOrderStatusHistory($order, $status, $origin = 'user')
  264. {
  265. $orderStatusHistoryClass = $this->em->getEntityName(OrderStatusHistoryInterface::class);
  266. $orderStatusHistory = new $orderStatusHistoryClass;
  267. $orderStatusHistory->setOrderShop($order);
  268. $orderStatusHistory->setOrderStatus($status);
  269. $orderStatusHistory->setOrigin($origin);
  270. $this->em->persist($orderStatusHistory);
  271. }
  272. public function mergeOrderShops($orderShop1, $orderShop2, $persist = true)
  273. {
  274. if ($orderShop1 && $orderShop2) {
  275. foreach ($orderShop2->getOrderProducts() as $orderProduct) {
  276. $orderProductAlreadyInCart = $this->hasOrderProductAlreadyInCart($orderShop1, $orderProduct) ;
  277. if($orderProductAlreadyInCart) {
  278. if($orderProduct->getQuantityOrder() > $orderProductAlreadyInCart->getQuantityOrder()) {
  279. $orderShop1->removeOrderProduct($orderProductAlreadyInCart) ;
  280. $this->addOrderProduct($orderShop1, $orderProduct);
  281. }
  282. }
  283. else {
  284. $this->addOrderProduct($orderShop1, $orderProduct);
  285. }
  286. if($persist) {
  287. $this->em->remove($orderProduct);
  288. }
  289. }
  290. if($persist) {
  291. $this->em->remove($orderShop2);
  292. $this->em->persist($orderShop1);
  293. $this->em->flush();
  294. }
  295. return $orderShop1;
  296. }
  297. }
  298. public function hasOrderProductAlreadyInCart($orderShop, $orderProductTest)
  299. {
  300. foreach($orderShop->getOrderProducts() as $orderProduct) {
  301. if($orderProduct->getProduct() == $orderProductTest->getProduct()) {
  302. return $orderProduct ;
  303. }
  304. }
  305. return false ;
  306. }
  307. public function getOrderProductsByProductFamilyInCart($productFamily)
  308. {
  309. $arrayOrderProducts = [] ;
  310. $orderShop = $this->getCartCurrent() ;
  311. if($orderShop) {
  312. foreach($orderShop->getOrderProducts() as $orderProduct) {
  313. if($orderProduct->getProduct()->getProductFamily() == $productFamily) {
  314. $arrayOrderProducts[] = $orderProduct ;
  315. }
  316. }
  317. }
  318. return $arrayOrderProducts ;
  319. }
  320. public function groupOrderProductsByProductFamily($orderProducts)
  321. {
  322. $orderProductsByProductFamily = [];
  323. foreach ($orderProducts as $orderProduct) {
  324. if ($orderProduct->getProduct() && $orderProduct->getProduct()->getProductFamily()) {
  325. $productFamily = $orderProduct->getProduct()->getProductFamily();
  326. if (!isset($orderProductsByProductFamily[$productFamily->getId()])) {
  327. $orderProductsByProductFamily[$productFamily->getId()] = [
  328. 'order_products' => [],
  329. 'total_quantity_weight' => 0,
  330. ];
  331. }
  332. $orderProductsByProductFamily[$productFamily->getId()]['order_products'][] = $orderProduct;
  333. $orderProductsByProductFamily[$productFamily->getId()]['total_quantity_weight'] += ($orderProduct->getQuantityProduct() / $orderProduct->getUnit()->getCoefficient()) * $orderProduct->getQuantityOrder();
  334. }
  335. }
  336. return $orderProductsByProductFamily;
  337. }
  338. public function isOrderShopPositiveAmount(OrderShopInterface $orderShop)
  339. {
  340. return $this->priceUtils->getTotalWithTax($orderShop) >= 0 ;
  341. }
  342. public function eventCartChange(OrderShopInterface $orderShop)
  343. {
  344. }
  345. public function addPayment($orderShop, $meanPayment, $amount)
  346. {
  347. $this->createOrderPayment([
  348. 'orderShop' => $orderShop,
  349. 'meanPayment' => $meanPayment,
  350. 'amount' => $amount
  351. ]) ;
  352. $this->em->refresh($orderShop) ;
  353. if($this->isOrderPaid($orderShop)) {
  354. $nextStatus = OrderStatus::ALIAS_PAID ;
  355. }
  356. else {
  357. $nextStatus = OrderStatus::ALIAS_PARTIAL_PAYMENT ;
  358. }
  359. if($orderShop->getOrderStatus()->getAlias() != $nextStatus) {
  360. $orderShop = $this->changeOrderStatus(
  361. $nextStatus,
  362. $orderShop
  363. );
  364. }
  365. return $orderShop ;
  366. }
  367. }