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.

757 line
26KB

  1. <?php
  2. /**
  3. Copyright La boîte à pain (2018)
  4. contact@laboiteapain.net
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace producer\controllers;
  32. use common\models\ProductDistribution ;
  33. use common\models\User ;
  34. use common\models\Producer ;
  35. use common\models\Order ;
  36. use DateTime;
  37. class OrderController extends ProducerBaseController
  38. {
  39. var $enableCsrfValidation = false;
  40. public function behaviors()
  41. {
  42. return [
  43. 'access' => [
  44. 'class' => AccessControl::className(),
  45. 'rules' => [
  46. [
  47. 'allow' => true,
  48. 'roles' => ['@'],
  49. ]
  50. ],
  51. ],
  52. ];
  53. }
  54. public function actionOrder()
  55. {
  56. return $this->render('order') ;
  57. }
  58. /**
  59. * Retourne au format JSON toutes les informations relatives à une
  60. * production donnée.
  61. *
  62. * @param integer $idDistribution
  63. * @return mixed
  64. */
  65. public function actionInfosDistribution($idDistribution)
  66. {
  67. $distribution = Distribution::searchOne([
  68. 'id' => $idDistribution
  69. ]);
  70. if ($distribution) {
  71. $arr = [];
  72. $productsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  73. $data['products'] = $productsArray;
  74. $pointSaleArray = PointSale::find()
  75. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  76. $q->where(['id_distribution' => $distribution->id]);
  77. }])
  78. ->where([
  79. 'id_producer' => $distribution->id_producer,
  80. ])
  81. ->all();
  82. $data['points_sale'] = [];
  83. foreach ($pointSaleArray as $pointSale) {
  84. if (isset($pointSale->pointSaleDistribution) &&
  85. isset($pointSale->pointSaleDistribution[0])) {
  86. $data['points_sale'][$pointSale->id] = $pointSale->pointSaleDistribution[0]->delivery;
  87. } else {
  88. $data['points_sale'][$pointSale->id] = false;
  89. }
  90. }
  91. return json_encode($data);
  92. }
  93. return json_encode([]);
  94. }
  95. /**
  96. * Initialise le formulaire de création/modification de commande.
  97. *
  98. * @param Order $order
  99. * @return array
  100. */
  101. public function initForm($order = null) {
  102. // Producteurs
  103. $producersArray = Yii::$app->user->identity->getBookmarkedProducers();
  104. $idProducer = $this->getProducer()->id;
  105. // Producteur
  106. $producer = Producer::findOne($idProducer);
  107. // Points de vente
  108. $pointsSaleArray = PointSale::find()
  109. ->with('userPointSale')
  110. ->where(['id_producer' => $idProducer])
  111. ->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)')
  112. ->params([':id_user' => User::getCurrentId()])
  113. ->all();
  114. // jours de production
  115. $deadline = 20;
  116. $date = date('Y-m-d');
  117. if (isset($producer)) {
  118. if($producer->order_deadline) {
  119. $deadline = $producer->order_deadline;
  120. }
  121. if (date('H') >= $deadline) {
  122. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay) * (24 * 60 * 60));
  123. } else {
  124. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay - 1) * (24 * 60 * 60));
  125. }
  126. }
  127. $distributionDays = Distribution::find()
  128. ->where(['active' => 1])
  129. ->andWhere('date > :date')
  130. ->andWhere(['id_producer' => $idProducer])
  131. ->addParams([':date' => $date])
  132. ->all();
  133. $distributionDaysArray = array('' => '--');
  134. foreach ($distributionDays as $distribution) {
  135. $distributionDaysArray[$distribution->id] = date('d/m/Y', strtotime($distribution->date));
  136. }
  137. // produits
  138. $products = Product::find()
  139. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  140. ->where(['product.active' => 1, 'id_producer' => $idProducer])
  141. ->orderBy('product.order ASC')->all();
  142. $productsArray = [] ;
  143. foreach ($products as $p)
  144. $productsArray[] = $p;
  145. // produits selec
  146. $posts = Yii::$app->request->post();
  147. $selectedProducts = [];
  148. if (isset($posts['Product'])) {
  149. foreach ($posts['Product'] as $key => $quantity) {
  150. $key = (int) str_replace('product_', '', $key);
  151. $product = Product::find()->where(['id' => $key])->one();
  152. if ($product && $quantity)
  153. $selectedProducts[$product->id] = (int) $quantity;
  154. }
  155. }
  156. elseif (!is_null($order)) {
  157. $productOrderArray = ProductOrder::searchAll([
  158. 'id_order' => $order->id
  159. ]) ;
  160. foreach ($productOrderArray as $productOrder) {
  161. $selectedProducts[$productOrder->id_product] = (int) $productOrder->quantity;
  162. }
  163. }
  164. $availableProducts = [] ;
  165. $distribution = null;
  166. if (!is_null($order) && $order->id_distribution) {
  167. $availableProducts = ProductDistribution::searchByDistribution($order->id_distribution);
  168. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  169. }
  170. $orders = Order::searchAll([
  171. 'id_user' => User::getCurrentId()
  172. ]) ;
  173. if ($idProducer) {
  174. $userProducer = UserProducer::searchOne([
  175. 'id_producer' => $idProducer,
  176. 'id_user' => User::getCurrentId()
  177. ]) ;
  178. $credit = $userProducer->credit;
  179. } else {
  180. $credit = 0;
  181. }
  182. return [
  183. 'pointsSaleArray' => $pointsSaleArray,
  184. 'distributionDaysArray' => $distributionDaysArray,
  185. 'productsArray' => $productsArray,
  186. 'selectedProducts' => $selectedProducts,
  187. 'availableProducts' => $availableProducts,
  188. 'distribution' => $distribution,
  189. 'ordersArray' => $orders,
  190. 'producersArray' => $producersArray,
  191. 'idProducer' => $idProducer,
  192. 'producer' => $producer,
  193. 'credit' => $credit
  194. ];
  195. }
  196. /**
  197. * Affiche l'historique des commandes de l'utilisateur
  198. *
  199. * @return ProducerView
  200. */
  201. public function actionHistory()
  202. {
  203. $dataProviderOrders = new ActiveDataProvider([
  204. 'query' => Order::find()
  205. ->with('productOrder', 'pointSale', 'creditHistory')
  206. ->joinWith('distribution', 'distribution.producer')
  207. ->where([
  208. 'id_user' => Yii::$app->user->id,
  209. 'distribution.id_producer' => $this->getProducer()->id
  210. ])
  211. ->orderBy('distribution.date DESC'),
  212. 'pagination' => [
  213. 'pageSize' => 10,
  214. ],
  215. ]);
  216. return $this->render('history', [
  217. 'dataProviderOrders' => $dataProviderOrders,
  218. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  219. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  220. ]);
  221. }
  222. /**
  223. * Supprime un producteur.
  224. *
  225. * @param integer $id
  226. */
  227. public function actionRemoveProducer($id = 0)
  228. {
  229. $userProducer = UserProducer::find()
  230. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  231. ->one();
  232. $userProducer->active = 0;
  233. $userProducer->save();
  234. $this->redirect(['order/index']);
  235. }
  236. /**
  237. * Crée une commande.
  238. *
  239. * @return mixed
  240. */
  241. public function actionAjaxProcess()
  242. {
  243. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  244. $order = new Order ;
  245. $idProducer = $this->getProducer()->id ;
  246. $posts = Yii::$app->request->post();
  247. if ($idProducer) {
  248. $this->_verifyProducerActive($idProducer);
  249. }
  250. if ($order->load($posts)) {
  251. $order = Order::find()
  252. ->where('id_distribution = :id_distribution')
  253. ->andWhere('id_user = :id_user')
  254. ->params([
  255. ':id_distribution' => $posts['Order']['id_distribution'],
  256. ':id_user' => User::getCurrentId()
  257. ])
  258. ->one();
  259. if (!$order) {
  260. $order = new Order;
  261. $order->load(Yii::$app->request->post());
  262. $order->id_user = User::getCurrentId();
  263. $order->date = date('Y-m-d H:i:s');
  264. $order->origin = Order::ORIGIN_USER;
  265. }
  266. $errors = $this->processForm($order);
  267. if(count($errors)) {
  268. return ['status' => 'error', 'errors' => $errors] ;
  269. }
  270. }
  271. return ['status' => 'success'] ;
  272. }
  273. /**
  274. * Modifie une commande.
  275. *
  276. * @param integer $id
  277. * @return mixed
  278. * @throws UserException
  279. */
  280. public function actionUpdate($id)
  281. {
  282. $order = Order::searchOne([
  283. 'id' => $id
  284. ]) ;
  285. if ($order->getState() != Order::STATE_OPEN) {
  286. throw new UserException('Cette commande n\'est pas modifiable.');
  287. }
  288. $this->_verifyProducerActive($order->distribution->id_producer);
  289. if ($order && $order->load(Yii::$app->request->post())) {
  290. $order->date_update = date('Y-m-d H:i:s');
  291. $this->processForm($order);
  292. }
  293. return $this->render('update', array_merge($this->initForm($order), [
  294. 'model' => $order,
  295. 'orderNotfound' => !$order,
  296. ]));
  297. }
  298. /**
  299. * Vérifie si un producteur est actif.
  300. *
  301. * @param integer $idProducer
  302. * @throws NotFoundHttpException
  303. */
  304. public function _verifyProducerActive($idProducer)
  305. {
  306. $producer = Producer::findOne($idProducer);
  307. if ($producer && !$producer->active) {
  308. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  309. }
  310. }
  311. /**
  312. * Traite le formulaire de création/modification de commande.
  313. *
  314. * @param Commande $order
  315. */
  316. public function processForm($order)
  317. {
  318. $posts = Yii::$app->request->post();
  319. $productsArray = [];
  320. $totalQuantity = 0;
  321. foreach ($posts['products'] as $key => $quantity) {
  322. $product = Product::find()->where(['id' => (int) $key])->one();
  323. $totalQuantity += $quantity;
  324. if ($product && $quantity) {
  325. $productsArray[] = $product;
  326. }
  327. }
  328. // date
  329. $errorDate = false;
  330. if (isset($order->id_distribution)) {
  331. // date de commande
  332. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  333. if (date('H') >= 20) {
  334. $date = date('Y-m-d', strtotime(date('Y-m-d')) + 60 * 60 * 24);
  335. } else {
  336. $date = date('Y-m-d');
  337. }
  338. if ($distribution->date < $date) {
  339. $errorDate = true;
  340. }
  341. }
  342. // point de vente
  343. $errorPointSale = false;
  344. if (isset($distribution) && $distribution) {
  345. $pointSaleDistribution = PointSaleDistribution::searchOne([
  346. 'id_distribution' => $distribution->id,
  347. 'id_point_sale' => $posts['Order']['id_point_sale']
  348. ]) ;
  349. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  350. $errorPointSale = true;
  351. }
  352. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  353. if ($pointSale) {
  354. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  355. $errorPointSale = true;
  356. }
  357. } else {
  358. $errorPointSale = true;
  359. }
  360. }
  361. $errors = [] ;
  362. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  363. // gestion point de vente
  364. $pointSale = PointSale::searchOne([
  365. 'id' => $order->id_point_sale
  366. ]) ;
  367. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  368. $pv->getComment() : '' ;
  369. // la commande est automatiquement réactivée lors d'une modification
  370. $order->date_delete = null ;
  371. // sauvegarde de la commande
  372. $order->save();
  373. // ajout de l'utilisateur à l'établissement
  374. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  375. // suppression de tous les enregistrements ProductOrder
  376. if (!is_null($order)) {
  377. ProductOrder::deleteAll(['id_order' => $order->id]);
  378. }
  379. // produits dispos
  380. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  381. // sauvegarde des produits
  382. foreach ($productsArray as $product) {
  383. if (isset($availableProducts[$product->id])) {
  384. $productOrder = new ProductOrder();
  385. $productOrder->id_order = $order->id;
  386. $productOrder->id_product = $product->id;
  387. $productOrder->price = $product->price;
  388. $quantity = (int) $posts['products'][$product->id] ;
  389. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  390. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  391. }
  392. $productOrder->quantity = $quantity;
  393. $productOrder->sale_mode = Product::SALE_MODE_UNIT ;
  394. $productOrder->save();
  395. }
  396. }
  397. // credit
  398. $credit = Producer::getConfig('credit');
  399. $order = Order::searchOne([
  400. 'id' => $order->id
  401. ]) ;
  402. if ($credit && ($pointSale->credit || $order->getAmount(Order::AMOUNT_PAID))) {
  403. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  404. // à payer
  405. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  406. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  407. $credit = Yii::$app->user->identity->getCredit($distribution->id_producer);
  408. if ($amountRemaining > $credit) {
  409. $amountRemaining = $credit;
  410. }
  411. if ($amountRemaining > 0) {
  412. $order->saveCreditHistory(
  413. CreditHistory::TYPE_PAYMENT,
  414. $amountRemaining,
  415. $distribution->id_producer,
  416. User::getCurrentId(),
  417. User::getCurrentId()
  418. );
  419. }
  420. }
  421. // surplus à rembourser
  422. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  423. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  424. $order->saveCreditHistory(
  425. CreditHistory::TYPE_REFUND,
  426. $amountSurplus,
  427. $distribution->id_producer,
  428. User::getCurrentId(),
  429. User::getCurrentId()
  430. );
  431. }
  432. }
  433. // redirection
  434. //$this->redirect(Yii::$app->urlManager->createUrl(['order/history', 'orderOk' => true]));
  435. }
  436. else {
  437. if (!count($productsArray)) {
  438. $errors[] = "Vous n'avez choisi aucun produit" ;
  439. }
  440. if ($errorDate) {
  441. $errors[] = "Vous ne pouvez pas commander pour cette date." ;
  442. }
  443. if ($errorPointSale) {
  444. $errors[] = "Point de vente invalide." ;
  445. }
  446. }
  447. return $errors ;
  448. }
  449. /**
  450. * Annule une commande.
  451. *
  452. * @param integer $id
  453. * @throws \yii\web\NotFoundHttpException
  454. * @throws UserException
  455. */
  456. public function actionCancel($id)
  457. {
  458. $order = Order::searchOne([
  459. 'id' => $id
  460. ]) ;
  461. if(!$order) {
  462. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  463. }
  464. if ($order->getState() != Order::STATE_OPEN) {
  465. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  466. }
  467. if ($order && User::getCurrentId() == $order->id_user) {
  468. // remboursement
  469. if ($order->getAmount(Order::AMOUNT_PAID)) {
  470. $order->saveCreditHistory(
  471. CreditHistory::TYPE_REFUND,
  472. $order->getAmount(Order::AMOUNT_PAID),
  473. $order->distribution->id_producer,
  474. User::getCurrentId(),
  475. User::getCurrentId()
  476. );
  477. }
  478. // delete
  479. $order->date_delete = date('Y-m-d H:i:s');
  480. $order->save() ;
  481. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  482. }
  483. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  484. }
  485. /**
  486. * Vérifie le code saisi pour un point de vente.
  487. *
  488. * @param integer $idPointSale
  489. * @param string $code
  490. * @return boolean
  491. */
  492. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  493. {
  494. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  495. $pointSale = PointSale::findOne($idPointSale);
  496. if ($pointSale) {
  497. if ($pointSale->validateCode($code)) {
  498. return 1;
  499. }
  500. }
  501. return 0;
  502. }
  503. public function actionAjaxInfos($date = '')
  504. {
  505. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  506. $json = [] ;
  507. $format = 'Y-m-d' ;
  508. $dateObject = DateTime::createFromFormat($format, $date);
  509. // Producteur
  510. $producer = Producer::searchOne([
  511. 'id' => $this->getProducer()->id
  512. ]) ;
  513. $json['producer'] = [
  514. 'order_infos' => $producer->order_infos,
  515. 'credit' => $producer->credit
  516. ] ;
  517. // Distributions
  518. $deadline = 20;
  519. $dateMini = date('Y-m-d');
  520. if (isset($producer)) {
  521. if($producer->order_deadline) {
  522. $deadline = $producer->order_deadline;
  523. }
  524. if (date('H') >= $deadline) {
  525. $dateMini = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay) * (24 * 60 * 60));
  526. } else {
  527. $dateMini = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay - 1) * (24 * 60 * 60));
  528. }
  529. }
  530. $distributionsArray = Distribution::searchAll([
  531. 'active' => 1
  532. ], [
  533. 'conditions' => ['date > :date'],
  534. 'params' => [':date' => $dateMini],
  535. ]) ;
  536. $json['distributions'] = $distributionsArray ;
  537. // Commandes de l'utilisateur
  538. $ordersUserArray = Order::searchAll([
  539. 'id_user' => User::getCurrentId()
  540. ], [
  541. 'conditions' => [
  542. 'distribution.date > :date'
  543. ],
  544. 'params' => [
  545. ':date' => $dateMini
  546. ]
  547. ]);
  548. foreach($ordersUserArray as &$order) {
  549. $order = array_merge($order->getAttributes(), [
  550. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  551. 'date_distribution' => $order->distribution->date,
  552. 'pointSale' => $order->pointSale->getAttributes()
  553. ]) ;
  554. }
  555. $json['orders'] = $ordersUserArray;
  556. // User
  557. $userProducer = UserProducer::searchOne([
  558. 'id_producer' => $producer->id,
  559. 'id_user' => User::getCurrentId()
  560. ]) ;
  561. $json['credit'] = $userProducer->credit ;
  562. if($dateObject && $dateObject->format($format) === $date) {
  563. // Commande de l'utilisateur
  564. $orderUser = Order::searchOne([
  565. 'distribution.date' => $date,
  566. 'id_user' => User::getCurrentId(),
  567. ]);
  568. if($orderUser) {
  569. $json['order'] = array_merge($orderUser->getAttributes(), [
  570. 'amount_total' => $orderUser->getAmount(Order::AMOUNT_TOTAL),
  571. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  572. ]) ;
  573. }
  574. // distribution
  575. $distribution = Distribution::initDistribution($date) ;
  576. $json['distribution'] = $distribution ;
  577. $pointsSaleArray = PointSale::find()
  578. ->joinWith(['pointSaleDistribution' => function($query) use ($distribution) {
  579. $query->where(['id_distribution' => $distribution->id]);
  580. }
  581. ])
  582. ->with(['userPointSale' => function($query) {
  583. $query->onCondition(['id_user' => User::getCurrentId()]) ;
  584. }])
  585. ->where([
  586. 'id_producer' => $distribution->id_producer,
  587. ])
  588. ->all();
  589. foreach($pointsSaleArray as &$pointSale) {
  590. $pointSale = array_merge($pointSale->getAttributes(),[
  591. 'pointSaleDistribution' => [
  592. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  593. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  594. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  595. ],
  596. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  597. ]) ;
  598. }
  599. $json['points_sale'] = $pointsSaleArray;
  600. // Commandes totales
  601. $ordersArray = Order::searchAll([
  602. 'distribution.date' => $date,
  603. ]);
  604. // Produits
  605. $productsArray = Product::find()
  606. ->where([
  607. 'id_producer' => $this->getProducer()->id,
  608. ])
  609. ->joinWith(['productDistribution' => function($query) use($distribution) {
  610. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  611. }])
  612. ->orderBy('product_distribution.active DESC, order ASC')
  613. ->asArray()
  614. ->all();
  615. $indexProduct = 0 ;
  616. foreach($productsArray as &$product) {
  617. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray) ;
  618. $product['quantity_ordered'] = $quantityOrder ;
  619. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder ;
  620. if($orderUser) {
  621. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser]) ;
  622. $product['quantity_ordered'] = $quantityOrder ;
  623. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser ;
  624. $product['quantity_form'] = $quantityOrderUser ;
  625. }
  626. else {
  627. $product['quantity_form'] = 0 ;
  628. }
  629. if($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0 ;
  630. $product['index'] = $indexProduct ++ ;
  631. }
  632. $json['products'] = $productsArray;
  633. }
  634. return $json ;
  635. }
  636. }