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.

603 lines
21KB

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