Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

OrderController.php 42KB

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