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 jaren geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
7 maanden geleden
7 maanden geleden
7 maanden geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
1 jaar geleden
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007
  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->getSolver()->isOnlinePaymentActive($producer) && $posts['payment_method'] == 'online') {
  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
  403. && $this->getUserCurrent()
  404. && $pointSale->payment_method_credit
  405. && $posts['payment_method'] == 'credit'
  406. && ($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL ||
  407. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  408. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  409. )) {
  410. // à payer
  411. if ($orderModule->getPaymentStatus($order) == Order::PAYMENT_UNPAID) {
  412. $paymentManager->payOrderByCredit($order, $this->getUserCurrent(), true);
  413. } // surplus à rembourser
  414. elseif ($orderModule->getPaymentStatus($order) == Order::PAYMENT_SURPLUS) {
  415. $paymentManager->refundSurplusOrderCredit($order, $this->getUserCurrent());
  416. }
  417. }
  418. /*
  419. * Envoi email de confirmation
  420. */
  421. $emailSubject = 'Confirmation de commande';
  422. $emailContentParams = [
  423. 'order' => $order,
  424. 'pointSale' => $pointSale,
  425. 'distribution' => $distribution,
  426. 'user' => $user,
  427. 'producer' => $producer
  428. ];
  429. // au client
  430. if ($producerModule->getConfig('option_email_confirm')) {
  431. \Yii::$app->mailerService->sendFromProducer(
  432. $emailSubject,
  433. 'orderConfirm',
  434. $emailContentParams,
  435. $user->email,
  436. $producer
  437. );
  438. }
  439. // au producteur
  440. $contactProducer = $producerModule->getMainContact($producer);
  441. if ($producerModule->getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  442. $contactProducer->email
  443. )) {
  444. \Yii::$app->mailerService->sendFromSite(
  445. $emailSubject,
  446. 'orderConfirmProducer',
  447. $emailContentParams,
  448. $contactProducer->email
  449. );
  450. }
  451. $order = $orderModule->findOneOrderById($order->id);
  452. $orderModule->initOrder($order);
  453. $orderModule->updateOrderTillerSynchronization($order);
  454. }
  455. if (!count($productsArray)) {
  456. $errors[] = "Vous n'avez choisi aucun produit";
  457. }
  458. if ($errorDate) {
  459. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  460. }
  461. if ($errorPointSale) {
  462. $errors[] = "Point de vente invalide.";
  463. }
  464. return $errors;
  465. }
  466. /**
  467. * Annule une commande.
  468. */
  469. public function actionCancel(int $id)
  470. {
  471. $orderModule = $this->getOrderModule();
  472. $order = $this->getOrderModule()->findOneOrderById($id);
  473. if (!$order) {
  474. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  475. }
  476. $orderModule->initOrder($order);
  477. if (!$orderModule->isOrderStateOpen($order)) {
  478. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  479. }
  480. if ($orderModule->isOrderbelongsToUser($order, GlobalParam::getCurrentUser())) {
  481. $orderModule->deleteOrder($order);
  482. $this->setFlash('success', 'Votre commande a bien été annulée.');
  483. }
  484. return $this->redirect($this->getUrlManagerProducer()->createUrl(['order/history']));
  485. }
  486. /**
  487. * Page de confirmation de commande.
  488. */
  489. public function actionConfirm(int $idOrder, string $returnPayment = '')
  490. {
  491. $orderModule = $this->getOrderModule();
  492. $order = $orderModule->findOneOrderById($idOrder);
  493. $producer = $this->getProducerCurrent();
  494. if (!$order || (!$producer->option_allow_order_guest && !$orderModule->isOrderBelongsToUser($order, GlobalParam::getCurrentUser()))) {
  495. $this->setFlash('error', 'Commande introuvable');
  496. return $this->redirect(['order/history']);
  497. }
  498. $orderModule->initOrder($order);
  499. return $this->render('confirm', [
  500. 'order' => $order,
  501. 'returnPayment' => $returnPayment
  502. ]);
  503. }
  504. /**
  505. * Vérifie le code saisi pour un point de vente.
  506. */
  507. public function actionAjaxValidateCodePointSale(int $idPointSale, string $code)
  508. {
  509. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  510. $pointSaleModule = $this->getPointSaleModule();
  511. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  512. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  513. return 1;
  514. }
  515. return 0;
  516. }
  517. public function actionAjaxInfos(string $date = '', int $pointSaleId = 0)
  518. {
  519. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  520. $user = GlobalParam::getCurrentUser();
  521. $producer = $this->getProducerCurrent();
  522. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($pointSaleId);
  523. $order = $this->getOrderUser($date, $pointSale);
  524. return $this->buildJsonAjaxInfos($date, $producer, $pointSale, $user, $order);
  525. }
  526. public function buildJsonAjaxInfos(
  527. string $date,
  528. Producer $producer,
  529. PointSale $pointSale = null,
  530. User $user = null,
  531. Order $order = null
  532. )
  533. {
  534. $orderModule = $this->getOrderModule();
  535. $json = [];
  536. $format = 'Y-m-d';
  537. $dateObject = DateTime::createFromFormat($format, $date);
  538. $json['producer'] = $this->ajaxInfosProducer($producer);
  539. $json['distributions'] = $this->ajaxInfosDistributions($producer, $pointSale);
  540. $json['orders'] = $this->ajaxInfosOrders($producer);
  541. $json['user'] = $this->ajaxInfosUser($producer);
  542. $json['points_sale'] = $this->ajaxInfosPointsSale($producer);
  543. if ($dateObject && $dateObject->format($format) === $date) {
  544. $distribution = $this-> getDistributionModule()->createDistributionIfNotExist($date);
  545. $json['distribution'] = $distribution;
  546. $json['points_sale'] = $this->ajaxInfosPointsSale($producer, $distribution);
  547. $json['categories'] = $this->ajaxInfosProductCategories($producer);
  548. $json['products'] = $this->ajaxInfosProducts($producer, $distribution, $pointSale, $user, $order);
  549. if ($order) {
  550. $json['order'] = array_merge($order->getAttributes(), [
  551. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  552. 'amount_paid' => $orderModule->getOrderAmountPaidByCredit($order),
  553. ]);
  554. }
  555. }
  556. return $json;
  557. }
  558. public function ajaxInfosProducer(Producer $producer)
  559. {
  560. return [
  561. 'order_infos' => nl2br($producer->order_infos),
  562. 'payment_infos' => nl2br($producer->option_payment_info),
  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. 'has_specific_delays' => $this->getProducerModule()->getSolver()->hasSpecificDelays($producer)
  573. ];
  574. }
  575. public function ajaxInfosDistributions(Producer $producer, PointSale $pointSaleCurrent = null)
  576. {
  577. $distributionModule = $this-> getDistributionModule();
  578. $dateMini = date('Y-m-d');
  579. $distributionsArray = Distribution::searchAll([
  580. 'active' => 1,
  581. 'id_producer' => $producer->id
  582. ], [
  583. 'conditions' => ['date > :date'],
  584. 'params' => [':date' => $dateMini],
  585. 'join_with' => ['pointSaleDistribution'],
  586. ]);
  587. $distributionsArray = $distributionModule->filterDistributionsByDateDelay($distributionsArray);
  588. // Filtre par point de vente
  589. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  590. $distributionsArrayFilterPointSale = [];
  591. for ($i = 0; $i < count($distributionsArray); $i++) {
  592. $distribution = $distributionsArray[$i];
  593. if ($distributionModule->isPointSaleActive($distribution, $pointSaleCurrent)) {
  594. $countOrders = Order::searchCount([
  595. 'id_distribution' => $distribution->id,
  596. 'id_point_sale' => $pointSaleCurrent->id
  597. ]);
  598. $orderUserPointSale = $this->getOrderUser($distribution->date, $pointSaleCurrent);
  599. if (!$pointSaleCurrent->maximum_number_orders
  600. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleCurrent->id)
  601. || ($pointSaleCurrent->maximum_number_orders &&
  602. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  603. $distributionsArrayFilterPointSale[] = $distribution;
  604. }
  605. }
  606. }
  607. return $distributionsArrayFilterPointSale;
  608. } else {
  609. return $distributionsArray;
  610. }
  611. }
  612. public function ajaxInfosOrders(Producer $producer, PointSale $pointSaleCurrent = null): array
  613. {
  614. $producerModule = $this->getProducerModule();
  615. $orderModule = $this->getOrderModule();
  616. $dateMini = date('Y-m-d');
  617. $ordersUserArray = [];
  618. if (GlobalParam::getCurrentUserId()) {
  619. $conditionsOrdersUser = [
  620. 'distribution.date > :date',
  621. 'order.online_payment_url IS NULL'
  622. ];
  623. $paramsOrdersUser = [
  624. ':date' => $dateMini
  625. ];
  626. if ($pointSaleCurrent && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  627. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  628. $paramsOrdersUser[':id_point_sale'] = $pointSaleCurrent->id;
  629. }
  630. $ordersUserArray = Order::searchAll([
  631. 'id_user' => GlobalParam::getCurrentUserId()
  632. ], [
  633. 'conditions' => $conditionsOrdersUser,
  634. 'params' => $paramsOrdersUser
  635. ]);
  636. }
  637. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  638. foreach ($ordersUserArray as &$order) {
  639. $orderModule->initOrder($order);
  640. $order = array_merge($order->getAttributes(), [
  641. 'amount_total' => $orderModule->getOrderAmountWithTax($order, Order::AMOUNT_TOTAL),
  642. 'date_distribution' => $order->distribution->date,
  643. 'pointSale' => $order->pointSale->getAttributes()
  644. ]);
  645. }
  646. }
  647. return $ordersUserArray;
  648. }
  649. public function ajaxInfosUser(Producer $producer)
  650. {
  651. $userProducerModule = $this->getUserProducerModule();
  652. $producerModule = $this->getProducerModule();
  653. $user = GlobalParam::getCurrentUser();
  654. if($user) {
  655. $userProducer = $userProducerModule->findOneUserProducer($user);
  656. if (!$userProducer) {
  657. $userProducer = $producerModule->addUser($user, $producer);
  658. }
  659. }
  660. $jsonUser = false;
  661. if ($user && $userProducer) {
  662. $jsonUser = [
  663. 'address' => $user->address,
  664. 'credit' => $userProducer->credit,
  665. 'credit_active' => $userProducer->credit_active,
  666. ];
  667. }
  668. return $jsonUser;
  669. }
  670. private function ajaxInfosPointsSale($producer, $distribution = false)
  671. {
  672. $pointSaleModule = $this->getPointSaleModule();
  673. $producerModule = $this->getProducerModule();
  674. $orderModule = $this->getOrderModule();
  675. $user = GlobalParam::getCurrentUser();
  676. $pointsSaleArray = PointSale::find();
  677. if ($distribution) {
  678. $pointsSaleArray = $pointsSaleArray->joinWith([
  679. 'pointSaleDistribution' => function ($query) use (
  680. $distribution
  681. ) {
  682. $query->where(
  683. [
  684. 'id_distribution' => $distribution->id,
  685. 'delivery' => 1
  686. ]
  687. );
  688. }
  689. ]);
  690. }
  691. if (GlobalParam::getCurrentUserId()) {
  692. $pointsSaleArray = $pointsSaleArray->with([
  693. 'userPointSale' => function ($query) {
  694. $query->onCondition(
  695. ['id_user' => GlobalParam::getCurrentUserId()]
  696. );
  697. }
  698. ]);
  699. }
  700. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $producer->id])
  701. ->andWhere(
  702. '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))'
  703. )
  704. ->params([':id_user' => GlobalParam::getCurrentUserId()])
  705. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, `default` DESC, name ASC')
  706. ->all();
  707. $creditFunctioningProducer = $producerModule->getConfig('credit_functioning');
  708. $position = 0;
  709. foreach ($pointsSaleArray as &$pointSale) {
  710. $pointSaleObject = $pointSale;
  711. $pointSale = array_merge($pointSale->getAttributes(), [
  712. 'pointSaleDistribution' => [
  713. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  714. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  715. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  716. ],
  717. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  718. ]);
  719. if ($pointSale['code'] && strlen($pointSale['code'])) {
  720. $pointSale['code'] = '***';
  721. }
  722. if (!strlen($pointSale['credit_functioning'])) {
  723. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  724. }
  725. if ($distribution) {
  726. $pointSale['count_orders'] = (int)Order::searchCount([
  727. 'id_distribution' => $distribution->id,
  728. 'id_point_sale' => $pointSale['id']
  729. ]);
  730. $pointSale['infos'] = $pointSaleModule->getStrInfos($pointSaleObject, strtolower(date('l', strtotime($distribution->date))));
  731. }
  732. $pointSale['position'] = $position;
  733. $position++;
  734. }
  735. $favoritePointSale = false;
  736. if ($user) {
  737. $favoritePointSale = $orderModule->getUserFavoritePointSale($user);
  738. }
  739. if ($favoritePointSale) {
  740. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  741. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  742. $theFavoritePointSale = $pointsSaleArray[$i];
  743. unset($pointsSaleArray[$i]);
  744. }
  745. }
  746. if (isset($theFavoritePointSale)) {
  747. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  748. $pointsSaleArray[] = $theFavoritePointSale;
  749. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  750. }
  751. }
  752. return $pointsSaleArray;
  753. }
  754. public function ajaxInfosProductCategories(Producer $producer)
  755. {
  756. $categoriesArray = $this->getProductCategoryModule()->findProductCategoriesAsArray();
  757. $countProductsWithoutCategory = $this->getProductModule()->countProductsWithoutCategory($producer);
  758. if ($countProductsWithoutCategory) {
  759. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  760. }
  761. return $categoriesArray;
  762. }
  763. public function ajaxInfosProducts(
  764. Producer $producer,
  765. Distribution $distribution,
  766. PointSale $pointSale = null,
  767. User $user = null,
  768. Order $order = null
  769. )
  770. {
  771. $unitModule = $this->getUnitModule();
  772. $productModule = $this->getProductModule();
  773. $orderModule = $this->getOrderModule();
  774. $ordersArray = $this->getOrderModule()->findOrdersByDistribution($distribution);
  775. $productsArray = Product::find()
  776. ->where([
  777. 'id_producer' => $producer->id,
  778. 'product.status' => 1,
  779. ]);
  780. $productsArray = $productsArray->joinWith([
  781. 'productDistribution' => function ($query) use (
  782. $distribution
  783. ) {
  784. $query->andOnCondition(
  785. 'product_distribution.id_distribution = ' . $distribution->id
  786. );
  787. },
  788. 'productPrice'
  789. ])
  790. ->orderBy('product_distribution.active DESC, order ASC')
  791. ->all();
  792. $productsArrayFilter = $productModule->filterProductsByPointSale($productsArray, $pointSale);
  793. $indexProduct = 0;
  794. foreach ($productsArrayFilter as $key => &$product) {
  795. $productObject = $product;
  796. $product = array_merge(
  797. $product->getAttributes(),
  798. [
  799. 'unit_coefficient' => Product::$unitsArray[$product->unit]['coefficient'],
  800. 'prices' => $productModule->getPriceArray($product, $user, $pointSale),
  801. 'price_unit_ref' => $productModule->getSolver()->getPriceUnitReferenceWithTax($product),
  802. 'productDistribution' => $product['productDistribution'],
  803. 'productPointSale' => $product['productPointSale'],
  804. ]
  805. );
  806. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  807. if (is_null($product['photo']) || strlen($product['photo']) == 0) {
  808. $product['photo'] = '';
  809. }
  810. else {
  811. $product['photo_big'] = Image::getThumbnailBig($product['photo']);
  812. $product['photo'] = Image::getThumbnailSmall($product['photo']);
  813. }
  814. $product['quantity_max'] = (isset($product['productDistribution']) && isset($product['productDistribution'][0])) ? $product['productDistribution'][0]['quantity_max'] : null;
  815. $quantityOrder = $orderModule->getProductQuantity($productObject, $ordersArray);
  816. $product['quantity_ordered'] = $quantityOrder;
  817. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  818. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_UNIT, true);
  819. $product['wording_unit_ref'] = $unitModule->getSolver()->strUnit($product['unit'], UnitDefinition::WORDING_SHORT, true);
  820. if ($order) {
  821. $quantityOrderUser = $orderModule->getProductQuantity($productObject, [$order], true);
  822. $product['quantity_ordered'] = $quantityOrder;
  823. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  824. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  825. foreach ($order->productOrder as $productOrder) {
  826. if ($productOrder->id_product == $product['id']) {
  827. $product['wording_unit'] = $productModule->getSolver()->strUnit($productOrder->product, 'wording_unit', true);
  828. $product['step'] = $productOrder->step;
  829. }
  830. }
  831. } else {
  832. $product['quantity_form'] = 0;
  833. $product['wording_unit'] = $unitModule->getSolver()->strUnit($product['unit'], 'wording_unit', true);
  834. }
  835. $product['coefficient_unit'] = $coefficient_unit;
  836. if ($product['quantity_remaining'] < 0) {
  837. $product['quantity_remaining'] = 0;
  838. }
  839. $product['index'] = $indexProduct++;
  840. }
  841. return $productsArrayFilter;
  842. }
  843. private function getOrderUser(string $date, PointSale $pointSale = null)
  844. {
  845. $orderModule = $this->getOrderModule();
  846. $orderUser = null;
  847. if (GlobalParam::getCurrentUserId()) {
  848. $conditionOrderUser = [
  849. 'distribution.date' => $date,
  850. 'id_user' => GlobalParam::getCurrentUserId(),
  851. ];
  852. if ($pointSale) {
  853. $conditionOrderUser['id_point_sale'] = $pointSale;
  854. }
  855. $orderUser = Order::searchOne($conditionOrderUser);
  856. if ($orderUser && $orderUser->online_payment_url) {
  857. $orderUser = null;
  858. }
  859. }
  860. if($orderUser) {
  861. $orderModule->initOrder($orderUser);
  862. }
  863. return $orderUser;
  864. }
  865. }