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 21KB

5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  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 DateTime;
  37. class OrderController extends ProducerBaseController
  38. {
  39. var $enableCsrfValidation = false;
  40. public function behaviors()
  41. {
  42. return [
  43. 'access' => [
  44. 'class' => AccessControl::className(),
  45. 'rules' => [
  46. [
  47. 'allow' => true,
  48. 'roles' => ['@'],
  49. ]
  50. ],
  51. ],
  52. ];
  53. }
  54. public function actionOrder($id = 0, $date = '')
  55. {
  56. $params = [] ;
  57. if($id) {
  58. $order = Order::searchOne([
  59. 'id' => $id
  60. ]) ;
  61. if($order) {
  62. if($order->getState() == Order::STATE_OPEN) {
  63. $params['order'] = $order ;
  64. }
  65. }
  66. }
  67. if(strlen($date)) {
  68. $distribution = Distribution::searchOne([
  69. 'date' => $date,
  70. 'id_producer' => Producer::getId()
  71. ]) ;
  72. if($distribution) {
  73. $params['date'] = $date ;
  74. }
  75. }
  76. return $this->render('order', $params) ;
  77. }
  78. /**
  79. * Affiche l'historique des commandes de l'utilisateur
  80. *
  81. * @return ProducerView
  82. */
  83. public function actionHistory($type = 'incoming')
  84. {
  85. $query = Order::find()
  86. ->with('productOrder', 'pointSale', 'creditHistory')
  87. ->joinWith('distribution', 'distribution.producer')
  88. ->where([
  89. 'id_user' => Yii::$app->user->id,
  90. 'distribution.id_producer' => Producer::getId()
  91. ])
  92. ->params([':date_today' => date('Y-m-d')]);
  93. $queryIncoming = clone $query ;
  94. $queryIncoming->andWhere('distribution.date >= :date_today')->orderBy('distribution.date ASC');
  95. $queryPassed = clone $query ;
  96. $queryPassed->andWhere('distribution.date < :date_today')->orderBy('distribution.date DESC');
  97. $dataProviderOrders = new ActiveDataProvider([
  98. 'query' => ($type == 'incoming') ? $queryIncoming : $queryPassed,
  99. 'pagination' => [
  100. 'pageSize' => 10,
  101. ],
  102. ]);
  103. return $this->render('history', [
  104. 'dataProviderOrders' => $dataProviderOrders,
  105. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  106. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  107. 'type' => $type,
  108. 'countIncoming' => $queryIncoming->count(),
  109. 'countPassed' => $queryPassed->count(),
  110. ]);
  111. }
  112. /**
  113. * Supprime un producteur.
  114. *
  115. * @param integer $id
  116. */
  117. public function actionRemoveProducer($id = 0)
  118. {
  119. $userProducer = UserProducer::find()
  120. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  121. ->one();
  122. $userProducer->active = 0;
  123. $userProducer->save();
  124. $this->redirect(['order/index']);
  125. }
  126. /**
  127. * Crée une commande.
  128. *
  129. * @return mixed
  130. */
  131. public function actionAjaxProcess()
  132. {
  133. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  134. $order = new Order ;
  135. $idProducer = $this->getProducer()->id ;
  136. $posts = Yii::$app->request->post();
  137. if ($idProducer) {
  138. $this->_verifyProducerActive($idProducer);
  139. }
  140. if ($order->load($posts)) {
  141. $order = Order::find()
  142. ->where('id_distribution = :id_distribution')
  143. ->andWhere('id_user = :id_user')
  144. ->params([
  145. ':id_distribution' => $posts['Order']['id_distribution'],
  146. ':id_user' => User::getCurrentId()
  147. ])
  148. ->one();
  149. if (!$order) {
  150. $order = new Order;
  151. $order->load(Yii::$app->request->post());
  152. $order->id_user = User::getCurrentId();
  153. $order->date = date('Y-m-d H:i:s');
  154. $order->origin = Order::ORIGIN_USER;
  155. }
  156. $errors = $this->processForm($order);
  157. if(count($errors)) {
  158. return ['status' => 'error', 'errors' => $errors] ;
  159. }
  160. }
  161. return ['status' => 'success', 'idOrder' => $order->id] ;
  162. }
  163. /**
  164. * Vérifie si un producteur est actif.
  165. *
  166. * @param integer $idProducer
  167. * @throws NotFoundHttpException
  168. */
  169. public function _verifyProducerActive($idProducer)
  170. {
  171. $producer = Producer::findOne($idProducer);
  172. if ($producer && !$producer->active) {
  173. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  174. }
  175. }
  176. /**
  177. * Traite le formulaire de création/modification de commande.
  178. *
  179. * @param Commande $order
  180. */
  181. public function processForm($order)
  182. {
  183. $posts = Yii::$app->request->post();
  184. $productsArray = [];
  185. $totalQuantity = 0;
  186. foreach ($posts['products'] as $key => $quantity) {
  187. $product = Product::find()->where(['id' => (int) $key])->one();
  188. $totalQuantity += $quantity;
  189. if ($product && $quantity) {
  190. $productsArray[] = $product;
  191. }
  192. }
  193. $producer = $this->getProducer() ;
  194. // date
  195. $errorDate = false;
  196. if (isset($order->id_distribution)) {
  197. // date de commande
  198. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  199. $date = $this->getProducer()->getEarliestDateOrder() ;
  200. if($order->getState() != Order::STATE_OPEN) {
  201. $errorDate = true;
  202. }
  203. }
  204. // point de vente
  205. $errorPointSale = false;
  206. if (isset($distribution) && $distribution) {
  207. $pointSaleDistribution = PointSaleDistribution::searchOne([
  208. 'id_distribution' => $distribution->id,
  209. 'id_point_sale' => $posts['Order']['id_point_sale']
  210. ]) ;
  211. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  212. $errorPointSale = true;
  213. }
  214. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  215. if ($pointSale) {
  216. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  217. $errorPointSale = true;
  218. }
  219. } else {
  220. $errorPointSale = true;
  221. }
  222. }
  223. $errors = [] ;
  224. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  225. // gestion point de vente
  226. $pointSale = PointSale::searchOne([
  227. 'id' => $order->id_point_sale
  228. ]) ;
  229. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  230. $pointSale->getComment() : '' ;
  231. // la commande est automatiquement réactivée lors d'une modification
  232. $order->date_delete = null ;
  233. // sauvegarde de la commande
  234. $order->save();
  235. // ajout de l'utilisateur à l'établissement
  236. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  237. // suppression de tous les enregistrements ProductOrder
  238. if (!is_null($order)) {
  239. ProductOrder::deleteAll(['id_order' => $order->id]);
  240. }
  241. // produits dispos
  242. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  243. // sauvegarde des produits
  244. foreach ($productsArray as $product) {
  245. if (isset($availableProducts[$product->id])) {
  246. $productOrder = new ProductOrder();
  247. $productOrder->id_order = $order->id;
  248. $productOrder->id_product = $product->id;
  249. $productOrder->price = $product->price;
  250. $quantity = (int) $posts['products'][$product->id] ;
  251. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  252. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  253. }
  254. $productOrder->quantity = $quantity;
  255. $productOrder->sale_mode = Product::SALE_MODE_UNIT ;
  256. $productOrder->save();
  257. }
  258. }
  259. // credit
  260. $credit = Producer::getConfig('credit');
  261. $order = Order::searchOne([
  262. 'id' => $order->id
  263. ]) ;
  264. if($credit && $pointSale->credit && ($posts['use_credit'] || $pointSale->credit_functioning == Producer::CREDIT_FUNCTIONING_MANDATORY)) {
  265. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  266. // à payer
  267. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  268. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  269. $credit = Yii::$app->user->identity->getCredit($distribution->id_producer);
  270. if ($amountRemaining > 0) {
  271. $order->saveCreditHistory(
  272. CreditHistory::TYPE_PAYMENT,
  273. $amountRemaining,
  274. $distribution->id_producer,
  275. User::getCurrentId(),
  276. User::getCurrentId()
  277. );
  278. }
  279. }
  280. // surplus à rembourser
  281. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  282. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  283. $order->saveCreditHistory(
  284. CreditHistory::TYPE_REFUND,
  285. $amountSurplus,
  286. $distribution->id_producer,
  287. User::getCurrentId(),
  288. User::getCurrentId()
  289. );
  290. }
  291. }
  292. }
  293. else {
  294. if (!count($productsArray)) {
  295. $errors[] = "Vous n'avez choisi aucun produit" ;
  296. }
  297. if ($errorDate) {
  298. $errors[] = "Vous ne pouvez pas commander pour cette date." ;
  299. }
  300. if ($errorPointSale) {
  301. $errors[] = "Point de vente invalide." ;
  302. }
  303. }
  304. return $errors ;
  305. }
  306. /**
  307. * Annule une commande.
  308. *
  309. * @param integer $id
  310. * @throws \yii\web\NotFoundHttpException
  311. * @throws UserException
  312. */
  313. public function actionCancel($id)
  314. {
  315. $order = Order::searchOne([
  316. 'id' => $id
  317. ]) ;
  318. if(!$order) {
  319. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  320. }
  321. if ($order->getState() != Order::STATE_OPEN) {
  322. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  323. }
  324. if ($order && User::getCurrentId() == $order->id_user) {
  325. // remboursement
  326. if ($order->getAmount(Order::AMOUNT_PAID)) {
  327. $order->saveCreditHistory(
  328. CreditHistory::TYPE_REFUND,
  329. $order->getAmount(Order::AMOUNT_PAID),
  330. $order->distribution->id_producer,
  331. User::getCurrentId(),
  332. User::getCurrentId()
  333. );
  334. }
  335. // delete
  336. $order->date_delete = date('Y-m-d H:i:s');
  337. $order->save() ;
  338. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  339. }
  340. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  341. }
  342. /**
  343. * Vérifie le code saisi pour un point de vente.
  344. *
  345. * @param integer $idPointSale
  346. * @param string $code
  347. * @return boolean
  348. */
  349. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  350. {
  351. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  352. $pointSale = PointSale::findOne($idPointSale);
  353. if ($pointSale) {
  354. if ($pointSale->validateCode($code)) {
  355. return 1;
  356. }
  357. }
  358. return 0;
  359. }
  360. public function actionAjaxInfos($date = '')
  361. {
  362. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  363. $json = [] ;
  364. $format = 'Y-m-d' ;
  365. $dateObject = DateTime::createFromFormat($format, $date);
  366. // Producteur
  367. $producer = Producer::searchOne([
  368. 'id' => $this->getProducer()->id
  369. ]) ;
  370. $json['producer'] = [
  371. 'order_infos' => $producer->order_infos,
  372. 'credit' => $producer->credit,
  373. 'credit_functioning' => $producer->credit_functioning,
  374. ] ;
  375. // Distributions
  376. $dateMini = $producer->getEarliestDateOrder() ;
  377. $distributionsArray = Distribution::searchAll([
  378. 'active' => 1
  379. ], [
  380. 'conditions' => ['date > :date'],
  381. 'params' => [':date' => $dateMini],
  382. ]) ;
  383. $json['distributions'] = $distributionsArray ;
  384. // Commandes de l'utilisateur
  385. $ordersUserArray = Order::searchAll([
  386. 'id_user' => User::getCurrentId()
  387. ], [
  388. 'conditions' => [
  389. 'distribution.date > :date'
  390. ],
  391. 'params' => [
  392. ':date' => $dateMini
  393. ]
  394. ]);
  395. if(is_array($ordersUserArray) && count($ordersUserArray)) {
  396. foreach($ordersUserArray as &$order) {
  397. $order = array_merge($order->getAttributes(), [
  398. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  399. 'date_distribution' => $order->distribution->date,
  400. 'pointSale' => $order->pointSale->getAttributes()
  401. ]) ;
  402. }
  403. $json['orders'] = $ordersUserArray;
  404. }
  405. // User
  406. $userProducer = UserProducer::searchOne([
  407. 'id_producer' => $producer->id,
  408. 'id_user' => User::getCurrentId()
  409. ]) ;
  410. $json['credit'] = $userProducer->credit ;
  411. if($dateObject && $dateObject->format($format) === $date) {
  412. // Commande de l'utilisateur
  413. $orderUser = Order::searchOne([
  414. 'distribution.date' => $date,
  415. 'id_user' => User::getCurrentId(),
  416. ]);
  417. if($orderUser) {
  418. $json['order'] = array_merge($orderUser->getAttributes(), [
  419. 'amount_total' => $orderUser->getAmount(Order::AMOUNT_TOTAL),
  420. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  421. ]) ;
  422. }
  423. // distribution
  424. $distribution = Distribution::initDistribution($date) ;
  425. $json['distribution'] = $distribution ;
  426. $pointsSaleArray = PointSale::find()
  427. ->joinWith(['pointSaleDistribution' => function($query) use ($distribution) {
  428. $query->where(['id_distribution' => $distribution->id]);
  429. }
  430. ])
  431. ->with(['userPointSale' => function($query) {
  432. $query->onCondition(['id_user' => User::getCurrentId()]) ;
  433. }])
  434. ->where([
  435. 'id_producer' => $distribution->id_producer,
  436. ])
  437. ->all();
  438. $creditFunctioningProducer = Producer::getConfig('credit_functioning') ;
  439. foreach($pointsSaleArray as &$pointSale) {
  440. $pointSale = array_merge($pointSale->getAttributes(),[
  441. 'pointSaleDistribution' => [
  442. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  443. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  444. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  445. ],
  446. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  447. ]) ;
  448. if($pointSale['code'] && strlen($pointSale['code'])) {
  449. $pointSale['code'] = '***' ;
  450. }
  451. if(!strlen($pointSale['credit_functioning'])) {
  452. $pointSale['credit_functioning'] = $creditFunctioningProducer ;
  453. }
  454. }
  455. $json['points_sale'] = $pointsSaleArray;
  456. // Commandes totales
  457. $ordersArray = Order::searchAll([
  458. 'distribution.date' => $date,
  459. ]);
  460. // Produits
  461. if(Producer::getConfig('option_allow_user_gift')) {
  462. $productsArray = Product::find()
  463. ->orWhere(['id_producer' => $this->getProducer()->id,])
  464. ->orWhere(['id_producer' => 0,]) ; // produit "Don";
  465. }
  466. else {
  467. $productsArray = Product::find()
  468. ->where(['id_producer' => $this->getProducer()->id,]) ;
  469. }
  470. $productsArray = $productsArray->joinWith(['productDistribution' => function($query) use($distribution) {
  471. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  472. }])
  473. ->orderBy('product_distribution.active DESC, order ASC')
  474. ->asArray()
  475. ->all();
  476. $indexProduct = 0 ;
  477. foreach($productsArray as &$product) {
  478. if(is_null($product['photo'])) {
  479. $product['photo'] = '' ;
  480. }
  481. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'] ;
  482. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray) ;
  483. $product['quantity_ordered'] = $quantityOrder ;
  484. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder ;
  485. if($orderUser) {
  486. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true) ;
  487. $product['quantity_ordered'] = $quantityOrder ;
  488. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser ;
  489. $product['quantity_form'] = $quantityOrderUser ;
  490. }
  491. else {
  492. $product['quantity_form'] = 0 ;
  493. }
  494. if($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0 ;
  495. $product['index'] = $indexProduct ++ ;
  496. }
  497. $json['products'] = $productsArray;
  498. }
  499. return $json ;
  500. }
  501. public function actionConfirm($idOrder)
  502. {
  503. $order = Order::searchOne(['id' => $idOrder]) ;
  504. if(!$order || $order->id_user != User::getCurrentId()) {
  505. throw new \yii\base\UserException('Commande introuvable.') ;
  506. }
  507. return $this->render('confirm',[
  508. 'order' => $order
  509. ]) ;
  510. }
  511. }