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

OrderController.php 38KB

пре 6 година
пре 3 година
пре 6 година
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818
  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. $user = User::searchOne([
  180. 'email' => $posts['user']['email']
  181. ]) ;
  182. if($user) {
  183. $producer->addUser($user->id, $idProducer) ;
  184. }
  185. if(!$user) {
  186. $user = new User ;
  187. $user->id_producer = 0;
  188. $password = Password::generate() ;
  189. //$password = $posts['user']['password'] ;
  190. $user->setPassword($password);
  191. $user->generateAuthKey();
  192. $user->username = $posts['user']['email'];
  193. $user->email = $posts['user']['email'];
  194. $user->name = $posts['user']['firstname'];
  195. $user->lastname = $posts['user']['lastname'];
  196. $user->phone = $posts['user']['phone'];
  197. $user->save() ;
  198. // liaison producer / user
  199. $producer->addUser($user->id, $idProducer) ;
  200. // mail bienvenue
  201. $user->sendMailWelcome($password);
  202. }
  203. else {
  204. $producer->addUser($user->id, $idProducer) ;
  205. }
  206. }
  207. $order = new Order;
  208. $order->load(Yii::$app->request->post());
  209. $order->id_user = $user ? $user->id : null;
  210. $order->status = 'tmp-order';
  211. $order->date = date('Y-m-d H:i:s');
  212. $order->origin = Order::ORIGIN_USER;
  213. }
  214. $errors = $this->processForm($order, $user);
  215. if (count($errors)) {
  216. return ['status' => 'error', 'errors' => $errors];
  217. }
  218. }
  219. return ['status' => 'success', 'idOrder' => $order->id];
  220. }
  221. /**
  222. * Vérifie si un producteur est actif.
  223. *
  224. * @param integer $idProducer
  225. * @throws NotFoundHttpException
  226. */
  227. public function _verifyProducerActive($idProducer)
  228. {
  229. $producer = Producer::findOne($idProducer);
  230. if ($producer && !$producer->active) {
  231. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  232. }
  233. }
  234. /**
  235. * Traite le formulaire de création/modification de commande.
  236. *
  237. * @param Commande $order
  238. */
  239. public function processForm($order, $user)
  240. {
  241. $posts = Yii::$app->request->post();
  242. $productsArray = [];
  243. $totalQuantity = 0;
  244. $producer = $this->getProducer();
  245. $isNewOrder = false ;
  246. if(!$order->id) {
  247. $isNewOrder = true ;
  248. }
  249. foreach ($posts['products'] as $key => $quantity) {
  250. $product = Product::find()->where(['id' => (int)$key])->one();
  251. $totalQuantity += $quantity;
  252. if ($product && $quantity) {
  253. $productsArray[] = $product;
  254. }
  255. }
  256. // date
  257. $errorDate = false;
  258. if (isset($order->id_distribution)) {
  259. // date de commande
  260. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  261. if ($order->getState() != Order::STATE_OPEN) {
  262. $errorDate = true;
  263. }
  264. }
  265. // point de vente
  266. $errorPointSale = false;
  267. if (isset($distribution) && $distribution) {
  268. $pointSaleDistribution = PointSaleDistribution::searchOne([
  269. 'id_distribution' => $distribution->id,
  270. 'id_point_sale' => $posts['Order']['id_point_sale']
  271. ]);
  272. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  273. $errorPointSale = true;
  274. }
  275. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  276. if ($pointSale) {
  277. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  278. $errorPointSale = true;
  279. }
  280. } else {
  281. $errorPointSale = true;
  282. }
  283. $userPointSale = UserPointSale::searchOne([
  284. 'id_user' => User::getCurrentId(),
  285. 'id_point_sale' => $pointSale->id
  286. ]);
  287. if ($pointSale->restricted_access && !$userPointSale) {
  288. $errorPointSale = true;
  289. }
  290. }
  291. $errors = [];
  292. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  293. $userProducer = UserProducer::searchOne([
  294. 'id_producer' => $order->distribution->id_producer,
  295. 'id_user' => $user->id
  296. ]);
  297. // gestion point de vente
  298. $pointSale = PointSale::searchOne([
  299. 'id' => $order->id_point_sale
  300. ]);
  301. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  302. $pointSale->getComment() : '';
  303. // la commande est automatiquement réactivée lors d'une modification
  304. $order->date_delete = null;
  305. // sauvegarde de la commande
  306. $order->save();
  307. $order->changeOrderStatus('new-order', 'user');
  308. // ajout de l'utilisateur à l'établissement
  309. Producer::addUser($user->id, $distribution->id_producer);
  310. // suppression de tous les enregistrements ProductOrder
  311. if (!is_null($order)) {
  312. ProductOrder::deleteAll(['id_order' => $order->id]);
  313. $stepsArray = [];
  314. if (isset($order->productOrder)) {
  315. foreach ($order->productOrder as $productOrder) {
  316. $unitsArray[$productOrder->id_product] = $productOrder->unit;
  317. }
  318. }
  319. }
  320. // produits dispos
  321. $availableProducts = ProductDistribution::searchByDistribution($distribution->id);
  322. // sauvegarde des produits
  323. foreach ($productsArray as $product) {
  324. if (isset($availableProducts[$product->id])) {
  325. $productOrder = new ProductOrder();
  326. $productOrder->id_order = $order->id;
  327. $productOrder->id_product = $product->id;
  328. $productOrder->price = $product->getPrice([
  329. 'user' => User::getCurrent(),
  330. 'user_producer' => $userProducer,
  331. 'point_sale' => $pointSale
  332. ]);
  333. $productOrder->id_tax_rate = $product->taxRate->id;
  334. $unit = (!is_null($order) && isset($unitsArray[$product->id])) ? $unitsArray[$product->id] : $product->unit;
  335. $coefficient = Product::$unitsArray[$unit]['coefficient'];
  336. $quantity = ((float)$posts['products'][$product->id]) / $coefficient;
  337. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  338. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  339. }
  340. $productOrder->quantity = $quantity;
  341. $productOrder->unit = $product->unit;
  342. $productOrder->step = $product->step;
  343. $productOrder->save();
  344. }
  345. }
  346. // lien utilisateur / point de vente
  347. $pointSale->linkUser($user->id);
  348. // credit
  349. $credit = Producer::getConfig('credit');
  350. $creditLimit = Producer::getConfig('credit_limit');
  351. $creditFunctioning = $pointSale->getCreditFunctioning();
  352. $creditUser = $user->getCredit($distribution->id_producer);
  353. $order = Order::searchOne([
  354. 'id' => $order->id
  355. ]);
  356. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  357. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING);
  358. if ($credit && $pointSale->credit &&
  359. (($creditFunctioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  360. $creditFunctioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  361. ($creditFunctioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  362. )) {
  363. $order->changeOrderStatus('waiting-paiement-by-credit', 'user');
  364. // à payer
  365. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  366. if (!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  367. $amountRemaining = $creditUser - $creditLimit;
  368. }
  369. if ($amountRemaining > 0) {
  370. $order->saveCreditHistory(
  371. CreditHistory::TYPE_PAYMENT,
  372. $amountRemaining,
  373. $distribution->id_producer,
  374. User::getCurrentId(),
  375. User::getCurrentId()
  376. );
  377. $order->changeOrderStatus('paid-by-credit', 'user');
  378. }else{
  379. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  380. }
  381. }
  382. // surplus à rembourser
  383. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  384. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS);
  385. $order->saveCreditHistory(
  386. CreditHistory::TYPE_REFUND,
  387. $amountSurplus,
  388. $distribution->id_producer,
  389. User::getCurrentId(),
  390. User::getCurrentId()
  391. );
  392. }
  393. }
  394. else{
  395. $order->changeOrderStatus('waiting-paiement-on-delivery', 'user');
  396. }
  397. $paramsEmail = [
  398. 'from_email' => $producer->getEmailOpendistrib(),
  399. 'from_name' => $producer->name,
  400. 'to_email' => $user->email,
  401. 'to_name' => $user->getUsername(),
  402. 'subject' => '['.$producer->name.'] Confirmation de commande',
  403. 'content_view_text' => '@common/mail/orderConfirm-text.php',
  404. 'content_view_html' => '@common/mail/orderConfirm-html.php',
  405. 'content_params' => [
  406. 'order' => $order,
  407. 'pointSale' => $pointSale,
  408. 'distribution' => $distribution,
  409. 'user' => $user
  410. ]
  411. ] ;
  412. /*
  413. * Envoi email de confirmation
  414. */
  415. if($isNewOrder) {
  416. // au client
  417. if(Producer::getConfig('option_email_confirm')) {
  418. Mailjet::sendMail($paramsEmail);
  419. }
  420. // au producteur
  421. $contactProducer = $producer->getMainContact() ;
  422. if(Producer::getConfig('option_email_confirm_producer') && $contactProducer && strlen($contactProducer->email)) {
  423. $paramsEmail['to_email'] = $contactProducer->email ;
  424. $paramsEmail['to_name'] = $contactProducer->name ;
  425. $paramsEmail['content_view_text'] = '@common/mail/orderConfirmProducer-text.php' ;
  426. $paramsEmail['content_view_html'] = '@common/mail/orderConfirmProducer-html.php' ;
  427. Mailjet::sendMail($paramsEmail);
  428. }
  429. }
  430. $order->setTillerSynchronization() ;
  431. $order->initReference() ;
  432. }
  433. if (!count($productsArray)) {
  434. $errors[] = "Vous n'avez choisi aucun produit";
  435. }
  436. if ($errorDate) {
  437. $errors[] = "Vous ne pouvez pas commander pour cette date.";
  438. }
  439. if ($errorPointSale) {
  440. $errors[] = "Point de vente invalide.";
  441. }
  442. return $errors;
  443. }
  444. /**
  445. * Annule une commande.
  446. *
  447. * @param integer $id
  448. * @throws \yii\web\NotFoundHttpException
  449. * @throws UserException
  450. */
  451. public function actionCancel($id)
  452. {
  453. $order = Order::searchOne([
  454. 'id' => $id
  455. ]);
  456. if (!$order) {
  457. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  458. }
  459. if ($order->getState() != Order::STATE_OPEN) {
  460. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  461. }
  462. if ($order && User::getCurrentId() == $order->id_user) {
  463. $order->delete();
  464. Yii::$app->session->setFlash('success', 'Votre commande a bien été annulée.');
  465. }
  466. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  467. }
  468. /**
  469. * Vérifie le code saisi pour un point de vente.
  470. *
  471. * @param integer $idPointSale
  472. * @param string $code
  473. * @return boolean
  474. */
  475. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  476. {
  477. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  478. $pointSale = PointSale::findOne($idPointSale);
  479. if ($pointSale) {
  480. if ($pointSale->validateCode($code)) {
  481. return 1;
  482. }
  483. }
  484. return 0;
  485. }
  486. public function actionAjaxInfos($date = '', $pointSaleId = 0)
  487. {
  488. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  489. $json = [];
  490. $format = 'Y-m-d';
  491. $dateObject = DateTime::createFromFormat($format, $date);
  492. // PointSale current
  493. $pointSaleCurrent = PointSale::findOne($pointSaleId) ;
  494. // Producteur
  495. $producer = Producer::searchOne([
  496. 'id' => $this->getProducer()->id
  497. ]);
  498. $json['producer'] = [
  499. 'order_infos' => $producer->order_infos,
  500. 'credit' => $producer->credit,
  501. 'credit_functioning' => $producer->credit_functioning,
  502. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  503. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null,
  504. 'option_allow_order_guest' => $producer->option_allow_order_guest,
  505. ];
  506. // Distributions
  507. $dateMini = date('Y-m-d') ;
  508. $distributionsArray = Distribution::searchAll([
  509. 'active' => 1
  510. 'id_producer' => $producer->id
  511. ], [
  512. 'conditions' => ['date > :date'],
  513. 'params' => [':date' => $dateMini],
  514. ]);
  515. $distributionsArray = Distribution::filterDistributionsByDateDelay($distributionsArray) ;
  516. $json['distributions'] = $distributionsArray;
  517. // Commandes de l'utilisateur
  518. $ordersUserArray = [] ;
  519. if(User::getCurrentId()) {
  520. $ordersUserArray = Order::searchAll([
  521. 'id_user' => User::getCurrentId()
  522. ], [
  523. 'conditions' => [
  524. 'distribution.date > :date'
  525. ],
  526. 'params' => [
  527. ':date' => $dateMini
  528. ]
  529. ]);
  530. }
  531. if (is_array($ordersUserArray) && count($ordersUserArray)) {
  532. foreach ($ordersUserArray as &$order) {
  533. $order = array_merge($order->getAttributes(), [
  534. 'amount_total' => $order->getAmountWithTax(Order::AMOUNT_TOTAL),
  535. 'date_distribution' => $order->distribution->date,
  536. 'pointSale' => $order->pointSale->getAttributes()
  537. ]);
  538. }
  539. $json['orders'] = $ordersUserArray;
  540. }
  541. // User
  542. $userProducer = UserProducer::searchOne([
  543. 'id_producer' => $producer->id,
  544. 'id_user' => User::getCurrentId()
  545. ]);
  546. $json['user'] = false ;
  547. if($userProducer) {
  548. $json['user'] = [
  549. 'credit' => $userProducer->credit,
  550. 'credit_active' => $userProducer->credit_active,
  551. ];
  552. }
  553. if ($dateObject && $dateObject->format($format) === $date) {
  554. // Commande de l'utilisateur
  555. $orderUser = false ;
  556. if(User::getCurrentId()) {
  557. $orderUser = Order::searchOne([
  558. 'distribution.date' => $date,
  559. 'id_user' => User::getCurrentId(),
  560. ]);
  561. }
  562. if ($orderUser) {
  563. $json['order'] = array_merge($orderUser->getAttributes(), [
  564. 'amount_total' => $orderUser->getAmountWithTax(Order::AMOUNT_TOTAL),
  565. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  566. ]);
  567. }
  568. // distribution
  569. $distribution = Distribution::initDistribution($date);
  570. $json['distribution'] = $distribution;
  571. $pointsSaleArray = PointSale::find()
  572. ->joinWith(['pointSaleDistribution' => function ($query) use ($distribution) {
  573. $query->where(['id_distribution' => $distribution->id]);
  574. }
  575. ])
  576. ->with(['userPointSale' => function ($query) {
  577. $query->onCondition(['id_user' => User::getCurrentId()]);
  578. }])
  579. ->where(['id_producer' => $distribution->id_producer])
  580. ->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)')
  581. ->params([':id_user' => User::getCurrentId()])
  582. ->all();
  583. $creditFunctioningProducer = Producer::getConfig('credit_functioning');
  584. foreach ($pointsSaleArray as &$pointSale) {
  585. $pointSale = array_merge($pointSale->getAttributes(), [
  586. 'pointSaleDistribution' => [
  587. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  588. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  589. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  590. ],
  591. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  592. ]);
  593. if ($pointSale['code'] && strlen($pointSale['code'])) {
  594. $pointSale['code'] = '***';
  595. }
  596. if (!strlen($pointSale['credit_functioning'])) {
  597. $pointSale['credit_functioning'] = $creditFunctioningProducer;
  598. }
  599. }
  600. $favoritePointSale = false ;
  601. if(User::getCurrent()) {
  602. $favoritePointSale = User::getCurrent()->getFavoritePointSale();
  603. }
  604. if ($favoritePointSale) {
  605. for ($i = 0; $i < count($pointsSaleArray); $i++) {
  606. if ($pointsSaleArray[$i]['id'] == $favoritePointSale->id) {
  607. $theFavoritePointSale = $pointsSaleArray[$i];
  608. unset($pointsSaleArray[$i]);
  609. }
  610. }
  611. if (isset($theFavoritePointSale)) {
  612. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  613. $pointsSaleArray[] = $theFavoritePointSale;
  614. $pointsSaleArray = array_reverse($pointsSaleArray, false);
  615. }
  616. }
  617. $json['points_sale'] = $pointsSaleArray;
  618. // Commandes totales
  619. $ordersArray = Order::searchAll([
  620. 'distribution.date' => $date,
  621. ]);
  622. // Catégories
  623. $categoriesArray = ProductCategory::searchAll([], ['orderby' => 'product_category.position ASC', 'as_array' => true]) ;
  624. array_unshift($categoriesArray, ['id' => null, 'name' => 'Catégorie par défaut']) ;
  625. $json['categories'] = $categoriesArray ;
  626. // Produits
  627. $productsArray = Product::find()
  628. ->where([
  629. 'id_producer' => $this->getProducer()->id,
  630. 'product.active' => 1,
  631. ]);
  632. $productsArray = $productsArray->joinWith(['productDistribution' => function ($query) use ($distribution) {
  633. $query->andOnCondition('product_distribution.id_distribution = ' . $distribution->id);
  634. }, 'productPrice'])
  635. ->orderBy('product_distribution.active DESC, order ASC')
  636. ->all();
  637. $indexProduct = 0;
  638. foreach ($productsArray as &$product) {
  639. $product = array_merge(
  640. $product->getAttributes(),
  641. [
  642. 'price_with_tax' => $product->getPriceWithTax([
  643. 'user' => User::getCurrent(),
  644. 'user_producer' => $userProducer,
  645. 'point_sale' => $pointSaleCurrent
  646. ]),
  647. 'productDistribution' => $product['productDistribution']
  648. ]
  649. );
  650. $coefficient_unit = Product::$unitsArray[$product['unit']]['coefficient'];
  651. if (is_null($product['photo'])) {
  652. $product['photo'] = '';
  653. }
  654. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'];
  655. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray);
  656. $product['quantity_ordered'] = $quantityOrder;
  657. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder;
  658. if ($orderUser) {
  659. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true);
  660. $product['quantity_ordered'] = $quantityOrder;
  661. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser;
  662. $product['quantity_form'] = $quantityOrderUser * $coefficient_unit;
  663. foreach ($orderUser->productOrder as $productOrder) {
  664. if ($productOrder->id_product == $product['id']) {
  665. $product['wording_unit'] = Product::strUnit($productOrder->unit, 'wording_unit', true);
  666. $product['step'] = $productOrder->step;
  667. }
  668. }
  669. } else {
  670. $product['quantity_form'] = 0;
  671. $product['wording_unit'] = Product::strUnit($product['unit'], 'wording_unit', true);
  672. }
  673. $product['coefficient_unit'] = $coefficient_unit;
  674. if ($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0;
  675. $product['index'] = $indexProduct++;
  676. }
  677. $json['products'] = $productsArray;
  678. }
  679. return $json;
  680. }
  681. public function actionConfirm($idOrder)
  682. {
  683. $order = Order::searchOne(['id' => $idOrder]);
  684. $producer = $this->getProducer() ;
  685. if (!$order || ($order->id_user != User::getCurrentId() && !$producer->option_allow_order_guest)) {
  686. throw new \yii\base\UserException('Commande introuvable.');
  687. }
  688. return $this->render('confirm', [
  689. 'order' => $order
  690. ]);
  691. }
  692. }