選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

OrderController.php 23KB

5年前
5年前
5年前
5年前
5年前
5年前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633
  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. foreach ($posts['products'] as $key => $quantity) {
  188. $product = Product::find()->where(['id' => (int) $key])->one();
  189. $totalQuantity += $quantity;
  190. if ($product && $quantity) {
  191. $productsArray[] = $product;
  192. }
  193. }
  194. $producer = $this->getProducer() ;
  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. // gestion point de vente
  234. $pointSale = PointSale::searchOne([
  235. 'id' => $order->id_point_sale
  236. ]) ;
  237. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  238. $pointSale->getComment() : '' ;
  239. // la commande est automatiquement réactivée lors d'une modification
  240. $order->date_delete = null ;
  241. // sauvegarde de la commande
  242. $order->save();
  243. // ajout de l'utilisateur à l'établissement
  244. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  245. // suppression de tous les enregistrements ProductOrder
  246. if (!is_null($order)) {
  247. ProductOrder::deleteAll(['id_order' => $order->id]);
  248. }
  249. // produits dispos
  250. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  251. // sauvegarde des produits
  252. foreach ($productsArray as $product) {
  253. if (isset($availableProducts[$product->id])) {
  254. $productOrder = new ProductOrder();
  255. $productOrder->id_order = $order->id;
  256. $productOrder->id_product = $product->id;
  257. $productOrder->price = $product->price;
  258. $quantity = (int) $posts['products'][$product->id] ;
  259. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  260. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  261. }
  262. $productOrder->quantity = $quantity;
  263. $productOrder->sale_mode = Product::SALE_MODE_UNIT ;
  264. $productOrder->save();
  265. }
  266. }
  267. // credit
  268. $credit = Producer::getConfig('credit');
  269. $creditLimit = Producer::getConfig('credit_limit');
  270. $creditFunctioning = $pointSale->getCreditFunctioning() ;
  271. $creditUser = Yii::$app->user->identity->getCredit($distribution->id_producer);
  272. $order = Order::searchOne([
  273. 'id' => $order->id
  274. ]) ;
  275. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  276. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  277. if($credit && $pointSale->credit && ($posts['use_credit'] || $pointSale->credit_functioning == Producer::CREDIT_FUNCTIONING_MANDATORY)) {
  278. // à payer
  279. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  280. if(!is_null($creditLimit) && $amountRemaining > $creditUser - $creditLimit) {
  281. $amountRemaining = $creditUser - $creditLimit ;
  282. }
  283. if ($amountRemaining > 0) {
  284. $order->saveCreditHistory(
  285. CreditHistory::TYPE_PAYMENT,
  286. $amountRemaining,
  287. $distribution->id_producer,
  288. User::getCurrentId(),
  289. User::getCurrentId()
  290. );
  291. }
  292. }
  293. // surplus à rembourser
  294. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  295. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  296. $order->saveCreditHistory(
  297. CreditHistory::TYPE_REFUND,
  298. $amountSurplus,
  299. $distribution->id_producer,
  300. User::getCurrentId(),
  301. User::getCurrentId()
  302. );
  303. }
  304. }
  305. }
  306. if (!count($productsArray)) {
  307. $errors[] = "Vous n'avez choisi aucun produit" ;
  308. }
  309. if ($errorDate) {
  310. $errors[] = "Vous ne pouvez pas commander pour cette date." ;
  311. }
  312. if ($errorPointSale) {
  313. $errors[] = "Point de vente invalide." ;
  314. }
  315. return $errors ;
  316. }
  317. /**
  318. * Annule une commande.
  319. *
  320. * @param integer $id
  321. * @throws \yii\web\NotFoundHttpException
  322. * @throws UserException
  323. */
  324. public function actionCancel($id)
  325. {
  326. $order = Order::searchOne([
  327. 'id' => $id
  328. ]) ;
  329. if(!$order) {
  330. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  331. }
  332. if ($order->getState() != Order::STATE_OPEN) {
  333. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  334. }
  335. if ($order && User::getCurrentId() == $order->id_user) {
  336. // remboursement
  337. if ($order->getAmount(Order::AMOUNT_PAID)) {
  338. $order->saveCreditHistory(
  339. CreditHistory::TYPE_REFUND,
  340. $order->getAmount(Order::AMOUNT_PAID),
  341. $order->distribution->id_producer,
  342. User::getCurrentId(),
  343. User::getCurrentId()
  344. );
  345. }
  346. // delete
  347. $order->date_delete = date('Y-m-d H:i:s');
  348. $order->save() ;
  349. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  350. }
  351. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  352. }
  353. /**
  354. * Vérifie le code saisi pour un point de vente.
  355. *
  356. * @param integer $idPointSale
  357. * @param string $code
  358. * @return boolean
  359. */
  360. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  361. {
  362. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  363. $pointSale = PointSale::findOne($idPointSale);
  364. if ($pointSale) {
  365. if ($pointSale->validateCode($code)) {
  366. return 1;
  367. }
  368. }
  369. return 0;
  370. }
  371. public function actionAjaxInfos($date = '')
  372. {
  373. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  374. $json = [] ;
  375. $format = 'Y-m-d' ;
  376. $dateObject = DateTime::createFromFormat($format, $date);
  377. // Producteur
  378. $producer = Producer::searchOne([
  379. 'id' => $this->getProducer()->id
  380. ]) ;
  381. $json['producer'] = [
  382. 'order_infos' => $producer->order_infos,
  383. 'credit' => $producer->credit,
  384. 'credit_functioning' => $producer->credit_functioning,
  385. 'use_credit_checked_default' => $producer->use_credit_checked_default,
  386. 'credit_limit' => is_numeric($producer->credit_limit) ? $producer->credit_limit : null
  387. ] ;
  388. // Distributions
  389. $dateMini = $producer->getEarliestDateOrder() ;
  390. $distributionsArray = Distribution::searchAll([
  391. 'active' => 1
  392. ], [
  393. 'conditions' => ['date > :date'],
  394. 'params' => [':date' => $dateMini],
  395. ]) ;
  396. $json['distributions'] = $distributionsArray ;
  397. // Commandes de l'utilisateur
  398. $ordersUserArray = Order::searchAll([
  399. 'id_user' => User::getCurrentId()
  400. ], [
  401. 'conditions' => [
  402. 'distribution.date > :date'
  403. ],
  404. 'params' => [
  405. ':date' => $dateMini
  406. ]
  407. ]);
  408. if(is_array($ordersUserArray) && count($ordersUserArray)) {
  409. foreach($ordersUserArray as &$order) {
  410. $order = array_merge($order->getAttributes(), [
  411. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  412. 'date_distribution' => $order->distribution->date,
  413. 'pointSale' => $order->pointSale->getAttributes()
  414. ]) ;
  415. }
  416. $json['orders'] = $ordersUserArray;
  417. }
  418. // User
  419. $userProducer = UserProducer::searchOne([
  420. 'id_producer' => $producer->id,
  421. 'id_user' => User::getCurrentId()
  422. ]) ;
  423. $json['credit'] = $userProducer->credit ;
  424. if($dateObject && $dateObject->format($format) === $date) {
  425. // Commande de l'utilisateur
  426. $orderUser = Order::searchOne([
  427. 'distribution.date' => $date,
  428. 'id_user' => User::getCurrentId(),
  429. ]);
  430. if($orderUser) {
  431. $json['order'] = array_merge($orderUser->getAttributes(), [
  432. 'amount_total' => $orderUser->getAmount(Order::AMOUNT_TOTAL),
  433. 'amount_paid' => $orderUser->getAmount(Order::AMOUNT_PAID),
  434. ]) ;
  435. }
  436. // distribution
  437. $distribution = Distribution::initDistribution($date) ;
  438. $json['distribution'] = $distribution ;
  439. $pointsSaleArray = PointSale::find()
  440. ->joinWith(['pointSaleDistribution' => function($query) use ($distribution) {
  441. $query->where(['id_distribution' => $distribution->id]);
  442. }
  443. ])
  444. ->with(['userPointSale' => function($query) {
  445. $query->onCondition(['id_user' => User::getCurrentId()]) ;
  446. }])
  447. ->where(['id_producer' => $distribution->id_producer])
  448. ->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)')
  449. ->params([':id_user' => User::getCurrentId()])
  450. ->all();
  451. $creditFunctioningProducer = Producer::getConfig('credit_functioning') ;
  452. foreach($pointsSaleArray as &$pointSale) {
  453. $pointSale = array_merge($pointSale->getAttributes(),[
  454. 'pointSaleDistribution' => [
  455. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  456. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  457. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  458. ],
  459. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  460. ]) ;
  461. if($pointSale['code'] && strlen($pointSale['code'])) {
  462. $pointSale['code'] = '***' ;
  463. }
  464. if(!strlen($pointSale['credit_functioning'])) {
  465. $pointSale['credit_functioning'] = $creditFunctioningProducer ;
  466. }
  467. }
  468. $json['points_sale'] = $pointsSaleArray;
  469. // Commandes totales
  470. $ordersArray = Order::searchAll([
  471. 'distribution.date' => $date,
  472. ]);
  473. // Produits
  474. if(Producer::getConfig('option_allow_user_gift')) {
  475. $productsArray = Product::find()
  476. ->orWhere(['id_producer' => $this->getProducer()->id,])
  477. ->orWhere(['id_producer' => 0,]) ; // produit "Don";
  478. }
  479. else {
  480. $productsArray = Product::find()
  481. ->where(['id_producer' => $this->getProducer()->id,]) ;
  482. }
  483. $productsArray = $productsArray->joinWith(['productDistribution' => function($query) use($distribution) {
  484. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  485. }])
  486. ->orderBy('product_distribution.active DESC, order ASC')
  487. ->asArray()
  488. ->all();
  489. $indexProduct = 0 ;
  490. foreach($productsArray as &$product) {
  491. if(is_null($product['photo'])) {
  492. $product['photo'] = '' ;
  493. }
  494. $product['quantity_max'] = $product['productDistribution'][0]['quantity_max'] ;
  495. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray) ;
  496. $product['quantity_ordered'] = $quantityOrder ;
  497. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder ;
  498. if($orderUser) {
  499. $quantityOrderUser = Order::getProductQuantity($product['id'], [$orderUser], true) ;
  500. $product['quantity_ordered'] = $quantityOrder ;
  501. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder + $quantityOrderUser ;
  502. $product['quantity_form'] = $quantityOrderUser ;
  503. }
  504. else {
  505. $product['quantity_form'] = 0 ;
  506. }
  507. if($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0 ;
  508. $product['index'] = $indexProduct ++ ;
  509. }
  510. $json['products'] = $productsArray;
  511. }
  512. return $json ;
  513. }
  514. public function actionConfirm($idOrder)
  515. {
  516. $order = Order::searchOne(['id' => $idOrder]) ;
  517. if(!$order || $order->id_user != User::getCurrentId()) {
  518. throw new \yii\base\UserException('Commande introuvable.') ;
  519. }
  520. return $this->render('confirm',[
  521. 'order' => $order
  522. ]) ;
  523. }
  524. }