Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

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\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. $productOrderModule = $this->getProductOrderModule();
  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' => intval($productOrderModule->getSolver()->getPriceWithTax($productOrder) * 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. $emailSubject = 'Confirmation de commande';
  421. $emailContentParams = [
  422. 'order' => $order,
  423. 'pointSale' => $pointSale,
  424. 'distribution' => $distribution,
  425. 'user' => $user,
  426. 'producer' => $producer
  427. ];
  428. // au client
  429. if ($producerModule->getConfig('option_email_confirm')) {
  430. \Yii::$app->mailerService->sendFromProducer(
  431. $emailSubject,
  432. 'orderConfirm',
  433. $emailContentParams,
  434. $user->email,
  435. $producer
  436. );
  437. }
  438. // au producteur
  439. $contactProducer = $producerModule->getMainContact($producer);
  440. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  441. $contactProducer->email
  442. )) {
  443. \Yii::$app->mailerService->sendFromSite(
  444. $emailSubject,
  445. 'orderConfirmProducer',
  446. $emailContentParams,
  447. $contactProducer->email
  448. );
  449. }
  450. $order = $orderModule->findOneOrderById($order->id);
  451. $orderModule->initOrder($order);
  452. $orderModule->updateOrderTillerSynchronization($order);
  453. }
  454. if (!count($productsArray)) {
  455. $errors[] = "Vous n'avez choisi aucun produit";
  456. }
  457. if ($errorDate) {
  458. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  459. }
  460. if ($errorPointSale) {
  461. $errors[] = "Point de vente invalide.";
  462. }
  463. return $errors;
  464. }
  465. /**
  466. * Annule une commande.
  467. */
  468. public function actionCancel(int $id)
  469. {
  470. $orderModule = $this->getOrderModule();
  471. $order = $this->getOrderModule()->findOneOrderById($id);
  472. if (!$order) {
  473. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  474. }
  475. $orderModule->initOrder($order);
  476. if (!$orderModule->isOrderStateOpen($order)) {
  477. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  478. }
  479. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  480. $orderModule->deleteOrder($order);
  481. $this->setFlash('success', 'Votre commande a bien été annulée.');
  482. }
  483. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  484. }
  485. /**
  486. * Page de confirmation de commande.
  487. */
  488. public function actionConfirm(int $idOrder, string $returnPayment = '')
  489. {
  490. $orderModule = $this->getOrderModule();
  491. $order = $orderModule->findOneOrderById($idOrder);
  492. $producer = $this->getProducerCurrent();
  493. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  494. $this->setFlash('error', 'Commande introuvable');
  495. return $this->redirect(['order/history']);
  496. }
  497. $orderModule->initOrder($order);
  498. return $this->render('confirm', [
  499. 'order' => $order,
  500. 'returnPayment' => $returnPayment
  501. ]);
  502. }
  503. /**
  504. * Vérifie le code saisi pour un point de vente.
  505. */
  506. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  507. {
  508. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  509. $pointSaleModule = $this->getPointSaleModule();
  510. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  511. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  512. return 1;
  513. }
  514. return 0;
  515. }
  516. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
  517. {
  518. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  519. $user = GlobalParam::getCurrentUser();
  520. $producer = $this->getProducerCurrent();
  521. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  522. $order = $this->getOrderUser($date, $pointSale);
  523. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
  524. }
  525. public function buildJsonAjaxInfos(
  526. string $date,
  527. Producer $producer,
  528. PointSale $pointSale = null,
  529. User $user = null,
  530. Order $order = null
  531. )
  532. {
  533. $orderModule = $this->getOrderModule();
  534. $json = [];
  535. $format = 'Y-m-d';
  536. $dateObject = DateTime::createFromFormat($format, $date);
  537. $json['producer'] = $this->ajaxInfosProducer($producer);
  538. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  539. $json['orders'] = $this->ajaxInfosOrders($producer);
  540. $json['user'] = $this->ajaxInfosUser($producer);
  541. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  542. if ($dateObject && $dateObject->format($format) === $date) {
  543. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  544. $json['distribution'] = $distribution;
  545. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  546. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  547. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
  548. if ($order) {
  549. $json['order'] = array_merge($order->getAttributes(), [
  550. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  551. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  552. ]);
  553. }
  554. }
  555. return $json;
  556. }
  557. public function ajaxInfosProducer(Producer $producer)
  558. {
  559. return [
  560. 'order_infos' => $producer->order_infos,
  561. 'credit' => $producer->credit,
  562. 'credit_functioning' => $producer->credit_functioning,
  563. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  564. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  565. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  566. 'option_order_entry_point' => $producer->option_order_entry_point,
  567. 'option_delivery' => $producer->option_delivery,
  568. 'online_payment' => $producer->online_payment,
  569. 'option_online_payment_type' => $producer->online_payment
  570. ];
  571. }
  572. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  573. {
  574. $distributionModule = $this-> getDistributionModule();
  575. $dateMini = date('Y-m-d');
  576. $distributionsArray = Distribution::searchAll([
  577. 'active' => 1,
  578. 'id_producer' => $producer->id
  579. ], [
  580. 'conditions' => ['date > :date'],
  581. 'params' => [':date' => $dateMini],
  582. 'join_with' => ['pointSaleDistribution'],
  583. ]);
  584. $distributionsArray = $distributionModule->filterDistributionsByDateDelay($distributionsArray);
  585. // Filtre par point de vente
  586. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  587. $distributionsArrayFilterPointSale = [];
  588. for ($i = 0; $i < count($distributionsArray); $i++) {
  589. $distribution = $distributionsArray[$i];
  590. if ($distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  591. $countOrders = Order::searchCount([
  592. 'id_distribution' => $distribution->id,
  593. 'id_point_sale' => $pointSaleCurrent->id
  594. ]);
  595. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  596. if (!$pointSaleCurrent->maximum_number_orders
  597. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  598. || ($pointSaleCurrent->maximum_number_orders &&
  599. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  600. $distributionsArrayFilterPointSale[] = $distribution;
  601. }
  602. }
  603. }
  604. return $distributionsArrayFilterPointSale;
  605. } else {
  606. return $distributionsArray;
  607. }
  608. }
  609. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  610. {
  611. $producerModule = $this->getProducerModule();
  612. $orderModule = $this->getOrderModule();
  613. $dateMini = date('Y-m-d');
  614. $ordersUserArray = [];
  615. if (GlobalParam::getCurrentUserId() && !$producerModule->isOnlinePaymentActiveAndTypeOrder($producer)) {
  616. $conditionsOrdersUser = [
  617. 'distribution.date > :date'
  618. ];
  619. $paramsOrdersUser = [
  620. ':date' => $dateMini
  621. ];
  622. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  623. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  624. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  625. }
  626. $ordersUserArray = Order::searchAll([
  627. 'id_user' => GlobalParam::getCurrentUserId()
  628. ], [
  629. 'conditions' => $conditionsOrdersUser,
  630. 'params' => $paramsOrdersUser
  631. ]);
  632. }
  633. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  634. foreach ($ordersUserArray as &$order) {
  635. $orderModule->initOrder($order);
  636. $order = array_merge($order->getAttributes(), [
  637. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  638. 'date_distribution' => $order->distribution->date,
  639. 'pointSale' => $order->pointSale->getAttributes()
  640. ]);
  641. }
  642. }
  643. return $ordersUserArray;
  644. }
  645. public function ajaxInfosUser(Producer $producer)
  646. {
  647. $userProducerModule = $this->getUserProducerModule();
  648. $producerModule = $this->getProducerModule();
  649. $user = GlobalParam::getCurrentUser();
  650. if($user) {
  651. $userProducer = $userProducerModule->findOneUserProducer($user);
  652. if (!$userProducer) {
  653. $userProducer = $producerModule->addUser($user, $producer);
  654. }
  655. }
  656. $jsonUser = false;
  657. if ($user && $userProducer) {
  658. $jsonUser = [
  659. 'address' => $user->address,
  660. 'credit' => $userProducer->credit,
  661. 'credit_active' => $userProducer->credit_active,
  662. ];
  663. }
  664. return $jsonUser;
  665. }
  666. private function ajaxInfosPointsSale($producer, $distribution = false)
  667. {
  668. $pointSaleModule = $this->getPointSaleModule();
  669. $producerModule = $this->getProducerModule();
  670. $orderModule = $this->getOrderModule();
  671. $user = GlobalParam::getCurrentUser();
  672. $pointsSaleArray = PointSale::find();
  673. if ($distribution) {
  674. $pointsSaleArray = $pointsSaleArray->joinWith([
  675. 'pointSaleDistribution' => function ($query) use (
  676. $distribution
  677. ) {
  678. $query->where(
  679. [
  680. 'id_distribution' => $distribution->id,
  681. 'delivery' => 1
  682. ]
  683. );
  684. }
  685. ]);
  686. }
  687. if (GlobalParam::getCurrentUserId()) {
  688. $pointsSaleArray = $pointsSaleArray->with([
  689. 'userPointSale' => function ($query) {
  690. $query->onCondition(
  691. ['id_user' => GlobalParam::getCurrentUserId()]
  692. );
  693. }
  694. ]);
  695. }
  696. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  697. ->andWhere(
  698. '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))'
  699. )
  700. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  701. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  702. ->all();
  703. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  704. $position = 0;
  705. foreach ($pointsSaleArray as &$pointSale) {
  706. $pointSaleObject = $pointSale;
  707. $pointSale = array_merge($pointSale->getAttributes(), [
  708. 'pointSaleDistribution' => [
  709. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  710. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  711. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  712. ],
  713. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  714. ]);
  715. if ($pointSale['code'] && strlen($pointSale['code'])) {
  716. $pointSale['code'] = '***';
  717. }
  718. if (!strlen($pointSale['credit_functioning'])) {
  719. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  720. }
  721. if ($distribution) {
  722. $pointSale['count_orders'] = (int)Order::searchCount([
  723. 'id_distribution' => $distribution->id,
  724. 'id_point_sale' => $pointSale['id']
  725. ]);
  726. $pointSale['infos'] = $pointSaleModule->getStrInfos($pointSaleObject, strtolower(date('l', strtotime($distribution->date))));
  727. }
  728. $pointSale['position'] = $position;
  729. $position++;
  730. }
  731. $favoritePointSale = false;
  732. if ($user) {
  733. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  734. }
  735. if ($favoritePointSale) {
  736. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  737. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  738. $theFavoritePointSale = $pointsSaleArray[$i];
  739. unset($pointsSaleArray[$i]);
  740. }
  741. }
  742. if (isset($theFavoritePointSale)) {
  743. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  744. $pointsSaleArray[] = $theFavoritePointSale;
  745. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  746. }
  747. }
  748. return $pointsSaleArray;
  749. }
  750. public function ajaxInfosProductCategories(Producer $producer)
  751. {
  752. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  753. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  754. if ($countProductsWithoutCategory) {
  755. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  756. }
  757. return $categoriesArray;
  758. }
  759. public function ajaxInfosProducts(
  760. Producer $producer,
  761. Distribution $distribution,
  762. PointSale $pointSale = null,
  763. User $user = null,
  764. Order $order = null
  765. )
  766. {
  767. $unitModule = $this->getUnitModule();
  768. $productModule = $this->getProductModule();
  769. $orderModule = $this->getOrderModule();
  770. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  771. $productsArray = Product::find()
  772. ->where([
  773. 'id_producer' => $producer->id,
  774. 'product.status' => 1,
  775. ]);
  776. $productsArray = $productsArray->joinWith([
  777. 'productDistribution' => function ($query) use (
  778. $distribution
  779. ) {
  780. $query->andOnCondition(
  781. 'product_distribution.id_distribution = ' . $distribution->id
  782. );
  783. },
  784. 'productPrice'
  785. ])
  786. ->orderBy('product_distribution.active DESC, order ASC')
  787. ->all();
  788. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  789. $indexProduct = 0;
  790. foreach ($productsArrayFilter as $key => &$product) {
  791. $productObject = $product;
  792. $product = array_merge(
  793. $product->getAttributes(),
  794. [
  795. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  796. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  797. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  798. 'productDistribution' => $product['productDistribution'],
  799. 'productPointSale' => $product['productPointSale'],
  800. ]
  801. );
  802. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  803. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  804. $product['photo'] = '';
  805. }
  806. else {
  807. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  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. }