You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

OrderController.php 40KB

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