No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

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