Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1072 lines
44KB

  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 ($order->load($posts)) {
  152. $user = $this->getUserCurrent();
  153. $order = Order::find()
  154. ->where('id_distribution = :id_distribution')
  155. ->andWhere('id_user = :id_user')
  156. ->andWhere('id_point_sale = :id_point_sale')
  157. ->andWhere(OrderRepositoryQuery::getSqlFilterIsValid())
  158. ->params([
  159. ':id_distribution' => $posts['Order']['id_distribution'],
  160. ':id_point_sale' => $posts['Order']['id_point_sale'],
  161. ':id_user' => $user ? $user->id : null
  162. ])
  163. ->one();
  164. if ($order && !$order->online_payment_url) {
  165. if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
  166. $order->id_point_sale = $posts['Order']['id_point_sale'];
  167. }
  168. } else {
  169. // gestion user : option_allow_order_guest
  170. if (isset($posts['user']) && $posts['user']) {
  171. $userIndividualExist = User::searchOne([
  172. 'email' => $posts['user']['email'],
  173. 'type' => User::TYPE_INDIVIDUAL
  174. ]);
  175. if ($userIndividualExist) {
  176. $errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . \Yii::$app->urlManagerFrontend->createUrl(
  177. ['site/producer', 'id' => $idProducer]
  178. ) . '">connecter à votre compte</a> ou en utiliser une autre.';
  179. return ['status' => 'error', 'errors' => [$errorUserGuest]];
  180. }
  181. $user = User::searchOne([
  182. 'email' => $posts['user']['email'],
  183. 'type' => User::TYPE_GUEST
  184. ]);
  185. if (!$user) {
  186. $user = new User;
  187. $user->id_producer = 0;
  188. $user->type = User::TYPE_GUEST;
  189. $userModule->setPassword($user, Password::generate());
  190. $userModule->generateAuthKey($user);
  191. $user->username = $posts['user']['email'];
  192. $user->email = $posts['user']['email'];
  193. $user->name = $posts['user']['firstname'];
  194. $user->lastname = $posts['user']['lastname'];
  195. $user->phone = $posts['user']['phone'];
  196. $user->save();
  197. // liaison producer / user
  198. $producerModule->addUser($user, $producer);
  199. } else {
  200. $producerModule->addUser($user, $producer);
  201. }
  202. }
  203. $order = new Order;
  204. $order->load(\Yii::$app->request->post());
  205. $order->id_user = $user ? $user->id : null;
  206. $order->date = date('Y-m-d H:i:s');
  207. $order->origin = Order::ORIGIN_USER;
  208. }
  209. $errors = $this->processForm($order, $user);
  210. if (count($errors)) {
  211. return ['status' => 'error', 'errors' => $errors];
  212. }
  213. if ($producerModule->getSolver()->isOnlinePaymentActive($producer) && $posts['payment_method'] == 'online') {
  214. $order = $orderModule->findOneOrderById($order->id);
  215. \Stripe\Stripe::setApiKey(
  216. $producerModule->getPrivateKeyApiStripe($producer)
  217. );
  218. $lineItems = [];
  219. foreach ($order->productOrder as $productOrder) {
  220. $product = $productOrder->product;
  221. $lineItems[] = [
  222. 'price_data' => [
  223. 'currency' => 'eur',
  224. 'product_data' => [
  225. 'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductModule()->getSolver()->strUnit(
  226. $product,
  227. UnitDefinition::WORDING_SHORT,
  228. true
  229. ) . ')',
  230. ],
  231. 'unit_amount' => intval($productOrderModule->getSolver()->getPriceWithTax($productOrder) * 100 * $productOrder->quantity),
  232. ],
  233. 'quantity' => 1,
  234. ];
  235. }
  236. $checkout_session = \Stripe\Checkout\Session::create([
  237. 'line_items' => $lineItems,
  238. 'payment_method_types' => ['card'],
  239. 'mode' => 'payment',
  240. 'customer_email' => $user->email,
  241. 'client_reference_id' => $user->id,
  242. 'payment_intent_data' => [
  243. 'metadata' => [
  244. 'user_id' => $user->id,
  245. 'producer_id' => $producer->id,
  246. 'order_id' => $order->id
  247. ],
  248. ],
  249. 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  250. [
  251. 'order/confirm',
  252. 'idOrder' => $order->id,
  253. 'returnPayment' => 'success'
  254. ]
  255. ),
  256. 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  257. [
  258. 'order/confirm',
  259. 'idOrder' => $order->id,
  260. 'returnPayment' => 'cancel'
  261. ]
  262. ),
  263. ]);
  264. $redirect = $checkout_session->url;
  265. $order->online_payment_url = $redirect;
  266. $order->save();
  267. }
  268. }
  269. return ['status' => 'success', 'idOrder' => $order->id, 'redirect' => $redirect];
  270. }
  271. /**
  272. * Vérifie si un producteur est actif.
  273. */
  274. public function _verifyProducerActive($idProducer)
  275. {
  276. $producer = $this->getProducerModule()->findOneProducerById($idProducer);
  277. if ($producer && !$producer->active) {
  278. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  279. }
  280. }
  281. /**
  282. * Traite le formulaire de création/modification de commande.
  283. */
  284. public function processForm($order, $user)
  285. {
  286. $productModule = $this->getProductModule();
  287. $distributionModule = $this-> getDistributionModule();
  288. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  289. $pointSaleModule = $this->getPointSaleModule();
  290. $userPointSaleModule = $this->getUserPointSaleModule();
  291. $userProducerModule = $this->getUserProducerModule();
  292. $orderModule = $this->getOrderModule();
  293. $producerModule = $this->getProducerModule();
  294. $productOrderModule = $this->getProductOrderModule();
  295. $userModule = $this->getUserModule();
  296. $paymentManager = $this->getPaymentModule();
  297. $posts = \Yii::$app->request->post();
  298. $productsArray = [];
  299. $totalQuantity = 0;
  300. $producer = $this->getProducerCurrent();
  301. $isNewOrder = false;
  302. if (!$order->id) {
  303. $isNewOrder = true;
  304. }
  305. foreach ($posts['products'] as $key => $quantity) {
  306. $product = $productModule->findOneProductById((int)$key);
  307. $totalQuantity += $quantity;
  308. if ($product && $quantity) {
  309. $productsArray[] = $product;
  310. }
  311. }
  312. $errorDate = false;
  313. if (isset($order->id_distribution)) {
  314. $distribution = $distributionModule->findOneDistributionById($order->id_distribution);
  315. if ($orderModule->getState($order) != Order::STATE_OPEN) {
  316. $errorDate = true;
  317. }
  318. }
  319. $errorPointSale = false;
  320. if (isset($distribution) && $distribution) {
  321. $order->populateDistribution($distribution);
  322. $pointSale = $pointSaleModule->findOnePointSaleById($posts['Order']['id_point_sale']);
  323. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution($distribution, $pointSale);
  324. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  325. $errorPointSale = true;
  326. }
  327. if ($pointSale) {
  328. if (strlen($pointSale->code) && !$pointSaleModule->validateCode($pointSale, $posts['code_point_sale'])) {
  329. $errorPointSale = true;
  330. }
  331. } else {
  332. $errorPointSale = true;
  333. }
  334. $userPointSale = $userPointSaleModule->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
  335. if ($pointSale && $pointSale->restricted_access && !$userPointSale) {
  336. $errorPointSale = true;
  337. }
  338. }
  339. $errors = [];
  340. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  341. $userProducer = $userProducerModule->findOneUserProducer($user);
  342. $pointSale = $pointSaleModule->findOnePointSaleById($order->id_point_sale);
  343. $order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ?
  344. $pointSaleModule->getComment($pointSale) : '';
  345. // une commande annulée est automatiquement réactivée lors d'une modification
  346. if($order->isOrderStatusCanceled()) {
  347. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $this->getUserCurrent());
  348. }
  349. $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
  350. $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
  351. // on sauvegarde l'adresse de livraison dans le profil de l'utilisateur pour qu'il n'ait plus à la ressaisir
  352. if($order->delivery_address && !$user->address) {
  353. $user->address = $order->delivery_address;
  354. $user->save();
  355. }
  356. $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
  357. $order->save();
  358. $orderModule->generateOrderReference($order);
  359. if($isNewOrder) {
  360. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
  361. }
  362. else {
  363. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $user);
  364. }
  365. $producerModule->addUser($user, $producer);
  366. // suppression de tous les enregistrements ProductOrder
  367. if (!is_null($order)) {
  368. $productOrderModule->deleteProductOrdersByOrder($order);
  369. if (isset($order->productOrder)) {
  370. foreach ($order->productOrder as $productOrder) {
  371. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  372. }
  373. }
  374. }
  375. $availableProducts = $orderModule->findProductDistributionsByDistribution($distribution);
  376. foreach ($productsArray as $product) {
  377. if (isset($availableProducts[$product->id])) {
  378. $productOrder = new ProductOrder();
  379. $productOrder->id_order = $order->id;
  380. $productOrder->id_product = $product->id;
  381. $productOrder->id_tax_rate = $product->taxRate->id;
  382. $unit = (!is_null(
  383. $order
  384. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  385. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  386. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  387. $quantityRemaining = $orderModule->getResolver()->getProductQuantityRemaining($product, $order->distribution);
  388. if(!is_null($quantityRemaining) && $quantity > $quantityRemaining) {
  389. $quantity = $quantityRemaining;
  390. }
  391. $productOrder->quantity = $quantity;
  392. $productOrder->price = $productModule->getPrice($product, [
  393. 'user' => $this->getUserCurrent(),
  394. 'user_producer' => $userProducer,
  395. 'point_sale' => $pointSale,
  396. 'quantity' => $quantity
  397. ]);
  398. $productOrder->unit = $product->unit;
  399. $productOrder->step = $product->step;
  400. if($quantity) {
  401. $productOrder->save();
  402. }
  403. }
  404. }
  405. // lien utilisateur / point de vente
  406. $pointSaleModule->addUser($user, $pointSale);
  407. // credit
  408. $credit = $producerModule->getConfig('credit');
  409. $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
  410. $order = $orderModule->findOneOrderById($order->id);
  411. $orderModule->initOrder($order);
  412. if ($credit
  413. && $this->getUserCurrent()
  414. && $pointSale->payment_method_credit
  415. && $posts['payment_method'] == 'credit'
  416. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  417. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  418. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  419. )) {
  420. // à payer
  421. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  422. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  423. } // surplus à rembourser
  424. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  425. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  426. }
  427. }
  428. /*
  429. * Envoi email de confirmation
  430. */
  431. $emailSubject = 'Confirmation de commande';
  432. $emailContentParams = [
  433. 'order' => $order,
  434. 'pointSale' => $pointSale,
  435. 'distribution' => $distribution,
  436. 'user' => $user,
  437. 'producer' => $producer
  438. ];
  439. // au client
  440. if ($producerModule->getConfig('option_email_confirm')) {
  441. \Yii::$app->mailerService->sendFromProducer(
  442. $emailSubject,
  443. 'orderConfirm',
  444. $emailContentParams,
  445. $user->email,
  446. $producer
  447. );
  448. }
  449. // au producteur
  450. $contactProducer = $producerModule->getMainContact($producer);
  451. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  452. $contactProducer->email
  453. )) {
  454. \Yii::$app->mailerService->sendFromSite(
  455. $emailSubject,
  456. 'orderConfirmProducer',
  457. $emailContentParams,
  458. $contactProducer->email
  459. );
  460. }
  461. $order = $orderModule->findOneOrderById($order->id);
  462. $orderModule->initOrder($order);
  463. $orderModule->updateOrderTillerSynchronization($order);
  464. }
  465. if (!count($productsArray)) {
  466. $errors[] = "Vous n'avez choisi aucun produit";
  467. }
  468. if ($errorDate) {
  469. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  470. }
  471. if ($errorPointSale) {
  472. $errors[] = "Point de vente invalide.";
  473. }
  474. return $errors;
  475. }
  476. /**
  477. * Annule une commande.
  478. */
  479. public function actionCancel(int $id)
  480. {
  481. $orderModule = $this->getOrderModule();
  482. $order = $this->getOrderModule()->findOneOrderById($id);
  483. if (!$order) {
  484. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  485. }
  486. $orderModule->getBuilder()->initOrder($order);
  487. if (!$orderModule->isOrderStateOpen($order)) {
  488. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  489. }
  490. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  491. $orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
  492. $this->setFlash('success', 'Votre commande a bien été annulée.');
  493. }
  494. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  495. }
  496. /**
  497. * Page de confirmation de commande.
  498. */
  499. public function actionConfirm(int $idOrder, string $returnPayment = '')
  500. {
  501. $orderModule = $this->getOrderModule();
  502. $order = $orderModule->findOneOrderById($idOrder);
  503. $producer = $this->getProducerCurrent();
  504. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  505. $this->setFlash('error', 'Commande introuvable');
  506. return $this->redirect(['order/history']);
  507. }
  508. $orderModule->initOrder($order);
  509. return $this->render('confirm', [
  510. 'order' => $order,
  511. 'returnPayment' => $returnPayment
  512. ]);
  513. }
  514. /**
  515. * Vérifie le code saisi pour un point de vente.
  516. */
  517. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  518. {
  519. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  520. $pointSaleModule = $this->getPointSaleModule();
  521. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  522. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  523. return 1;
  524. }
  525. return 0;
  526. }
  527. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0, string $productsJson = null, bool $loadingProducts = false)
  528. {
  529. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  530. $productsArray = json_decode($productsJson, true);
  531. $user = GlobalParam::getCurrentUser();
  532. $producer = $this->getProducerCurrent();
  533. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  534. $order = $this->getOrderUser($date, $pointSale);
  535. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order, $productsArray, $loadingProducts);
  536. }
  537. public function buildJsonAjaxInfos(
  538. string $date,
  539. Producer $producer,
  540. PointSale $pointSale = null,
  541. User $user = null,
  542. Order $order = null,
  543. array $productsArray = null,
  544. bool $loadingProducts = false
  545. )
  546. {
  547. $orderModule = $this->getOrderModule();
  548. $json = [];
  549. $format = 'Y-m-d';
  550. $dateObject = DateTime::createFromFormat($format, $date);
  551. $json['producer'] = $this->ajaxInfosProducer($producer);
  552. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  553. $json['orders'] = $this->ajaxInfosOrders($producer);
  554. $json['user'] = $this->ajaxInfosUser($producer);
  555. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  556. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  557. if ($dateObject && $dateObject->format($format) === $date) {
  558. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  559. $json['distribution'] = $distribution;
  560. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  561. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  562. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order, $productsArray);
  563. if ($order) {
  564. $json['order'] = array_merge($order->getAttributes(), [
  565. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  566. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  567. ]);
  568. }
  569. }
  570. return $json;
  571. }
  572. public function ajaxInfosLeavePeriod(Producer $producer)
  573. {
  574. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  575. return [
  576. 'start' => $producer->option_leave_period_start,
  577. 'end' => $producer->option_leave_period_end,
  578. ];
  579. }
  580. return false;
  581. }
  582. public function ajaxInfosProducer(Producer $producer)
  583. {
  584. return [
  585. 'order_infos' => nl2br($producer->order_infos),
  586. 'payment_infos' => nl2br($producer->option_payment_info),
  587. 'credit' => $producer->credit,
  588. 'credit_functioning' => $producer->credit_functioning,
  589. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  590. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  591. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  592. 'option_order_entry_point' => $producer->option_order_entry_point,
  593. 'option_delivery' => $producer->option_delivery,
  594. 'online_payment' => $producer->online_payment,
  595. 'option_online_payment_type' => $producer->online_payment,
  596. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer),
  597. 'feature_product_accessory_enabled' => $this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_PRODUCT_ACCESSORY),
  598. ];
  599. }
  600. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  601. {
  602. $distributionModule = $this-> getDistributionModule();
  603. $dateMini = date('Y-m-d');
  604. $distributionsArray = Distribution::searchAll([
  605. 'active' => 1,
  606. 'id_producer' => $producer->id
  607. ], [
  608. 'conditions' => ['date > :date'],
  609. 'params' => [':date' => $dateMini],
  610. 'join_with' => ['pointSaleDistribution'],
  611. ]);
  612. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  613. // Filtre par période de congé
  614. foreach ($distributionsArray as $keyDistribution => $distribution) {
  615. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  616. unset($distributionsArray[$keyDistribution]);
  617. }
  618. }
  619. // Filtre par point de vente
  620. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  621. $distributionsArrayFilterPointSale = [];
  622. for ($i = 0; $i < count($distributionsArray); $i++) {
  623. $distribution = $distributionsArray[$i];
  624. if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  625. $countOrders = Order::searchCount([
  626. 'id_distribution' => $distribution->id,
  627. 'id_point_sale' => $pointSaleCurrent->id
  628. ]);
  629. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  630. if (!$pointSaleCurrent->maximum_number_orders
  631. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  632. || ($pointSaleCurrent->maximum_number_orders &&
  633. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  634. $distributionsArrayFilterPointSale[] = $distribution;
  635. }
  636. }
  637. }
  638. return $distributionsArrayFilterPointSale;
  639. } else {
  640. return $distributionsArray;
  641. }
  642. }
  643. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  644. {
  645. $orderModule = $this->getOrderModule();
  646. $dateMini = date('Y-m-d');
  647. $ordersUserArray = [];
  648. if (GlobalParam::getCurrentUserId()) {
  649. $conditionsOrdersUser = [
  650. 'distribution.date > :date',
  651. 'order.online_payment_url IS NULL'
  652. ];
  653. $paramsOrdersUser = [
  654. ':date' => $dateMini
  655. ];
  656. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  657. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  658. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  659. }
  660. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  661. $ordersUserArray = Order::searchAll([
  662. 'id_user' => GlobalParam::getCurrentUserId()
  663. ], [
  664. 'conditions' => $conditionsOrdersUser,
  665. 'params' => $paramsOrdersUser
  666. ]);
  667. }
  668. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  669. foreach ($ordersUserArray as &$order) {
  670. $orderModule->initOrder($order);
  671. $order = array_merge($order->getAttributes(), [
  672. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  673. 'date_distribution' => $order->distribution->date,
  674. 'pointSale' => $order->pointSale->getAttributes()
  675. ]);
  676. }
  677. }
  678. return $ordersUserArray;
  679. }
  680. public function ajaxInfosUser(Producer $producer)
  681. {
  682. $userProducerModule = $this->getUserProducerModule();
  683. $producerModule = $this->getProducerModule();
  684. $user = GlobalParam::getCurrentUser();
  685. if($user) {
  686. $userProducer = $userProducerModule->findOneUserProducer($user);
  687. if (!$userProducer) {
  688. $userProducer = $producerModule->addUser($user, $producer);
  689. }
  690. }
  691. $jsonUser = false;
  692. if ($user && $userProducer) {
  693. $jsonUser = [
  694. 'address' => $user->address,
  695. 'credit' => $userProducer->credit,
  696. 'credit_active' => $userProducer->credit_active,
  697. ];
  698. }
  699. return $jsonUser;
  700. }
  701. private function ajaxInfosPointsSale($producer, $distribution = null)
  702. {
  703. $pointSaleModule = $this->getPointSaleModule();
  704. $producerModule = $this->getProducerModule();
  705. $orderModule = $this->getOrderModule();
  706. $user = GlobalParam::getCurrentUser();
  707. $userProducer = null;
  708. if($user) {
  709. $userProducer = $this->getUserProducerModule()->getRepository()->findOneUserProducer($user);
  710. }
  711. $pointsSaleArray = PointSale::find();
  712. if ($distribution) {
  713. $pointsSaleArray = $pointsSaleArray->joinWith([
  714. 'pointSaleDistribution' => function ($query) use (
  715. $distribution
  716. ) {
  717. $query->where(
  718. [
  719. 'id_distribution' => $distribution->id,
  720. 'delivery' => 1
  721. ]
  722. );
  723. }
  724. ]);
  725. }
  726. if (GlobalParam::getCurrentUserId()) {
  727. $pointsSaleArray = $pointsSaleArray->with([
  728. 'userPointSale' => function ($query) {
  729. $query->onCondition(
  730. ['id_user' => GlobalParam::getCurrentUserId()]
  731. );
  732. }
  733. ]);
  734. }
  735. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  736. ->andWhere(
  737. '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))'
  738. )
  739. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  740. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  741. ->all();
  742. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  743. $position = 0;
  744. foreach ($pointsSaleArray as &$pointSale) {
  745. $pointSaleObject = $pointSale;
  746. $pointSale = array_merge($pointSale->getAttributes(), [
  747. 'pointSaleDistribution' => [
  748. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  749. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  750. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  751. ],
  752. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  753. ]);
  754. if ($pointSale['code'] && strlen($pointSale['code'])) {
  755. $pointSale['code'] = '***';
  756. }
  757. if (!strlen($pointSale['credit_functioning'])) {
  758. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  759. }
  760. if ($distribution) {
  761. $pointSale['count_orders'] = (int)Order::searchCount([
  762. 'id_distribution' => $distribution->id,
  763. 'id_point_sale' => $pointSale['id']
  764. ]);
  765. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  766. }
  767. $pointSale['producers_sharing_point_sale_as_string'] = false;
  768. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  769. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  770. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  771. }
  772. $pointSale['position'] = $position;
  773. $position++;
  774. }
  775. $favoritePointSale = false;
  776. if ($user) {
  777. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  778. }
  779. if ($favoritePointSale) {
  780. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  781. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  782. $theFavoritePointSale = $pointsSaleArray[$i];
  783. unset($pointsSaleArray[$i]);
  784. }
  785. }
  786. if (isset($theFavoritePointSale)) {
  787. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  788. $pointsSaleArray[] = $theFavoritePointSale;
  789. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  790. }
  791. }
  792. // Filtre par accès exclusif aux points de vente
  793. if($userProducer) {
  794. $pointsSaleArray = $this->getUserProducerModule()->getSolver()->filterPointsSaleByExclusiveAccess(
  795. $userProducer,
  796. $pointsSaleArray
  797. );
  798. }
  799. return $pointsSaleArray;
  800. }
  801. public function ajaxInfosProductCategories(Producer $producer)
  802. {
  803. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  804. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  805. if ($countProductsWithoutCategory) {
  806. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  807. }
  808. return $categoriesArray;
  809. }
  810. public function ajaxInfosProducts(
  811. Producer $producer,
  812. Distribution $distribution,
  813. PointSale $pointSale = null,
  814. User $user = null,
  815. Order $order = null,
  816. array $productsFormArray = null
  817. )
  818. {
  819. $unitModule = $this->getUnitModule();
  820. $productModule = $this->getProductModule();
  821. $orderModule = $this->getOrderModule();
  822. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  823. $productsArray = Product::find()
  824. ->where([
  825. 'id_producer' => $producer->id,
  826. 'product.status' => 1,
  827. ]);
  828. $productsArray = $productsArray->joinWith([
  829. 'productDistribution' => function ($query) use (
  830. $distribution
  831. ) {
  832. $query->andOnCondition(
  833. 'product_distribution.id_distribution = ' . $distribution->id
  834. );
  835. },
  836. 'productPrice'
  837. ])
  838. ->orderBy('product_distribution.active DESC, order ASC')
  839. ->all();
  840. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  841. $orderCurrent = $order;
  842. if($productsFormArray && count($productsFormArray)) {
  843. $productOrdersArray = [];
  844. foreach($productsFormArray as $idProduct => $quantityProduct) {
  845. if($idProduct) {
  846. $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
  847. $productOrdersArray[$idProduct] = [
  848. 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
  849. ];
  850. }
  851. }
  852. $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
  853. }
  854. $indexProduct = 0;
  855. foreach ($productsArrayFilter as $key => &$product) {
  856. $productObject = $product;
  857. $product = array_merge(
  858. $product->getAttributes(),
  859. [
  860. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  861. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  862. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  863. 'productDistribution' => $product['productDistribution'],
  864. 'productPointSale' => $product['productPointSale'],
  865. ]
  866. );
  867. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  868. $product['photo'] = '';
  869. }
  870. else {
  871. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  872. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  873. }
  874. $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
  875. $product['coefficient_unit'] = $coefficientUnit;
  876. $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
  877. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  878. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  879. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  880. $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
  881. $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
  882. if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
  883. $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
  884. $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
  885. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  886. }
  887. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  888. if ($order) {
  889. foreach ($order->productOrder as $productOrder) {
  890. if ($productOrder->id_product == $product['id']) {
  891. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  892. $product['step'] = $productOrder->step;
  893. }
  894. }
  895. }
  896. $product['index'] = $indexProduct++;
  897. }
  898. return $productsArrayFilter;
  899. }
  900. private function getOrderUser(string $date, PointSale $pointSale = null)
  901. {
  902. $orderModule = $this->getOrderModule();
  903. $orderUser = null;
  904. if (GlobalParam::getCurrentUserId()) {
  905. $conditionOrderUser = [
  906. 'distribution.date' => $date,
  907. 'id_user' => GlobalParam::getCurrentUserId()
  908. ];
  909. if ($pointSale) {
  910. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  911. }
  912. $orderUser = Order::searchOne($conditionOrderUser, [
  913. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  914. ]);
  915. if ($orderUser && $orderUser->online_payment_url) {
  916. $orderUser = null;
  917. }
  918. }
  919. if($orderUser) {
  920. $orderModule->initOrder($orderUser);
  921. }
  922. return $orderUser;
  923. }
  924. }