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.

991 lines
38KB

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