You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1063 lines
43KB

  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, string $productsJson = null, bool $loadingProducts = false)
  530. {
  531. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  532. $productsArray = json_decode($productsJson, true);
  533. $user = GlobalParam::getCurrentUser();
  534. $producer = $this->getProducerCurrent();
  535. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  536. $order = $this->getOrderUser($date, $pointSale);
  537. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order, $productsArray, $loadingProducts);
  538. }
  539. public function buildJsonAjaxInfos(
  540. string $date,
  541. Producer $producer,
  542. PointSale $pointSale = null,
  543. User $user = null,
  544. Order $order = null,
  545. array $productsArray = null,
  546. bool $loadingProducts = false
  547. )
  548. {
  549. $orderModule = $this->getOrderModule();
  550. $json = [];
  551. $format = 'Y-m-d';
  552. $dateObject = DateTime::createFromFormat($format, $date);
  553. $json['producer'] = $this->ajaxInfosProducer($producer);
  554. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  555. $json['orders'] = $this->ajaxInfosOrders($producer);
  556. $json['user'] = $this->ajaxInfosUser($producer);
  557. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  558. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  559. if ($dateObject && $dateObject->format($format) === $date) {
  560. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  561. $json['distribution'] = $distribution;
  562. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  563. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  564. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order, $productsArray);
  565. if ($order) {
  566. $json['order'] = array_merge($order->getAttributes(), [
  567. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  568. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  569. ]);
  570. }
  571. }
  572. return $json;
  573. }
  574. public function ajaxInfosLeavePeriod(Producer $producer)
  575. {
  576. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  577. return [
  578. 'start' => $producer->option_leave_period_start,
  579. 'end' => $producer->option_leave_period_end,
  580. ];
  581. }
  582. return false;
  583. }
  584. public function ajaxInfosProducer(Producer $producer)
  585. {
  586. return [
  587. 'order_infos' => nl2br($producer->order_infos),
  588. 'payment_infos' => nl2br($producer->option_payment_info),
  589. 'credit' => $producer->credit,
  590. 'credit_functioning' => $producer->credit_functioning,
  591. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  592. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  593. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  594. 'option_order_entry_point' => $producer->option_order_entry_point,
  595. 'option_delivery' => $producer->option_delivery,
  596. 'online_payment' => $producer->online_payment,
  597. 'option_online_payment_type' => $producer->online_payment,
  598. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  599. ];
  600. }
  601. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  602. {
  603. $distributionModule = $this-> getDistributionModule();
  604. $dateMini = date('Y-m-d');
  605. $distributionsArray = Distribution::searchAll([
  606. 'active' => 1,
  607. 'id_producer' => $producer->id
  608. ], [
  609. 'conditions' => ['date > :date'],
  610. 'params' => [':date' => $dateMini],
  611. 'join_with' => ['pointSaleDistribution'],
  612. ]);
  613. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  614. // Filtre par période de congé
  615. foreach ($distributionsArray as $keyDistribution => $distribution) {
  616. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  617. unset($distributionsArray[$keyDistribution]);
  618. }
  619. }
  620. // Filtre par point de vente
  621. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  622. $distributionsArrayFilterPointSale = [];
  623. for ($i = 0; $i < count($distributionsArray); $i++) {
  624. $distribution = $distributionsArray[$i];
  625. if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  626. $countOrders = Order::searchCount([
  627. 'id_distribution' => $distribution->id,
  628. 'id_point_sale' => $pointSaleCurrent->id
  629. ]);
  630. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  631. if (!$pointSaleCurrent->maximum_number_orders
  632. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  633. || ($pointSaleCurrent->maximum_number_orders &&
  634. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  635. $distributionsArrayFilterPointSale[] = $distribution;
  636. }
  637. }
  638. }
  639. return $distributionsArrayFilterPointSale;
  640. } else {
  641. return $distributionsArray;
  642. }
  643. }
  644. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  645. {
  646. $orderModule = $this->getOrderModule();
  647. $dateMini = date('Y-m-d');
  648. $ordersUserArray = [];
  649. if (GlobalParam::getCurrentUserId()) {
  650. $conditionsOrdersUser = [
  651. 'distribution.date > :date',
  652. 'order.online_payment_url IS NULL'
  653. ];
  654. $paramsOrdersUser = [
  655. ':date' => $dateMini
  656. ];
  657. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  658. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  659. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  660. }
  661. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  662. $ordersUserArray = Order::searchAll([
  663. 'id_user' => GlobalParam::getCurrentUserId()
  664. ], [
  665. 'conditions' => $conditionsOrdersUser,
  666. 'params' => $paramsOrdersUser
  667. ]);
  668. }
  669. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  670. foreach ($ordersUserArray as &$order) {
  671. $orderModule->initOrder($order);
  672. $order = array_merge($order->getAttributes(), [
  673. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  674. 'date_distribution' => $order->distribution->date,
  675. 'pointSale' => $order->pointSale->getAttributes()
  676. ]);
  677. }
  678. }
  679. return $ordersUserArray;
  680. }
  681. public function ajaxInfosUser(Producer $producer)
  682. {
  683. $userProducerModule = $this->getUserProducerModule();
  684. $producerModule = $this->getProducerModule();
  685. $user = GlobalParam::getCurrentUser();
  686. if($user) {
  687. $userProducer = $userProducerModule->findOneUserProducer($user);
  688. if (!$userProducer) {
  689. $userProducer = $producerModule->addUser($user, $producer);
  690. }
  691. }
  692. $jsonUser = false;
  693. if ($user && $userProducer) {
  694. $jsonUser = [
  695. 'address' => $user->address,
  696. 'credit' => $userProducer->credit,
  697. 'credit_active' => $userProducer->credit_active,
  698. ];
  699. }
  700. return $jsonUser;
  701. }
  702. private function ajaxInfosPointsSale($producer, $distribution = null)
  703. {
  704. $pointSaleModule = $this->getPointSaleModule();
  705. $producerModule = $this->getProducerModule();
  706. $orderModule = $this->getOrderModule();
  707. $user = GlobalParam::getCurrentUser();
  708. $pointsSaleArray = PointSale::find();
  709. if ($distribution) {
  710. $pointsSaleArray = $pointsSaleArray->joinWith([
  711. 'pointSaleDistribution' => function ($query) use (
  712. $distribution
  713. ) {
  714. $query->where(
  715. [
  716. 'id_distribution' => $distribution->id,
  717. 'delivery' => 1
  718. ]
  719. );
  720. }
  721. ]);
  722. }
  723. if (GlobalParam::getCurrentUserId()) {
  724. $pointsSaleArray = $pointsSaleArray->with([
  725. 'userPointSale' => function ($query) {
  726. $query->onCondition(
  727. ['id_user' => GlobalParam::getCurrentUserId()]
  728. );
  729. }
  730. ]);
  731. }
  732. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  733. ->andWhere(
  734. '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))'
  735. )
  736. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  737. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  738. ->all();
  739. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  740. $position = 0;
  741. foreach ($pointsSaleArray as &$pointSale) {
  742. $pointSaleObject = $pointSale;
  743. $pointSale = array_merge($pointSale->getAttributes(), [
  744. 'pointSaleDistribution' => [
  745. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  746. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  747. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  748. ],
  749. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  750. ]);
  751. if ($pointSale['code'] && strlen($pointSale['code'])) {
  752. $pointSale['code'] = '***';
  753. }
  754. if (!strlen($pointSale['credit_functioning'])) {
  755. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  756. }
  757. if ($distribution) {
  758. $pointSale['count_orders'] = (int)Order::searchCount([
  759. 'id_distribution' => $distribution->id,
  760. 'id_point_sale' => $pointSale['id']
  761. ]);
  762. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  763. }
  764. $pointSale['producers_sharing_point_sale_as_string'] = false;
  765. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  766. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  767. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  768. }
  769. $pointSale['position'] = $position;
  770. $position++;
  771. }
  772. $favoritePointSale = false;
  773. if ($user) {
  774. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  775. }
  776. if ($favoritePointSale) {
  777. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  778. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  779. $theFavoritePointSale = $pointsSaleArray[$i];
  780. unset($pointsSaleArray[$i]);
  781. }
  782. }
  783. if (isset($theFavoritePointSale)) {
  784. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  785. $pointsSaleArray[] = $theFavoritePointSale;
  786. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  787. }
  788. }
  789. return $pointsSaleArray;
  790. }
  791. public function ajaxInfosProductCategories(Producer $producer)
  792. {
  793. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  794. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  795. if ($countProductsWithoutCategory) {
  796. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  797. }
  798. return $categoriesArray;
  799. }
  800. public function ajaxInfosProducts(
  801. Producer $producer,
  802. Distribution $distribution,
  803. PointSale $pointSale = null,
  804. User $user = null,
  805. Order $order = null,
  806. array $productsFormArray = null
  807. )
  808. {
  809. $unitModule = $this->getUnitModule();
  810. $productModule = $this->getProductModule();
  811. $orderModule = $this->getOrderModule();
  812. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  813. $productsArray = Product::find()
  814. ->where([
  815. 'id_producer' => $producer->id,
  816. 'product.status' => 1,
  817. ]);
  818. $productsArray = $productsArray->joinWith([
  819. 'productDistribution' => function ($query) use (
  820. $distribution
  821. ) {
  822. $query->andOnCondition(
  823. 'product_distribution.id_distribution = ' . $distribution->id
  824. );
  825. },
  826. 'productPrice'
  827. ])
  828. ->orderBy('product_distribution.active DESC, order ASC')
  829. ->all();
  830. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  831. $orderCurrent = $order;
  832. if(count($productsFormArray)) {
  833. $productOrdersArray = [];
  834. foreach($productsFormArray as $idProduct => $quantityProduct) {
  835. if($idProduct) {
  836. $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
  837. $productOrdersArray[$idProduct] = [
  838. 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
  839. ];
  840. }
  841. }
  842. $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
  843. }
  844. $indexProduct = 0;
  845. foreach ($productsArrayFilter as $key => &$product) {
  846. $productObject = $product;
  847. $product = array_merge(
  848. $product->getAttributes(),
  849. [
  850. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  851. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  852. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  853. 'productDistribution' => $product['productDistribution'],
  854. 'productPointSale' => $product['productPointSale'],
  855. ]
  856. );
  857. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  858. $product['photo'] = '';
  859. }
  860. else {
  861. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  862. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  863. }
  864. $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
  865. $product['coefficient_unit'] = $coefficientUnit;
  866. $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
  867. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  868. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  869. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  870. $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
  871. $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
  872. if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
  873. $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
  874. $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
  875. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  876. }
  877. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  878. if ($order) {
  879. foreach ($order->productOrder as $productOrder) {
  880. if ($productOrder->id_product == $product['id']) {
  881. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  882. $product['step'] = $productOrder->step;
  883. }
  884. }
  885. }
  886. $product['index'] = $indexProduct++;
  887. }
  888. return $productsArrayFilter;
  889. }
  890. private function getOrderUser(string $date, PointSale $pointSale = null)
  891. {
  892. $orderModule = $this->getOrderModule();
  893. $orderUser = null;
  894. if (GlobalParam::getCurrentUserId()) {
  895. $conditionOrderUser = [
  896. 'distribution.date' => $date,
  897. 'id_user' => GlobalParam::getCurrentUserId()
  898. ];
  899. if ($pointSale) {
  900. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  901. }
  902. $orderUser = Order::searchOne($conditionOrderUser, [
  903. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  904. ]);
  905. if ($orderUser && $orderUser->online_payment_url) {
  906. $orderUser = null;
  907. }
  908. }
  909. if($orderUser) {
  910. $orderModule->initOrder($orderUser);
  911. }
  912. return $orderUser;
  913. }
  914. }