Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

OrderController.php 34KB

il y a 6 ans
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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. $user = User::getCurrent() ;
  351. $paramsEmail = [
  352. 'from_email' => $producer->getEmailOpendistrib(),
  353. 'from_name' => $producer->name,
  354. 'to_email' => $user->email,
  355. 'to_name' => $user->getUsername(),
  356. 'subject' => '['.$producer->name.'] Confirmation de commande',
  357. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  358. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  359. 'content_params' => [
  360. 'order' => $order,
  361. 'pointSale' => $pointSale,
  362. 'distribution' => $distribution,
  363. 'user' => $user
  364. ]
  365. ] ;
  366. /*
  367. * Envoi email de confirmation
  368. */
  369. if($isNewOrder) {
  370. // au client
  371. if(Producer::getConfig('option_email_confirm')) {
  372. Mailjet::sendMail($paramsEmail);
  373. }
  374. // au producteur
  375. $contactProducer = $producer->getMainContact() ;
  376. if(Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen($contactProducer->email)) {
  377. $paramsEmail['to_email'] = $contactProducer->email ;
  378. $paramsEmail['to_name'] = $contactProducer->name ;
  379. Mailjet::sendMail($paramsEmail);
  380. }
  381. }
  382. $order->setTillerSynchronization() ;
  383. }
  384. if (!count($productsArray)) {
  385. $errors[] = "Vous n'avez choisi aucun produit";
  386. }
  387. if ($errorDate) {
  388. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  389. }
  390. if ($errorPointSale) {
  391. $errors[] = "Point de vente invalide.";
  392. }
  393. return $errors;
  394. }
  395. /**
  396. * Annule une commande.
  397. *
  398. * @param integer $id
  399. * @throws \yii\web\NotFoundHttpException
  400. * @throws UserException
  401. */
  402. public function actionCancel($id)
  403. {
  404. $order = Order::searchOne([
  405. 'id' => $id
  406. ]);
  407. if (!$order) {
  408. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  409. }
  410. if ($order->getState() != Order::STATE_OPEN) {
  411. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  412. }
  413. if ($order && User::getCurrentId() == $order->id_user) {
  414. $order->delete();
  415. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  416. }
  417. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  418. }
  419. /**
  420. * Vérifie le code saisi pour un point de vente.
  421. *
  422. * @param integer $idPointSale
  423. * @param string $code
  424. * @return boolean
  425. */
  426. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  427. {
  428. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  429. $pointSale = PointSale::findOne($idPointSale);
  430. if ($pointSale) {
  431. if ($pointSale->validateCode($code)) {
  432. return 1;
  433. }
  434. }
  435. return 0;
  436. }
  437. public function actionAjaxInfos($date = '')
  438. {
  439. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  440. $json = [];
  441. $format = 'Y-m-d';
  442. $dateObject = DateTime::createFromFormat($format, $date);
  443. // Producteur
  444. $producer = Producer::searchOne([
  445. 'id' => $this->getProducer()->id
  446. ]);
  447. $json['producer'] = [
  448. 'order_infos' => $producer->order_infos,
  449. 'credit' => $producer->credit,
  450. 'credit_functioning' => $producer->credit_functioning,
  451. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  452. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  453. ];
  454. // Distributions
  455. $dateMini = date('Y-m-d') ;
  456. $distributionsArray = Distribution::searchAll([
  457. 'active' => 1
  458. ], [
  459. 'conditions' => ['date > :date'],
  460. 'params' => [':date' => $dateMini],
  461. ]);
  462. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray) ;
  463. $json['distributions'] = $distributionsArray;
  464. // Commandes de l'utilisateur
  465. $ordersUserArray = Order::searchAll([
  466. 'id_user' => User::getCurrentId()
  467. ], [
  468. 'conditions' => [
  469. 'distribution.date > :date'
  470. ],
  471. 'params' => [
  472. ':date' => $dateMini
  473. ]
  474. ]);
  475. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  476. foreach ($ordersUserArray as &$order) {
  477. $order = array_merge($order->getAttributes(), [
  478. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  479. 'date_distribution' => $order->distribution->date,
  480. 'pointSale' => $order->pointSale->getAttributes()
  481. ]);
  482. }
  483. $json['orders'] = $ordersUserArray;
  484. }
  485. // User
  486. $userProducer = UserProducer::searchOne([
  487. 'id_producer' => $producer->id,
  488. 'id_user' => User::getCurrentId()
  489. ]);
  490. $json['user'] = [
  491. 'credit' => $userProducer->credit,
  492. 'credit_active' => $userProducer->credit_active,
  493. ];
  494. if ($dateObject && $dateObject->format($format) === $date) {
  495. // Commande de l'utilisateur
  496. $orderUser = Order::searchOne([
  497. 'distribution.date' => $date,
  498. 'id_user' => User::getCurrentId(),
  499. ]);
  500. if ($orderUser) {
  501. $json['order'] = array_merge($orderUser->getAttributes(), [
  502. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  503. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  504. ]);
  505. }
  506. // distribution
  507. $distribution = Distribution::initDistribution($date);
  508. $json['distribution'] = $distribution;
  509. $pointsSaleArray = PointSale::find()
  510. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  511. $query->where(['id_distribution' => $distribution->id]);
  512. }
  513. ])
  514. ->with(['userPointSale' => function ($query) {
  515. $query->onCondition(['id_user' => User::getCurrentId()]);
  516. }])
  517. ->where(['id_producer' => $distribution->id_producer])
  518. ->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)')
  519. ->params([':id_user' => User::getCurrentId()])
  520. ->all();
  521. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  522. foreach ($pointsSaleArray as &$pointSale) {
  523. $pointSale = array_merge($pointSale->getAttributes(), [
  524. 'pointSaleDistribution' => [
  525. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  526. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  527. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  528. ],
  529. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  530. ]);
  531. if ($pointSale['code'] && strlen($pointSale['code'])) {
  532. $pointSale['code'] = '***';
  533. }
  534. if (!strlen($pointSale['credit_functioning'])) {
  535. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  536. }
  537. }
  538. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  539. if ($favoritePointSale) {
  540. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  541. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  542. $theFavoritePointSale = $pointsSaleArray[$i];
  543. unset($pointsSaleArray[$i]);
  544. }
  545. }
  546. if (isset($theFavoritePointSale)) {
  547. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  548. $pointsSaleArray[] = $theFavoritePointSale;
  549. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  550. }
  551. }
  552. $json['points_sale'] = $pointsSaleArray;
  553. // Commandes totales
  554. $ordersArray = Order::searchAll([
  555. 'distribution.date' => $date,
  556. ]);
  557. // Produits
  558. /*if (Producer::getConfig('option_allow_user_gift')) {
  559. $productsArray = Product::find()
  560. ->orWhere(['id_producer' => $this->getProducer()->id,])
  561. //->orWhere(['id_producer' => 0,]) // produit "Don";
  562. ;
  563. } else {
  564. $productsArray = Product::find()
  565. ->where(['id_producer' => $this->getProducer()->id,]);
  566. }*/
  567. $productsArray = Product::find()
  568. ->where([
  569. 'id_producer' => $this->getProducer()->id,
  570. 'product.active' => 1,
  571. ]);
  572. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  573. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  574. }])
  575. ->orderBy('product_distribution.active DESC, order ASC')
  576. ->all();
  577. $indexProduct = 0;
  578. foreach ($productsArray as &$product) {
  579. $product = array_merge(
  580. $product->getAttributes(),
  581. [
  582. 'price_with_tax' => $product->getPriceWithTax(),
  583. 'productDistribution' => $product['productDistribution']
  584. ]
  585. );
  586. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  587. if (is_null($product['photo'])) {
  588. $product['photo'] = '';
  589. }
  590. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  591. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  592. $product['quantity_ordered'] = $quantityOrder;
  593. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  594. if ($orderUser) {
  595. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  596. $product['quantity_ordered'] = $quantityOrder;
  597. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  598. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  599. foreach ($orderUser->productOrder as $productOrder) {
  600. if ($productOrder->id_product == $product['id']) {
  601. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  602. $product['step'] = $productOrder->step;
  603. }
  604. }
  605. } else {
  606. $product['quantity_form'] = 0;
  607. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  608. }
  609. $product['coefficient_unit'] = $coefficient_unit;
  610. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  611. $product['index'] = $indexProduct++;
  612. }
  613. $json['products'] = $productsArray;
  614. }
  615. return $json;
  616. }
  617. public function actionConfirm($idOrder)
  618. {
  619. $order = Order::searchOne(['id' => $idOrder]);
  620. if (!$order || $order->id_user != User::getCurrentId()) {
  621. throw new \yii\base\UserException('Commande introuvable.');
  622. }
  623. return $this->render('confirm', [
  624. 'order' => $order
  625. ]);
  626. }
  627. }