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.

726 line
33KB

  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. $order = new Order;
  165. $order->load(Yii::$app->request->post());
  166. $order->id_user = User::getCurrentId();
  167. $order->status = 'tmp-order';
  168. $order->date = date('Y-m-d H:i:s');
  169. $order->origin = Order::ORIGIN_USER;
  170. }
  171. $errors = $this->processForm($order);
  172. if (count($errors)) {
  173. return ['status' => 'error', 'errors' => $errors];
  174. }
  175. }
  176. return ['status' => 'success', 'idOrder' => $order->id];
  177. }
  178. /**
  179. * Vérifie si un producteur est actif.
  180. *
  181. * @param integer $idProducer
  182. * @throws NotFoundHttpException
  183. */
  184. public function _verifyProducerActive($idProducer)
  185. {
  186. $producer = Producer::findOne($idProducer);
  187. if ($producer && !$producer->active) {
  188. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  189. }
  190. }
  191. /**
  192. * Traite le formulaire de création/modification de commande.
  193. *
  194. * @param Commande $order
  195. */
  196. public function processForm($order)
  197. {
  198. $posts = Yii::$app->request->post();
  199. $productsArray = [];
  200. $totalQuantity = 0;
  201. $producer = $this->getProducer();
  202. $isNewOrder = false ;
  203. if(!$order->id) {
  204. $isNewOrder = true ;
  205. }
  206. foreach ($posts['products'] as $key => $quantity) {
  207. $product = Product::find()->where(['id' => (int)$key])->one();
  208. $totalQuantity += $quantity;
  209. if ($product && $quantity) {
  210. $productsArray[] = $product;
  211. }
  212. }
  213. // date
  214. $errorDate = false;
  215. if (isset($order->id_distribution)) {
  216. // date de commande
  217. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  218. if ($order->getState() != Order::STATE_OPEN) {
  219. $errorDate = true;
  220. }
  221. }
  222. // point de vente
  223. $errorPointSale = false;
  224. if (isset($distribution) && $distribution) {
  225. $pointSaleDistribution = PointSaleDistribution::searchOne([
  226. 'id_distribution' => $distribution->id,
  227. 'id_point_sale' => $posts['Order']['id_point_sale']
  228. ]);
  229. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  230. $errorPointSale = true;
  231. }
  232. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  233. if ($pointSale) {
  234. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  235. $errorPointSale = true;
  236. }
  237. } else {
  238. $errorPointSale = true;
  239. }
  240. $userPointSale = UserPointSale::searchOne([
  241. 'id_user' => User::getCurrentId(),
  242. 'id_point_sale' => $pointSale->id
  243. ]);
  244. if ($pointSale->restricted_access && !$userPointSale) {
  245. $errorPointSale = true;
  246. }
  247. }
  248. $errors = [];
  249. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  250. $userProducer = UserProducer::searchOne([
  251. 'id_producer' => $order->distribution->id_producer,
  252. 'id_user' => User::getCurrentId()
  253. ]);
  254. // gestion point de vente
  255. $pointSale = PointSale::searchOne([
  256. 'id' => $order->id_point_sale
  257. ]);
  258. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  259. $pointSale->getComment() : '';
  260. // la commande est automatiquement réactivée lors d'une modification
  261. $order->date_delete = null;
  262. // sauvegarde de la commande
  263. $order->save();
  264. $order->changeOrderStatus('new-order', 'user');
  265. // ajout de l'utilisateur à l'établissement
  266. Producer::addUser(User::getCurrentId(), $distribution->id_producer);
  267. // suppression de tous les enregistrements ProductOrder
  268. if (!is_null($order)) {
  269. ProductOrder::deleteAll(['id_order' => $order->id]);
  270. $stepsArray = [];
  271. if (isset($order->productOrder)) {
  272. foreach ($order->productOrder as $productOrder) {
  273. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  274. }
  275. }
  276. }
  277. // produits dispos
  278. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  279. // sauvegarde des produits
  280. foreach ($productsArray as $product) {
  281. if (isset($availableProducts[$product->id])) {
  282. $productOrder = new ProductOrder();
  283. $productOrder->id_order = $order->id;
  284. $productOrder->id_product = $product->id;
  285. $productOrder->price = $product->price;
  286. $productOrder->id_tax_rate = $product->taxRate->id;
  287. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  288. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  289. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  290. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  291. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  292. }
  293. $productOrder->quantity = $quantity;
  294. $productOrder->unit = $product->unit;
  295. $productOrder->step = $product->step;
  296. $productOrder->save();
  297. }
  298. }
  299. // lien utilisateur / point de vente
  300. $pointSale->linkUser(User::getCurrentId());
  301. // credit
  302. $credit = Producer::getConfig('credit');
  303. $creditLimit = Producer::getConfig('credit_limit');
  304. $creditFunctioning = $pointSale->getCreditFunctioning();
  305. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  306. $order = Order::searchOne([
  307. 'id' => $order->id
  308. ]);
  309. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  310. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  311. if ($credit && $pointSale->credit &&
  312. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  313. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  314. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  315. )) {
  316. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  317. // à payer
  318. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  319. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  320. $amountRemaining = $creditUser - $creditLimit;
  321. }
  322. if ($amountRemaining > 0) {
  323. $order->saveCreditHistory(
  324. CreditHistory::TYPE_PAYMENT,
  325. $amountRemaining,
  326. $distribution->id_producer,
  327. User::getCurrentId(),
  328. User::getCurrentId()
  329. );
  330. $order->changeOrderStatus('paid-by-credit', 'user');
  331. }else{
  332. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  333. }
  334. }
  335. // surplus à rembourser
  336. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  337. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  338. $order->saveCreditHistory(
  339. CreditHistory::TYPE_REFUND,
  340. $amountSurplus,
  341. $distribution->id_producer,
  342. User::getCurrentId(),
  343. User::getCurrentId()
  344. );
  345. }
  346. }
  347. else{
  348. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  349. }
  350. // envoi mail de confirmation
  351. if($isNewOrder && Producer::getConfig('option_email_confirm')) {
  352. $user = User::getCurrent() ;
  353. $successMail = Mailjet::sendMail([
  354. 'from_email' => $producer->getEmailOpendistrib(),
  355. 'from_name' => $producer->name,
  356. 'to_email' => $user->email,
  357. 'to_name' => $user->getUsername(),
  358. 'subject' => '['.$producer->name.'] Confirmation de commande',
  359. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  360. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  361. 'content_params' => [
  362. 'order' => $order,
  363. 'pointSale' => $pointSale,
  364. 'distribution' => $distribution,
  365. 'user' => $user
  366. ]
  367. ]);
  368. }
  369. $order->setTillerSynchronization() ;
  370. }
  371. if (!count($productsArray)) {
  372. $errors[] = "Vous n'avez choisi aucun produit";
  373. }
  374. if ($errorDate) {
  375. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  376. }
  377. if ($errorPointSale) {
  378. $errors[] = "Point de vente invalide.";
  379. }
  380. return $errors;
  381. }
  382. /**
  383. * Annule une commande.
  384. *
  385. * @param integer $id
  386. * @throws \yii\web\NotFoundHttpException
  387. * @throws UserException
  388. */
  389. public function actionCancel($id)
  390. {
  391. $order = Order::searchOne([
  392. 'id' => $id
  393. ]);
  394. if (!$order) {
  395. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  396. }
  397. if ($order->getState() != Order::STATE_OPEN) {
  398. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  399. }
  400. if ($order && User::getCurrentId() == $order->id_user) {
  401. $order->delete();
  402. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  403. }
  404. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  405. }
  406. /**
  407. * Vérifie le code saisi pour un point de vente.
  408. *
  409. * @param integer $idPointSale
  410. * @param string $code
  411. * @return boolean
  412. */
  413. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  414. {
  415. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  416. $pointSale = PointSale::findOne($idPointSale);
  417. if ($pointSale) {
  418. if ($pointSale->validateCode($code)) {
  419. return 1;
  420. }
  421. }
  422. return 0;
  423. }
  424. public function actionAjaxInfos($date = '')
  425. {
  426. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  427. $json = [];
  428. $format = 'Y-m-d';
  429. $dateObject = DateTime::createFromFormat($format, $date);
  430. // Producteur
  431. $producer = Producer::searchOne([
  432. 'id' => $this->getProducer()->id
  433. ]);
  434. $json['producer'] = [
  435. 'order_infos' => $producer->order_infos,
  436. 'credit' => $producer->credit,
  437. 'credit_functioning' => $producer->credit_functioning,
  438. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  439. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  440. ];
  441. // Distributions
  442. $dateMini = date('Y-m-d') ;
  443. $distributionsArray = Distribution::searchAll([
  444. 'active' => 1
  445. ], [
  446. 'conditions' => ['date > :date'],
  447. 'params' => [':date' => $dateMini],
  448. ]);
  449. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray) ;
  450. $json['distributions'] = $distributionsArray;
  451. // Commandes de l'utilisateur
  452. $ordersUserArray = Order::searchAll([
  453. 'id_user' => User::getCurrentId()
  454. ], [
  455. 'conditions' => [
  456. 'distribution.date > :date'
  457. ],
  458. 'params' => [
  459. ':date' => $dateMini
  460. ]
  461. ]);
  462. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  463. foreach ($ordersUserArray as &$order) {
  464. $order = array_merge($order->getAttributes(), [
  465. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  466. 'date_distribution' => $order->distribution->date,
  467. 'pointSale' => $order->pointSale->getAttributes()
  468. ]);
  469. }
  470. $json['orders'] = $ordersUserArray;
  471. }
  472. // User
  473. $userProducer = UserProducer::searchOne([
  474. 'id_producer' => $producer->id,
  475. 'id_user' => User::getCurrentId()
  476. ]);
  477. $json['user'] = [
  478. 'credit' => $userProducer->credit,
  479. 'credit_active' => $userProducer->credit_active,
  480. ];
  481. if ($dateObject && $dateObject->format($format) === $date) {
  482. // Commande de l'utilisateur
  483. $orderUser = Order::searchOne([
  484. 'distribution.date' => $date,
  485. 'id_user' => User::getCurrentId(),
  486. ]);
  487. if ($orderUser) {
  488. $json['order'] = array_merge($orderUser->getAttributes(), [
  489. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  490. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  491. ]);
  492. }
  493. // distribution
  494. $distribution = Distribution::initDistribution($date);
  495. $json['distribution'] = $distribution;
  496. $pointsSaleArray = PointSale::find()
  497. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  498. $query->where(['id_distribution' => $distribution->id]);
  499. }
  500. ])
  501. ->with(['userPointSale' => function ($query) {
  502. $query->onCondition(['id_user' => User::getCurrentId()]);
  503. }])
  504. ->where(['id_producer' => $distribution->id_producer])
  505. ->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)')
  506. ->params([':id_user' => User::getCurrentId()])
  507. ->all();
  508. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  509. foreach ($pointsSaleArray as &$pointSale) {
  510. $pointSale = array_merge($pointSale->getAttributes(), [
  511. 'pointSaleDistribution' => [
  512. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  513. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  514. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  515. ],
  516. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  517. ]);
  518. if ($pointSale['code'] && strlen($pointSale['code'])) {
  519. $pointSale['code'] = '***';
  520. }
  521. if (!strlen($pointSale['credit_functioning'])) {
  522. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  523. }
  524. }
  525. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  526. if ($favoritePointSale) {
  527. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  528. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  529. $theFavoritePointSale = $pointsSaleArray[$i];
  530. unset($pointsSaleArray[$i]);
  531. }
  532. }
  533. if (isset($theFavoritePointSale)) {
  534. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  535. $pointsSaleArray[] = $theFavoritePointSale;
  536. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  537. }
  538. }
  539. $json['points_sale'] = $pointsSaleArray;
  540. // Commandes totales
  541. $ordersArray = Order::searchAll([
  542. 'distribution.date' => $date,
  543. ]);
  544. // Produits
  545. /*if (Producer::getConfig('option_allow_user_gift')) {
  546. $productsArray = Product::find()
  547. ->orWhere(['id_producer' => $this->getProducer()->id,])
  548. //->orWhere(['id_producer' => 0,]) // produit "Don";
  549. ;
  550. } else {
  551. $productsArray = Product::find()
  552. ->where(['id_producer' => $this->getProducer()->id,]);
  553. }*/
  554. $productsArray = Product::find()
  555. ->where([
  556. 'id_producer' => $this->getProducer()->id,
  557. 'product.active' => 1,
  558. ]);
  559. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  560. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  561. }])
  562. ->orderBy('product_distribution.active DESC, order ASC')
  563. ->all();
  564. $indexProduct = 0;
  565. foreach ($productsArray as &$product) {
  566. $product = array_merge(
  567. $product->getAttributes(),
  568. [
  569. 'price_with_tax' => $product->getPriceWithTax(),
  570. 'productDistribution' => $product['productDistribution']
  571. ]
  572. );
  573. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  574. if (is_null($product['photo'])) {
  575. $product['photo'] = '';
  576. }
  577. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  578. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  579. $product['quantity_ordered'] = $quantityOrder;
  580. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  581. if ($orderUser) {
  582. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  583. $product['quantity_ordered'] = $quantityOrder;
  584. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  585. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  586. foreach ($orderUser->productOrder as $productOrder) {
  587. if ($productOrder->id_product == $product['id']) {
  588. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  589. $product['step'] = $productOrder->step;
  590. }
  591. }
  592. } else {
  593. $product['quantity_form'] = 0;
  594. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  595. }
  596. $product['coefficient_unit'] = $coefficient_unit;
  597. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  598. $product['index'] = $indexProduct++;
  599. }
  600. $json['products'] = $productsArray;
  601. }
  602. return $json;
  603. }
  604. public function actionConfirm($idOrder)
  605. {
  606. $order = Order::searchOne(['id' => $idOrder]);
  607. if (!$order || $order->id_user != User::getCurrentId()) {
  608. throw new \yii\base\UserException('Commande introuvable.');
  609. }
  610. return $this->render('confirm', [
  611. 'order' => $order
  612. ]);
  613. }
  614. }