您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

1029 行
45KB

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