選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

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