Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

992 rindas
39KB

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