You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1064 lines
43KB

  1. <?php
  2. /**
  3. * Copyright Souke (2018)
  4. *
  5. * contact@souke.fr
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace producer\controllers;
  38. use common\helpers\GlobalParam;
  39. use common\helpers\Image;
  40. use common\helpers\Password;
  41. use domain\Config\Unit\UnitDefinition;
  42. use domain\Distribution\Distribution\Distribution;
  43. use domain\Feature\Feature\Feature;
  44. use domain\Order\Order\Order;
  45. use domain\Order\Order\OrderRepositoryQuery;
  46. use domain\Order\OrderStatus\OrderStatus;
  47. use domain\Order\ProductOrder\ProductOrder;
  48. use domain\PointSale\PointSale\PointSale;
  49. use domain\Producer\Producer\Producer;
  50. use domain\Product\Product\Product;
  51. use DateTime;
  52. use domain\User\User\User;
  53. use yii\base\UserException;
  54. use yii\data\ActiveDataProvider;
  55. use yii\filters\AccessControl;
  56. use yii\web\NotFoundHttpException;
  57. class OrderController extends ProducerBaseController
  58. {
  59. var $enableCsrfValidation = false;
  60. public function behaviors()
  61. {
  62. return [
  63. 'access' => [
  64. 'class' => AccessControl::class,
  65. 'only' => [
  66. 'history',
  67. 'remove-producer',
  68. 'cancel'
  69. ],
  70. 'rules' => [
  71. [
  72. 'allow' => true,
  73. 'roles' => ['@']
  74. ]
  75. ],
  76. ],
  77. ];
  78. }
  79. public function actionOrder(int $id = 0, string $date = '', int $idPointSale = null)
  80. {
  81. $orderModule = $this->getOrderModule();
  82. $distributionModule = $this-> getDistributionModule();
  83. $params = [];
  84. $producer = $this->getProducerCurrent();
  85. if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) {
  86. return $this->redirect(
  87. $this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id])
  88. );
  89. }
  90. $order = $orderModule->getRepository()->findOneOrderById($id);
  91. if ($order && $orderModule->getRepository()->isOrderStateOpen($order)) {
  92. $params['order'] = $order;
  93. }
  94. if ($distributionModule->isDistributionDateAvailable($date)) {
  95. $params['date'] = $date;
  96. }
  97. if($idPointSale) {
  98. $params['idPointSale'] = $idPointSale;
  99. }
  100. return $this->render('order', $params);
  101. }
  102. /**
  103. * Affiche l'historique des commandes de l'utilisateur.
  104. */
  105. public function actionHistory($type = 'incoming')
  106. {
  107. $queryHistoryArray = $this->getOrderModule()
  108. ->queryOrdersHistory($this->getProducerCurrent(), $this->getUserCurrent());
  109. $queryHistoryIncoming = $queryHistoryArray['incoming'];
  110. $queryHistoryPassed = $queryHistoryArray['passed'];
  111. $dataProviderOrders = new ActiveDataProvider([
  112. 'query' => ($type == 'incoming') ? $queryHistoryIncoming->query() : $queryHistoryPassed->query(),
  113. 'pagination' => [
  114. 'pageSize' => 10,
  115. ],
  116. ]);
  117. return $this->render('history', [
  118. 'dataProviderOrders' => $dataProviderOrders,
  119. 'orderOk' => \Yii::$app->getRequest()->get('orderOk', false),
  120. 'cancelOk' => \Yii::$app->getRequest()->get('cancelOk', false),
  121. 'type' => $type,
  122. 'countIncoming' => $queryHistoryIncoming->count(),
  123. 'countPassed' => $queryHistoryPassed->count(),
  124. ]);
  125. }
  126. public function actionRemoveProducer(int $id = 0)
  127. {
  128. $producer = $this->getProducerModule()->findOneProducerById($id);
  129. $this->getUserProducerModule()->updateActive(
  130. $this->getUserCurrent(),
  131. $producer,
  132. false
  133. );
  134. return $this->redirect(['order/index']);
  135. }
  136. /**
  137. * Crée une commande.
  138. */
  139. public function actionAjaxProcess()
  140. {
  141. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  142. $posts = \Yii::$app->request->post();
  143. $orderModule = $this->getOrderModule();
  144. $producerModule = $this->getProducerModule();
  145. $userModule = $this->getUserModule();
  146. $productOrderModule = $this->getProductOrderModule();
  147. $producer = $this->getProducerCurrent();
  148. $redirect = null;
  149. $idProducer = $producer->id;
  150. $order = new Order;
  151. if ($idProducer) {
  152. $this->_verifyProducerActive($idProducer);
  153. }
  154. if ($order->load($posts)) {
  155. $user = $this->getUserCurrent();
  156. $order = Order::find()
  157. ->where('id_distribution = :id_distribution')
  158. ->andWhere('id_user = :id_user')
  159. ->andWhere('id_point_sale = :id_point_sale')
  160. ->andWhere(OrderRepositoryQuery::getSqlFilterIsValid())
  161. ->params([
  162. ':id_distribution' => $posts['Order']['id_distribution'],
  163. ':id_point_sale' => $posts['Order']['id_point_sale'],
  164. ':id_user' => $user ? $user->id : null
  165. ])
  166. ->one();
  167. if ($order && !$order->online_payment_url) {
  168. if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
  169. $order->id_point_sale = $posts['Order']['id_point_sale'];
  170. }
  171. } else {
  172. // gestion user : option_allow_order_guest
  173. if (isset($posts['user']) && $posts['user']) {
  174. $userIndividualExist = User::searchOne([
  175. 'email' => $posts['user']['email'],
  176. 'type' => User::TYPE_INDIVIDUAL
  177. ]);
  178. if ($userIndividualExist) {
  179. $errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . \Yii::$app->urlManagerFrontend->createUrl(
  180. ['site/producer', 'id' => $idProducer]
  181. ) . '">connecter à votre compte</a> ou en utiliser une autre.';
  182. return ['status' => 'error', 'errors' => [$errorUserGuest]];
  183. }
  184. $user = User::searchOne([
  185. 'email' => $posts['user']['email'],
  186. 'type' => User::TYPE_GUEST
  187. ]);
  188. if (!$user) {
  189. $user = new User;
  190. $user->id_producer = 0;
  191. $user->type = User::TYPE_GUEST;
  192. $userModule->setPassword($user, Password::generate());
  193. $userModule->generateAuthKey($user);
  194. $user->username = $posts['user']['email'];
  195. $user->email = $posts['user']['email'];
  196. $user->name = $posts['user']['firstname'];
  197. $user->lastname = $posts['user']['lastname'];
  198. $user->phone = $posts['user']['phone'];
  199. $user->save();
  200. // liaison producer / user
  201. $producerModule->addUser($user, $producer);
  202. } else {
  203. $producerModule->addUser($user, $producer);
  204. }
  205. }
  206. $order = new Order;
  207. $order->load(\Yii::$app->request->post());
  208. $order->id_user = $user ? $user->id : null;
  209. $order->date = date('Y-m-d H:i:s');
  210. $order->origin = Order::ORIGIN_USER;
  211. }
  212. $errors = $this->processForm($order, $user);
  213. if (count($errors)) {
  214. return ['status' => 'error', 'errors' => $errors];
  215. }
  216. if ($producerModule->getSolver()->isOnlinePaymentActive($producer) && $posts['payment_method'] == 'online') {
  217. $order = $orderModule->findOneOrderById($order->id);
  218. \Stripe\Stripe::setApiKey(
  219. $producerModule->getPrivateKeyApiStripe($producer)
  220. );
  221. $lineItems = [];
  222. foreach ($order->productOrder as $productOrder) {
  223. $product = $productOrder->product;
  224. $lineItems[] = [
  225. 'price_data' => [
  226. 'currency' => 'eur',
  227. 'product_data' => [
  228. 'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductModule()->getSolver()->strUnit(
  229. $product,
  230. UnitDefinition::WORDING_SHORT,
  231. true
  232. ) . ')',
  233. ],
  234. 'unit_amount' => intval($productOrderModule->getSolver()->getPriceWithTax($productOrder) * 100 * $productOrder->quantity),
  235. ],
  236. 'quantity' => 1,
  237. ];
  238. }
  239. $checkout_session = \Stripe\Checkout\Session::create([
  240. 'line_items' => $lineItems,
  241. 'payment_method_types' => ['card'],
  242. 'mode' => 'payment',
  243. 'customer_email' => $user->email,
  244. 'client_reference_id' => $user->id,
  245. 'payment_intent_data' => [
  246. 'metadata' => [
  247. 'user_id' => $user->id,
  248. 'producer_id' => $producer->id,
  249. 'order_id' => $order->id
  250. ],
  251. ],
  252. 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  253. [
  254. 'order/confirm',
  255. 'idOrder' => $order->id,
  256. 'returnPayment' => 'success'
  257. ]
  258. ),
  259. 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  260. [
  261. 'order/confirm',
  262. 'idOrder' => $order->id,
  263. 'returnPayment' => 'cancel'
  264. ]
  265. ),
  266. ]);
  267. $redirect = $checkout_session->url;
  268. $order->online_payment_url = $redirect;
  269. $order->save();
  270. }
  271. }
  272. return ['status' => 'success', 'idOrder' => $order->id, 'redirect' => $redirect];
  273. }
  274. /**
  275. * Vérifie si un producteur est actif.
  276. */
  277. public function _verifyProducerActive($idProducer)
  278. {
  279. $producer = $this->getProducerModule()->findOneProducerById($idProducer);
  280. if ($producer && !$producer->active) {
  281. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  282. }
  283. }
  284. /**
  285. * Traite le formulaire de création/modification de commande.
  286. */
  287. public function processForm($order, $user)
  288. {
  289. $productModule = $this->getProductModule();
  290. $distributionModule = $this-> getDistributionModule();
  291. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  292. $pointSaleModule = $this->getPointSaleModule();
  293. $userPointSaleModule = $this->getUserPointSaleModule();
  294. $userProducerModule = $this->getUserProducerModule();
  295. $orderModule = $this->getOrderModule();
  296. $producerModule = $this->getProducerModule();
  297. $productOrderModule = $this->getProductOrderModule();
  298. $userModule = $this->getUserModule();
  299. $paymentManager = $this->getPaymentModule();
  300. $posts = \Yii::$app->request->post();
  301. $productsArray = [];
  302. $totalQuantity = 0;
  303. $producer = $this->getProducerCurrent();
  304. $isNewOrder = false;
  305. if (!$order->id) {
  306. $isNewOrder = true;
  307. }
  308. foreach ($posts['products'] as $key => $quantity) {
  309. $product = $productModule->findOneProductById((int)$key);
  310. $totalQuantity += $quantity;
  311. if ($product && $quantity) {
  312. $productsArray[] = $product;
  313. }
  314. }
  315. $errorDate = false;
  316. if (isset($order->id_distribution)) {
  317. $distribution = $distributionModule->findOneDistributionById($order->id_distribution);
  318. if ($orderModule->getState($order) != Order::STATE_OPEN) {
  319. $errorDate = true;
  320. }
  321. }
  322. $errorPointSale = false;
  323. if (isset($distribution) && $distribution) {
  324. $order->populateDistribution($distribution);
  325. $pointSale = $pointSaleModule->findOnePointSaleById($posts['Order']['id_point_sale']);
  326. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution($distribution, $pointSale);
  327. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  328. $errorPointSale = true;
  329. }
  330. if ($pointSale) {
  331. if (strlen($pointSale->code) && !$pointSaleModule->validateCode($pointSale, $posts['code_point_sale'])) {
  332. $errorPointSale = true;
  333. }
  334. } else {
  335. $errorPointSale = true;
  336. }
  337. $userPointSale = $userPointSaleModule->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
  338. if ($pointSale && $pointSale->restricted_access && !$userPointSale) {
  339. $errorPointSale = true;
  340. }
  341. }
  342. $errors = [];
  343. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  344. $userProducer = $userProducerModule->findOneUserProducer($user);
  345. $pointSale = $pointSaleModule->findOnePointSaleById($order->id_point_sale);
  346. $order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ?
  347. $pointSaleModule->getComment($pointSale) : '';
  348. // une commande annulée est automatiquement réactivée lors d'une modification
  349. if($orderModule->getSolver()->isOrderStatusCanceled($order)) {
  350. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $this->getUserCurrent());
  351. }
  352. $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
  353. $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
  354. // on sauvegarde l'adresse de livraison dans le profil de l'utilisateur pour qu'il n'ait plus à la ressaisir
  355. if($order->delivery_address && !$user->address) {
  356. $user->address = $order->delivery_address;
  357. $user->save();
  358. }
  359. $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
  360. $order->save();
  361. $orderModule->generateOrderReference($order);
  362. if($isNewOrder) {
  363. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
  364. }
  365. else {
  366. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $user);
  367. }
  368. $producerModule->addUser($user, $producer);
  369. // suppression de tous les enregistrements ProductOrder
  370. if (!is_null($order)) {
  371. $productOrderModule->deleteProductOrdersByOrder($order);
  372. if (isset($order->productOrder)) {
  373. foreach ($order->productOrder as $productOrder) {
  374. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  375. }
  376. }
  377. }
  378. $availableProducts = $orderModule->findProductDistributionsByDistribution($distribution);
  379. foreach ($productsArray as $product) {
  380. if (isset($availableProducts[$product->id])) {
  381. $productOrder = new ProductOrder();
  382. $productOrder->id_order = $order->id;
  383. $productOrder->id_product = $product->id;
  384. $productOrder->id_tax_rate = $product->taxRate->id;
  385. $unit = (!is_null(
  386. $order
  387. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  388. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  389. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  390. $quantityRemaining = $orderModule->getResolver()->getProductQuantityRemaining($product, $order->distribution);
  391. if(!is_null($quantityRemaining) && $quantity > $quantityRemaining) {
  392. $quantity = $quantityRemaining;
  393. }
  394. $productOrder->quantity = $quantity;
  395. $productOrder->price = $productModule->getPrice($product, [
  396. 'user' => $this->getUserCurrent(),
  397. 'user_producer' => $userProducer,
  398. 'point_sale' => $pointSale,
  399. 'quantity' => $quantity
  400. ]);
  401. $productOrder->unit = $product->unit;
  402. $productOrder->step = $product->step;
  403. if($quantity) {
  404. $productOrder->save();
  405. }
  406. }
  407. }
  408. // lien utilisateur / point de vente
  409. $pointSaleModule->addUser($user, $pointSale);
  410. // credit
  411. $credit = $producerModule->getConfig('credit');
  412. $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
  413. $order = $orderModule->findOneOrderById($order->id);
  414. $orderModule->initOrder($order);
  415. if ($credit
  416. && $this->getUserCurrent()
  417. && $pointSale->payment_method_credit
  418. && $posts['payment_method'] == 'credit'
  419. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  420. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  421. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  422. )) {
  423. // à payer
  424. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  425. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  426. } // surplus à rembourser
  427. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  428. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  429. }
  430. }
  431. /*
  432. * Envoi email de confirmation
  433. */
  434. $emailSubject = 'Confirmation de commande';
  435. $emailContentParams = [
  436. 'order' => $order,
  437. 'pointSale' => $pointSale,
  438. 'distribution' => $distribution,
  439. 'user' => $user,
  440. 'producer' => $producer
  441. ];
  442. // au client
  443. if ($producerModule->getConfig('option_email_confirm')) {
  444. \Yii::$app->mailerService->sendFromProducer(
  445. $emailSubject,
  446. 'orderConfirm',
  447. $emailContentParams,
  448. $user->email,
  449. $producer
  450. );
  451. }
  452. // au producteur
  453. $contactProducer = $producerModule->getMainContact($producer);
  454. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  455. $contactProducer->email
  456. )) {
  457. \Yii::$app->mailerService->sendFromSite(
  458. $emailSubject,
  459. 'orderConfirmProducer',
  460. $emailContentParams,
  461. $contactProducer->email
  462. );
  463. }
  464. $order = $orderModule->findOneOrderById($order->id);
  465. $orderModule->initOrder($order);
  466. $orderModule->updateOrderTillerSynchronization($order);
  467. }
  468. if (!count($productsArray)) {
  469. $errors[] = "Vous n'avez choisi aucun produit";
  470. }
  471. if ($errorDate) {
  472. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  473. }
  474. if ($errorPointSale) {
  475. $errors[] = "Point de vente invalide.";
  476. }
  477. return $errors;
  478. }
  479. /**
  480. * Annule une commande.
  481. */
  482. public function actionCancel(int $id)
  483. {
  484. $orderModule = $this->getOrderModule();
  485. $order = $this->getOrderModule()->findOneOrderById($id);
  486. if (!$order) {
  487. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  488. }
  489. $orderModule->getBuilder()->initOrder($order);
  490. if (!$orderModule->isOrderStateOpen($order)) {
  491. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  492. }
  493. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  494. $orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
  495. $this->setFlash('success', 'Votre commande a bien été annulée.');
  496. }
  497. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  498. }
  499. /**
  500. * Page de confirmation de commande.
  501. */
  502. public function actionConfirm(int $idOrder, string $returnPayment = '')
  503. {
  504. $orderModule = $this->getOrderModule();
  505. $order = $orderModule->findOneOrderById($idOrder);
  506. $producer = $this->getProducerCurrent();
  507. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  508. $this->setFlash('error', 'Commande introuvable');
  509. return $this->redirect(['order/history']);
  510. }
  511. $orderModule->initOrder($order);
  512. return $this->render('confirm', [
  513. 'order' => $order,
  514. 'returnPayment' => $returnPayment
  515. ]);
  516. }
  517. /**
  518. * Vérifie le code saisi pour un point de vente.
  519. */
  520. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  521. {
  522. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  523. $pointSaleModule = $this->getPointSaleModule();
  524. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  525. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  526. return 1;
  527. }
  528. return 0;
  529. }
  530. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0, string $productsJson = null, bool $loadingProducts = false)
  531. {
  532. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  533. $productsArray = json_decode($productsJson, true);
  534. $user = GlobalParam::getCurrentUser();
  535. $producer = $this->getProducerCurrent();
  536. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  537. $order = $this->getOrderUser($date, $pointSale);
  538. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order, $productsArray, $loadingProducts);
  539. }
  540. public function buildJsonAjaxInfos(
  541. string $date,
  542. Producer $producer,
  543. PointSale $pointSale = null,
  544. User $user = null,
  545. Order $order = null,
  546. array $productsArray = null,
  547. bool $loadingProducts = false
  548. )
  549. {
  550. $orderModule = $this->getOrderModule();
  551. $json = [];
  552. $format = 'Y-m-d';
  553. $dateObject = DateTime::createFromFormat($format, $date);
  554. $json['producer'] = $this->ajaxInfosProducer($producer);
  555. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  556. $json['orders'] = $this->ajaxInfosOrders($producer);
  557. $json['user'] = $this->ajaxInfosUser($producer);
  558. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  559. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  560. if ($dateObject && $dateObject->format($format) === $date) {
  561. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  562. $json['distribution'] = $distribution;
  563. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  564. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  565. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order, $productsArray);
  566. if ($order) {
  567. $json['order'] = array_merge($order->getAttributes(), [
  568. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  569. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  570. ]);
  571. }
  572. }
  573. return $json;
  574. }
  575. public function ajaxInfosLeavePeriod(Producer $producer)
  576. {
  577. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  578. return [
  579. 'start' => $producer->option_leave_period_start,
  580. 'end' => $producer->option_leave_period_end,
  581. ];
  582. }
  583. return false;
  584. }
  585. public function ajaxInfosProducer(Producer $producer)
  586. {
  587. return [
  588. 'order_infos' => nl2br($producer->order_infos),
  589. 'payment_infos' => nl2br($producer->option_payment_info),
  590. 'credit' => $producer->credit,
  591. 'credit_functioning' => $producer->credit_functioning,
  592. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  593. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  594. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  595. 'option_order_entry_point' => $producer->option_order_entry_point,
  596. 'option_delivery' => $producer->option_delivery,
  597. 'online_payment' => $producer->online_payment,
  598. 'option_online_payment_type' => $producer->online_payment,
  599. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  600. ];
  601. }
  602. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  603. {
  604. $distributionModule = $this-> getDistributionModule();
  605. $dateMini = date('Y-m-d');
  606. $distributionsArray = Distribution::searchAll([
  607. 'active' => 1,
  608. 'id_producer' => $producer->id
  609. ], [
  610. 'conditions' => ['date > :date'],
  611. 'params' => [':date' => $dateMini],
  612. 'join_with' => ['pointSaleDistribution'],
  613. ]);
  614. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  615. // Filtre par période de congé
  616. foreach ($distributionsArray as $keyDistribution => $distribution) {
  617. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  618. unset($distributionsArray[$keyDistribution]);
  619. }
  620. }
  621. // Filtre par point de vente
  622. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  623. $distributionsArrayFilterPointSale = [];
  624. for ($i = 0; $i < count($distributionsArray); $i++) {
  625. $distribution = $distributionsArray[$i];
  626. if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  627. $countOrders = Order::searchCount([
  628. 'id_distribution' => $distribution->id,
  629. 'id_point_sale' => $pointSaleCurrent->id
  630. ]);
  631. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  632. if (!$pointSaleCurrent->maximum_number_orders
  633. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  634. || ($pointSaleCurrent->maximum_number_orders &&
  635. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  636. $distributionsArrayFilterPointSale[] = $distribution;
  637. }
  638. }
  639. }
  640. return $distributionsArrayFilterPointSale;
  641. } else {
  642. return $distributionsArray;
  643. }
  644. }
  645. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  646. {
  647. $orderModule = $this->getOrderModule();
  648. $dateMini = date('Y-m-d');
  649. $ordersUserArray = [];
  650. if (GlobalParam::getCurrentUserId()) {
  651. $conditionsOrdersUser = [
  652. 'distribution.date > :date',
  653. 'order.online_payment_url IS NULL'
  654. ];
  655. $paramsOrdersUser = [
  656. ':date' => $dateMini
  657. ];
  658. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  659. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  660. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  661. }
  662. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  663. $ordersUserArray = Order::searchAll([
  664. 'id_user' => GlobalParam::getCurrentUserId()
  665. ], [
  666. 'conditions' => $conditionsOrdersUser,
  667. 'params' => $paramsOrdersUser
  668. ]);
  669. }
  670. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  671. foreach ($ordersUserArray as &$order) {
  672. $orderModule->initOrder($order);
  673. $order = array_merge($order->getAttributes(), [
  674. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  675. 'date_distribution' => $order->distribution->date,
  676. 'pointSale' => $order->pointSale->getAttributes()
  677. ]);
  678. }
  679. }
  680. return $ordersUserArray;
  681. }
  682. public function ajaxInfosUser(Producer $producer)
  683. {
  684. $userProducerModule = $this->getUserProducerModule();
  685. $producerModule = $this->getProducerModule();
  686. $user = GlobalParam::getCurrentUser();
  687. if($user) {
  688. $userProducer = $userProducerModule->findOneUserProducer($user);
  689. if (!$userProducer) {
  690. $userProducer = $producerModule->addUser($user, $producer);
  691. }
  692. }
  693. $jsonUser = false;
  694. if ($user && $userProducer) {
  695. $jsonUser = [
  696. 'address' => $user->address,
  697. 'credit' => $userProducer->credit,
  698. 'credit_active' => $userProducer->credit_active,
  699. ];
  700. }
  701. return $jsonUser;
  702. }
  703. private function ajaxInfosPointsSale($producer, $distribution = null)
  704. {
  705. $pointSaleModule = $this->getPointSaleModule();
  706. $producerModule = $this->getProducerModule();
  707. $orderModule = $this->getOrderModule();
  708. $user = GlobalParam::getCurrentUser();
  709. $pointsSaleArray = PointSale::find();
  710. if ($distribution) {
  711. $pointsSaleArray = $pointsSaleArray->joinWith([
  712. 'pointSaleDistribution' => function ($query) use (
  713. $distribution
  714. ) {
  715. $query->where(
  716. [
  717. 'id_distribution' => $distribution->id,
  718. 'delivery' => 1
  719. ]
  720. );
  721. }
  722. ]);
  723. }
  724. if (GlobalParam::getCurrentUserId()) {
  725. $pointsSaleArray = $pointsSaleArray->with([
  726. 'userPointSale' => function ($query) {
  727. $query->onCondition(
  728. ['id_user' => GlobalParam::getCurrentUserId()]
  729. );
  730. }
  731. ]);
  732. }
  733. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  734. ->andWhere(
  735. 'status = 1 AND (restricted_access = 0 OR (restricted_access = 1 AND (SELECT COUNT(*) FROM user_point_sale WHERE point_sale.id = user_point_sale.id_point_sale AND user_point_sale.id_user = :id_user) > 0))'
  736. )
  737. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  738. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  739. ->all();
  740. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  741. $position = 0;
  742. foreach ($pointsSaleArray as &$pointSale) {
  743. $pointSaleObject = $pointSale;
  744. $pointSale = array_merge($pointSale->getAttributes(), [
  745. 'pointSaleDistribution' => [
  746. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  747. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  748. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  749. ],
  750. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  751. ]);
  752. if ($pointSale['code'] && strlen($pointSale['code'])) {
  753. $pointSale['code'] = '***';
  754. }
  755. if (!strlen($pointSale['credit_functioning'])) {
  756. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  757. }
  758. if ($distribution) {
  759. $pointSale['count_orders'] = (int)Order::searchCount([
  760. 'id_distribution' => $distribution->id,
  761. 'id_point_sale' => $pointSale['id']
  762. ]);
  763. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  764. }
  765. $pointSale['producers_sharing_point_sale_as_string'] = false;
  766. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  767. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  768. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  769. }
  770. $pointSale['position'] = $position;
  771. $position++;
  772. }
  773. $favoritePointSale = false;
  774. if ($user) {
  775. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  776. }
  777. if ($favoritePointSale) {
  778. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  779. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  780. $theFavoritePointSale = $pointsSaleArray[$i];
  781. unset($pointsSaleArray[$i]);
  782. }
  783. }
  784. if (isset($theFavoritePointSale)) {
  785. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  786. $pointsSaleArray[] = $theFavoritePointSale;
  787. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  788. }
  789. }
  790. return $pointsSaleArray;
  791. }
  792. public function ajaxInfosProductCategories(Producer $producer)
  793. {
  794. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  795. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  796. if ($countProductsWithoutCategory) {
  797. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  798. }
  799. return $categoriesArray;
  800. }
  801. public function ajaxInfosProducts(
  802. Producer $producer,
  803. Distribution $distribution,
  804. PointSale $pointSale = null,
  805. User $user = null,
  806. Order $order = null,
  807. array $productsFormArray = null
  808. )
  809. {
  810. $unitModule = $this->getUnitModule();
  811. $productModule = $this->getProductModule();
  812. $orderModule = $this->getOrderModule();
  813. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  814. $productsArray = Product::find()
  815. ->where([
  816. 'id_producer' => $producer->id,
  817. 'product.status' => 1,
  818. ]);
  819. $productsArray = $productsArray->joinWith([
  820. 'productDistribution' => function ($query) use (
  821. $distribution
  822. ) {
  823. $query->andOnCondition(
  824. 'product_distribution.id_distribution = ' . $distribution->id
  825. );
  826. },
  827. 'productPrice'
  828. ])
  829. ->orderBy('product_distribution.active DESC, order ASC')
  830. ->all();
  831. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  832. $orderCurrent = $order;
  833. if(count($productsFormArray)) {
  834. $productOrdersArray = [];
  835. foreach($productsFormArray as $idProduct => $quantityProduct) {
  836. if($idProduct) {
  837. $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
  838. $productOrdersArray[$idProduct] = [
  839. 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
  840. ];
  841. }
  842. }
  843. $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
  844. }
  845. $indexProduct = 0;
  846. foreach ($productsArrayFilter as $key => &$product) {
  847. $productObject = $product;
  848. $product = array_merge(
  849. $product->getAttributes(),
  850. [
  851. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  852. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  853. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  854. 'productDistribution' => $product['productDistribution'],
  855. 'productPointSale' => $product['productPointSale'],
  856. ]
  857. );
  858. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  859. $product['photo'] = '';
  860. }
  861. else {
  862. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  863. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  864. }
  865. $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
  866. $product['coefficient_unit'] = $coefficientUnit;
  867. $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
  868. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  869. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  870. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  871. $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
  872. $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
  873. if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
  874. $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
  875. $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
  876. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  877. }
  878. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  879. if ($order) {
  880. foreach ($order->productOrder as $productOrder) {
  881. if ($productOrder->id_product == $product['id']) {
  882. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  883. $product['step'] = $productOrder->step;
  884. }
  885. }
  886. }
  887. $product['index'] = $indexProduct++;
  888. }
  889. return $productsArrayFilter;
  890. }
  891. private function getOrderUser(string $date, PointSale $pointSale = null)
  892. {
  893. $orderModule = $this->getOrderModule();
  894. $orderUser = null;
  895. if (GlobalParam::getCurrentUserId()) {
  896. $conditionOrderUser = [
  897. 'distribution.date' => $date,
  898. 'id_user' => GlobalParam::getCurrentUserId()
  899. ];
  900. if ($pointSale) {
  901. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  902. }
  903. $orderUser = Order::searchOne($conditionOrderUser, [
  904. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  905. ]);
  906. if ($orderUser && $orderUser->online_payment_url) {
  907. $orderUser = null;
  908. }
  909. }
  910. if($orderUser) {
  911. $orderModule->initOrder($orderUser);
  912. }
  913. return $orderUser;
  914. }
  915. }