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.

819 lines
38KB

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