Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

976 Zeilen
43KB

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