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.

719 lines
25KB

  1. <?php
  2. /**
  3. Copyright La boîte à pain (2018)
  4. contact@laboiteapain.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()
  55. {
  56. return $this->render('order') ;
  57. }
  58. /**
  59. * Retourne au format JSON toutes les informations relatives à une
  60. * production donnée.
  61. *
  62. * @param integer $idDistribution
  63. * @return mixed
  64. */
  65. public function actionInfosDistribution($idDistribution)
  66. {
  67. $distribution = Distribution::searchOne([
  68. 'id' => $idDistribution
  69. ]);
  70. if ($distribution) {
  71. $arr = [];
  72. $productsArray = ProductDistribution::searchByDistribution($distribution->id) ;
  73. $data['products'] = $productsArray;
  74. $pointSaleArray = PointSale::find()
  75. ->joinWith(['pointSaleDistribution' => function($q) use ($distribution) {
  76. $q->where(['id_distribution' => $distribution->id]);
  77. }])
  78. ->where([
  79. 'id_producer' => $distribution->id_producer,
  80. ])
  81. ->all();
  82. $data['points_sale'] = [];
  83. foreach ($pointSaleArray as $pointSale) {
  84. if (isset($pointSale->pointSaleDistribution) &&
  85. isset($pointSale->pointSaleDistribution[0])) {
  86. $data['points_sale'][$pointSale->id] = $pointSale->pointSaleDistribution[0]->delivery;
  87. } else {
  88. $data['points_sale'][$pointSale->id] = false;
  89. }
  90. }
  91. return json_encode($data);
  92. }
  93. return json_encode([]);
  94. }
  95. /**
  96. * Initialise le formulaire de création/modification de commande.
  97. *
  98. * @param Order $order
  99. * @return array
  100. */
  101. public function initForm($order = null) {
  102. // Producteurs
  103. $producersArray = Yii::$app->user->identity->getBookmarkedProducers();
  104. $idProducer = $this->getProducer()->id;
  105. // Producteur
  106. $producer = Producer::findOne($idProducer);
  107. // Points de vente
  108. $pointsSaleArray = PointSale::find()
  109. ->with('userPointSale')
  110. ->where(['id_producer' => $idProducer])
  111. ->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)')
  112. ->params([':id_user' => User::getCurrentId()])
  113. ->all();
  114. // jours de production
  115. $deadline = 20;
  116. $date = date('Y-m-d');
  117. if (isset($producer)) {
  118. $deadline = $producer->order_deadline;
  119. if (date('H') >= $deadline) {
  120. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay) * (24 * 60 * 60));
  121. } else {
  122. $date = date('Y-m-d', strtotime(date('Y-m-d')) + ($producer->order_delay - 1) * (24 * 60 * 60));
  123. }
  124. }
  125. $distributionDays = Distribution::find()
  126. ->where(['active' => 1])
  127. ->andWhere('date > :date')
  128. ->andWhere(['id_producer' => $idProducer])
  129. ->addParams([':date' => $date])
  130. ->all();
  131. $distributionDaysArray = array('' => '--');
  132. foreach ($distributionDays as $distribution) {
  133. $distributionDaysArray[$distribution->id] = date('d/m/Y', strtotime($distribution->date));
  134. }
  135. // produits
  136. $products = Product::find()
  137. ->leftJoin('product_distribution', 'product.id = product_distribution.id_product')
  138. ->where(['product.active' => 1, 'id_producer' => $idProducer])
  139. ->orderBy('product.order ASC')->all();
  140. $productsArray = [] ;
  141. foreach ($products as $p)
  142. $productsArray[] = $p;
  143. // produits selec
  144. $posts = Yii::$app->request->post();
  145. $selectedProducts = [];
  146. if (isset($posts['Product'])) {
  147. foreach ($posts['Product'] as $key => $quantity) {
  148. $key = (int) str_replace('product_', '', $key);
  149. $product = Product::find()->where(['id' => $key])->one();
  150. if ($product && $quantity)
  151. $selectedProducts[$product->id] = (int) $quantity;
  152. }
  153. }
  154. elseif (!is_null($order)) {
  155. $productOrderArray = ProductOrder::searchAll([
  156. 'id_order' => $order->id
  157. ]) ;
  158. foreach ($productOrderArray as $productOrder) {
  159. $selectedProducts[$productOrder->id_product] = (int) $productOrder->quantity;
  160. }
  161. }
  162. $availableProducts = [] ;
  163. $distribution = null;
  164. if (!is_null($order) && $order->id_distribution) {
  165. $availableProducts = ProductDistribution::searchByDistribution($order->id_distribution);
  166. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  167. }
  168. $orders = Order::searchAll([
  169. 'id_user' => User::getCurrentId()
  170. ]) ;
  171. if ($idProducer) {
  172. $userProducer = UserProducer::searchOne([
  173. 'id_producer' => $idProducer,
  174. 'id_user' => User::getCurrentId()
  175. ]) ;
  176. $credit = $userProducer->credit;
  177. } else {
  178. $credit = 0;
  179. }
  180. return [
  181. 'pointsSaleArray' => $pointsSaleArray,
  182. 'distributionDaysArray' => $distributionDaysArray,
  183. 'productsArray' => $productsArray,
  184. 'selectedProducts' => $selectedProducts,
  185. 'availableProducts' => $availableProducts,
  186. 'distribution' => $distribution,
  187. 'ordersArray' => $orders,
  188. 'producersArray' => $producersArray,
  189. 'idProducer' => $idProducer,
  190. 'producer' => $producer,
  191. 'credit' => $credit
  192. ];
  193. }
  194. /**
  195. * Affiche l'historique des commandes de l'utilisateur
  196. *
  197. * @return ProducerView
  198. */
  199. public function actionHistory()
  200. {
  201. $dataProviderOrders = new ActiveDataProvider([
  202. 'query' => Order::find()
  203. ->with('productOrder', 'pointSale', 'creditHistory')
  204. ->joinWith('distribution', 'distribution.producer')
  205. ->where([
  206. 'id_user' => Yii::$app->user->id,
  207. 'distribution.id_producer' => $this->getProducer()->id
  208. ])
  209. ->orderBy('distribution.date DESC'),
  210. 'pagination' => [
  211. 'pageSize' => 10,
  212. ],
  213. ]);
  214. return $this->render('history', [
  215. 'dataProviderOrders' => $dataProviderOrders,
  216. 'orderOk' => Yii::$app->getRequest()->get('orderOk', false),
  217. 'cancelOk' => Yii::$app->getRequest()->get('cancelOk', false),
  218. ]);
  219. }
  220. /**
  221. * Supprime un producteur.
  222. *
  223. * @param integer $id
  224. */
  225. public function actionRemoveProducer($id = 0)
  226. {
  227. $userProducer = UserProducer::find()
  228. ->where(['id_producer' => $id, 'id_user' => User::getCurrentId()])
  229. ->one();
  230. $userProducer->active = 0;
  231. $userProducer->save();
  232. $this->redirect(['order/index']);
  233. }
  234. /**
  235. * Crée une commande.
  236. *
  237. * @return mixed
  238. */
  239. public function actionAjaxCreate()
  240. {
  241. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  242. $idProducer = $this->getProducer()->id ;
  243. $order = new Order;
  244. $posts = Yii::$app->request->post();
  245. if ($idProducer) {
  246. $this->_verifyProducerActive($idProducer);
  247. }
  248. if ($order->load($posts)) {
  249. $order = Order::find()
  250. ->where('id_distribution = :id_distribution')
  251. ->andWhere('id_user = :id_user')
  252. ->params([
  253. ':id_distribution' => $posts['Order']['id_distribution'],
  254. ':id_user' => User::getCurrentId()
  255. ])
  256. ->one();
  257. if (!$order) {
  258. $order = new Order;
  259. $order->load(Yii::$app->request->post());
  260. $order->id_user = User::getCurrentId();
  261. $order->date = date('Y-m-d H:i:s');
  262. $order->origin = Order::ORIGIN_USER;
  263. }
  264. $errors = $this->processForm($order);
  265. if(count($errors)) {
  266. return ['status' => 'error', 'errors' => $errors] ;
  267. }
  268. }
  269. return ['status' => 'success'] ;
  270. }
  271. /**
  272. * Modifie une commande.
  273. *
  274. * @param integer $id
  275. * @return mixed
  276. * @throws UserException
  277. */
  278. public function actionUpdate($id)
  279. {
  280. $order = Order::searchOne([
  281. 'id' => $id
  282. ]) ;
  283. if ($order->getState() != Order::STATE_OPEN) {
  284. throw new UserException('Cette commande n\'est pas modifiable.');
  285. }
  286. $this->_verifyProducerActive($order->distribution->id_producer);
  287. if ($order && $order->load(Yii::$app->request->post())) {
  288. $order->date_update = date('Y-m-d H:i:s');
  289. $this->processForm($order);
  290. }
  291. return $this->render('update', array_merge($this->initForm($order), [
  292. 'model' => $order,
  293. 'orderNotfound' => !$order,
  294. ]));
  295. }
  296. /**
  297. * Vérifie si un producteur est actif.
  298. *
  299. * @param integer $idProducer
  300. * @throws NotFoundHttpException
  301. */
  302. public function _verifyProducerActive($idProducer)
  303. {
  304. $producer = Producer::findOne($idProducer);
  305. if ($producer && !$producer->active) {
  306. throw new NotFoundHttpException('Ce producteur est actuellement hors ligne.');
  307. }
  308. }
  309. /**
  310. * Traite le formulaire de création/modification de commande.
  311. *
  312. * @param Commande $order
  313. */
  314. public function processForm($order)
  315. {
  316. $posts = Yii::$app->request->post();
  317. $productsArray = [];
  318. $totalQuantity = 0;
  319. foreach ($posts['products'] as $key => $quantity) {
  320. $product = Product::find()->where(['id' => (int) $key])->one();
  321. $totalQuantity += $quantity;
  322. if ($product && $quantity) {
  323. $productsArray[] = $product;
  324. }
  325. }
  326. // date
  327. $errorDate = false;
  328. if (isset($order->id_distribution)) {
  329. // date de commande
  330. $distribution = Distribution::find()->where(['id' => $order->id_distribution])->one();
  331. if (date('H') >= 20) {
  332. $date = date('Y-m-d', strtotime(date('Y-m-d')) + 60 * 60 * 24);
  333. } else {
  334. $date = date('Y-m-d');
  335. }
  336. if ($distribution->date < $date) {
  337. $errorDate = true;
  338. }
  339. }
  340. // point de vente
  341. $errorPointSale = false;
  342. if (isset($distribution) && $distribution) {
  343. $pointSaleDistribution = PointSaleDistribution::searchOne([
  344. 'id_distribution' => $distribution->id,
  345. 'id_point_sale' => $posts['Order']['id_point_sale']
  346. ]) ;
  347. if (!$pointSaleDistribution || !$pointSaleDistribution->delivery) {
  348. $errorPointSale = true;
  349. }
  350. $pointSale = PointSale::findOne($posts['Order']['id_point_sale']);
  351. if ($pointSale) {
  352. if (strlen($pointSale->code) && !$pointSale->validateCode($posts['code_point_sale'])) {
  353. $errorPointSale = true;
  354. }
  355. } else {
  356. $errorPointSale = true;
  357. }
  358. }
  359. $errors = [] ;
  360. if ($order->validate() && count($productsArray) && !$errorDate && !$errorPointSale) {
  361. // gestion point de vente
  362. $pointSale = PointSale::searchOne([
  363. 'id' => $order->id_point_sale
  364. ]) ;
  365. $order->comment_point_sale = ($pointSale && strlen($pointSale->getComment())) ?
  366. $pv->getComment() : '' ;
  367. // la commande est automatiquement réactivée lors d'une modification
  368. $order->date_delete = null ;
  369. // sauvegarde de la commande
  370. $order->save();
  371. // ajout de l'utilisateur à l'établissement
  372. Producer::addUser(User::getCurrentId(), $distribution->id_producer) ;
  373. // suppression de tous les enregistrements ProductOrder
  374. if (!is_null($order)) {
  375. ProductOrder::deleteAll(['id_order' => $order->id]);
  376. }
  377. // produits dispos
  378. $availableProducts = ProductDistribution::searchByDistribution($distribution->id) ;
  379. // sauvegarde des produits
  380. foreach ($productsArray as $product) {
  381. if (isset($availableProducts[$product->id])) {
  382. $productOrder = new ProductOrder();
  383. $productOrder->id_order = $order->id;
  384. $productOrder->id_product = $product->id;
  385. $productOrder->price = $product->price;
  386. $quantity = (int) $posts['products'][$product->id] ;
  387. if ($availableProducts[$product->id]['quantity_max'] && $quantity > $availableProducts[$product->id]['quantity_remaining']) {
  388. $quantity = $availableProducts[$product->id]['quantity_remaining'];
  389. }
  390. $productOrder->quantity = $quantity;
  391. $productOrder->sale_mode = Product::SALE_MODE_UNIT ;
  392. $productOrder->save();
  393. }
  394. }
  395. // credit
  396. $credit = isset($posts['use_credit']) && $posts['use_credit'];
  397. $order = Order::searchOne([
  398. 'id' => $order->id
  399. ]) ;
  400. if ($credit && ($pointSale->credit || $order->getAmount(Order::AMOUNT_PAID))) {
  401. $amountPaid = $order->getAmount(Order::AMOUNT_PAID);
  402. // à payer
  403. if ($order->getPaymentStatus() == Order::PAYMENT_UNPAID) {
  404. $amountRemaining = $order->getAmount(Order::AMOUNT_REMAINING) ;
  405. $credit = Yii::$app->user->identity->getCredit($distribution->id_producer);
  406. if ($amountRemaining > $credit) {
  407. $amountRemaining = $credit;
  408. }
  409. if ($amountRemaining > 0) {
  410. $order->saveCreditHistory(
  411. CreditHistory::TYPE_PAYMENT,
  412. $amountRemaining,
  413. $distribution->id_producer,
  414. User::getCurrentId(),
  415. User::getCurrentId()
  416. );
  417. }
  418. }
  419. // surplus à rembourser
  420. elseif ($order->getPaymentStatus() == Order::PAYMENT_SURPLUS) {
  421. $amountSurplus = $order->getAmount(Order::AMOUNT_SURPLUS) ;
  422. $order->saveCreditHistory(
  423. CreditHistory::TYPE_REFUND,
  424. $amountSurplus,
  425. $distribution->id_producer,
  426. User::getCurrentId(),
  427. User::getCurrentId()
  428. );
  429. }
  430. }
  431. // redirection
  432. //$this->redirect(Yii::$app->urlManager->createUrl(['order/history', 'orderOk' => true]));
  433. }
  434. else {
  435. if (!count($productsArray)) {
  436. $errors[] = "Vous n'avez choisi aucun produit" ;
  437. }
  438. if ($errorDate) {
  439. $errors[] = "Vous ne pouvez pas commander pour cette date." ;
  440. }
  441. if ($errorPointSale) {
  442. $errors[] = "Point de vente invalide." ;
  443. }
  444. }
  445. return $errors ;
  446. }
  447. /**
  448. * Annule une commande.
  449. *
  450. * @param integer $id
  451. * @throws \yii\web\NotFoundHttpException
  452. * @throws UserException
  453. */
  454. public function actionCancel($id)
  455. {
  456. $order = Order::searchOne([
  457. 'id' => $id
  458. ]) ;
  459. if(!$order) {
  460. throw new \yii\web\NotFoundHttpException('Commande introuvable');
  461. }
  462. if ($order->getState() != Order::STATE_OPEN) {
  463. throw new UserException('Vous ne pouvez plus annuler cette commande.');
  464. }
  465. if ($order && User::getCurrentId() == $order->id_user) {
  466. // remboursement
  467. if ($order->getAmount(Order::AMOUNT_PAID)) {
  468. $order->saveCreditHistory(
  469. CreditHistory::TYPE_REFUND,
  470. $order->getAmount(Order::AMOUNT_PAID),
  471. $order->distribution->id_producer,
  472. User::getCurrentId(),
  473. User::getCurrentId()
  474. );
  475. }
  476. // delete
  477. $order->date_delete = date('Y-m-d H:i:s');
  478. $order->save() ;
  479. Yii::$app->session->setFlash('success','Votre commande a bien été annulée.') ;
  480. }
  481. $this->redirect(Yii::$app->urlManager->createUrl(['order/history']));
  482. }
  483. /**
  484. * Vérifie le code saisi pour un point de vente.
  485. *
  486. * @param integer $idPointSale
  487. * @param string $code
  488. * @return boolean
  489. */
  490. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  491. {
  492. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  493. $pointSale = PointSale::findOne($idPointSale);
  494. if ($pointSale) {
  495. if ($pointSale->validateCode($code)) {
  496. return 1;
  497. }
  498. }
  499. return 0;
  500. }
  501. public function actionAjaxInfos($date = '')
  502. {
  503. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  504. $json = [] ;
  505. $format = 'Y-m-d' ;
  506. $dateObject = DateTime::createFromFormat($format, $date);
  507. // Distributions
  508. $distributionsArray = Distribution::searchAll([
  509. 'active' => 1
  510. ], [
  511. 'conditions' => ['date > :date_today'],
  512. 'params' => [':date_today' => date('Y-m-d')],
  513. ]) ;
  514. $json['distributions'] = $distributionsArray ;
  515. // Commandes de l'utilisateur
  516. $ordersUserArray = Order::searchAll([
  517. 'id_user' => User::getCurrentId()
  518. ], [
  519. 'conditions' => [
  520. 'distribution.date >= :date'
  521. ],
  522. 'params' => [
  523. ':date' => date('Y-m-d')
  524. ]
  525. ]);
  526. foreach($ordersUserArray as &$order) {
  527. $order = array_merge($order->getAttributes(), [
  528. 'amount_total' => $order->getAmount(Order::AMOUNT_TOTAL),
  529. 'date_distribution' => $order->distribution->date,
  530. 'pointSale' => $order->pointSale->getAttributes()
  531. ]) ;
  532. }
  533. $json['orders'] = $ordersUserArray;
  534. // Producteur
  535. $producer = Producer::searchOne([
  536. 'id' => $this->getProducer()->id
  537. ]) ;
  538. $json['producer'] = [
  539. 'order_infos' => $producer->order_infos
  540. ] ;
  541. // User
  542. $userProducer = UserProducer::searchOne([
  543. 'id_producer' => $producer->id,
  544. 'id_user' => User::getCurrentId()
  545. ]) ;
  546. $json['credit'] = $userProducer->credit ;
  547. if($dateObject && $dateObject->format($format) === $date) {
  548. // distribution
  549. $distribution = Distribution::initDistribution($date) ;
  550. $json['distribution'] = $distribution ;
  551. $pointsSaleArray = PointSale::find()
  552. ->joinWith(['pointSaleDistribution' => function($query) use ($distribution) {
  553. $query->where(['id_distribution' => $distribution->id]);
  554. }
  555. ])
  556. ->with(['userPointSale' => function($query) {
  557. $query->onCondition(['id_user' => User::getCurrentId()]) ;
  558. }])
  559. ->where([
  560. 'id_producer' => $distribution->id_producer,
  561. ])
  562. ->all();
  563. foreach($pointsSaleArray as &$pointSale) {
  564. $pointSale = array_merge($pointSale->getAttributes(),[
  565. 'code_form' => '',
  566. 'pointSaleDistribution' => [
  567. 'id_distribution' => $pointSale->pointSaleDistribution[0]->id_distribution,
  568. 'id_point_sale' => $pointSale->pointSaleDistribution[0]->id_point_sale,
  569. 'delivery' => $pointSale->pointSaleDistribution[0]->delivery
  570. ],
  571. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  572. ]) ;
  573. }
  574. $json['points_sale'] = $pointsSaleArray;
  575. // Commandes totales
  576. $ordersArray = Order::searchAll([
  577. 'distribution.date' => $date,
  578. ]);
  579. // Produits
  580. $productsArray = Product::find()
  581. ->where([
  582. 'id_producer' => $this->getProducer()->id,
  583. ])
  584. ->joinWith(['productDistribution' => function($query) use($distribution) {
  585. $query->andOnCondition('product_distribution.id_distribution = '.$distribution->id) ;
  586. }])
  587. ->orderBy('product_distribution.active DESC, order ASC')
  588. ->asArray()
  589. ->all();
  590. $indexProduct = 0 ;
  591. foreach($productsArray as &$product) {
  592. $quantityOrder = Order::getProductQuantity($product['id'], $ordersArray) ;
  593. $product['quantity_ordered'] = $quantityOrder ;
  594. $product['quantity_remaining'] = $product['quantity_max'] - $quantityOrder ;
  595. if($product['quantity_remaining'] < 0) $product['quantity_remaining'] = 0 ;
  596. $product['quantity_form'] = 0 ;
  597. $product['index'] = $indexProduct ++ ;
  598. }
  599. $json['products'] = $productsArray;
  600. }
  601. return $json ;
  602. }
  603. }