OrderController.php 44KB

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