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 34KB

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