Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

1077 linhas
44KB

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