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.

1030 lines
45KB

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