Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

OrderController.php 45KB

6 лет назад
3 лет назад
3 лет назад
3 лет назад
3 лет назад
6 лет назад
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031
  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->price = $product->getPrice([
  405. 'user' => User::getCurrent(),
  406. 'user_producer' => $userProducer,
  407. 'point_sale' => $pointSale
  408. ]);
  409. $productOrder->id_tax_rate = $product->taxRate->id;
  410. $unit = (!is_null(
  411. $order
  412. ) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  413. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  414. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  415. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  416. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  417. }
  418. $productOrder->quantity = $quantity;
  419. $productOrder->unit = $product->unit;
  420. $productOrder->step = $product->step;
  421. $productOrder->save();
  422. }
  423. }
  424. // lien utilisateur / point de vente
  425. $pointSale->linkUser($user->id);
  426. // credit
  427. $credit = Producer::getConfig('credit');
  428. $creditLimit = Producer::getConfig('credit_limit');
  429. $creditFunctioning = $pointSale->getCreditFunctioning();
  430. $creditUser = $user->getCredit($distribution->id_producer);
  431. $order = Order::searchOne([
  432. 'id' => $order->id
  433. ]);
  434. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  435. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  436. if ($credit && $pointSale->credit &&
  437. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  438. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  439. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  440. )) {
  441. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  442. // à payer
  443. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  444. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  445. $amountRemaining = $creditUser - $creditLimit;
  446. }
  447. if ($amountRemaining > 0) {
  448. $order->saveCreditHistory(
  449. CreditHistory::TYPE_PAYMENT,
  450. $amountRemaining,
  451. $distribution->id_producer,
  452. User::getCurrentId(),
  453. User::getCurrentId()
  454. );
  455. $order->changeOrderStatus('paid-by-credit', 'user');
  456. } else {
  457. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  458. }
  459. } // surplus à rembourser
  460. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  461. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  462. $order->saveCreditHistory(
  463. CreditHistory::TYPE_REFUND,
  464. $amountSurplus,
  465. $distribution->id_producer,
  466. User::getCurrentId(),
  467. User::getCurrentId()
  468. );
  469. }
  470. } else {
  471. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  472. }
  473. $paramsEmail = [
  474. 'from_email' => $producer->getEmailOpendistrib(),
  475. 'from_name' => $producer->name,
  476. 'to_email' => $user->email,
  477. 'to_name' => $user->getUsername(),
  478. 'subject' => '[' . $producer->name . '] Confirmation de commande',
  479. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  480. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  481. 'content_params' => [
  482. 'order' => $order,
  483. 'pointSale' => $pointSale,
  484. 'distribution' => $distribution,
  485. 'user' => $user,
  486. 'producer' => $producer
  487. ]
  488. ];
  489. /*
  490. * Envoi email de confirmation
  491. */
  492. if ($isNewOrder) {
  493. // au client
  494. if (Producer::getConfig('option_email_confirm')) {
  495. Mailjet::sendMail($paramsEmail);
  496. }
  497. // au producteur
  498. $contactProducer = $producer->getMainContact();
  499. if (Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen(
  500. $contactProducer->email
  501. )) {
  502. $paramsEmail['to_email'] = $contactProducer->email;
  503. $paramsEmail['to_name'] = $contactProducer->name;
  504. $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php';
  505. $paramsEmail['content_view_html'] = '@common/mail/orderConfirmProducer-html.php';
  506. Mailjet::sendMail($paramsEmail);
  507. }
  508. }
  509. $order->setTillerSynchronization();
  510. }
  511. if (!count($productsArray)) {
  512. $errors[] = "Vous n'avez choisi aucun produit";
  513. }
  514. if ($errorDate) {
  515. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  516. }
  517. if ($errorPointSale) {
  518. $errors[] = "Point de vente invalide.";
  519. }
  520. return $errors;
  521. }
  522. /**
  523. * Annule une commande.
  524. *
  525. * @param integer $id
  526. * @throws \yii\web\NotFoundHttpException
  527. * @throws UserException
  528. */
  529. public function actionCancel($id)
  530. {
  531. $order = Order::searchOne([
  532. 'id' => $id
  533. ]);
  534. if (!$order) {
  535. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  536. }
  537. if ($order->getState() != Order::STATE_OPEN) {
  538. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  539. }
  540. if ($order && User::getCurrentId() == $order->id_user) {
  541. $order->delete();
  542. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  543. }
  544. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  545. }
  546. /**
  547. * Vérifie le code saisi pour un point de vente.
  548. *
  549. * @param integer $idPointSale
  550. * @param string $code
  551. * @return boolean
  552. */
  553. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  554. {
  555. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  556. $pointSale = PointSale::findOne($idPointSale);
  557. if ($pointSale) {
  558. if ($pointSale->validateCode($code)) {
  559. return 1;
  560. }
  561. }
  562. return 0;
  563. }
  564. public function actionAjaxInfos($date = '', $pointSaleId = 0)
  565. {
  566. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  567. $json = [];
  568. $format = 'Y-m-d';
  569. $dateObject = DateTime::createFromFormat($format, $date);
  570. $user = User::getCurrent();
  571. // PointSale current
  572. $pointSaleCurrent = PointSale::findOne($pointSaleId);
  573. // Commande de l'utilisateur
  574. $orderUser = $this->_getOrderUser($date, $pointSaleId);
  575. // Producteur
  576. $producer = Producer::searchOne([
  577. 'id' => $this->getProducer()->id
  578. ]);
  579. $json['producer'] = [
  580. 'order_infos' => $producer->order_infos,
  581. 'credit' => $producer->credit,
  582. 'credit_functioning' => $producer->credit_functioning,
  583. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  584. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  585. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  586. 'option_order_entry_point' => $producer->option_order_entry_point,
  587. 'option_delivery' => $producer->option_delivery,
  588. 'online_payment' => $producer->online_payment,
  589. 'option_online_payment_type' => $producer->online_payment,
  590. ];
  591. // Distributions
  592. $dateMini = date('Y-m-d');
  593. $distributionsArray = Distribution::searchAll([
  594. 'active' => 1,
  595. 'id_producer' => $producer->id
  596. ], [
  597. 'conditions' => ['date > :date'],
  598. 'params' => [':date' => $dateMini],
  599. 'join_with' => ['pointSaleDistribution'],
  600. ]);
  601. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray);
  602. // Filtre par point de vente
  603. if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  604. $distributionsArrayFilterPointSale = [];
  605. for ($i = 0; $i < count($distributionsArray); $i++) {
  606. $distribution = $distributionsArray[$i];
  607. if (Distribution::isPointSaleActive($distribution, $pointSaleId)) {
  608. $countOrders = (int) Order::searchCount([
  609. 'id_distribution' => $distribution->id,
  610. 'id_point_sale' => $pointSaleId
  611. ]);
  612. $orderUserPointSale = $this->_getOrderUser($distribution->date, $pointSaleId);
  613. if(!$pointSaleCurrent->maximum_number_orders
  614. || ($orderUserPointSale && $orderUserPointSale->id_point_sale == $pointSaleId)
  615. || ($pointSaleCurrent->maximum_number_orders &&
  616. ($countOrders < $pointSaleCurrent->maximum_number_orders))) {
  617. $distributionsArrayFilterPointSale[] = $distribution;
  618. }
  619. }
  620. }
  621. $json['distributions'] = $distributionsArrayFilterPointSale;
  622. } else {
  623. $json['distributions'] = $distributionsArray;
  624. }
  625. // Commandes de l'utilisateur
  626. $ordersUserArray = [];
  627. if (User::getCurrentId() && !$producer->isOnlinePaymentActiveAndTypeOrder()) {
  628. $conditionsOrdersUser = [
  629. 'distribution.date > :date'
  630. ];
  631. $paramsOrdersUser = [
  632. ':date' => $dateMini
  633. ];
  634. if ($pointSaleId && $producer->option_order_entry_point == Producer::ORDER_ENTRY_POINT_POINT_SALE) {
  635. $conditionsOrdersUser[] = 'order.id_point_sale = :id_point_sale';
  636. $paramsOrdersUser[':id_point_sale'] = $pointSaleId;
  637. }
  638. $ordersUserArray = Order::searchAll([
  639. 'id_user' => User::getCurrentId()
  640. ], [
  641. 'conditions' => $conditionsOrdersUser,
  642. 'params' => $paramsOrdersUser
  643. ]);
  644. }
  645. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  646. foreach ($ordersUserArray as &$order) {
  647. $order = array_merge($order->getAttributes(), [
  648. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  649. 'date_distribution' => $order->distribution->date,
  650. 'pointSale' => $order->pointSale->getAttributes()
  651. ]);
  652. }
  653. $json['orders'] = $ordersUserArray;
  654. }
  655. // User
  656. $userProducer = UserProducer::searchOne([
  657. 'id_producer' => $producer->id,
  658. 'id_user' => User::getCurrentId()
  659. ]);
  660. $json['user'] = false;
  661. if ($userProducer) {
  662. $json['user'] = [
  663. 'address' => $user->address,
  664. 'credit' => $userProducer->credit,
  665. 'credit_active' => $userProducer->credit_active,
  666. ];
  667. }
  668. if ($dateObject && $dateObject->format($format) === $date) {
  669. // distribution
  670. $distribution = Distribution::initDistribution($date, $producer->id);
  671. $json['distribution'] = $distribution;
  672. // Points de vente
  673. $json['points_sale'] = $this->_initPointsSale($producer->id, $distribution);
  674. // Commandes totales
  675. $ordersArray = Order::searchAll([
  676. 'distribution.date' => $date,
  677. ]);
  678. // Catégories
  679. $categoriesArray = ProductCategory::searchAll(
  680. [],
  681. [
  682. 'orderby' => 'product_category.position ASC',
  683. 'as_array' => true
  684. ]
  685. );
  686. $countProductsWithoutCategories = Product::searchCount([
  687. 'id_producer' => $this->getProducer()->id,
  688. 'product.active' => 1,
  689. 'product.id_product_category' => null
  690. ]);
  691. if ($countProductsWithoutCategories) {
  692. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']);
  693. }
  694. $json['categories'] = $categoriesArray;
  695. // Produits
  696. $productsArray = Product::find()
  697. ->where([
  698. 'id_producer' => $this->getProducer()->id,
  699. 'product.active' => 1,
  700. ]);
  701. $productsArray = $productsArray->joinWith([
  702. 'productDistribution' => function ($query) use ($distribution) {
  703. $query->andOnCondition(
  704. 'product_distribution.id_distribution = ' . $distribution->id
  705. );
  706. },
  707. /*'productPointSale' => function ($query) use ($pointSaleCurrent) {
  708. $query->andOnCondition(
  709. 'product_point_sale.id_point_sale = ' . $pointSaleCurrent->id
  710. );
  711. },*/
  712. 'productPrice'
  713. ])
  714. ->orderBy('product_distribution.active DESC, order ASC')
  715. ->all();
  716. $productsArrayFilter = [];
  717. // filtre sur les points de vente
  718. foreach($productsArray as $product) {
  719. if($product->isAvailableOnPointSale($pointSaleCurrent)) {
  720. $productsArrayFilter[] = $product;
  721. }
  722. }
  723. $indexProduct = 0;
  724. foreach ($productsArrayFilter as $key => &$product) {
  725. $product = array_merge(
  726. $product->getAttributes(),
  727. [
  728. 'price_with_tax' => $product->getPriceWithTax([
  729. 'user' => User::getCurrent(),
  730. 'user_producer' => $userProducer,
  731. 'point_sale' => $pointSaleCurrent
  732. ]),
  733. 'productDistribution' => $product['productDistribution'],
  734. 'productPointSale' => $product['productPointSale'],
  735. ]
  736. );
  737. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  738. if (is_null($product['photo'])) {
  739. $product['photo'] = '';
  740. }
  741. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  742. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  743. $product['quantity_ordered'] = $quantityOrder;
  744. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  745. if ($orderUser) {
  746. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  747. $product['quantity_ordered'] = $quantityOrder;
  748. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  749. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  750. foreach ($orderUser->productOrder as $productOrder) {
  751. if ($productOrder->id_product == $product['id']) {
  752. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  753. $product['step'] = $productOrder->step;
  754. }
  755. }
  756. } else {
  757. $product['quantity_form'] = 0;
  758. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  759. }
  760. $product['coefficient_unit'] = $coefficient_unit;
  761. if ($product['quantity_remaining'] < 0) {
  762. $product['quantity_remaining'] = 0;
  763. }
  764. $product['index'] = $indexProduct++;
  765. }
  766. $json['products'] = $productsArrayFilter;
  767. } else {
  768. $json['points_sale'] = $this->_initPointsSale($producer->id);
  769. }
  770. return $json;
  771. }
  772. private function _getOrderUser($date, $pointSaleId = false) {
  773. $orderUser = false;
  774. if (User::getCurrentId()) {
  775. $conditionOrderUser = [
  776. 'distribution.date' => $date,
  777. 'id_user' => User::getCurrentId(),
  778. ];
  779. if ($pointSaleId) {
  780. $conditionOrderUser['id_point_sale'] = $pointSaleId;
  781. }
  782. $orderUser = Order::searchOne($conditionOrderUser);
  783. if ($orderUser && $orderUser->online_payment_url) {
  784. $orderUser = false;
  785. }
  786. }
  787. if ($orderUser) {
  788. $json['order'] = array_merge($orderUser->getAttributes(), [
  789. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  790. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  791. ]);
  792. }
  793. return $orderUser;
  794. }
  795. private function _initPointsSale($idProducer, $distribution = false)
  796. {
  797. $pointsSaleArray = PointSale::find();
  798. if ($distribution) {
  799. $pointsSaleArray = $pointsSaleArray->joinWith([
  800. 'pointSaleDistribution' => function ($query) use (
  801. $distribution
  802. ) {
  803. $query->where(
  804. [
  805. 'id_distribution' => $distribution->id,
  806. 'delivery' => 1
  807. ]
  808. );
  809. }
  810. ]);
  811. }
  812. if (User::getCurrentId()) {
  813. $pointsSaleArray = $pointsSaleArray->with([
  814. 'userPointSale' => function ($query) {
  815. $query->onCondition(
  816. ['id_user' => User::getCurrentId()]
  817. );
  818. }
  819. ]);
  820. }
  821. $pointsSaleArray = $pointsSaleArray->where(['id_producer' => $idProducer])
  822. ->andWhere(
  823. '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)'
  824. )
  825. ->params([':id_user' => User::getCurrentId()])
  826. ->orderBy('code ASC, restricted_access ASC, is_bread_box ASC, name ASC')
  827. ->all();
  828. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  829. $position = 0;
  830. foreach ($pointsSaleArray as &$pointSale) {
  831. $pointSale = array_merge($pointSale->getAttributes(), [
  832. 'pointSaleDistribution' => [
  833. 'id_distribution' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_distribution : false,
  834. 'id_point_sale' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->id_point_sale : false,
  835. 'delivery' => $pointSale->pointSaleDistribution ? $pointSale->pointSaleDistribution[0]->delivery : false,
  836. ],
  837. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  838. ]);
  839. if ($pointSale['code'] && strlen($pointSale['code'])) {
  840. $pointSale['code'] = '***';
  841. }
  842. if (!strlen($pointSale['credit_functioning'])) {
  843. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  844. }
  845. if ($distribution) {
  846. $pointSale['count_orders'] = (int) Order::searchCount([
  847. 'id_distribution' => $distribution->id,
  848. 'id_point_sale' => $pointSale['id']
  849. ]);
  850. }
  851. $pointSale['position'] = $position;
  852. $position ++;
  853. }
  854. $favoritePointSale = false;
  855. if (User::getCurrent()) {
  856. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  857. }
  858. if ($favoritePointSale) {
  859. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  860. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  861. $theFavoritePointSale = $pointsSaleArray[$i];
  862. unset($pointsSaleArray[$i]);
  863. }
  864. }
  865. if (isset($theFavoritePointSale)) {
  866. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  867. $pointsSaleArray[] = $theFavoritePointSale;
  868. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  869. }
  870. }
  871. return $pointsSaleArray;
  872. }
  873. public function actionConfirm($idOrder, $returnPayment = '')
  874. {
  875. $order = Order::searchOne(['id' => $idOrder]);
  876. $producer = $this->getProducer();
  877. if (!$order || ($order->id_user != User::getCurrentId() && !$producer->option_allow_order_guest)) {
  878. throw new \yii\base\UserException('Commande introuvable.');
  879. }
  880. return $this->render('confirm', [
  881. 'order' => $order,
  882. 'returnPayment' => $returnPayment
  883. ]);
  884. }
  885. }