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

OrderController.php 42KB

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