Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1046 lines
42KB

  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, $date = '')
  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->findOneOrderById($id);
  91. if ($order && $orderModule->isOrderStateOpen($order)) {
  92. $params['order'] = $order;
  93. }
  94. if ($distributionModule->isDistributionDateAvailable($date)) {
  95. $params['date'] = $date;
  96. }
  97. return $this->render('order', $params);
  98. }
  99. /**
  100. * Affiche l'historique des commandes de l'utilisateur.
  101. */
  102. public function actionHistory($type = 'incoming')
  103. {
  104. $queryHistoryArray = $this->getOrderModule()
  105. ->queryOrdersHistory($this->getProducerCurrent(), $this->getUserCurrent());
  106. $queryHistoryIncoming = $queryHistoryArray['incoming'];
  107. $queryHistoryPassed = $queryHistoryArray['passed'];
  108. $dataProviderOrders = new ActiveDataProvider([
  109. 'query' => ($type == 'incoming') ? $queryHistoryIncoming->query() : $queryHistoryPassed->query(),
  110. 'pagination' => [
  111. 'pageSize' => 10,
  112. ],
  113. ]);
  114. return $this->render('history', [
  115. 'dataProviderOrders' => $dataProviderOrders,
  116. 'orderOk' => \Yii::$app->getRequest()->get('orderOk', false),
  117. 'cancelOk' => \Yii::$app->getRequest()->get('cancelOk', false),
  118. 'type' => $type,
  119. 'countIncoming' => $queryHistoryIncoming->count(),
  120. 'countPassed' => $queryHistoryPassed->count(),
  121. ]);
  122. }
  123. public function actionRemoveProducer(int $id = 0)
  124. {
  125. $producer = $this->getProducerModule()->findOneProducerById($id);
  126. $this->getUserProducerModule()->updateActive(
  127. $this->getUserCurrent(),
  128. $producer,
  129. false
  130. );
  131. return $this->redirect(['order/index']);
  132. }
  133. /**
  134. * Crée une commande.
  135. */
  136. public function actionAjaxProcess()
  137. {
  138. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  139. $posts = \Yii::$app->request->post();
  140. $orderModule = $this->getOrderModule();
  141. $producerModule = $this->getProducerModule();
  142. $userModule = $this->getUserModule();
  143. $productOrderModule = $this->getProductOrderModule();
  144. $producer = $this->getProducerCurrent();
  145. $redirect = null;
  146. $idProducer = $producer->id;
  147. $order = new Order;
  148. if ($idProducer) {
  149. $this->_verifyProducerActive($idProducer);
  150. }
  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($orderModule->getSolver()->isOrderStatusCanceled($order)) {
  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. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  388. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  389. }
  390. $productOrder->quantity = $quantity;
  391. $productOrder->price = $productModule->getPrice($product, [
  392. 'user' => $this->getUserCurrent(),
  393. 'user_producer' => $userProducer,
  394. 'point_sale' => $pointSale,
  395. 'quantity' => $quantity
  396. ]);
  397. $productOrder->unit = $product->unit;
  398. $productOrder->step = $product->step;
  399. if($quantity) {
  400. $productOrder->save();
  401. }
  402. }
  403. }
  404. // lien utilisateur / point de vente
  405. $pointSaleModule->addUser($user, $pointSale);
  406. // credit
  407. $credit = $producerModule->getConfig('credit');
  408. $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
  409. $order = $orderModule->findOneOrderById($order->id);
  410. $orderModule->initOrder($order);
  411. if ($credit
  412. && $this->getUserCurrent()
  413. && $pointSale->payment_method_credit
  414. && $posts['payment_method'] == 'credit'
  415. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  416. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  417. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  418. )) {
  419. // à payer
  420. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  421. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  422. } // surplus à rembourser
  423. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  424. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  425. }
  426. }
  427. /*
  428. * Envoi email de confirmation
  429. */
  430. $emailSubject = 'Confirmation de commande';
  431. $emailContentParams = [
  432. 'order' => $order,
  433. 'pointSale' => $pointSale,
  434. 'distribution' => $distribution,
  435. 'user' => $user,
  436. 'producer' => $producer
  437. ];
  438. // au client
  439. if ($producerModule->getConfig('option_email_confirm')) {
  440. \Yii::$app->mailerService->sendFromProducer(
  441. $emailSubject,
  442. 'orderConfirm',
  443. $emailContentParams,
  444. $user->email,
  445. $producer
  446. );
  447. }
  448. // au producteur
  449. $contactProducer = $producerModule->getMainContact($producer);
  450. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  451. $contactProducer->email
  452. )) {
  453. \Yii::$app->mailerService->sendFromSite(
  454. $emailSubject,
  455. 'orderConfirmProducer',
  456. $emailContentParams,
  457. $contactProducer->email
  458. );
  459. }
  460. $order = $orderModule->findOneOrderById($order->id);
  461. $orderModule->initOrder($order);
  462. $orderModule->updateOrderTillerSynchronization($order);
  463. }
  464. if (!count($productsArray)) {
  465. $errors[] = "Vous n'avez choisi aucun produit";
  466. }
  467. if ($errorDate) {
  468. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  469. }
  470. if ($errorPointSale) {
  471. $errors[] = "Point de vente invalide.";
  472. }
  473. return $errors;
  474. }
  475. /**
  476. * Annule une commande.
  477. */
  478. public function actionCancel(int $id)
  479. {
  480. $orderModule = $this->getOrderModule();
  481. $order = $this->getOrderModule()->findOneOrderById($id);
  482. if (!$order) {
  483. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  484. }
  485. $orderModule->getBuilder()->initOrder($order);
  486. if (!$orderModule->isOrderStateOpen($order)) {
  487. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  488. }
  489. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  490. $orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
  491. $this->setFlash('success', 'Votre commande a bien été annulée.');
  492. }
  493. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  494. }
  495. /**
  496. * Page de confirmation de commande.
  497. */
  498. public function actionConfirm(int $idOrder, string $returnPayment = '')
  499. {
  500. $orderModule = $this->getOrderModule();
  501. $order = $orderModule->findOneOrderById($idOrder);
  502. $producer = $this->getProducerCurrent();
  503. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  504. $this->setFlash('error', 'Commande introuvable');
  505. return $this->redirect(['order/history']);
  506. }
  507. $orderModule->initOrder($order);
  508. return $this->render('confirm', [
  509. 'order' => $order,
  510. 'returnPayment' => $returnPayment
  511. ]);
  512. }
  513. /**
  514. * Vérifie le code saisi pour un point de vente.
  515. */
  516. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  517. {
  518. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  519. $pointSaleModule = $this->getPointSaleModule();
  520. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  521. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  522. return 1;
  523. }
  524. return 0;
  525. }
  526. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
  527. {
  528. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  529. $user = GlobalParam::getCurrentUser();
  530. $producer = $this->getProducerCurrent();
  531. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  532. $order = $this->getOrderUser($date, $pointSale);
  533. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
  534. }
  535. public function buildJsonAjaxInfos(
  536. string $date,
  537. Producer $producer,
  538. PointSale $pointSale = null,
  539. User $user = null,
  540. Order $order = null
  541. )
  542. {
  543. $orderModule = $this->getOrderModule();
  544. $json = [];
  545. $format = 'Y-m-d';
  546. $dateObject = DateTime::createFromFormat($format, $date);
  547. $json['producer'] = $this->ajaxInfosProducer($producer);
  548. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  549. $json['orders'] = $this->ajaxInfosOrders($producer);
  550. $json['user'] = $this->ajaxInfosUser($producer);
  551. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  552. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  553. if ($dateObject && $dateObject->format($format) === $date) {
  554. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  555. $json['distribution'] = $distribution;
  556. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  557. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  558. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
  559. if ($order) {
  560. $json['order'] = array_merge($order->getAttributes(), [
  561. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  562. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  563. ]);
  564. }
  565. }
  566. return $json;
  567. }
  568. public function ajaxInfosLeavePeriod(Producer $producer)
  569. {
  570. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  571. return [
  572. 'start' => $producer->option_leave_period_start,
  573. 'end' => $producer->option_leave_period_end,
  574. ];
  575. }
  576. return false;
  577. }
  578. public function ajaxInfosProducer(Producer $producer)
  579. {
  580. return [
  581. 'order_infos' => nl2br($producer->order_infos),
  582. 'payment_infos' => nl2br($producer->option_payment_info),
  583. 'credit' => $producer->credit,
  584. 'credit_functioning' => $producer->credit_functioning,
  585. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  586. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  587. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  588. 'option_order_entry_point' => $producer->option_order_entry_point,
  589. 'option_delivery' => $producer->option_delivery,
  590. 'online_payment' => $producer->online_payment,
  591. 'option_online_payment_type' => $producer->online_payment,
  592. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  593. ];
  594. }
  595. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  596. {
  597. $distributionModule = $this-> getDistributionModule();
  598. $dateMini = date('Y-m-d');
  599. $distributionsArray = Distribution::searchAll([
  600. 'active' => 1,
  601. 'id_producer' => $producer->id
  602. ], [
  603. 'conditions' => ['date > :date'],
  604. 'params' => [':date' => $dateMini],
  605. 'join_with' => ['pointSaleDistribution'],
  606. ]);
  607. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  608. // Filtre par période de congé
  609. foreach ($distributionsArray as $keyDistribution => $distribution) {
  610. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  611. unset($distributionsArray[$keyDistribution]);
  612. }
  613. }
  614. // Filtre par point de vente
  615. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  616. $distributionsArrayFilterPointSale = [];
  617. for ($i = 0; $i < count($distributionsArray); $i++) {
  618. $distribution = $distributionsArray[$i];
  619. if ($distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  620. $countOrders = Order::searchCount([
  621. 'id_distribution' => $distribution->id,
  622. 'id_point_sale' => $pointSaleCurrent->id
  623. ]);
  624. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  625. if (!$pointSaleCurrent->maximum_number_orders
  626. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  627. || ($pointSaleCurrent->maximum_number_orders &&
  628. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  629. $distributionsArrayFilterPointSale[] = $distribution;
  630. }
  631. }
  632. }
  633. return $distributionsArrayFilterPointSale;
  634. } else {
  635. return $distributionsArray;
  636. }
  637. }
  638. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  639. {
  640. $orderModule = $this->getOrderModule();
  641. $dateMini = date('Y-m-d');
  642. $ordersUserArray = [];
  643. if (GlobalParam::getCurrentUserId()) {
  644. $conditionsOrdersUser = [
  645. 'distribution.date > :date',
  646. 'order.online_payment_url IS NULL'
  647. ];
  648. $paramsOrdersUser = [
  649. ':date' => $dateMini
  650. ];
  651. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  652. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  653. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  654. }
  655. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  656. $ordersUserArray = Order::searchAll([
  657. 'id_user' => GlobalParam::getCurrentUserId()
  658. ], [
  659. 'conditions' => $conditionsOrdersUser,
  660. 'params' => $paramsOrdersUser
  661. ]);
  662. }
  663. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  664. foreach ($ordersUserArray as &$order) {
  665. $orderModule->initOrder($order);
  666. $order = array_merge($order->getAttributes(), [
  667. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  668. 'date_distribution' => $order->distribution->date,
  669. 'pointSale' => $order->pointSale->getAttributes()
  670. ]);
  671. }
  672. }
  673. return $ordersUserArray;
  674. }
  675. public function ajaxInfosUser(Producer $producer)
  676. {
  677. $userProducerModule = $this->getUserProducerModule();
  678. $producerModule = $this->getProducerModule();
  679. $user = GlobalParam::getCurrentUser();
  680. if($user) {
  681. $userProducer = $userProducerModule->findOneUserProducer($user);
  682. if (!$userProducer) {
  683. $userProducer = $producerModule->addUser($user, $producer);
  684. }
  685. }
  686. $jsonUser = false;
  687. if ($user && $userProducer) {
  688. $jsonUser = [
  689. 'address' => $user->address,
  690. 'credit' => $userProducer->credit,
  691. 'credit_active' => $userProducer->credit_active,
  692. ];
  693. }
  694. return $jsonUser;
  695. }
  696. private function ajaxInfosPointsSale($producer, $distribution = null)
  697. {
  698. $pointSaleModule = $this->getPointSaleModule();
  699. $producerModule = $this->getProducerModule();
  700. $orderModule = $this->getOrderModule();
  701. $user = GlobalParam::getCurrentUser();
  702. $pointsSaleArray = PointSale::find();
  703. if ($distribution) {
  704. $pointsSaleArray = $pointsSaleArray->joinWith([
  705. 'pointSaleDistribution' => function ($query) use (
  706. $distribution
  707. ) {
  708. $query->where(
  709. [
  710. 'id_distribution' => $distribution->id,
  711. 'delivery' => 1
  712. ]
  713. );
  714. }
  715. ]);
  716. }
  717. if (GlobalParam::getCurrentUserId()) {
  718. $pointsSaleArray = $pointsSaleArray->with([
  719. 'userPointSale' => function ($query) {
  720. $query->onCondition(
  721. ['id_user' => GlobalParam::getCurrentUserId()]
  722. );
  723. }
  724. ]);
  725. }
  726. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  727. ->andWhere(
  728. '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))'
  729. )
  730. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  731. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  732. ->all();
  733. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  734. $position = 0;
  735. foreach ($pointsSaleArray as &$pointSale) {
  736. $pointSaleObject = $pointSale;
  737. $pointSale = array_merge($pointSale->getAttributes(), [
  738. 'pointSaleDistribution' => [
  739. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  740. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  741. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  742. ],
  743. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  744. ]);
  745. if ($pointSale['code'] && strlen($pointSale['code'])) {
  746. $pointSale['code'] = '***';
  747. }
  748. if (!strlen($pointSale['credit_functioning'])) {
  749. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  750. }
  751. if ($distribution) {
  752. $pointSale['count_orders'] = (int)Order::searchCount([
  753. 'id_distribution' => $distribution->id,
  754. 'id_point_sale' => $pointSale['id']
  755. ]);
  756. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  757. }
  758. $pointSale['producers_sharing_point_sale_as_string'] = false;
  759. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  760. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  761. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  762. }
  763. $pointSale['position'] = $position;
  764. $position++;
  765. }
  766. $favoritePointSale = false;
  767. if ($user) {
  768. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  769. }
  770. if ($favoritePointSale) {
  771. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  772. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  773. $theFavoritePointSale = $pointsSaleArray[$i];
  774. unset($pointsSaleArray[$i]);
  775. }
  776. }
  777. if (isset($theFavoritePointSale)) {
  778. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  779. $pointsSaleArray[] = $theFavoritePointSale;
  780. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  781. }
  782. }
  783. return $pointsSaleArray;
  784. }
  785. public function ajaxInfosProductCategories(Producer $producer)
  786. {
  787. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  788. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  789. if ($countProductsWithoutCategory) {
  790. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  791. }
  792. return $categoriesArray;
  793. }
  794. public function ajaxInfosProducts(
  795. Producer $producer,
  796. Distribution $distribution,
  797. PointSale $pointSale = null,
  798. User $user = null,
  799. Order $order = null
  800. )
  801. {
  802. $unitModule = $this->getUnitModule();
  803. $productModule = $this->getProductModule();
  804. $orderModule = $this->getOrderModule();
  805. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  806. $productsArray = Product::find()
  807. ->where([
  808. 'id_producer' => $producer->id,
  809. 'product.status' => 1,
  810. ]);
  811. $productsArray = $productsArray->joinWith([
  812. 'productDistribution' => function ($query) use (
  813. $distribution
  814. ) {
  815. $query->andOnCondition(
  816. 'product_distribution.id_distribution = ' . $distribution->id
  817. );
  818. },
  819. 'productPrice'
  820. ])
  821. ->orderBy('product_distribution.active DESC, order ASC')
  822. ->all();
  823. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  824. $indexProduct = 0;
  825. foreach ($productsArrayFilter as $key => &$product) {
  826. $productObject = $product;
  827. $product = array_merge(
  828. $product->getAttributes(),
  829. [
  830. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  831. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  832. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  833. 'productDistribution' => $product['productDistribution'],
  834. 'productPointSale' => $product['productPointSale'],
  835. ]
  836. );
  837. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  838. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  839. $product['photo'] = '';
  840. }
  841. else {
  842. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  843. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  844. }
  845. $product['quantity_max'] = (isset($product['productDistribution']) && isset($product['productDistribution'][0])) ? $product['productDistribution'][0]['quantity_max'] : null;
  846. $quantityOrder = $orderModule->getProductQuantity($productObject, $ordersArray);
  847. $product['quantity_ordered'] = $quantityOrder;
  848. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  849. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  850. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  851. if ($order) {
  852. $quantityOrderUser = $orderModule->getProductQuantity($productObject, [$order], true);
  853. $product['quantity_ordered'] = $quantityOrder;
  854. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  855. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  856. foreach ($order->productOrder as $productOrder) {
  857. if ($productOrder->id_product == $product['id']) {
  858. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  859. $product['step'] = $productOrder->step;
  860. }
  861. }
  862. } else {
  863. $product['quantity_form'] = 0;
  864. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  865. }
  866. $product['coefficient_unit'] = $coefficient_unit;
  867. if ($product['quantity_remaining'] < 0) {
  868. $product['quantity_remaining'] = 0;
  869. }
  870. $product['index'] = $indexProduct++;
  871. }
  872. return $productsArrayFilter;
  873. }
  874. private function getOrderUser(string $date, PointSale $pointSale = null)
  875. {
  876. $orderModule = $this->getOrderModule();
  877. $orderUser = null;
  878. if (GlobalParam::getCurrentUserId()) {
  879. $conditionOrderUser = [
  880. 'distribution.date' => $date,
  881. 'id_user' => GlobalParam::getCurrentUserId()
  882. ];
  883. if ($pointSale) {
  884. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  885. }
  886. $orderUser = Order::searchOne($conditionOrderUser, [
  887. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  888. ]);
  889. if ($orderUser && $orderUser->online_payment_url) {
  890. $orderUser = null;
  891. }
  892. }
  893. if($orderUser) {
  894. $orderModule->initOrder($orderUser);
  895. }
  896. return $orderUser;
  897. }
  898. }