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.

1029 lines
46KB

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