You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1004 lines
40KB

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