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.

OrderController.php 32KB

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