Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

1028 lines
41KB

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