Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

1079 Zeilen
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. for ($i = 0; $i < count($distributionsArray); $i++) {
  629. $distribution = $distributionsArray[$i];
  630. if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  631. $countOrders = Order::searchCount([
  632. 'id_distribution' => $distribution->id,
  633. 'id_point_sale' => $pointSaleCurrent->id
  634. ]);
  635. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  636. if (!$pointSaleCurrent->maximum_number_orders
  637. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  638. || ($pointSaleCurrent->maximum_number_orders &&
  639. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  640. $distributionsArrayFilterPointSale[] = $distribution;
  641. }
  642. }
  643. }
  644. return $distributionsArrayFilterPointSale;
  645. } else {
  646. return $distributionsArray;
  647. }
  648. }
  649. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  650. {
  651. $orderModule = $this->getOrderModule();
  652. $dateMini = date('Y-m-d');
  653. $ordersUserArray = [];
  654. if (GlobalParam::getCurrentUserId()) {
  655. $conditionsOrdersUser = [
  656. 'distribution.date > :date',
  657. 'order.online_payment_url IS NULL'
  658. ];
  659. $paramsOrdersUser = [
  660. ':date' => $dateMini
  661. ];
  662. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  663. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  664. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  665. }
  666. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  667. $ordersUserArray = Order::searchAll([
  668. 'id_user' => GlobalParam::getCurrentUserId()
  669. ], [
  670. 'conditions' => $conditionsOrdersUser,
  671. 'params' => $paramsOrdersUser
  672. ]);
  673. }
  674. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  675. foreach ($ordersUserArray as &$order) {
  676. $orderModule->initOrder($order);
  677. $order = array_merge($order->getAttributes(), [
  678. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  679. 'date_distribution' => $order->distribution->date,
  680. 'pointSale' => $order->pointSale->getAttributes()
  681. ]);
  682. }
  683. }
  684. return $ordersUserArray;
  685. }
  686. public function ajaxInfosUser(Producer $producer)
  687. {
  688. $userProducerModule = $this->getUserProducerModule();
  689. $producerModule = $this->getProducerModule();
  690. $user = GlobalParam::getCurrentUser();
  691. if($user) {
  692. $userProducer = $userProducerModule->findOneUserProducer($user);
  693. if (!$userProducer) {
  694. $userProducer = $producerModule->addUser($user, $producer);
  695. }
  696. }
  697. $jsonUser = false;
  698. if ($user && $userProducer) {
  699. $jsonUser = [
  700. 'address' => $user->address,
  701. 'credit' => $userProducer->credit,
  702. 'credit_active' => $userProducer->credit_active,
  703. ];
  704. }
  705. return $jsonUser;
  706. }
  707. private function ajaxInfosPointsSale($producer, $distribution = null)
  708. {
  709. $pointSaleModule = $this->getPointSaleModule();
  710. $producerModule = $this->getProducerModule();
  711. $orderModule = $this->getOrderModule();
  712. $user = GlobalParam::getCurrentUser();
  713. $userProducer = null;
  714. if($user) {
  715. $userProducer = $this->getUserProducerModule()->getRepository()->findOneUserProducer($user);
  716. }
  717. $pointsSaleArray = PointSale::find();
  718. if ($distribution) {
  719. $pointsSaleArray = $pointsSaleArray->joinWith([
  720. 'pointSaleDistribution' => function ($query) use (
  721. $distribution
  722. ) {
  723. $query->where(
  724. [
  725. 'id_distribution' => $distribution->id,
  726. 'delivery' => 1
  727. ]
  728. );
  729. }
  730. ]);
  731. }
  732. if (GlobalParam::getCurrentUserId()) {
  733. $pointsSaleArray = $pointsSaleArray->with([
  734. 'userPointSale' => function ($query) {
  735. $query->onCondition(
  736. ['id_user' => GlobalParam::getCurrentUserId()]
  737. );
  738. }
  739. ]);
  740. }
  741. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  742. ->andWhere(
  743. '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))'
  744. )
  745. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  746. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  747. ->all();
  748. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  749. $position = 0;
  750. foreach ($pointsSaleArray as &$pointSale) {
  751. $pointSaleObject = $pointSale;
  752. $pointSale = array_merge($pointSale->getAttributes(), [
  753. 'pointSaleDistribution' => [
  754. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  755. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  756. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  757. ],
  758. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  759. ]);
  760. if ($pointSale['code'] && strlen($pointSale['code'])) {
  761. $pointSale['code'] = '***';
  762. }
  763. if (!strlen($pointSale['credit_functioning'])) {
  764. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  765. }
  766. if ($distribution) {
  767. $pointSale['count_orders'] = (int)Order::searchCount([
  768. 'id_distribution' => $distribution->id,
  769. 'id_point_sale' => $pointSale['id']
  770. ]);
  771. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  772. }
  773. $pointSale['producers_sharing_point_sale_as_string'] = false;
  774. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  775. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  776. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  777. }
  778. $pointSale['position'] = $position;
  779. $position++;
  780. }
  781. $favoritePointSale = false;
  782. if ($user) {
  783. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  784. }
  785. if ($favoritePointSale) {
  786. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  787. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  788. $theFavoritePointSale = $pointsSaleArray[$i];
  789. unset($pointsSaleArray[$i]);
  790. }
  791. }
  792. if (isset($theFavoritePointSale)) {
  793. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  794. $pointsSaleArray[] = $theFavoritePointSale;
  795. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  796. }
  797. }
  798. // Filtre par accès exclusif aux points de vente
  799. if($userProducer) {
  800. $pointsSaleArray = $this->getUserProducerModule()->getSolver()->filterPointsSaleByExclusiveAccess(
  801. $userProducer,
  802. $pointsSaleArray
  803. );
  804. }
  805. return $pointsSaleArray;
  806. }
  807. public function ajaxInfosProductCategories(Producer $producer)
  808. {
  809. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  810. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  811. if ($countProductsWithoutCategory) {
  812. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  813. }
  814. return $categoriesArray;
  815. }
  816. public function ajaxInfosProducts(
  817. Producer $producer,
  818. Distribution $distribution,
  819. PointSale $pointSale = null,
  820. User $user = null,
  821. Order $order = null,
  822. array $productsFormArray = null
  823. )
  824. {
  825. $unitModule = $this->getUnitModule();
  826. $productModule = $this->getProductModule();
  827. $orderModule = $this->getOrderModule();
  828. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  829. $productsArray = Product::find()
  830. ->where([
  831. 'id_producer' => $producer->id,
  832. 'product.status' => 1,
  833. ]);
  834. $productsArray = $productsArray->joinWith([
  835. 'productDistribution' => function ($query) use (
  836. $distribution
  837. ) {
  838. $query->andOnCondition(
  839. 'product_distribution.id_distribution = ' . $distribution->id
  840. );
  841. },
  842. 'productPrice'
  843. ])
  844. ->orderBy('product_distribution.active DESC, order ASC')
  845. ->all();
  846. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  847. $orderCurrent = $order;
  848. if($productsFormArray && count($productsFormArray)) {
  849. $productOrdersArray = [];
  850. foreach($productsFormArray as $idProduct => $quantityProduct) {
  851. if($idProduct) {
  852. $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
  853. $productOrdersArray[$idProduct] = [
  854. 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
  855. ];
  856. }
  857. }
  858. $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
  859. }
  860. $indexProduct = 0;
  861. foreach ($productsArrayFilter as $key => &$product) {
  862. $productObject = $product;
  863. $product = array_merge(
  864. $product->getAttributes(),
  865. [
  866. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  867. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  868. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  869. 'productDistribution' => $product['productDistribution'],
  870. 'productPointSale' => $product['productPointSale'],
  871. ]
  872. );
  873. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  874. $product['photo'] = '';
  875. }
  876. else {
  877. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  878. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  879. }
  880. $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
  881. $product['coefficient_unit'] = $coefficientUnit;
  882. $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
  883. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  884. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  885. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  886. $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
  887. $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
  888. if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
  889. $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
  890. $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
  891. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  892. }
  893. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  894. if ($order) {
  895. foreach ($order->productOrder as $productOrder) {
  896. if ($productOrder->id_product == $product['id']) {
  897. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  898. $product['step'] = $productOrder->step;
  899. }
  900. }
  901. }
  902. $product['index'] = $indexProduct++;
  903. }
  904. return $productsArrayFilter;
  905. }
  906. private function getOrderUser(string $date, PointSale $pointSale = null)
  907. {
  908. $orderModule = $this->getOrderModule();
  909. $orderUser = null;
  910. if (GlobalParam::getCurrentUserId()) {
  911. $conditionOrderUser = [
  912. 'distribution.date' => $date,
  913. 'id_user' => GlobalParam::getCurrentUserId()
  914. ];
  915. if ($pointSale) {
  916. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  917. }
  918. $orderUser = Order::searchOne($conditionOrderUser, [
  919. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  920. ]);
  921. if ($orderUser && $orderUser->online_payment_url) {
  922. $orderUser = null;
  923. }
  924. }
  925. if($orderUser) {
  926. $orderModule->initOrder($orderUser);
  927. }
  928. return $orderUser;
  929. }
  930. }