No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

1039 líneas
41KB

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