您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1036 行
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\OrderStatus\OrderStatus;
  45. use domain\Order\ProductOrder\ProductOrder;
  46. use domain\PointSale\PointSale\PointSale;
  47. use domain\Producer\Producer\Producer;
  48. use domain\Product\Product\Product;
  49. use DateTime;
  50. use domain\User\User\User;
  51. use yii\base\UserException;
  52. use yii\data\ActiveDataProvider;
  53. use yii\filters\AccessControl;
  54. use yii\web\NotFoundHttpException;
  55. class OrderController extends ProducerBaseController
  56. {
  57. var $enableCsrfValidation = false;
  58. public function behaviors()
  59. {
  60. return [
  61. 'access' => [
  62. 'class' => AccessControl::class,
  63. 'only' => [
  64. 'history',
  65. 'remove-producer',
  66. 'cancel'
  67. ],
  68. 'rules' => [
  69. [
  70. 'allow' => true,
  71. 'roles' => ['@']
  72. ]
  73. ],
  74. ],
  75. ];
  76. }
  77. public function actionOrder(int $id = 0, $date = '')
  78. {
  79. $orderModule = $this->getOrderModule();
  80. $distributionModule = $this-> getDistributionModule();
  81. $params = [];
  82. $producer = $this->getProducerCurrent();
  83. if (\Yii::$app->user->isGuest && !$producer->option_allow_order_guest) {
  84. return $this->redirect(
  85. $this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id])
  86. );
  87. }
  88. $order = $orderModule->findOneOrderById($id);
  89. if ($order && $orderModule->isOrderStateOpen($order)) {
  90. $params['order'] = $order;
  91. }
  92. if ($distributionModule->isDistributionDateAvailable($date)) {
  93. $params['date'] = $date;
  94. }
  95. return $this->render('order', $params);
  96. }
  97. /**
  98. * Affiche l'historique des commandes de l'utilisateur.
  99. */
  100. public function actionHistory($type = 'incoming')
  101. {
  102. $queryHistoryArray = $this->getOrderModule()
  103. ->queryOrdersHistory($this->getProducerCurrent(), $this->getUserCurrent());
  104. $queryHistoryIncoming = $queryHistoryArray['incoming'];
  105. $queryHistoryPassed = $queryHistoryArray['passed'];
  106. $dataProviderOrders = new ActiveDataProvider([
  107. 'query' => ($type == 'incoming') ? $queryHistoryIncoming->query() : $queryHistoryPassed->query(),
  108. 'pagination' => [
  109. 'pageSize' => 10,
  110. ],
  111. ]);
  112. return $this->render('history', [
  113. 'dataProviderOrders' => $dataProviderOrders,
  114. 'orderOk' => \Yii::$app->getRequest()->get('orderOk', false),
  115. 'cancelOk' => \Yii::$app->getRequest()->get('cancelOk', false),
  116. 'type' => $type,
  117. 'countIncoming' => $queryHistoryIncoming->count(),
  118. 'countPassed' => $queryHistoryPassed->count(),
  119. ]);
  120. }
  121. public function actionRemoveProducer(int $id = 0)
  122. {
  123. $producer = $this->getProducerModule()->findOneProducerById($id);
  124. $this->getUserProducerModule()->updateActive(
  125. $this->getUserCurrent(),
  126. $producer,
  127. false
  128. );
  129. return $this->redirect(['order/index']);
  130. }
  131. /**
  132. * Crée une commande.
  133. */
  134. public function actionAjaxProcess()
  135. {
  136. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  137. $posts = \Yii::$app->request->post();
  138. $orderModule = $this->getOrderModule();
  139. $producerModule = $this->getProducerModule();
  140. $userModule = $this->getUserModule();
  141. $productOrderModule = $this->getProductOrderModule();
  142. $producer = $this->getProducerCurrent();
  143. $redirect = null;
  144. $idProducer = $producer->id;
  145. $order = new Order;
  146. if ($idProducer) {
  147. $this->_verifyProducerActive($idProducer);
  148. }
  149. if ($order->load($posts)) {
  150. $user = $this->getUserCurrent();
  151. $order = Order::find()
  152. ->where('id_distribution = :id_distribution')
  153. ->andWhere('id_user = :id_user')
  154. ->andWhere('id_point_sale = :id_point_sale')
  155. ->params([
  156. ':id_distribution' => $posts['Order']['id_distribution'],
  157. ':id_point_sale' => $posts['Order']['id_point_sale'],
  158. ':id_user' => $user ? $user->id : null
  159. ])
  160. ->one();
  161. if ($order && !$order->online_payment_url) {
  162. if ($order->id_point_sale != $posts['Order']['id_point_sale']) {
  163. $order->id_point_sale = $posts['Order']['id_point_sale'];
  164. $order->date_update = date('Y-m-d H:i:s');
  165. }
  166. } else {
  167. // gestion user : option_allow_order_guest
  168. if (isset($posts['user']) && $posts['user']) {
  169. $userIndividualExist = User::searchOne([
  170. 'email' => $posts['user']['email'],
  171. 'type' => User::TYPE_INDIVIDUAL
  172. ]);
  173. if ($userIndividualExist) {
  174. $errorUserGuest = 'Cette adresse email est déjà utilisée, veuillez vous <a href="' . \Yii::$app->urlManagerFrontend->createUrl(
  175. ['site/producer', 'id' => $idProducer]
  176. ) . '">connecter à votre compte</a> ou en utiliser une autre.';
  177. return ['status' => 'error', 'errors' => [$errorUserGuest]];
  178. }
  179. $user = User::searchOne([
  180. 'email' => $posts['user']['email'],
  181. 'type' => User::TYPE_GUEST
  182. ]);
  183. if (!$user) {
  184. $user = new User;
  185. $user->id_producer = 0;
  186. $user->type = User::TYPE_GUEST;
  187. $userModule->setPassword($user, Password::generate());
  188. $userModule->generateAuthKey($user);
  189. $user->username = $posts['user']['email'];
  190. $user->email = $posts['user']['email'];
  191. $user->name = $posts['user']['firstname'];
  192. $user->lastname = $posts['user']['lastname'];
  193. $user->phone = $posts['user']['phone'];
  194. $user->save();
  195. // liaison producer / user
  196. $producerModule->addUser($user, $producer);
  197. } else {
  198. $producerModule->addUser($user, $producer);
  199. }
  200. }
  201. $order = new Order;
  202. $order->load(\Yii::$app->request->post());
  203. $order->id_user = $user ? $user->id : null;
  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. // une commande annulée est automatiquement réactivée lors d'une modification
  344. if($orderModule->getSolver()->isOrderStatusCanceled($order)) {
  345. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $this->getUserCurrent());
  346. }
  347. $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
  348. $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
  349. // on sauvegarde l'adresse de livraison dans le profil de l'utilisateur pour qu'il n'ait plus à la ressaisir
  350. if($order->delivery_address && !$user->address) {
  351. $user->address = $order->delivery_address;
  352. $user->save();
  353. }
  354. $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
  355. if(!$isNewOrder) {
  356. $order->date_update = date('Y-m-d H:i:s');
  357. }
  358. $order->save();
  359. $orderModule->generateOrderReference($order);
  360. $orderModule->getManager()->changeOrderStatus($order, OrderStatus::ALIAS_ORDERED, $user);
  361. $producerModule->addUser($user, $producer);
  362. // suppression de tous les enregistrements ProductOrder
  363. if (!is_null($order)) {
  364. $productOrderModule->deleteProductOrdersByOrder($order);
  365. if (isset($order->productOrder)) {
  366. foreach ($order->productOrder as $productOrder) {
  367. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  368. }
  369. }
  370. }
  371. $availableProducts = $orderModule->findProductDistributionsByDistribution($distribution);
  372. foreach ($productsArray as $product) {
  373. if (isset($availableProducts[$product->id])) {
  374. $productOrder = new ProductOrder();
  375. $productOrder->id_order = $order->id;
  376. $productOrder->id_product = $product->id;
  377. $productOrder->id_tax_rate = $product->taxRate->id;
  378. $unit = (!is_null(
  379. $order
  380. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  381. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  382. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  383. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  384. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  385. }
  386. $productOrder->quantity = $quantity;
  387. $productOrder->price = $productModule->getPrice($product, [
  388. 'user' => $this->getUserCurrent(),
  389. 'user_producer' => $userProducer,
  390. 'point_sale' => $pointSale,
  391. 'quantity' => $quantity
  392. ]);
  393. $productOrder->unit = $product->unit;
  394. $productOrder->step = $product->step;
  395. if($quantity) {
  396. $productOrder->save();
  397. }
  398. }
  399. }
  400. // lien utilisateur / point de vente
  401. $pointSaleModule->addUser($user, $pointSale);
  402. // credit
  403. $credit = $producerModule->getConfig('credit');
  404. $creditFunctioning = $producerModule->getPointSaleCreditFunctioning($pointSale);
  405. $order = $orderModule->findOneOrderById($order->id);
  406. $orderModule->initOrder($order);
  407. if ($credit
  408. && $this->getUserCurrent()
  409. && $pointSale->payment_method_credit
  410. && $posts['payment_method'] == 'credit'
  411. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  412. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  413. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  414. )) {
  415. // à payer
  416. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  417. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  418. } // surplus à rembourser
  419. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  420. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  421. }
  422. }
  423. /*
  424. * Envoi email de confirmation
  425. */
  426. $emailSubject = 'Confirmation de commande';
  427. $emailContentParams = [
  428. 'order' => $order,
  429. 'pointSale' => $pointSale,
  430. 'distribution' => $distribution,
  431. 'user' => $user,
  432. 'producer' => $producer
  433. ];
  434. // au client
  435. if ($producerModule->getConfig('option_email_confirm')) {
  436. \Yii::$app->mailerService->sendFromProducer(
  437. $emailSubject,
  438. 'orderConfirm',
  439. $emailContentParams,
  440. $user->email,
  441. $producer
  442. );
  443. }
  444. // au producteur
  445. $contactProducer = $producerModule->getMainContact($producer);
  446. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  447. $contactProducer->email
  448. )) {
  449. \Yii::$app->mailerService->sendFromSite(
  450. $emailSubject,
  451. 'orderConfirmProducer',
  452. $emailContentParams,
  453. $contactProducer->email
  454. );
  455. }
  456. $order = $orderModule->findOneOrderById($order->id);
  457. $orderModule->initOrder($order);
  458. $orderModule->updateOrderTillerSynchronization($order);
  459. }
  460. if (!count($productsArray)) {
  461. $errors[] = "Vous n'avez choisi aucun produit";
  462. }
  463. if ($errorDate) {
  464. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  465. }
  466. if ($errorPointSale) {
  467. $errors[] = "Point de vente invalide.";
  468. }
  469. return $errors;
  470. }
  471. /**
  472. * Annule une commande.
  473. */
  474. public function actionCancel(int $id)
  475. {
  476. $orderModule = $this->getOrderModule();
  477. $order = $this->getOrderModule()->findOneOrderById($id);
  478. if (!$order) {
  479. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  480. }
  481. $orderModule->getBuilder()->initOrder($order);
  482. if (!$orderModule->isOrderStateOpen($order)) {
  483. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  484. }
  485. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  486. $orderModule->getManager()->deleteOrder($order, $this->getUserCurrent());
  487. $this->setFlash('success', 'Votre commande a bien été annulée.');
  488. }
  489. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  490. }
  491. /**
  492. * Page de confirmation de commande.
  493. */
  494. public function actionConfirm(int $idOrder, string $returnPayment = '')
  495. {
  496. $orderModule = $this->getOrderModule();
  497. $order = $orderModule->findOneOrderById($idOrder);
  498. $producer = $this->getProducerCurrent();
  499. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  500. $this->setFlash('error', 'Commande introuvable');
  501. return $this->redirect(['order/history']);
  502. }
  503. $orderModule->initOrder($order);
  504. return $this->render('confirm', [
  505. 'order' => $order,
  506. 'returnPayment' => $returnPayment
  507. ]);
  508. }
  509. /**
  510. * Vérifie le code saisi pour un point de vente.
  511. */
  512. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  513. {
  514. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  515. $pointSaleModule = $this->getPointSaleModule();
  516. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  517. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  518. return 1;
  519. }
  520. return 0;
  521. }
  522. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
  523. {
  524. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  525. $user = GlobalParam::getCurrentUser();
  526. $producer = $this->getProducerCurrent();
  527. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  528. $order = $this->getOrderUser($date, $pointSale);
  529. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
  530. }
  531. public function buildJsonAjaxInfos(
  532. string $date,
  533. Producer $producer,
  534. PointSale $pointSale = null,
  535. User $user = null,
  536. Order $order = null
  537. )
  538. {
  539. $orderModule = $this->getOrderModule();
  540. $json = [];
  541. $format = 'Y-m-d';
  542. $dateObject = DateTime::createFromFormat($format, $date);
  543. $json['producer'] = $this->ajaxInfosProducer($producer);
  544. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  545. $json['orders'] = $this->ajaxInfosOrders($producer);
  546. $json['user'] = $this->ajaxInfosUser($producer);
  547. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  548. $json['leave_period'] = $this->ajaxInfosLeavePeriod($producer);
  549. if ($dateObject && $dateObject->format($format) === $date) {
  550. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  551. $json['distribution'] = $distribution;
  552. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  553. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  554. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
  555. if ($order) {
  556. $json['order'] = array_merge($order->getAttributes(), [
  557. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  558. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  559. ]);
  560. }
  561. }
  562. return $json;
  563. }
  564. public function ajaxInfosLeavePeriod(Producer $producer)
  565. {
  566. if($this->getProducerModule()->getSolver()->hasLeavePeriodDefined($producer)) {
  567. return [
  568. 'start' => $producer->option_leave_period_start,
  569. 'end' => $producer->option_leave_period_end,
  570. ];
  571. }
  572. return false;
  573. }
  574. public function ajaxInfosProducer(Producer $producer)
  575. {
  576. return [
  577. 'order_infos' => nl2br($producer->order_infos),
  578. 'payment_infos' => nl2br($producer->option_payment_info),
  579. 'credit' => $producer->credit,
  580. 'credit_functioning' => $producer->credit_functioning,
  581. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  582. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  583. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  584. 'option_order_entry_point' => $producer->option_order_entry_point,
  585. 'option_delivery' => $producer->option_delivery,
  586. 'online_payment' => $producer->online_payment,
  587. 'option_online_payment_type' => $producer->online_payment,
  588. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  589. ];
  590. }
  591. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  592. {
  593. $distributionModule = $this-> getDistributionModule();
  594. $dateMini = date('Y-m-d');
  595. $distributionsArray = Distribution::searchAll([
  596. 'active' => 1,
  597. 'id_producer' => $producer->id
  598. ], [
  599. 'conditions' => ['date > :date'],
  600. 'params' => [':date' => $dateMini],
  601. 'join_with' => ['pointSaleDistribution'],
  602. ]);
  603. $distributionsArray = $distributionModule->getSolver()->filterDistributionsByDateDelay($distributionsArray);
  604. // Filtre par période de congé
  605. foreach ($distributionsArray as $keyDistribution => $distribution) {
  606. if($this->getProducerModule()->getSolver()->isOnLeavePeriod($this->getProducerCurrent(), new DateTime($distribution->date))) {
  607. unset($distributionsArray[$keyDistribution]);
  608. }
  609. }
  610. // Filtre par point de vente
  611. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  612. $distributionsArrayFilterPointSale = [];
  613. for ($i = 0; $i < count($distributionsArray); $i++) {
  614. $distribution = $distributionsArray[$i];
  615. if ($distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  616. $countOrders = Order::searchCount([
  617. 'id_distribution' => $distribution->id,
  618. 'id_point_sale' => $pointSaleCurrent->id
  619. ]);
  620. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  621. if (!$pointSaleCurrent->maximum_number_orders
  622. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  623. || ($pointSaleCurrent->maximum_number_orders &&
  624. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  625. $distributionsArrayFilterPointSale[] = $distribution;
  626. }
  627. }
  628. }
  629. return $distributionsArrayFilterPointSale;
  630. } else {
  631. return $distributionsArray;
  632. }
  633. }
  634. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  635. {
  636. $producerModule = $this->getProducerModule();
  637. $orderModule = $this->getOrderModule();
  638. $dateMini = date('Y-m-d');
  639. $ordersUserArray = [];
  640. if (GlobalParam::getCurrentUserId()) {
  641. $conditionsOrdersUser = [
  642. 'distribution.date > :date',
  643. 'order.online_payment_url IS NULL'
  644. ];
  645. $paramsOrdersUser = [
  646. ':date' => $dateMini
  647. ];
  648. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  649. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  650. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  651. }
  652. $ordersUserArray = Order::searchAll([
  653. 'id_user' => GlobalParam::getCurrentUserId()
  654. ], [
  655. 'conditions' => $conditionsOrdersUser,
  656. 'params' => $paramsOrdersUser
  657. ]);
  658. }
  659. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  660. foreach ($ordersUserArray as &$order) {
  661. $orderModule->initOrder($order);
  662. $order = array_merge($order->getAttributes(), [
  663. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  664. 'date_distribution' => $order->distribution->date,
  665. 'pointSale' => $order->pointSale->getAttributes()
  666. ]);
  667. }
  668. }
  669. return $ordersUserArray;
  670. }
  671. public function ajaxInfosUser(Producer $producer)
  672. {
  673. $userProducerModule = $this->getUserProducerModule();
  674. $producerModule = $this->getProducerModule();
  675. $user = GlobalParam::getCurrentUser();
  676. if($user) {
  677. $userProducer = $userProducerModule->findOneUserProducer($user);
  678. if (!$userProducer) {
  679. $userProducer = $producerModule->addUser($user, $producer);
  680. }
  681. }
  682. $jsonUser = false;
  683. if ($user && $userProducer) {
  684. $jsonUser = [
  685. 'address' => $user->address,
  686. 'credit' => $userProducer->credit,
  687. 'credit_active' => $userProducer->credit_active,
  688. ];
  689. }
  690. return $jsonUser;
  691. }
  692. private function ajaxInfosPointsSale($producer, $distribution = false)
  693. {
  694. $pointSaleModule = $this->getPointSaleModule();
  695. $producerModule = $this->getProducerModule();
  696. $orderModule = $this->getOrderModule();
  697. $user = GlobalParam::getCurrentUser();
  698. $pointsSaleArray = PointSale::find();
  699. if ($distribution) {
  700. $pointsSaleArray = $pointsSaleArray->joinWith([
  701. 'pointSaleDistribution' => function ($query) use (
  702. $distribution
  703. ) {
  704. $query->where(
  705. [
  706. 'id_distribution' => $distribution->id,
  707. 'delivery' => 1
  708. ]
  709. );
  710. }
  711. ]);
  712. }
  713. if (GlobalParam::getCurrentUserId()) {
  714. $pointsSaleArray = $pointsSaleArray->with([
  715. 'userPointSale' => function ($query) {
  716. $query->onCondition(
  717. ['id_user' => GlobalParam::getCurrentUserId()]
  718. );
  719. }
  720. ]);
  721. }
  722. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  723. ->andWhere(
  724. '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))'
  725. )
  726. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  727. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  728. ->all();
  729. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  730. $position = 0;
  731. foreach ($pointsSaleArray as &$pointSale) {
  732. $pointSaleObject = $pointSale;
  733. $pointSale = array_merge($pointSale->getAttributes(), [
  734. 'pointSaleDistribution' => [
  735. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  736. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  737. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  738. ],
  739. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  740. ]);
  741. if ($pointSale['code'] && strlen($pointSale['code'])) {
  742. $pointSale['code'] = '***';
  743. }
  744. if (!strlen($pointSale['credit_functioning'])) {
  745. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  746. }
  747. if ($distribution) {
  748. $pointSale['count_orders'] = (int)Order::searchCount([
  749. 'id_distribution' => $distribution->id,
  750. 'id_point_sale' => $pointSale['id']
  751. ]);
  752. $pointSale['infos'] = $pointSaleModule->getSolver()->getStrInfosByDistribution($pointSaleObject, $distribution);
  753. }
  754. $pointSale['position'] = $position;
  755. $position++;
  756. }
  757. $favoritePointSale = false;
  758. if ($user) {
  759. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  760. }
  761. if ($favoritePointSale) {
  762. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  763. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  764. $theFavoritePointSale = $pointsSaleArray[$i];
  765. unset($pointsSaleArray[$i]);
  766. }
  767. }
  768. if (isset($theFavoritePointSale)) {
  769. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  770. $pointsSaleArray[] = $theFavoritePointSale;
  771. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  772. }
  773. }
  774. return $pointsSaleArray;
  775. }
  776. public function ajaxInfosProductCategories(Producer $producer)
  777. {
  778. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  779. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  780. if ($countProductsWithoutCategory) {
  781. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  782. }
  783. return $categoriesArray;
  784. }
  785. public function ajaxInfosProducts(
  786. Producer $producer,
  787. Distribution $distribution,
  788. PointSale $pointSale = null,
  789. User $user = null,
  790. Order $order = null
  791. )
  792. {
  793. $unitModule = $this->getUnitModule();
  794. $productModule = $this->getProductModule();
  795. $orderModule = $this->getOrderModule();
  796. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  797. $productsArray = Product::find()
  798. ->where([
  799. 'id_producer' => $producer->id,
  800. 'product.status' => 1,
  801. ]);
  802. $productsArray = $productsArray->joinWith([
  803. 'productDistribution' => function ($query) use (
  804. $distribution
  805. ) {
  806. $query->andOnCondition(
  807. 'product_distribution.id_distribution = ' . $distribution->id
  808. );
  809. },
  810. 'productPrice'
  811. ])
  812. ->orderBy('product_distribution.active DESC, order ASC')
  813. ->all();
  814. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  815. $indexProduct = 0;
  816. foreach ($productsArrayFilter as $key => &$product) {
  817. $productObject = $product;
  818. $product = array_merge(
  819. $product->getAttributes(),
  820. [
  821. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  822. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  823. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  824. 'productDistribution' => $product['productDistribution'],
  825. 'productPointSale' => $product['productPointSale'],
  826. ]
  827. );
  828. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  829. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  830. $product['photo'] = '';
  831. }
  832. else {
  833. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  834. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  835. }
  836. $product['quantity_max'] = (isset($product['productDistribution']) && isset($product['productDistribution'][0])) ? $product['productDistribution'][0]['quantity_max'] : null;
  837. $quantityOrder = $orderModule->getProductQuantity($productObject, $ordersArray);
  838. $product['quantity_ordered'] = $quantityOrder;
  839. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  840. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  841. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  842. if ($order) {
  843. $quantityOrderUser = $orderModule->getProductQuantity($productObject, [$order], true);
  844. $product['quantity_ordered'] = $quantityOrder;
  845. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  846. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  847. foreach ($order->productOrder as $productOrder) {
  848. if ($productOrder->id_product == $product['id']) {
  849. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  850. $product['step'] = $productOrder->step;
  851. }
  852. }
  853. } else {
  854. $product['quantity_form'] = 0;
  855. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  856. }
  857. $product['coefficient_unit'] = $coefficient_unit;
  858. if ($product['quantity_remaining'] < 0) {
  859. $product['quantity_remaining'] = 0;
  860. }
  861. $product['index'] = $indexProduct++;
  862. }
  863. return $productsArrayFilter;
  864. }
  865. private function getOrderUser(string $date, PointSale $pointSale = null)
  866. {
  867. $orderModule = $this->getOrderModule();
  868. $orderUser = null;
  869. if (GlobalParam::getCurrentUserId()) {
  870. $conditionOrderUser = [
  871. 'distribution.date' => $date,
  872. 'id_user' => GlobalParam::getCurrentUserId(),
  873. ];
  874. if ($pointSale) {
  875. $conditionOrderUser['id_point_sale'] = $pointSale;
  876. }
  877. $orderUser = Order::searchOne($conditionOrderUser);
  878. if ($orderUser && $orderUser->online_payment_url) {
  879. $orderUser = null;
  880. }
  881. }
  882. if($orderUser) {
  883. $orderModule->initOrder($orderUser);
  884. }
  885. return $orderUser;
  886. }
  887. }