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.

1031 Zeilen
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. if($quantity) {
  393. $productOrder->save();
  394. }
  395. }
  396. }
  397. // lien utilisateur / point de vente
  398. $pointSaleModule->addUser($user, $pointSale);
  399. // credit
  400. $credit = $producerModule->getConfig('credit');
  401. $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
  402. $order = $orderModule->findOneOrderById($order->id);
  403. $orderModule->initOrder($order);
  404. if ($credit
  405. && $this->getUserCurrent()
  406. && $pointSale->payment_method_credit
  407. && $posts['payment_method'] == 'credit'
  408. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  409. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  410. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  411. )) {
  412. // à payer
  413. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  414. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  415. } // surplus à rembourser
  416. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  417. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  418. }
  419. }
  420. /*
  421. * Envoi email de confirmation
  422. */
  423. $emailSubject = 'Confirmation de commande';
  424. $emailContentParams = [
  425. 'order' => $order,
  426. 'pointSale' => $pointSale,
  427. 'distribution' => $distribution,
  428. 'user' => $user,
  429. 'producer' => $producer
  430. ];
  431. // au client
  432. if ($producerModule->getConfig('option_email_confirm')) {
  433. \Yii::$app->mailerService->sendFromProducer(
  434. $emailSubject,
  435. 'orderConfirm',
  436. $emailContentParams,
  437. $user->email,
  438. $producer
  439. );
  440. }
  441. // au producteur
  442. $contactProducer = $producerModule->getMainContact($producer);
  443. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  444. $contactProducer->email
  445. )) {
  446. \Yii::$app->mailerService->sendFromSite(
  447. $emailSubject,
  448. 'orderConfirmProducer',
  449. $emailContentParams,
  450. $contactProducer->email
  451. );
  452. }
  453. $order = $orderModule->findOneOrderById($order->id);
  454. $orderModule->initOrder($order);
  455. $orderModule->updateOrderTillerSynchronization($order);
  456. }
  457. if (!count($productsArray)) {
  458. $errors[] = "Vous n'avez choisi aucun produit";
  459. }
  460. if ($errorDate) {
  461. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  462. }
  463. if ($errorPointSale) {
  464. $errors[] = "Point de vente invalide.";
  465. }
  466. return $errors;
  467. }
  468. /**
  469. * Annule une commande.
  470. */
  471. public function actionCancel(int $id)
  472. {
  473. $orderModule = $this->getOrderModule();
  474. $order = $this->getOrderModule()->findOneOrderById($id);
  475. if (!$order) {
  476. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  477. }
  478. $orderModule->initOrder($order);
  479. if (!$orderModule->isOrderStateOpen($order)) {
  480. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  481. }
  482. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  483. $orderModule->deleteOrder($order);
  484. $this->setFlash('success', 'Votre commande a bien été annulée.');
  485. }
  486. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  487. }
  488. /**
  489. * Page de confirmation de commande.
  490. */
  491. public function actionConfirm(int $idOrder, string $returnPayment = '')
  492. {
  493. $orderModule = $this->getOrderModule();
  494. $order = $orderModule->findOneOrderById($idOrder);
  495. $producer = $this->getProducerCurrent();
  496. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  497. $this->setFlash('error', 'Commande introuvable');
  498. return $this->redirect(['order/history']);
  499. }
  500. $orderModule->initOrder($order);
  501. return $this->render('confirm', [
  502. 'order' => $order,
  503. 'returnPayment' => $returnPayment
  504. ]);
  505. }
  506. /**
  507. * Vérifie le code saisi pour un point de vente.
  508. */
  509. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  510. {
  511. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  512. $pointSaleModule = $this->getPointSaleModule();
  513. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  514. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  515. return 1;
  516. }
  517. return 0;
  518. }
  519. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
  520. {
  521. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  522. $user = GlobalParam::getCurrentUser();
  523. $producer = $this->getProducerCurrent();
  524. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  525. $order = $this->getOrderUser($date, $pointSale);
  526. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
  527. }
  528. public function buildJsonAjaxInfos(
  529. string $date,
  530. Producer $producer,
  531. PointSale $pointSale = null,
  532. User $user = null,
  533. Order $order = null
  534. )
  535. {
  536. $orderModule = $this->getOrderModule();
  537. $json = [];
  538. $format = 'Y-m-d';
  539. $dateObject = DateTime::createFromFormat($format, $date);
  540. $json['producer'] = $this->ajaxInfosProducer($producer);
  541. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  542. $json['orders'] = $this->ajaxInfosOrders($producer);
  543. $json['user'] = $this->ajaxInfosUser($producer);
  544. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  545. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  546. if ($dateObject && $dateObject->format($format) === $date) {
  547. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  548. $json['distribution'] = $distribution;
  549. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  550. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  551. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
  552. if ($order) {
  553. $json['order'] = array_merge($order->getAttributes(), [
  554. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  555. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  556. ]);
  557. }
  558. }
  559. return $json;
  560. }
  561. public function ajaxInfosLeavePeriod(Producer $producer)
  562. {
  563. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  564. return [
  565. 'start' => $producer->option_leave_period_start,
  566. 'end' => $producer->option_leave_period_end,
  567. ];
  568. }
  569. return false;
  570. }
  571. public function ajaxInfosProducer(Producer $producer)
  572. {
  573. return [
  574. 'order_infos' => nl2br($producer->order_infos),
  575. 'payment_infos' => nl2br($producer->option_payment_info),
  576. 'credit' => $producer->credit,
  577. 'credit_functioning' => $producer->credit_functioning,
  578. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  579. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  580. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  581. 'option_order_entry_point' => $producer->option_order_entry_point,
  582. 'option_delivery' => $producer->option_delivery,
  583. 'online_payment' => $producer->online_payment,
  584. 'option_online_payment_type' => $producer->online_payment,
  585. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  586. ];
  587. }
  588. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  589. {
  590. $distributionModule = $this-> getDistributionModule();
  591. $dateMini = date('Y-m-d');
  592. $distributionsArray = Distribution::searchAll([
  593. 'active' => 1,
  594. 'id_producer' => $producer->id
  595. ], [
  596. 'conditions' => ['date > :date'],
  597. 'params' => [':date' => $dateMini],
  598. 'join_with' => ['pointSaleDistribution'],
  599. ]);
  600. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  601. // Filtre par période de congé
  602. foreach ($distributionsArray as $keyDistribution => $distribution) {
  603. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  604. unset($distributionsArray[$keyDistribution]);
  605. }
  606. }
  607. // Filtre par point de vente
  608. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  609. $distributionsArrayFilterPointSale = [];
  610. for ($i = 0; $i < count($distributionsArray); $i++) {
  611. $distribution = $distributionsArray[$i];
  612. if ($distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  613. $countOrders = Order::searchCount([
  614. 'id_distribution' => $distribution->id,
  615. 'id_point_sale' => $pointSaleCurrent->id
  616. ]);
  617. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  618. if (!$pointSaleCurrent->maximum_number_orders
  619. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  620. || ($pointSaleCurrent->maximum_number_orders &&
  621. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  622. $distributionsArrayFilterPointSale[] = $distribution;
  623. }
  624. }
  625. }
  626. return $distributionsArrayFilterPointSale;
  627. } else {
  628. return $distributionsArray;
  629. }
  630. }
  631. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  632. {
  633. $producerModule = $this->getProducerModule();
  634. $orderModule = $this->getOrderModule();
  635. $dateMini = date('Y-m-d');
  636. $ordersUserArray = [];
  637. if (GlobalParam::getCurrentUserId()) {
  638. $conditionsOrdersUser = [
  639. 'distribution.date > :date',
  640. 'order.online_payment_url IS NULL'
  641. ];
  642. $paramsOrdersUser = [
  643. ':date' => $dateMini
  644. ];
  645. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  646. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  647. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  648. }
  649. $ordersUserArray = Order::searchAll([
  650. 'id_user' => GlobalParam::getCurrentUserId()
  651. ], [
  652. 'conditions' => $conditionsOrdersUser,
  653. 'params' => $paramsOrdersUser
  654. ]);
  655. }
  656. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  657. foreach ($ordersUserArray as &$order) {
  658. $orderModule->initOrder($order);
  659. $order = array_merge($order->getAttributes(), [
  660. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  661. 'date_distribution' => $order->distribution->date,
  662. 'pointSale' => $order->pointSale->getAttributes()
  663. ]);
  664. }
  665. }
  666. return $ordersUserArray;
  667. }
  668. public function ajaxInfosUser(Producer $producer)
  669. {
  670. $userProducerModule = $this->getUserProducerModule();
  671. $producerModule = $this->getProducerModule();
  672. $user = GlobalParam::getCurrentUser();
  673. if($user) {
  674. $userProducer = $userProducerModule->findOneUserProducer($user);
  675. if (!$userProducer) {
  676. $userProducer = $producerModule->addUser($user, $producer);
  677. }
  678. }
  679. $jsonUser = false;
  680. if ($user && $userProducer) {
  681. $jsonUser = [
  682. 'address' => $user->address,
  683. 'credit' => $userProducer->credit,
  684. 'credit_active' => $userProducer->credit_active,
  685. ];
  686. }
  687. return $jsonUser;
  688. }
  689. private function ajaxInfosPointsSale($producer, $distribution = false)
  690. {
  691. $pointSaleModule = $this->getPointSaleModule();
  692. $producerModule = $this->getProducerModule();
  693. $orderModule = $this->getOrderModule();
  694. $user = GlobalParam::getCurrentUser();
  695. $pointsSaleArray = PointSale::find();
  696. if ($distribution) {
  697. $pointsSaleArray = $pointsSaleArray->joinWith([
  698. 'pointSaleDistribution' => function ($query) use (
  699. $distribution
  700. ) {
  701. $query->where(
  702. [
  703. 'id_distribution' => $distribution->id,
  704. 'delivery' => 1
  705. ]
  706. );
  707. }
  708. ]);
  709. }
  710. if (GlobalParam::getCurrentUserId()) {
  711. $pointsSaleArray = $pointsSaleArray->with([
  712. 'userPointSale' => function ($query) {
  713. $query->onCondition(
  714. ['id_user' => GlobalParam::getCurrentUserId()]
  715. );
  716. }
  717. ]);
  718. }
  719. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  720. ->andWhere(
  721. '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))'
  722. )
  723. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  724. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  725. ->all();
  726. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  727. $position = 0;
  728. foreach ($pointsSaleArray as &$pointSale) {
  729. $pointSaleObject = $pointSale;
  730. $pointSale = array_merge($pointSale->getAttributes(), [
  731. 'pointSaleDistribution' => [
  732. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  733. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  734. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  735. ],
  736. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  737. ]);
  738. if ($pointSale['code'] && strlen($pointSale['code'])) {
  739. $pointSale['code'] = '***';
  740. }
  741. if (!strlen($pointSale['credit_functioning'])) {
  742. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  743. }
  744. if ($distribution) {
  745. $pointSale['count_orders'] = (int)Order::searchCount([
  746. 'id_distribution' => $distribution->id,
  747. 'id_point_sale' => $pointSale['id']
  748. ]);
  749. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  750. }
  751. $pointSale['position'] = $position;
  752. $position++;
  753. }
  754. $favoritePointSale = false;
  755. if ($user) {
  756. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  757. }
  758. if ($favoritePointSale) {
  759. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  760. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  761. $theFavoritePointSale = $pointsSaleArray[$i];
  762. unset($pointsSaleArray[$i]);
  763. }
  764. }
  765. if (isset($theFavoritePointSale)) {
  766. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  767. $pointsSaleArray[] = $theFavoritePointSale;
  768. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  769. }
  770. }
  771. return $pointsSaleArray;
  772. }
  773. public function ajaxInfosProductCategories(Producer $producer)
  774. {
  775. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  776. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  777. if ($countProductsWithoutCategory) {
  778. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  779. }
  780. return $categoriesArray;
  781. }
  782. public function ajaxInfosProducts(
  783. Producer $producer,
  784. Distribution $distribution,
  785. PointSale $pointSale = null,
  786. User $user = null,
  787. Order $order = null
  788. )
  789. {
  790. $unitModule = $this->getUnitModule();
  791. $productModule = $this->getProductModule();
  792. $orderModule = $this->getOrderModule();
  793. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  794. $productsArray = Product::find()
  795. ->where([
  796. 'id_producer' => $producer->id,
  797. 'product.status' => 1,
  798. ]);
  799. $productsArray = $productsArray->joinWith([
  800. 'productDistribution' => function ($query) use (
  801. $distribution
  802. ) {
  803. $query->andOnCondition(
  804. 'product_distribution.id_distribution = ' . $distribution->id
  805. );
  806. },
  807. 'productPrice'
  808. ])
  809. ->orderBy('product_distribution.active DESC, order ASC')
  810. ->all();
  811. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  812. $indexProduct = 0;
  813. foreach ($productsArrayFilter as $key => &$product) {
  814. $productObject = $product;
  815. $product = array_merge(
  816. $product->getAttributes(),
  817. [
  818. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  819. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  820. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  821. 'productDistribution' => $product['productDistribution'],
  822. 'productPointSale' => $product['productPointSale'],
  823. ]
  824. );
  825. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  826. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  827. $product['photo'] = '';
  828. }
  829. else {
  830. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  831. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  832. }
  833. $product['quantity_max'] = (isset($product['productDistribution']) && isset($product['productDistribution'][0])) ? $product['productDistribution'][0]['quantity_max'] : null;
  834. $quantityOrder = $orderModule->getProductQuantity($productObject, $ordersArray);
  835. $product['quantity_ordered'] = $quantityOrder;
  836. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  837. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  838. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  839. if ($order) {
  840. $quantityOrderUser = $orderModule->getProductQuantity($productObject, [$order], true);
  841. $product['quantity_ordered'] = $quantityOrder;
  842. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  843. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  844. foreach ($order->productOrder as $productOrder) {
  845. if ($productOrder->id_product == $product['id']) {
  846. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  847. $product['step'] = $productOrder->step;
  848. }
  849. }
  850. } else {
  851. $product['quantity_form'] = 0;
  852. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  853. }
  854. $product['coefficient_unit'] = $coefficient_unit;
  855. if ($product['quantity_remaining'] < 0) {
  856. $product['quantity_remaining'] = 0;
  857. }
  858. $product['index'] = $indexProduct++;
  859. }
  860. return $productsArrayFilter;
  861. }
  862. private function getOrderUser(string $date, PointSale $pointSale = null)
  863. {
  864. $orderModule = $this->getOrderModule();
  865. $orderUser = null;
  866. if (GlobalParam::getCurrentUserId()) {
  867. $conditionOrderUser = [
  868. 'distribution.date' => $date,
  869. 'id_user' => GlobalParam::getCurrentUserId(),
  870. ];
  871. if ($pointSale) {
  872. $conditionOrderUser['id_point_sale'] = $pointSale;
  873. }
  874. $orderUser = Order::searchOne($conditionOrderUser);
  875. if ($orderUser && $orderUser->online_payment_url) {
  876. $orderUser = null;
  877. }
  878. }
  879. if($orderUser) {
  880. $orderModule->initOrder($orderUser);
  881. }
  882. return $orderUser;
  883. }
  884. }