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.

999 line
44KB

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