Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

995 lines
39KB

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