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.

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