Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

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