Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

751 lines
35KB

  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\ProductDistribution;
  42. use common\models\User;
  43. use common\models\Producer;
  44. use common\models\Order;
  45. use common\models\UserPointSale;
  46. use common\models\Product;
  47. use DateTime;
  48. class OrderController extends ProducerBaseController
  49. {
  50. var $enableCsrfValidation = false;
  51. public function behaviors()
  52. {
  53. return [
  54. 'access' => [
  55. 'class' => AccessControl::className(),
  56. 'rules' => [
  57. [
  58. 'allow' => true,
  59. 'roles' => ['@'],
  60. ]
  61. ],
  62. ],
  63. ];
  64. }
  65. public function actionOrder($id = 0, $date = '')
  66. {
  67. $params = [];
  68. if ($id) {
  69. $order = Order::searchOne([
  70. 'id' => $id
  71. ]);
  72. if ($order) {
  73. if ($order->getState() == Order::STATE_OPEN) {
  74. $params['order'] = $order;
  75. }
  76. }
  77. }
  78. if (strlen($date)) {
  79. $distribution = Distribution::searchOne([
  80. 'date' => $date,
  81. 'id_producer' => GlobalParam::getCurrentProducerId()
  82. ]);
  83. if($distribution) {
  84. $distributionsArray = Distribution::filterDistributionsByDateDelay([$distribution]) ;
  85. if (count($distributionsArray) == 1) {
  86. $params['date'] = $date;
  87. }
  88. }
  89. }
  90. return $this->render('order', $params);
  91. }
  92. /**
  93. * Affiche l'historique des commandes de l'utilisateur
  94. *
  95. * @return ProducerView
  96. */
  97. public function actionHistory($type = 'incoming')
  98. {
  99. $query = Order::find()
  100. ->with('productOrder', 'pointSale', 'creditHistory')
  101. ->joinWith('distribution', 'distribution.producer')
  102. ->where([
  103. 'id_user' => Yii::$app->user->id,
  104. 'distribution.id_producer' => GlobalParam::getCurrentProducerId()
  105. ])
  106. ->params([':date_today' => date('Y-m-d')]);
  107. $queryIncoming = clone $query;
  108. $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
  109. $queryPassed = clone $query;
  110. $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');
  111. $dataProviderOrders = new ActiveDataProvider([
  112. 'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
  113. 'pagination' => [
  114. 'pageSize' => 10,
  115. ],
  116. ]);
  117. return $this->render('history', [
  118. 'dataProviderOrders' => $dataProviderOrders,
  119. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  120. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  121. 'type' => $type,
  122. 'countIncoming' => $queryIncoming->count(),
  123. 'countPassed' => $queryPassed->count(),
  124. ]);
  125. }
  126. /**
  127. * Supprime un producteur.
  128. *
  129. * @param integer $id
  130. */
  131. public function actionRemoveProducer($id = 0)
  132. {
  133. $userProducer = UserProducer::find()
  134. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  135. ->one();
  136. $userProducer->active = 0;
  137. $userProducer->save();
  138. $this->redirect(['order/index']);
  139. }
  140. /**
  141. * Crée une commande.
  142. *
  143. * @return mixed
  144. */
  145. public function actionAjaxProcess()
  146. {
  147. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  148. $order = new Order;
  149. $idProducer = $this->getProducer()->id;
  150. $posts = Yii::$app->request->post();
  151. if ($idProducer) {
  152. $this->_verifyProducerActive($idProducer);
  153. }
  154. if ($order->load($posts)) {
  155. $order = Order::find()
  156. ->where('id_distribution = :id_distribution')
  157. ->andWhere('id_user = :id_user')
  158. ->params([
  159. ':id_distribution' => $posts['Order']['id_distribution'],
  160. ':id_user' => User::getCurrentId()
  161. ])
  162. ->one();
  163. if($order) {
  164. if($order->id_point_sale != $posts['Order']['id_point_sale']) {
  165. $order->id_point_sale = $posts['Order']['id_point_sale'] ;
  166. $order->date_update = date('Y-m-d H:i:s') ;
  167. }
  168. }
  169. else {
  170. $order = new Order;
  171. $order->load(Yii::$app->request->post());
  172. $order->id_user = User::getCurrentId();
  173. $order->status = 'tmp-order';
  174. $order->date = date('Y-m-d H:i:s');
  175. $order->origin = Order::ORIGIN_USER;
  176. }
  177. $errors = $this->processForm($order);
  178. if (count($errors)) {
  179. return ['status' => 'error', 'errors' => $errors];
  180. }
  181. }
  182. return ['status' => 'success', 'idOrder' => $order->id];
  183. }
  184. /**
  185. * Vérifie si un producteur est actif.
  186. *
  187. * @param integer $idProducer
  188. * @throws NotFoundHttpException
  189. */
  190. public function _verifyProducerActive($idProducer)
  191. {
  192. $producer = Producer::findOne($idProducer);
  193. if ($producer && !$producer->active) {
  194. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  195. }
  196. }
  197. /**
  198. * Traite le formulaire de création/modification de commande.
  199. *
  200. * @param Commande $order
  201. */
  202. public function processForm($order)
  203. {
  204. $posts = Yii::$app->request->post();
  205. $productsArray = [];
  206. $totalQuantity = 0;
  207. $producer = $this->getProducer();
  208. $isNewOrder = false ;
  209. if(!$order->id) {
  210. $isNewOrder = true ;
  211. }
  212. foreach ($posts['products'] as $key => $quantity) {
  213. $product = Product::find()->where(['id' => (int)$key])->one();
  214. $totalQuantity += $quantity;
  215. if ($product && $quantity) {
  216. $productsArray[] = $product;
  217. }
  218. }
  219. // date
  220. $errorDate = false;
  221. if (isset($order->id_distribution)) {
  222. // date de commande
  223. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  224. if ($order->getState() != Order::STATE_OPEN) {
  225. $errorDate = true;
  226. }
  227. }
  228. // point de vente
  229. $errorPointSale = false;
  230. if (isset($distribution) && $distribution) {
  231. $pointSaleDistribution = PointSaleDistribution::searchOne([
  232. 'id_distribution' => $distribution->id,
  233. 'id_point_sale' => $posts['Order']['id_point_sale']
  234. ]);
  235. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  236. $errorPointSale = true;
  237. }
  238. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  239. if ($pointSale) {
  240. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  241. $errorPointSale = true;
  242. }
  243. } else {
  244. $errorPointSale = true;
  245. }
  246. $userPointSale = UserPointSale::searchOne([
  247. 'id_user' => User::getCurrentId(),
  248. 'id_point_sale' => $pointSale->id
  249. ]);
  250. if ($pointSale->restricted_access && !$userPointSale) {
  251. $errorPointSale = true;
  252. }
  253. }
  254. $errors = [];
  255. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  256. $userProducer = UserProducer::searchOne([
  257. 'id_producer' => $order->distribution->id_producer,
  258. 'id_user' => User::getCurrentId()
  259. ]);
  260. // gestion point de vente
  261. $pointSale = PointSale::searchOne([
  262. 'id' => $order->id_point_sale
  263. ]);
  264. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  265. $pointSale->getComment() : '';
  266. // la commande est automatiquement réactivée lors d'une modification
  267. $order->date_delete = null;
  268. // sauvegarde de la commande
  269. $order->save();
  270. $order->changeOrderStatus('new-order', 'user');
  271. // ajout de l'utilisateur à l'établissement
  272. Producer::addUser(User::getCurrentId(), $distribution->id_producer);
  273. // suppression de tous les enregistrements ProductOrder
  274. if (!is_null($order)) {
  275. ProductOrder::deleteAll(['id_order' => $order->id]);
  276. $stepsArray = [];
  277. if (isset($order->productOrder)) {
  278. foreach ($order->productOrder as $productOrder) {
  279. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  280. }
  281. }
  282. }
  283. // produits dispos
  284. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  285. // sauvegarde des produits
  286. foreach ($productsArray as $product) {
  287. if (isset($availableProducts[$product->id])) {
  288. $productOrder = new ProductOrder();
  289. $productOrder->id_order = $order->id;
  290. $productOrder->id_product = $product->id;
  291. $productOrder->price = $product->getPrice([
  292. 'user' => User::getCurrent(),
  293. 'user_producer' => $userProducer,
  294. 'point_sale' => $pointSale
  295. ]);
  296. $productOrder->id_tax_rate = $product->taxRate->id;
  297. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  298. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  299. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  300. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  301. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  302. }
  303. $productOrder->quantity = $quantity;
  304. $productOrder->unit = $product->unit;
  305. $productOrder->step = $product->step;
  306. $productOrder->save();
  307. }
  308. }
  309. // lien utilisateur / point de vente
  310. $pointSale->linkUser(User::getCurrentId());
  311. // credit
  312. $credit = Producer::getConfig('credit');
  313. $creditLimit = Producer::getConfig('credit_limit');
  314. $creditFunctioning = $pointSale->getCreditFunctioning();
  315. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  316. $order = Order::searchOne([
  317. 'id' => $order->id
  318. ]);
  319. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  320. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  321. if ($credit && $pointSale->credit &&
  322. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  323. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  324. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  325. )) {
  326. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  327. // à payer
  328. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  329. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  330. $amountRemaining = $creditUser - $creditLimit;
  331. }
  332. if ($amountRemaining > 0) {
  333. $order->saveCreditHistory(
  334. CreditHistory::TYPE_PAYMENT,
  335. $amountRemaining,
  336. $distribution->id_producer,
  337. User::getCurrentId(),
  338. User::getCurrentId()
  339. );
  340. $order->changeOrderStatus('paid-by-credit', 'user');
  341. }else{
  342. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  343. }
  344. }
  345. // surplus à rembourser
  346. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  347. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  348. $order->saveCreditHistory(
  349. CreditHistory::TYPE_REFUND,
  350. $amountSurplus,
  351. $distribution->id_producer,
  352. User::getCurrentId(),
  353. User::getCurrentId()
  354. );
  355. }
  356. }
  357. else{
  358. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  359. }
  360. $user = User::getCurrent() ;
  361. $paramsEmail = [
  362. 'from_email' => $producer->getEmailOpendistrib(),
  363. 'from_name' => $producer->name,
  364. 'to_email' => $user->email,
  365. 'to_name' => $user->getUsername(),
  366. 'subject' => '['.$producer->name.'] Confirmation de commande',
  367. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  368. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  369. 'content_params' => [
  370. 'order' => $order,
  371. 'pointSale' => $pointSale,
  372. 'distribution' => $distribution,
  373. 'user' => $user
  374. ]
  375. ] ;
  376. /*
  377. * Envoi email de confirmation
  378. */
  379. if($isNewOrder) {
  380. // au client
  381. if(Producer::getConfig('option_email_confirm')) {
  382. Mailjet::sendMail($paramsEmail);
  383. }
  384. // au producteur
  385. $contactProducer = $producer->getMainContact() ;
  386. if(Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen($contactProducer->email)) {
  387. $paramsEmail['to_email'] = $contactProducer->email ;
  388. $paramsEmail['to_name'] = $contactProducer->name ;
  389. $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php' ;
  390. $paramsEmail['content_view_html'] = '@common/mail/orderConfirmProducer-html.php' ;
  391. Mailjet::sendMail($paramsEmail);
  392. }
  393. }
  394. $order->setTillerSynchronization() ;
  395. }
  396. if (!count($productsArray)) {
  397. $errors[] = "Vous n'avez choisi aucun produit";
  398. }
  399. if ($errorDate) {
  400. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  401. }
  402. if ($errorPointSale) {
  403. $errors[] = "Point de vente invalide.";
  404. }
  405. return $errors;
  406. }
  407. /**
  408. * Annule une commande.
  409. *
  410. * @param integer $id
  411. * @throws \yii\web\NotFoundHttpException
  412. * @throws UserException
  413. */
  414. public function actionCancel($id)
  415. {
  416. $order = Order::searchOne([
  417. 'id' => $id
  418. ]);
  419. if (!$order) {
  420. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  421. }
  422. if ($order->getState() != Order::STATE_OPEN) {
  423. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  424. }
  425. if ($order && User::getCurrentId() == $order->id_user) {
  426. $order->delete();
  427. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  428. }
  429. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  430. }
  431. /**
  432. * Vérifie le code saisi pour un point de vente.
  433. *
  434. * @param integer $idPointSale
  435. * @param string $code
  436. * @return boolean
  437. */
  438. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  439. {
  440. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  441. $pointSale = PointSale::findOne($idPointSale);
  442. if ($pointSale) {
  443. if ($pointSale->validateCode($code)) {
  444. return 1;
  445. }
  446. }
  447. return 0;
  448. }
  449. public function actionAjaxInfos($date = '', $pointSaleId = 0)
  450. {
  451. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  452. $json = [];
  453. $format = 'Y-m-d';
  454. $dateObject = DateTime::createFromFormat($format, $date);
  455. // PointSale current
  456. $pointSaleCurrent = PointSale::findOne($pointSaleId) ;
  457. // Producteur
  458. $producer = Producer::searchOne([
  459. 'id' => $this->getProducer()->id
  460. ]);
  461. $json['producer'] = [
  462. 'order_infos' => $producer->order_infos,
  463. 'credit' => $producer->credit,
  464. 'credit_functioning' => $producer->credit_functioning,
  465. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  466. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  467. ];
  468. // Distributions
  469. $dateMini = date('Y-m-d') ;
  470. $distributionsArray = Distribution::searchAll([
  471. 'active' => 1
  472. ], [
  473. 'conditions' => ['date > :date'],
  474. 'params' => [':date' => $dateMini],
  475. ]);
  476. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray) ;
  477. $json['distributions'] = $distributionsArray;
  478. // Commandes de l'utilisateur
  479. $ordersUserArray = Order::searchAll([
  480. 'id_user' => User::getCurrentId()
  481. ], [
  482. 'conditions' => [
  483. 'distribution.date > :date'
  484. ],
  485. 'params' => [
  486. ':date' => $dateMini
  487. ]
  488. ]);
  489. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  490. foreach ($ordersUserArray as &$order) {
  491. $order = array_merge($order->getAttributes(), [
  492. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  493. 'date_distribution' => $order->distribution->date,
  494. 'pointSale' => $order->pointSale->getAttributes()
  495. ]);
  496. }
  497. $json['orders'] = $ordersUserArray;
  498. }
  499. // User
  500. $userProducer = UserProducer::searchOne([
  501. 'id_producer' => $producer->id,
  502. 'id_user' => User::getCurrentId()
  503. ]);
  504. $json['user'] = [
  505. 'credit' => $userProducer->credit,
  506. 'credit_active' => $userProducer->credit_active,
  507. ];
  508. if ($dateObject && $dateObject->format($format) === $date) {
  509. // Commande de l'utilisateur
  510. $orderUser = Order::searchOne([
  511. 'distribution.date' => $date,
  512. 'id_user' => User::getCurrentId(),
  513. ]);
  514. if ($orderUser) {
  515. $json['order'] = array_merge($orderUser->getAttributes(), [
  516. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  517. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  518. ]);
  519. }
  520. // distribution
  521. $distribution = Distribution::initDistribution($date);
  522. $json['distribution'] = $distribution;
  523. $pointsSaleArray = PointSale::find()
  524. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  525. $query->where(['id_distribution' => $distribution->id]);
  526. }
  527. ])
  528. ->with(['userPointSale' => function ($query) {
  529. $query->onCondition(['id_user' => User::getCurrentId()]);
  530. }])
  531. ->where(['id_producer' => $distribution->id_producer])
  532. ->andWhere('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)')
  533. ->params([':id_user' => User::getCurrentId()])
  534. ->all();
  535. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  536. foreach ($pointsSaleArray as &$pointSale) {
  537. $pointSale = array_merge($pointSale->getAttributes(), [
  538. 'pointSaleDistribution' => [
  539. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  540. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  541. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  542. ],
  543. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  544. ]);
  545. if ($pointSale['code'] && strlen($pointSale['code'])) {
  546. $pointSale['code'] = '***';
  547. }
  548. if (!strlen($pointSale['credit_functioning'])) {
  549. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  550. }
  551. }
  552. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  553. if ($favoritePointSale) {
  554. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  555. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  556. $theFavoritePointSale = $pointsSaleArray[$i];
  557. unset($pointsSaleArray[$i]);
  558. }
  559. }
  560. if (isset($theFavoritePointSale)) {
  561. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  562. $pointsSaleArray[] = $theFavoritePointSale;
  563. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  564. }
  565. }
  566. $json['points_sale'] = $pointsSaleArray;
  567. // Commandes totales
  568. $ordersArray = Order::searchAll([
  569. 'distribution.date' => $date,
  570. ]);
  571. // Produits
  572. $productsArray = Product::find()
  573. ->where([
  574. 'id_producer' => $this->getProducer()->id,
  575. 'product.active' => 1,
  576. ]);
  577. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  578. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  579. }, 'productPrice'])
  580. ->orderBy('product_distribution.active DESC, order ASC')
  581. ->all();
  582. $indexProduct = 0;
  583. foreach ($productsArray as &$product) {
  584. $product = array_merge(
  585. $product->getAttributes(),
  586. [
  587. 'price_with_tax' => $product->getPriceWithTax([
  588. 'user' => User::getCurrent(),
  589. 'user_producer' => $userProducer,
  590. 'point_sale' => $pointSaleCurrent
  591. ]),
  592. 'productDistribution' => $product['productDistribution']
  593. ]
  594. );
  595. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  596. if (is_null($product['photo'])) {
  597. $product['photo'] = '';
  598. }
  599. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  600. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  601. $product['quantity_ordered'] = $quantityOrder;
  602. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  603. if ($orderUser) {
  604. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  605. $product['quantity_ordered'] = $quantityOrder;
  606. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  607. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  608. foreach ($orderUser->productOrder as $productOrder) {
  609. if ($productOrder->id_product == $product['id']) {
  610. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  611. $product['step'] = $productOrder->step;
  612. }
  613. }
  614. } else {
  615. $product['quantity_form'] = 0;
  616. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  617. }
  618. $product['coefficient_unit'] = $coefficient_unit;
  619. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  620. $product['index'] = $indexProduct++;
  621. }
  622. $json['products'] = $productsArray;
  623. }
  624. return $json;
  625. }
  626. public function actionConfirm($idOrder)
  627. {
  628. $order = Order::searchOne(['id' => $idOrder]);
  629. if (!$order || $order->id_user != User::getCurrentId()) {
  630. throw new \yii\base\UserException('Commande introuvable.');
  631. }
  632. return $this->render('confirm', [
  633. 'order' => $order
  634. ]);
  635. }
  636. }