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

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