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

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