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.

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