Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

OrderController.php 31KB

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