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

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