You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

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