Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

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