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 43KB

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