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.

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