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.

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