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.

OrderController.php 40KB

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