Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

5 місяці тому
5 роки тому
5 місяці тому
1 рік тому
5 місяці тому
5 місяці тому
1 рік тому
3 роки тому
1 рік тому
1 рік тому
1 рік тому
5 місяці тому
1 рік тому
1 рік тому
1 рік тому
1 рік тому
8 місяці тому
7 місяці тому
7 місяці тому
5 місяці тому
1 рік тому
1 рік тому
1 рік тому
1 рік тому
1 рік тому
5 місяці тому
5 місяці тому
1 рік тому
1 рік тому
10 місяці тому
1 рік тому
1 рік тому
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071
  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(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. }