Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1007 lines
40KB

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