Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

981 line
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. $order->online_payment_url = $redirect;
  280. $order->save();
  281. }
  282. }
  283. return ['status' => 'success', 'idOrder' => $order->id, 'redirect' => $redirect];
  284. }
  285. /**
  286. * Vérifie si un producteur est actif.
  287. *
  288. * @param integer $idProducer
  289. * @throws NotFoundHttpException
  290. */
  291. public function _verifyProducerActive($idProducer)
  292. {
  293. $producer = Producer::findOne($idProducer);
  294. if ($producer && !$producer->active) {
  295. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  296. }
  297. }
  298. /**
  299. * Traite le formulaire de création/modification de commande.
  300. *
  301. * @param Commande $order
  302. */
  303. public function processForm($order, $user)
  304. {
  305. $posts = Yii::$app->request->post();
  306. $productsArray = [];
  307. $totalQuantity = 0;
  308. $producer = $this->getProducer();
  309. $isNewOrder = false;
  310. if (!$order->id) {
  311. $isNewOrder = true;
  312. }
  313. foreach ($posts['products'] as $key => $quantity) {
  314. $product = Product::find()->where(['id' => (int)$key])->one();
  315. $totalQuantity += $quantity;
  316. if ($product && $quantity) {
  317. $productsArray[] = $product;
  318. }
  319. }
  320. // date
  321. $errorDate = false;
  322. if (isset($order->id_distribution)) {
  323. // date de commande
  324. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  325. if ($order->getState() != Order::STATE_OPEN) {
  326. $errorDate = true;
  327. }
  328. }
  329. // point de vente
  330. $errorPointSale = false;
  331. if (isset($distribution) && $distribution) {
  332. $pointSaleDistribution = PointSaleDistribution::searchOne([
  333. 'id_distribution' => $distribution->id,
  334. 'id_point_sale' => $posts['Order']['id_point_sale']
  335. ]);
  336. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  337. $errorPointSale = true;
  338. }
  339. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  340. if ($pointSale) {
  341. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  342. $errorPointSale = true;
  343. }
  344. } else {
  345. $errorPointSale = true;
  346. }
  347. $userPointSale = UserPointSale::searchOne([
  348. 'id_user' => User::getCurrentId(),
  349. 'id_point_sale' => $pointSale->id
  350. ]);
  351. if ($pointSale->restricted_access && !$userPointSale) {
  352. $errorPointSale = true;
  353. }
  354. }
  355. $errors = [];
  356. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  357. $userProducer = UserProducer::searchOne([
  358. 'id_producer' => $order->distribution->id_producer,
  359. 'id_user' => $user->id
  360. ]);
  361. // gestion point de vente
  362. $pointSale = PointSale::searchOne([
  363. 'id' => $order->id_point_sale
  364. ]);
  365. // commentaire point de vente
  366. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  367. $pointSale->getComment() : '';
  368. // la commande est automatiquement réactivée lors d'une modification
  369. $order->date_delete = null;
  370. // delivery
  371. $order->delivery_home = isset($posts['Order']['delivery_home']) ? $posts['Order']['delivery_home'] : false;
  372. $order->delivery_address = (isset($posts['Order']['delivery_address']) && $order->delivery_home) ? $posts['Order']['delivery_address'] : null;
  373. // comment
  374. $order->comment = isset($posts['Order']['comment']) ? $posts['Order']['comment'] : null;
  375. // sauvegarde de la commande
  376. $order->save();
  377. $order->initReference();
  378. $order->changeOrderStatus('new-order', 'user');
  379. // ajout de l'utilisateur à l'établissement
  380. Producer::addUser($user->id, $distribution->id_producer);
  381. // suppression de tous les enregistrements ProductOrder
  382. if (!is_null($order)) {
  383. ProductOrder::deleteAll(['id_order' => $order->id]);
  384. $stepsArray = [];
  385. if (isset($order->productOrder)) {
  386. foreach ($order->productOrder as $productOrder) {
  387. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  388. }
  389. }
  390. }
  391. // produits dispos
  392. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  393. // sauvegarde des produits
  394. foreach ($productsArray as $product) {
  395. if (isset($availableProducts[$product->id])) {
  396. $productOrder = new ProductOrder();
  397. $productOrder->id_order = $order->id;
  398. $productOrder->id_product = $product->id;
  399. $productOrder->price = $product->getPrice([
  400. 'user' => User::getCurrent(),
  401. 'user_producer' => $userProducer,
  402. 'point_sale' => $pointSale
  403. ]);
  404. $productOrder->id_tax_rate = $product->taxRate->id;
  405. $unit = (!is_null(
  406. $order
  407. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  408. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  409. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  410. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  411. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  412. }
  413. $productOrder->quantity = $quantity;
  414. $productOrder->unit = $product->unit;
  415. $productOrder->step = $product->step;
  416. $productOrder->save();
  417. }
  418. }
  419. // lien utilisateur / point de vente
  420. $pointSale->linkUser($user->id);
  421. // credit
  422. $credit = Producer::getConfig('credit');
  423. $creditLimit = Producer::getConfig('credit_limit');
  424. $creditFunctioning = $pointSale->getCreditFunctioning();
  425. $creditUser = $user->getCredit($distribution->id_producer);
  426. $order = Order::searchOne([
  427. 'id' => $order->id
  428. ]);
  429. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  430. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  431. if ($credit && $pointSale->credit &&
  432. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  433. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  434. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  435. )) {
  436. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  437. // à payer
  438. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  439. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  440. $amountRemaining = $creditUser - $creditLimit;
  441. }
  442. if ($amountRemaining > 0) {
  443. $order->saveCreditHistory(
  444. CreditHistory::TYPE_PAYMENT,
  445. $amountRemaining,
  446. $distribution->id_producer,
  447. User::getCurrentId(),
  448. User::getCurrentId()
  449. );
  450. $order->changeOrderStatus('paid-by-credit', 'user');
  451. } else {
  452. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  453. }
  454. } // surplus à rembourser
  455. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  456. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  457. $order->saveCreditHistory(
  458. CreditHistory::TYPE_REFUND,
  459. $amountSurplus,
  460. $distribution->id_producer,
  461. User::getCurrentId(),
  462. User::getCurrentId()
  463. );
  464. }
  465. } else {
  466. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  467. }
  468. $paramsEmail = [
  469. 'from_email' => $producer->getEmailOpendistrib(),
  470. 'from_name' => $producer->name,
  471. 'to_email' => $user->email,
  472. 'to_name' => $user->getUsername(),
  473. 'subject' => '[' . $producer->name . '] Confirmation de commande',
  474. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  475. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  476. 'content_params' => [
  477. 'order' => $order,
  478. 'pointSale' => $pointSale,
  479. 'distribution' => $distribution,
  480. 'user' => $user,
  481. 'producer' => $producer
  482. ]
  483. ];
  484. /*
  485. * Envoi email de confirmation
  486. */
  487. if ($isNewOrder) {
  488. // au client
  489. if (Producer::getConfig('option_email_confirm')) {
  490. Mailjet::sendMail($paramsEmail);
  491. }
  492. // au producteur
  493. $contactProducer = $producer->getMainContact();
  494. if (Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  495. $contactProducer->email
  496. )) {
  497. $paramsEmail['to_email'] = $contactProducer->email;
  498. $paramsEmail['to_name'] = $contactProducer->name;
  499. $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php';
  500. $paramsEmail['content_view_html'] = '@common/mail/orderConfirmProducer-html.php';
  501. Mailjet::sendMail($paramsEmail);
  502. }
  503. }
  504. $order->setTillerSynchronization();
  505. }
  506. if (!count($productsArray)) {
  507. $errors[] = "Vous n'avez choisi aucun produit";
  508. }
  509. if ($errorDate) {
  510. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  511. }
  512. if ($errorPointSale) {
  513. $errors[] = "Point de vente invalide.";
  514. }
  515. return $errors;
  516. }
  517. /**
  518. * Annule une commande.
  519. *
  520. * @param integer $id
  521. * @throws \yii\web\NotFoundHttpException
  522. * @throws UserException
  523. */
  524. public function actionCancel($id)
  525. {
  526. $order = Order::searchOne([
  527. 'id' => $id
  528. ]);
  529. if (!$order) {
  530. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  531. }
  532. if ($order->getState() != Order::STATE_OPEN) {
  533. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  534. }
  535. if ($order && User::getCurrentId() == $order->id_user) {
  536. $order->delete();
  537. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  538. }
  539. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  540. }
  541. /**
  542. * Vérifie le code saisi pour un point de vente.
  543. *
  544. * @param integer $idPointSale
  545. * @param string $code
  546. * @return boolean
  547. */
  548. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  549. {
  550. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  551. $pointSale = PointSale::findOne($idPointSale);
  552. if ($pointSale) {
  553. if ($pointSale->validateCode($code)) {
  554. return 1;
  555. }
  556. }
  557. return 0;
  558. }
  559. public function actionAjaxInfos($date = '', $pointSaleId = 0)
  560. {
  561. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  562. $json = [];
  563. $format = 'Y-m-d';
  564. $dateObject = DateTime::createFromFormat($format, $date);
  565. $user = User::getCurrent();
  566. // PointSale current
  567. $pointSaleCurrent = PointSale::findOne($pointSaleId);
  568. // Producteur
  569. $producer = Producer::searchOne([
  570. 'id' => $this->getProducer()->id
  571. ]);
  572. $json['producer'] = [
  573. 'order_infos' => $producer->order_infos,
  574. 'credit' => $producer->credit,
  575. 'credit_functioning' => $producer->credit_functioning,
  576. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  577. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  578. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  579. 'option_order_entry_point' => $producer->option_order_entry_point,
  580. 'option_delivery' => $producer->option_delivery,
  581. 'online_payment' => $producer->online_payment,
  582. 'option_online_payment_type' => $producer->online_payment,
  583. ];
  584. // Distributions
  585. $dateMini = date('Y-m-d');
  586. $distributionsArray = Distribution::searchAll([
  587. 'active' => 1,
  588. 'id_producer' => $producer->id
  589. ], [
  590. 'conditions' => ['date > :date'],
  591. 'params' => [':date' => $dateMini],
  592. 'join_with' => ['pointSaleDistribution'],
  593. ]);
  594. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray);
  595. // Filtre par point de vente
  596. if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  597. $distributionsArrayFilterPointSale = [];
  598. for ($i = 0; $i < count($distributionsArray); $i++) {
  599. $distribution = $distributionsArray[$i];
  600. if (Distribution::isPointSaleActive($distribution, $pointSaleId)) {
  601. $distributionsArrayFilterPointSale[] = $distribution;
  602. }
  603. }
  604. $json['distributions'] = $distributionsArrayFilterPointSale;
  605. } else {
  606. $json['distributions'] = $distributionsArray;
  607. }
  608. // Commandes de l'utilisateur
  609. $ordersUserArray = [];
  610. if (User::getCurrentId()) {
  611. $conditionsOrdersUser = [
  612. 'distribution.date > :date'
  613. ];
  614. $paramsOrdersUser = [
  615. ':date' => $dateMini
  616. ];
  617. if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  618. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  619. $paramsOrdersUser[':id_point_sale'] = $pointSaleId;
  620. }
  621. $ordersUserArray = Order::searchAll([
  622. 'id_user' => User::getCurrentId()
  623. ], [
  624. 'conditions' => $conditionsOrdersUser,
  625. 'params' => $paramsOrdersUser
  626. ]);
  627. }
  628. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  629. foreach ($ordersUserArray as &$order) {
  630. $order = array_merge($order->getAttributes(), [
  631. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  632. 'date_distribution' => $order->distribution->date,
  633. 'pointSale' => $order->pointSale->getAttributes()
  634. ]);
  635. }
  636. $json['orders'] = $ordersUserArray;
  637. }
  638. // User
  639. $userProducer = UserProducer::searchOne([
  640. 'id_producer' => $producer->id,
  641. 'id_user' => User::getCurrentId()
  642. ]);
  643. $json['user'] = false;
  644. if ($userProducer) {
  645. $json['user'] = [
  646. 'address' => $user->address,
  647. 'credit' => $userProducer->credit,
  648. 'credit_active' => $userProducer->credit_active,
  649. ];
  650. }
  651. if ($dateObject && $dateObject->format($format) === $date) {
  652. // Commande de l'utilisateur
  653. $orderUser = false;
  654. if (User::getCurrentId()) {
  655. $conditionOrderUser = [
  656. 'distribution.date' => $date,
  657. 'id_user' => User::getCurrentId(),
  658. ];
  659. if ($pointSaleId) {
  660. $conditionOrderUser['id_point_sale'] = $pointSaleId;
  661. }
  662. $orderUser = Order::searchOne($conditionOrderUser);
  663. }
  664. if ($orderUser) {
  665. $json['order'] = array_merge($orderUser->getAttributes(), [
  666. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  667. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  668. ]);
  669. }
  670. // distribution
  671. $distribution = Distribution::initDistribution($date, $producer->id);
  672. $json['distribution'] = $distribution;
  673. // Points de vente
  674. $json['points_sale'] = $this->_initPointsSale($producer->id, $distribution);
  675. // Commandes totales
  676. $ordersArray = Order::searchAll([
  677. 'distribution.date' => $date,
  678. ]);
  679. // Catégories
  680. $categoriesArray = ProductCategory::searchAll(
  681. [],
  682. [
  683. 'orderby' => 'product_category.position ASC',
  684. 'as_array' => true
  685. ]
  686. );
  687. $countProductsWithoutCategories = Product::searchCount([
  688. 'id_producer' => $this->getProducer()->id,
  689. 'product.active' => 1,
  690. 'product.id_product_category' => null
  691. ]);
  692. if ($countProductsWithoutCategories) {
  693. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  694. }
  695. $json['categories'] = $categoriesArray;
  696. // Produits
  697. $productsArray = Product::find()
  698. ->where([
  699. 'id_producer' => $this->getProducer()->id,
  700. 'product.active' => 1,
  701. ]);
  702. $productsArray = $productsArray->joinWith([
  703. 'productDistribution' => function ($query) use (
  704. $distribution
  705. ) {
  706. $query->andOnCondition(
  707. 'product_distribution.id_distribution = ' . $distribution->id
  708. );
  709. },
  710. 'productPrice'
  711. ])
  712. ->orderBy('product_distribution.active DESC, order ASC')
  713. ->all();
  714. $indexProduct = 0;
  715. foreach ($productsArray as &$product) {
  716. $product = array_merge(
  717. $product->getAttributes(),
  718. [
  719. 'price_with_tax' => $product->getPriceWithTax([
  720. 'user' => User::getCurrent(),
  721. 'user_producer' => $userProducer,
  722. 'point_sale' => $pointSaleCurrent
  723. ]),
  724. 'productDistribution' => $product['productDistribution']
  725. ]
  726. );
  727. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  728. if (is_null($product['photo'])) {
  729. $product['photo'] = '';
  730. }
  731. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  732. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  733. $product['quantity_ordered'] = $quantityOrder;
  734. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  735. if ($orderUser) {
  736. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  737. $product['quantity_ordered'] = $quantityOrder;
  738. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  739. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  740. foreach ($orderUser->productOrder as $productOrder) {
  741. if ($productOrder->id_product == $product['id']) {
  742. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  743. $product['step'] = $productOrder->step;
  744. }
  745. }
  746. } else {
  747. $product['quantity_form'] = 0;
  748. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  749. }
  750. $product['coefficient_unit'] = $coefficient_unit;
  751. if ($product['quantity_remaining'] < 0) {
  752. $product['quantity_remaining'] = 0;
  753. }
  754. $product['index'] = $indexProduct++;
  755. }
  756. $json['products'] = $productsArray;
  757. } else {
  758. $json['points_sale'] = $this->_initPointsSale($producer->id);
  759. }
  760. return $json;
  761. }
  762. private function _initPointsSale($idProducer, $distribution = false)
  763. {
  764. $pointsSaleArray = PointSale::find();
  765. if ($distribution) {
  766. $pointsSaleArray = $pointsSaleArray->joinWith([
  767. 'pointSaleDistribution' => function ($query) use (
  768. $distribution
  769. ) {
  770. $query->where(
  771. [
  772. 'id_distribution' => $distribution->id,
  773. 'delivery' => 1
  774. ]
  775. );
  776. }
  777. ]);
  778. }
  779. if (User::getCurrentId()) {
  780. $pointsSaleArray = $pointsSaleArray->with([
  781. 'userPointSale' => function ($query) {
  782. $query->onCondition(
  783. ['id_user' => User::getCurrentId()]
  784. );
  785. }
  786. ]);
  787. }
  788. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $idProducer])
  789. ->andWhere(
  790. '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)'
  791. )
  792. ->params([':id_user' => User::getCurrentId()])
  793. ->all();
  794. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  795. foreach ($pointsSaleArray as &$pointSale) {
  796. $pointSale = array_merge($pointSale->getAttributes(), [
  797. 'pointSaleDistribution' => [
  798. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  799. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  800. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  801. ],
  802. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  803. ]);
  804. if ($pointSale['code'] && strlen($pointSale['code'])) {
  805. $pointSale['code'] = '***';
  806. }
  807. if (!strlen($pointSale['credit_functioning'])) {
  808. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  809. }
  810. }
  811. $favoritePointSale = false;
  812. if (User::getCurrent()) {
  813. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  814. }
  815. if ($favoritePointSale) {
  816. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  817. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  818. $theFavoritePointSale = $pointsSaleArray[$i];
  819. unset($pointsSaleArray[$i]);
  820. }
  821. }
  822. if (isset($theFavoritePointSale)) {
  823. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  824. $pointsSaleArray[] = $theFavoritePointSale;
  825. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  826. }
  827. }
  828. return $pointsSaleArray;
  829. }
  830. public function actionConfirm($idOrder, $returnPayment = '')
  831. {
  832. $order = Order::searchOne(['id' => $idOrder]);
  833. $producer = $this->getProducer();
  834. if (!$order || ($order->id_user != User::getCurrentId() && !$producer->option_allow_order_guest)) {
  835. throw new \yii\base\UserException('Commande introuvable.');
  836. }
  837. return $this->render('confirm', [
  838. 'order' => $order,
  839. 'returnPayment' => $returnPayment
  840. ]);
  841. }
  842. }