選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

1075 行
44KB

  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 ($order->load($posts)) {
  152. $user = $this->getUserCurrent();
  153. $order = Order::find()
  154. ->where('id_distribution = :id_distribution')
  155. ->andWhere('id_user = :id_user')
  156. ->andWhere('id_point_sale = :id_point_sale')
  157. ->andWhere(OrderRepositoryQuery::getSqlFilterIsValid())
  158. ->params([
  159. ':id_distribution' => $posts['Order']['id_distribution'],
  160. ':id_point_sale' => $posts['Order']['id_point_sale'],
  161. ':id_user' => $user ? $user->id : null
  162. ])
  163. ->one();
  164. if ($order && !$order->online_payment_url) {
  165. if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
  166. $order->id_point_sale = $posts['Order']['id_point_sale'];
  167. }
  168. } else {
  169. // gestion user : option_allow_order_guest
  170. if (isset($posts['user']) && $posts['user']) {
  171. $userIndividualExist = User::searchOne([
  172. 'email' => $posts['user']['email'],
  173. 'type' => User::TYPE_INDIVIDUAL
  174. ]);
  175. if ($userIndividualExist) {
  176. $errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . \Yii::$app->urlManagerFrontend->createUrl(
  177. ['site/producer', 'id' => $idProducer]
  178. ) . '">connecter à votre compte</a> ou en utiliser une autre.';
  179. return ['status' => 'error', 'errors' => [$errorUserGuest]];
  180. }
  181. $user = User::searchOne([
  182. 'email' => $posts['user']['email'],
  183. 'type' => User::TYPE_GUEST
  184. ]);
  185. if (!$user) {
  186. $user = new User;
  187. $user->id_producer = 0;
  188. $user->type = User::TYPE_GUEST;
  189. $userModule->setPassword($user, Password::generate());
  190. $userModule->generateAuthKey($user);
  191. $user->username = $posts['user']['email'];
  192. $user->email = $posts['user']['email'];
  193. $user->name = $posts['user']['firstname'];
  194. $user->lastname = $posts['user']['lastname'];
  195. $user->phone = $posts['user']['phone'];
  196. $user->save();
  197. // liaison producer / user
  198. $producerModule->addUser($user, $producer);
  199. } else {
  200. $producerModule->addUser($user, $producer);
  201. }
  202. }
  203. $order = new Order;
  204. $order->load(\Yii::$app->request->post());
  205. $order->id_user = $user ? $user->id : null;
  206. $order->date = date('Y-m-d H:i:s');
  207. $order->origin = Order::ORIGIN_USER;
  208. }
  209. $errors = $this->processForm($order, $user);
  210. if (count($errors)) {
  211. return ['status' => 'error', 'errors' => $errors];
  212. }
  213. if ($producerModule->getSolver()->isOnlinePaymentActive($producer) && $posts['payment_method'] == 'online') {
  214. $order = $orderModule->findOneOrderById($order->id);
  215. \Stripe\Stripe::setApiKey(
  216. $producerModule->getPrivateKeyApiStripe($producer)
  217. );
  218. $lineItems = [];
  219. foreach ($order->productOrder as $productOrder) {
  220. $product = $productOrder->product;
  221. $lineItems[] = [
  222. 'price_data' => [
  223. 'currency' => 'eur',
  224. 'product_data' => [
  225. 'name' => $product->name . ' (' . $productOrder->quantity . ' ' . $this->getProductModule()->getSolver()->strUnit(
  226. $product,
  227. UnitDefinition::WORDING_SHORT,
  228. true
  229. ) . ')',
  230. ],
  231. 'unit_amount' => intval($productOrderModule->getSolver()->getPriceWithTax($productOrder) * 100 * $productOrder->quantity),
  232. ],
  233. 'quantity' => 1,
  234. ];
  235. }
  236. $checkout_session = \Stripe\Checkout\Session::create([
  237. 'line_items' => $lineItems,
  238. 'payment_method_types' => ['card'],
  239. 'mode' => 'payment',
  240. 'customer_email' => $user->email,
  241. 'client_reference_id' => $user->id,
  242. 'payment_intent_data' => [
  243. 'metadata' => [
  244. 'user_id' => $user->id,
  245. 'producer_id' => $producer->id,
  246. 'order_id' => $order->id
  247. ],
  248. ],
  249. 'success_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  250. [
  251. 'order/confirm',
  252. 'idOrder' => $order->id,
  253. 'returnPayment' => 'success'
  254. ]
  255. ),
  256. 'cancel_url' => $this->getUrlManagerProducer()->createAbsoluteUrl(
  257. [
  258. 'order/confirm',
  259. 'idOrder' => $order->id,
  260. 'returnPayment' => 'cancel'
  261. ]
  262. ),
  263. ]);
  264. $redirect = $checkout_session->url;
  265. $order->online_payment_url = $redirect;
  266. $order->save();
  267. }
  268. }
  269. return ['status' => 'success', 'idOrder' => $order->id, 'redirect' => $redirect];
  270. }
  271. /**
  272. * Vérifie si un producteur est actif.
  273. */
  274. public function _verifyProducerActive($idProducer)
  275. {
  276. $producer = $this->getProducerModule()->findOneProducerById($idProducer);
  277. if ($producer && !$producer->active) {
  278. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  279. }
  280. }
  281. /**
  282. * Traite le formulaire de création/modification de commande.
  283. */
  284. public function processForm($order, $user)
  285. {
  286. $productModule = $this->getProductModule();
  287. $distributionModule = $this-> getDistributionModule();
  288. $pointSaleDistributionModule = $this->getPointSaleDistributionModule();
  289. $pointSaleModule = $this->getPointSaleModule();
  290. $userPointSaleModule = $this->getUserPointSaleModule();
  291. $userProducerModule = $this->getUserProducerModule();
  292. $orderModule = $this->getOrderModule();
  293. $producerModule = $this->getProducerModule();
  294. $productOrderModule = $this->getProductOrderModule();
  295. $userModule = $this->getUserModule();
  296. $paymentManager = $this->getPaymentModule();
  297. $posts = \Yii::$app->request->post();
  298. $productsArray = [];
  299. $totalQuantity = 0;
  300. $producer = $this->getProducerCurrent();
  301. $isNewOrder = false;
  302. if (!$order->id) {
  303. $isNewOrder = true;
  304. }
  305. foreach ($posts['products'] as $key => $quantity) {
  306. $product = $productModule->findOneProductById((int)$key);
  307. $totalQuantity += $quantity;
  308. if ($product && $quantity) {
  309. $productsArray[] = $product;
  310. }
  311. }
  312. $errorDate = false;
  313. if (isset($order->id_distribution)) {
  314. $distribution = $distributionModule->findOneDistributionById($order->id_distribution);
  315. if ($orderModule->getState($order) != Order::STATE_OPEN) {
  316. $errorDate = true;
  317. }
  318. }
  319. $errorPointSale = false;
  320. if (isset($distribution) && $distribution) {
  321. $order->populateDistribution($distribution);
  322. $pointSale = $pointSaleModule->findOnePointSaleById($posts['Order']['id_point_sale']);
  323. $pointSaleDistribution = $pointSaleDistributionModule->findOnePointSaleDistribution($distribution, $pointSale);
  324. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  325. $errorPointSale = true;
  326. }
  327. if ($pointSale) {
  328. if (strlen($pointSale->code) && !$pointSaleModule->validateCode($pointSale, $posts['code_point_sale'])) {
  329. $errorPointSale = true;
  330. }
  331. } else {
  332. $errorPointSale = true;
  333. }
  334. $userPointSale = $userPointSaleModule->findOneUserPointSale(GlobalParam::getCurrentUser(), $pointSale);
  335. if ($pointSale && $pointSale->restricted_access && !$userPointSale) {
  336. $errorPointSale = true;
  337. }
  338. }
  339. $errors = [];
  340. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  341. $userProducer = $userProducerModule->findOneUserProducer($user);
  342. $pointSale = $pointSaleModule->findOnePointSaleById($order->id_point_sale);
  343. $order->comment_point_sale = ($pointSale && strlen($pointSaleModule->getComment($pointSale))) ?
  344. $pointSaleModule->getComment($pointSale) : '';
  345. // une commande annulée est automatiquement réactivée lors d'une modification
  346. if($order->isOrderStatusCanceled()) {
  347. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $this->getUserCurrent());
  348. }
  349. $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
  350. $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
  351. // on sauvegarde l'adresse de livraison dans le profil de l'utilisateur pour qu'il n'ait plus à la ressaisir
  352. if($order->delivery_address && !$user->address) {
  353. $user->address = $order->delivery_address;
  354. $user->save();
  355. }
  356. $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
  357. $order->save();
  358. $orderModule->generateOrderReference($order);
  359. if($isNewOrder) {
  360. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
  361. }
  362. else {
  363. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_UPDATED, $user);
  364. }
  365. $producerModule->addUser($user, $producer);
  366. // suppression de tous les enregistrements ProductOrder
  367. if (!is_null($order)) {
  368. $productOrderModule->deleteProductOrdersByOrder($order);
  369. if (isset($order->productOrder)) {
  370. foreach ($order->productOrder as $productOrder) {
  371. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  372. }
  373. }
  374. }
  375. $availableProducts = $orderModule->findProductDistributionsByDistribution($distribution);
  376. foreach ($productsArray as $product) {
  377. if (isset($availableProducts[$product->id])
  378. && $availableProducts[$product->id]
  379. && $availableProducts[$product->id]['active']) {
  380. $productOrder = new ProductOrder();
  381. $productOrder->id_order = $order->id;
  382. $productOrder->id_product = $product->id;
  383. $productOrder->id_tax_rate = $product->taxRate->id;
  384. $unit = (!is_null(
  385. $order
  386. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  387. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  388. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  389. $quantityRemaining = $orderModule->getResolver()->getProductQuantityRemaining($product, $order->distribution);
  390. if(!is_null($quantityRemaining) && $quantity > $quantityRemaining) {
  391. $quantity = $quantityRemaining;
  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. 'feature_product_accessory_enabled' => $this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_PRODUCT_ACCESSORY),
  600. ];
  601. }
  602. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  603. {
  604. $distributionModule = $this-> getDistributionModule();
  605. $dateMini = date('Y-m-d');
  606. $distributionsArray = Distribution::searchAll([
  607. 'active' => 1,
  608. 'id_producer' => $producer->id
  609. ], [
  610. 'conditions' => ['date > :date'],
  611. 'params' => [':date' => $dateMini],
  612. 'join_with' => ['pointSaleDistribution'],
  613. ]);
  614. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  615. // Filtre par période de congé
  616. foreach ($distributionsArray as $keyDistribution => $distribution) {
  617. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  618. unset($distributionsArray[$keyDistribution]);
  619. }
  620. }
  621. // Filtre par point de vente
  622. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  623. $distributionsArrayFilterPointSale = [];
  624. for ($i = 0; $i < count($distributionsArray); $i++) {
  625. $distribution = $distributionsArray[$i];
  626. if ($distribution && $distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  627. $countOrders = Order::searchCount([
  628. 'id_distribution' => $distribution->id,
  629. 'id_point_sale' => $pointSaleCurrent->id
  630. ]);
  631. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  632. if (!$pointSaleCurrent->maximum_number_orders
  633. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  634. || ($pointSaleCurrent->maximum_number_orders &&
  635. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  636. $distributionsArrayFilterPointSale[] = $distribution;
  637. }
  638. }
  639. }
  640. return $distributionsArrayFilterPointSale;
  641. } else {
  642. return $distributionsArray;
  643. }
  644. }
  645. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  646. {
  647. $orderModule = $this->getOrderModule();
  648. $dateMini = date('Y-m-d');
  649. $ordersUserArray = [];
  650. if (GlobalParam::getCurrentUserId()) {
  651. $conditionsOrdersUser = [
  652. 'distribution.date > :date',
  653. 'order.online_payment_url IS NULL'
  654. ];
  655. $paramsOrdersUser = [
  656. ':date' => $dateMini
  657. ];
  658. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  659. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  660. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  661. }
  662. $conditionsOrdersUser[] = OrderRepositoryQuery::getSqlFilterIsValid();
  663. $ordersUserArray = Order::searchAll([
  664. 'id_user' => GlobalParam::getCurrentUserId()
  665. ], [
  666. 'conditions' => $conditionsOrdersUser,
  667. 'params' => $paramsOrdersUser
  668. ]);
  669. }
  670. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  671. foreach ($ordersUserArray as &$order) {
  672. $orderModule->initOrder($order);
  673. $order = array_merge($order->getAttributes(), [
  674. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  675. 'date_distribution' => $order->distribution->date,
  676. 'pointSale' => $order->pointSale->getAttributes()
  677. ]);
  678. }
  679. }
  680. return $ordersUserArray;
  681. }
  682. public function ajaxInfosUser(Producer $producer)
  683. {
  684. $userProducerModule = $this->getUserProducerModule();
  685. $producerModule = $this->getProducerModule();
  686. $user = GlobalParam::getCurrentUser();
  687. if($user) {
  688. $userProducer = $userProducerModule->findOneUserProducer($user);
  689. if (!$userProducer) {
  690. $userProducer = $producerModule->addUser($user, $producer);
  691. }
  692. }
  693. $jsonUser = false;
  694. if ($user && $userProducer) {
  695. $jsonUser = [
  696. 'address' => $user->address,
  697. 'credit' => $userProducer->credit,
  698. 'credit_active' => $userProducer->credit_active,
  699. ];
  700. }
  701. return $jsonUser;
  702. }
  703. private function ajaxInfosPointsSale($producer, $distribution = null)
  704. {
  705. $pointSaleModule = $this->getPointSaleModule();
  706. $producerModule = $this->getProducerModule();
  707. $orderModule = $this->getOrderModule();
  708. $user = GlobalParam::getCurrentUser();
  709. $userProducer = null;
  710. if($user) {
  711. $userProducer = $this->getUserProducerModule()->getRepository()->findOneUserProducer($user);
  712. }
  713. $pointsSaleArray = PointSale::find();
  714. if ($distribution) {
  715. $pointsSaleArray = $pointsSaleArray->joinWith([
  716. 'pointSaleDistribution' => function ($query) use (
  717. $distribution
  718. ) {
  719. $query->where(
  720. [
  721. 'id_distribution' => $distribution->id,
  722. 'delivery' => 1
  723. ]
  724. );
  725. }
  726. ]);
  727. }
  728. if (GlobalParam::getCurrentUserId()) {
  729. $pointsSaleArray = $pointsSaleArray->with([
  730. 'userPointSale' => function ($query) {
  731. $query->onCondition(
  732. ['id_user' => GlobalParam::getCurrentUserId()]
  733. );
  734. }
  735. ]);
  736. }
  737. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  738. ->andWhere(
  739. '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))'
  740. )
  741. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  742. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  743. ->all();
  744. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  745. $position = 0;
  746. foreach ($pointsSaleArray as &$pointSale) {
  747. $pointSaleObject = $pointSale;
  748. $pointSale = array_merge($pointSale->getAttributes(), [
  749. 'pointSaleDistribution' => [
  750. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  751. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  752. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  753. ],
  754. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  755. ]);
  756. if ($pointSale['code'] && strlen($pointSale['code'])) {
  757. $pointSale['code'] = '***';
  758. }
  759. if (!strlen($pointSale['credit_functioning'])) {
  760. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  761. }
  762. if ($distribution) {
  763. $pointSale['count_orders'] = (int)Order::searchCount([
  764. 'id_distribution' => $distribution->id,
  765. 'id_point_sale' => $pointSale['id']
  766. ]);
  767. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  768. }
  769. $pointSale['producers_sharing_point_sale_as_string'] = false;
  770. if($this->getFeatureModule()->getChecker()->isEnabled(Feature::ALIAS_SHARED_POINT_SALE)) {
  771. $pointSale['producers_sharing_point_sale_as_string'] = $this->getSharedPointSaleModule()->getResolver()
  772. ->getProducersSharingPointSaleAsString($pointSaleObject, $distribution, ', ', true);
  773. }
  774. $pointSale['position'] = $position;
  775. $position++;
  776. }
  777. $favoritePointSale = false;
  778. if ($user) {
  779. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  780. }
  781. if ($favoritePointSale) {
  782. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  783. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  784. $theFavoritePointSale = $pointsSaleArray[$i];
  785. unset($pointsSaleArray[$i]);
  786. }
  787. }
  788. if (isset($theFavoritePointSale)) {
  789. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  790. $pointsSaleArray[] = $theFavoritePointSale;
  791. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  792. }
  793. }
  794. // Filtre par accès exclusif aux points de vente
  795. if($userProducer) {
  796. $pointsSaleArray = $this->getUserProducerModule()->getSolver()->filterPointsSaleByExclusiveAccess(
  797. $userProducer,
  798. $pointsSaleArray
  799. );
  800. }
  801. return $pointsSaleArray;
  802. }
  803. public function ajaxInfosProductCategories(Producer $producer)
  804. {
  805. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  806. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  807. if ($countProductsWithoutCategory) {
  808. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  809. }
  810. return $categoriesArray;
  811. }
  812. public function ajaxInfosProducts(
  813. Producer $producer,
  814. Distribution $distribution,
  815. PointSale $pointSale = null,
  816. User $user = null,
  817. Order $order = null,
  818. array $productsFormArray = null
  819. )
  820. {
  821. $unitModule = $this->getUnitModule();
  822. $productModule = $this->getProductModule();
  823. $orderModule = $this->getOrderModule();
  824. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  825. $productsArray = Product::find()
  826. ->where([
  827. 'id_producer' => $producer->id,
  828. 'product.status' => 1,
  829. ]);
  830. $productsArray = $productsArray->joinWith([
  831. 'productDistribution' => function ($query) use (
  832. $distribution
  833. ) {
  834. $query->andOnCondition(
  835. 'product_distribution.id_distribution = ' . $distribution->id
  836. );
  837. },
  838. 'productPrice'
  839. ])
  840. ->orderBy('product_distribution.active DESC, order ASC')
  841. ->all();
  842. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  843. $orderCurrent = $order;
  844. if($productsFormArray && count($productsFormArray)) {
  845. $productOrdersArray = [];
  846. foreach($productsFormArray as $idProduct => $quantityProduct) {
  847. if($idProduct) {
  848. $productObject1 = $productModule->getRepository()->findOneProductById($idProduct);
  849. $productOrdersArray[$idProduct] = [
  850. 'quantity' => $quantityProduct / $productModule->getSolver()->getUnitCoefficient($productObject1)
  851. ];
  852. }
  853. }
  854. $orderCurrent = $orderModule->getBuilder()->instanciateOrderFromProductOrdersArray($productOrdersArray, $orderCurrent);
  855. }
  856. $indexProduct = 0;
  857. foreach ($productsArrayFilter as $key => &$product) {
  858. $productObject = $product;
  859. $product = array_merge(
  860. $product->getAttributes(),
  861. [
  862. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  863. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  864. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  865. 'productDistribution' => $product['productDistribution'],
  866. 'productPointSale' => $product['productPointSale'],
  867. ]
  868. );
  869. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  870. $product['photo'] = '';
  871. }
  872. else {
  873. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  874. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  875. }
  876. $coefficientUnit = Product::$unitsArray[$product['unit']]['coefficient'];
  877. $product['coefficient_unit'] = $coefficientUnit;
  878. $product['quantity_max'] = $orderModule->getResolver()->getProductQuantityMaxOrderable($productObject, $distribution, $orderCurrent);
  879. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  880. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  881. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  882. $quantityOrderUser = $orderModule->getSolver()->getProductQuantity($productObject, $orderCurrent ? [$orderCurrent] : [], true);
  883. $product['quantity_form'] = $quantityOrderUser * $coefficientUnit;
  884. if($product['quantity_remaining'] < 0 && $product['quantity_form']) {
  885. $product['quantity_form'] = $product['quantity_form'] + ($product['quantity_remaining'] * $coefficientUnit);
  886. $orderModule->getBuilder()->deleteProductOrderQuantity($orderCurrent, $productObject, abs($product['quantity_remaining']));
  887. $product['quantity_remaining'] = $orderModule->getResolver()->getProductQuantityRemaining($productObject, $distribution, $orderCurrent);
  888. }
  889. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  890. if ($order) {
  891. foreach ($order->productOrder as $productOrder) {
  892. if ($productOrder->id_product == $product['id']) {
  893. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  894. $product['step'] = $productOrder->step;
  895. }
  896. }
  897. }
  898. $product['index'] = $indexProduct++;
  899. }
  900. return $productsArrayFilter;
  901. }
  902. private function getOrderUser(string $date, PointSale $pointSale = null)
  903. {
  904. $orderModule = $this->getOrderModule();
  905. $orderUser = null;
  906. if (GlobalParam::getCurrentUserId()) {
  907. $conditionOrderUser = [
  908. 'distribution.date' => $date,
  909. 'id_user' => GlobalParam::getCurrentUserId()
  910. ];
  911. if ($pointSale) {
  912. $conditionOrderUser['id_point_sale'] = $pointSale->id;
  913. }
  914. $orderUser = Order::searchOne($conditionOrderUser, [
  915. 'conditions' => OrderRepositoryQuery::getSqlFilterIsValid()
  916. ]);
  917. if ($orderUser && $orderUser->online_payment_url) {
  918. $orderUser = null;
  919. }
  920. }
  921. if($orderUser) {
  922. $orderModule->initOrder($orderUser);
  923. }
  924. return $orderUser;
  925. }
  926. }