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.

758 lines
35KB

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