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

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