Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

OrderController.php 23KB

pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
pirms 6 gadiem
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647
  1. <?php
  2. /**
  3. Copyright distrib (2018)
  4. contact@opendistrib.net
  5. Ce logiciel est un programme informatique servant à aider les producteurs
  6. à distribuer leur production en circuits courts.
  7. Ce logiciel est régi par la licence CeCILL soumise au droit français et
  8. respectant les principes de diffusion des logiciels libres. Vous pouvez
  9. utiliser, modifier et/ou redistribuer ce programme sous les conditions
  10. de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  11. sur le site "http://www.cecill.info".
  12. En contrepartie de l'accessibilité au code source et des droits de copie,
  13. de modification et de redistribution accordés par cette licence, il n'est
  14. offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  15. seule une responsabilité restreinte pèse sur l'auteur du programme, le
  16. titulaire des droits patrimoniaux et les concédants successifs.
  17. A cet égard l'attention de l'utilisateur est attirée sur les risques
  18. associés au chargement, à l'utilisation, à la modification et/ou au
  19. développement et à la reproduction du logiciel par l'utilisateur étant
  20. donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  21. manipuler et qui le réserve donc à des développeurs et des professionnels
  22. avertis possédant des connaissances informatiques approfondies. Les
  23. utilisateurs sont donc invités à charger et tester l'adéquation du
  24. logiciel à leurs besoins dans des conditions permettant d'assurer la
  25. sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  26. à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  27. Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  28. pris connaissance de la licence CeCILL, et que vous en avez accepté les
  29. termes.
  30. */
  31. namespace producer\controllers;
  32. use common\models\ProductDistribution ;
  33. use common\models\User ;
  34. use common\models\Producer ;
  35. use common\models\Order ;
  36. use common\models\UserPointSale ;
  37. use DateTime;
  38. class OrderController extends ProducerBaseController
  39. {
  40. var $enableCsrfValidation = false;
  41. public function behaviors()
  42. {
  43. return [
  44. 'access' => [
  45. 'class' => AccessControl::className(),
  46. 'rules' => [
  47. [
  48. 'allow' => true,
  49. 'roles' => ['@'],
  50. ]
  51. ],
  52. ],
  53. ];
  54. }
  55. public function actionOrder($id = 0, $date = '')
  56. {
  57. $params = [] ;
  58. if($id) {
  59. $order = Order::searchOne([
  60. 'id' => $id
  61. ]) ;
  62. if($order) {
  63. if($order->getState() == Order::STATE_OPEN) {
  64. $params['order'] = $order ;
  65. }
  66. }
  67. }
  68. if(strlen($date)) {
  69. $distribution = Distribution::searchOne([
  70. 'date' => $date,
  71. 'id_producer' => Producer::getId()
  72. ]) ;
  73. if($distribution) {
  74. $params['date'] = $date ;
  75. }
  76. }
  77. return $this->render('order', $params) ;
  78. }
  79. /**
  80. * Affiche l'historique des commandes de l'utilisateur
  81. *
  82. * @return ProducerView
  83. */
  84. public function actionHistory($type = 'incoming')
  85. {
  86. $query = Order::find()
  87. ->with('productOrder', 'pointSale', 'creditHistory')
  88. ->joinWith('distribution', 'distribution.producer')
  89. ->where([
  90. 'id_user' => Yii::$app->user->id,
  91. 'distribution.id_producer' => Producer::getId()
  92. ])
  93. ->params([':date_today' => date('Y-m-d')]);
  94. $queryIncoming = clone $query ;
  95. $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
  96. $queryPassed = clone $query ;
  97. $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');
  98. $dataProviderOrders = new ActiveDataProvider([
  99. 'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
  100. 'pagination' => [
  101. 'pageSize' => 10,
  102. ],
  103. ]);
  104. return $this->render('history', [
  105. 'dataProviderOrders' => $dataProviderOrders,
  106. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  107. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  108. 'type' => $type,
  109. 'countIncoming' => $queryIncoming->count(),
  110. 'countPassed' => $queryPassed->count(),
  111. ]);
  112. }
  113. /**
  114. * Supprime un producteur.
  115. *
  116. * @param integer $id
  117. */
  118. public function actionRemoveProducer($id = 0)
  119. {
  120. $userProducer = UserProducer::find()
  121. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  122. ->one();
  123. $userProducer->active = 0;
  124. $userProducer->save();
  125. $this->redirect(['order/index']);
  126. }
  127. /**
  128. * Crée une commande.
  129. *
  130. * @return mixed
  131. */
  132. public function actionAjaxProcess()
  133. {
  134. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  135. $order = new Order ;
  136. $idProducer = $this->getProducer()->id ;
  137. $posts = Yii::$app->request->post();
  138. if ($idProducer) {
  139. $this->_verifyProducerActive($idProducer);
  140. }
  141. if ($order->load($posts)) {
  142. $order = Order::find()
  143. ->where('id_distribution = :id_distribution')
  144. ->andWhere('id_user = :id_user')
  145. ->params([
  146. ':id_distribution' => $posts['Order']['id_distribution'],
  147. ':id_user' => User::getCurrentId()
  148. ])
  149. ->one();
  150. if (!$order) {
  151. $order = new Order;
  152. $order->load(Yii::$app->request->post());
  153. $order->id_user = User::getCurrentId();
  154. $order->date = date('Y-m-d H:i:s');
  155. $order->origin = Order::ORIGIN_USER;
  156. }
  157. $errors = $this->processForm($order);
  158. if(count($errors)) {
  159. return ['status' => 'error', 'errors' => $errors] ;
  160. }
  161. }
  162. return ['status' => 'success', 'idOrder' => $order->id] ;
  163. }
  164. /**
  165. * Vérifie si un producteur est actif.
  166. *
  167. * @param integer $idProducer
  168. * @throws NotFoundHttpException
  169. */
  170. public function _verifyProducerActive($idProducer)
  171. {
  172. $producer = Producer::findOne($idProducer);
  173. if ($producer && !$producer->active) {
  174. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  175. }
  176. }
  177. /**
  178. * Traite le formulaire de création/modification de commande.
  179. *
  180. * @param Commande $order
  181. */
  182. public function processForm($order)
  183. {
  184. $posts = Yii::$app->request->post();
  185. $productsArray = [];
  186. $totalQuantity = 0;
  187. $producer = $this->getProducer() ;
  188. foreach ($posts['products'] as $key => $quantity) {
  189. $product = Product::find()->where(['id' => (int) $key])->one();
  190. $totalQuantity += $quantity;
  191. if ($product && $quantity) {
  192. $productsArray[] = $product;
  193. }
  194. }
  195. // date
  196. $errorDate = false;
  197. if (isset($order->id_distribution)) {
  198. // date de commande
  199. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  200. $date = $this->getProducer()->getEarliestDateOrder() ;
  201. if($order->getState() != Order::STATE_OPEN) {
  202. $errorDate = true;
  203. }
  204. }
  205. // point de vente
  206. $errorPointSale = false;
  207. if (isset($distribution) && $distribution) {
  208. $pointSaleDistribution = PointSaleDistribution::searchOne([
  209. 'id_distribution' => $distribution->id,
  210. 'id_point_sale' => $posts['Order']['id_point_sale']
  211. ]) ;
  212. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  213. $errorPointSale = true;
  214. }
  215. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  216. if ($pointSale) {
  217. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  218. $errorPointSale = true;
  219. }
  220. } else {
  221. $errorPointSale = true;
  222. }
  223. $userPointSale = UserPointSale::searchOne([
  224. 'id_user' => User::getCurrentId(),
  225. 'id_point_sale' => $pointSale->id
  226. ]) ;
  227. if($pointSale->restricted_access && !$userPointSale) {
  228. $errorPointSale = true;
  229. }
  230. }
  231. $errors = [] ;
  232. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  233. $userProducer = UserProducer::searchOne([
  234. 'id_producer' => $order->distribution->id_producer,
  235. 'id_user' => User::getCurrentId()
  236. ]) ;
  237. // gestion point de vente
  238. $pointSale = PointSale::searchOne([
  239. 'id' => $order->id_point_sale
  240. ]) ;
  241. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  242. $pointSale->getComment() : '' ;
  243. // la commande est automatiquement réactivée lors d'une modification
  244. $order->date_delete = null ;
  245. // sauvegarde de la commande
  246. $order->save();
  247. // ajout de l'utilisateur à l'établissement
  248. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  249. // suppression de tous les enregistrements ProductOrder
  250. if (!is_null($order)) {
  251. ProductOrder::deleteAll(['id_order' => $order->id]);
  252. }
  253. // produits dispos
  254. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  255. // sauvegarde des produits
  256. foreach ($productsArray as $product) {
  257. if (isset($availableProducts[$product->id])) {
  258. $productOrder = new ProductOrder();
  259. $productOrder->id_order = $order->id;
  260. $productOrder->id_product = $product->id;
  261. $productOrder->price = $product->price;
  262. $quantity = (int) $posts['products'][$product->id] ;
  263. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  264. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  265. }
  266. $productOrder->quantity = $quantity;
  267. $productOrder->sale_mode = Product::SALE_MODE_UNIT ;
  268. $productOrder->save();
  269. }
  270. }
  271. // lien utilisateur / point de vente
  272. $pointSale->linkUser(User::getCurrentId()) ;
  273. // credit
  274. $credit = Producer::getConfig('credit');
  275. $creditLimit = Producer::getConfig('credit_limit');
  276. $creditFunctioning = $pointSale->getCreditFunctioning() ;
  277. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  278. $order = Order::searchOne([
  279. 'id' => $order->id
  280. ]) ;
  281. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  282. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  283. if($credit && $pointSale->credit &&
  284. ( ($pointSale->credit_functioning == Producer::CREDIT_FUNCTIONING_OPTIONAL && $posts['use_credit']) ||
  285. $pointSale->credit_functioning == Producer::CREDIT_FUNCTIONING_MANDATORY ||
  286. ($pointSale->credit_functioning == Producer::CREDIT_FUNCTIONING_USER && $userProducer->credit_active)
  287. )) {
  288. // à payer
  289. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  290. if(!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  291. $amountRemaining = $creditUser - $creditLimit ;
  292. }
  293. if ($amountRemaining > 0) {
  294. $order->saveCreditHistory(
  295. CreditHistory::TYPE_PAYMENT,
  296. $amountRemaining,
  297. $distribution->id_producer,
  298. User::getCurrentId(),
  299. User::getCurrentId()
  300. );
  301. }
  302. }
  303. // surplus à rembourser
  304. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  305. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  306. $order->saveCreditHistory(
  307. CreditHistory::TYPE_REFUND,
  308. $amountSurplus,
  309. $distribution->id_producer,
  310. User::getCurrentId(),
  311. User::getCurrentId()
  312. );
  313. }
  314. }
  315. }
  316. if (!count($productsArray)) {
  317. $errors[] = "Vous n'avez choisi aucun produit" ;
  318. }
  319. if ($errorDate) {
  320. $errors[] = "Vous ne pouvez pas commander pour cette date." ;
  321. }
  322. if ($errorPointSale) {
  323. $errors[] = "Point de vente invalide." ;
  324. }
  325. return $errors ;
  326. }
  327. /**
  328. * Annule une commande.
  329. *
  330. * @param integer $id
  331. * @throws \yii\web\NotFoundHttpException
  332. * @throws UserException
  333. */
  334. public function actionCancel($id)
  335. {
  336. $order = Order::searchOne([
  337. 'id' => $id
  338. ]) ;
  339. if(!$order) {
  340. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  341. }
  342. if ($order->getState() != Order::STATE_OPEN) {
  343. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  344. }
  345. if ($order && User::getCurrentId() == $order->id_user) {
  346. // remboursement
  347. if ($order->getAmount(Order::AMOUNT_PAID)) {
  348. $order->saveCreditHistory(
  349. CreditHistory::TYPE_REFUND,
  350. $order->getAmount(Order::AMOUNT_PAID),
  351. $order->distribution->id_producer,
  352. User::getCurrentId(),
  353. User::getCurrentId()
  354. );
  355. }
  356. // delete
  357. $order->date_delete = date('Y-m-d H:i:s');
  358. $order->save() ;
  359. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  360. }
  361. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  362. }
  363. /**
  364. * Vérifie le code saisi pour un point de vente.
  365. *
  366. * @param integer $idPointSale
  367. * @param string $code
  368. * @return boolean
  369. */
  370. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  371. {
  372. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  373. $pointSale = PointSale::findOne($idPointSale);
  374. if ($pointSale) {
  375. if ($pointSale->validateCode($code)) {
  376. return 1;
  377. }
  378. }
  379. return 0;
  380. }
  381. public function actionAjaxInfos($date = '')
  382. {
  383. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  384. $json = [] ;
  385. $format = 'Y-m-d' ;
  386. $dateObject = DateTime::createFromFormat($format, $date);
  387. // Producteur
  388. $producer = Producer::searchOne([
  389. 'id' => $this->getProducer()->id
  390. ]) ;
  391. $json['producer'] = [
  392. 'order_infos' => $producer->order_infos,
  393. 'credit' => $producer->credit,
  394. 'credit_functioning' => $producer->credit_functioning,
  395. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  396. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  397. ] ;
  398. // Distributions
  399. $dateMini = $producer->getEarliestDateOrder() ;
  400. $distributionsArray = Distribution::searchAll([
  401. 'active' => 1
  402. ], [
  403. 'conditions' => ['date > :date'],
  404. 'params' => [':date' => $dateMini],
  405. ]) ;
  406. $json['distributions'] = $distributionsArray ;
  407. // Commandes de l'utilisateur
  408. $ordersUserArray = Order::searchAll([
  409. 'id_user' => User::getCurrentId()
  410. ], [
  411. 'conditions' => [
  412. 'distribution.date > :date'
  413. ],
  414. 'params' => [
  415. ':date' => $dateMini
  416. ]
  417. ]);
  418. if(is_array($ordersUserArray) && count($ordersUserArray)) {
  419. foreach($ordersUserArray as &$order) {
  420. $order = array_merge($order->getAttributes(), [
  421. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  422. 'date_distribution' => $order->distribution->date,
  423. 'pointSale' => $order->pointSale->getAttributes()
  424. ]) ;
  425. }
  426. $json['orders'] = $ordersUserArray;
  427. }
  428. // User
  429. $userProducer = UserProducer::searchOne([
  430. 'id_producer' => $producer->id,
  431. 'id_user' => User::getCurrentId()
  432. ]) ;
  433. $json['user'] = [
  434. 'credit' => $userProducer->credit,
  435. 'credit_active' => $userProducer->credit_active,
  436. ] ;
  437. if($dateObject && $dateObject->format($format) === $date) {
  438. // Commande de l'utilisateur
  439. $orderUser = Order::searchOne([
  440. 'distribution.date' => $date,
  441. 'id_user' => User::getCurrentId(),
  442. ]);
  443. if($orderUser) {
  444. $json['order'] = array_merge($orderUser->getAttributes(), [
  445. 'amount_total' => $orderUser->getAmount(Order::AMOUNT_TOTAL),
  446. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  447. ]) ;
  448. }
  449. // distribution
  450. $distribution = Distribution::initDistribution($date) ;
  451. $json['distribution'] = $distribution ;
  452. $pointsSaleArray = PointSale::find()
  453. ->joinWith(['pointSaleDistribution' => function($query) use ($distribution) {
  454. $query->where(['id_distribution' => $distribution->id]);
  455. }
  456. ])
  457. ->with(['userPointSale' => function($query) {
  458. $query->onCondition(['id_user' => User::getCurrentId()]) ;
  459. }])
  460. ->where(['id_producer' => $distribution->id_producer])
  461. ->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)')
  462. ->params([':id_user' => User::getCurrentId()])
  463. ->all();
  464. $creditFunctioningProducer = Producer::getConfig('credit_functioning') ;
  465. foreach($pointsSaleArray as &$pointSale) {
  466. $pointSale = array_merge($pointSale->getAttributes(),[
  467. 'pointSaleDistribution' => [
  468. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  469. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  470. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  471. ],
  472. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  473. ]) ;
  474. if($pointSale['code'] && strlen($pointSale['code'])) {
  475. $pointSale['code'] = '***' ;
  476. }
  477. if(!strlen($pointSale['credit_functioning'])) {
  478. $pointSale['credit_functioning'] = $creditFunctioningProducer ;
  479. }
  480. }
  481. $json['points_sale'] = $pointsSaleArray;
  482. // Commandes totales
  483. $ordersArray = Order::searchAll([
  484. 'distribution.date' => $date,
  485. ]);
  486. // Produits
  487. if(Producer::getConfig('option_allow_user_gift')) {
  488. $productsArray = Product::find()
  489. ->orWhere(['id_producer' => $this->getProducer()->id,])
  490. ->orWhere(['id_producer' => 0,]) ; // produit "Don";
  491. }
  492. else {
  493. $productsArray = Product::find()
  494. ->where(['id_producer' => $this->getProducer()->id,]) ;
  495. }
  496. $productsArray = $productsArray->joinWith(['productDistribution' => function($query) use($distribution) {
  497. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  498. }])
  499. ->orderBy('product_distribution.active DESC, order ASC')
  500. ->asArray()
  501. ->all();
  502. $indexProduct = 0 ;
  503. foreach($productsArray as &$product) {
  504. if(is_null($product['photo'])) {
  505. $product['photo'] = '' ;
  506. }
  507. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'] ;
  508. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray) ;
  509. $product['quantity_ordered'] = $quantityOrder ;
  510. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder ;
  511. if($orderUser) {
  512. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true) ;
  513. $product['quantity_ordered'] = $quantityOrder ;
  514. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser ;
  515. $product['quantity_form'] = $quantityOrderUser ;
  516. }
  517. else {
  518. $product['quantity_form'] = 0 ;
  519. }
  520. if($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0 ;
  521. $product['index'] = $indexProduct ++ ;
  522. }
  523. $json['products'] = $productsArray;
  524. }
  525. return $json ;
  526. }
  527. public function actionConfirm($idOrder)
  528. {
  529. $order = Order::searchOne(['id' => $idOrder]) ;
  530. if(!$order || $order->id_user != User::getCurrentId()) {
  531. throw new \yii\base\UserException('Commande introuvable.') ;
  532. }
  533. return $this->render('confirm',[
  534. 'order' => $order
  535. ]) ;
  536. }
  537. }