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.

820 lines
39KB

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