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

SubscriptionController.php 14KB

3ヶ月前
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. <?php
  2. /**
  3. * Copyright Guillaume Bourgeois (2018)
  4. *
  5. * contact@souke.fr
  6. *
  7. * Ce logiciel est un programme informatique servant à aider les producteurs
  8. * à distribuer leur production en circuits courts.
  9. *
  10. * Ce logiciel est régi par la licence CeCILL soumise au droit français et
  11. * respectant les principes de diffusion des logiciels libres. Vous pouvez
  12. * utiliser, modifier et/ou redistribuer ce programme sous les conditions
  13. * de la licence CeCILL telle que diffusée par le CEA, le CNRS et l'INRIA
  14. * sur le site "http://www.cecill.info".
  15. *
  16. * En contrepartie de l'accessibilité au code source et des droits de copie,
  17. * de modification et de redistribution accordés par cette licence, il n'est
  18. * offert aux utilisateurs qu'une garantie limitée. Pour les mêmes raisons,
  19. * seule une responsabilité restreinte pèse sur l'auteur du programme, le
  20. * titulaire des droits patrimoniaux et les concédants successifs.
  21. *
  22. * A cet égard l'attention de l'utilisateur est attirée sur les risques
  23. * associés au chargement, à l'utilisation, à la modification et/ou au
  24. * développement et à la reproduction du logiciel par l'utilisateur étant
  25. * donné sa spécificité de logiciel libre, qui peut le rendre complexe à
  26. * manipuler et qui le réserve donc à des développeurs et des professionnels
  27. * avertis possédant des connaissances informatiques approfondies. Les
  28. * utilisateurs sont donc invités à charger et tester l'adéquation du
  29. * logiciel à leurs besoins dans des conditions permettant d'assurer la
  30. * sécurité de leurs systèmes et ou de leurs données et, plus généralement,
  31. * à l'utiliser et l'exploiter dans les mêmes conditions de sécurité.
  32. *
  33. * Le fait que vous puissiez accéder à cet en-tête signifie que vous avez
  34. * pris connaissance de la licence CeCILL, et que vous en avez accepté les
  35. * termes.
  36. */
  37. namespace producer\controllers;
  38. use common\forms\SubscriptionForm;
  39. use common\helpers\GlobalParam;
  40. use domain\Config\Unit\UnitDefinition;
  41. use domain\Subscription\ProductSubscription\ProductSubscription;
  42. use domain\Subscription\Subscription\Subscription;
  43. use domain\Subscription\Subscription\SubscriptionSearch;
  44. use yii\base\UserException;
  45. use yii\filters\AccessControl;
  46. use yii\web\NotFoundHttpException;
  47. class SubscriptionController extends ProducerBaseController
  48. {
  49. var $enableCsrfValidation = false;
  50. public function behaviors()
  51. {
  52. return [
  53. 'access' => [
  54. 'class' => AccessControl::class,
  55. 'rules' => [
  56. [
  57. 'allow' => true,
  58. 'roles' => ['@'],
  59. ]
  60. ],
  61. ],
  62. ];
  63. }
  64. /**
  65. * Liste les abonnements de l'utilisateur.
  66. */
  67. public function actionIndex()
  68. {
  69. if (\Yii::$app->user->isGuest) {
  70. $producer = $this->getProducerCurrent();
  71. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  72. }
  73. $searchModel = new SubscriptionSearch();
  74. $searchModel->id_user = GlobalParam::getCurrentUserId();
  75. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  76. return $this->render('index', [
  77. 'searchModel' => $searchModel,
  78. 'dataProvider' => $dataProvider
  79. ]);
  80. }
  81. public function actionAjaxProcess()
  82. {
  83. $orderModule = $this->getOrderModule();
  84. $subscriptionModule = $this->getSubscriptionModule();
  85. $model = new SubscriptionForm();
  86. $model->id_producer = GlobalParam::getCurrentProducerId();
  87. $model->id_user = GlobalParam::getCurrentUserId();
  88. $posts = \Yii::$app->request->post();
  89. $idSubscription = (int)$posts['idSubscription'];
  90. $isUpdate = false;
  91. if ($idSubscription) {
  92. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  93. if ($subscription) {
  94. $model->id = $idSubscription;
  95. $isUpdate = true;
  96. }
  97. }
  98. if ($model->load($posts) && $model->validate() && $model->save()) {
  99. $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($model->id);
  100. $orderModule->getManager()
  101. ->updateOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent(), $isUpdate);
  102. if ($isUpdate) {
  103. $this->setFlash('success', "L'abonnement a bien été modifié");
  104. } else {
  105. $this->setFlash('success', "L'abonnement a bien été ajouté");
  106. }
  107. }
  108. }
  109. /**
  110. * Crée un abonnement
  111. */
  112. public function actionForm(int $id = 0)
  113. {
  114. if (\Yii::$app->user->isGuest) {
  115. $producer = $this->getProducerCurrent();
  116. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  117. }
  118. $subscriptionModule = $this->getSubscriptionModule();
  119. if($id) {
  120. $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($id);
  121. if(!$subscription) {
  122. $this->setFlash('error', "L'abonnement est introuvable");
  123. return $this->redirect(['subscription/index']);
  124. }
  125. }
  126. return $this->render('form', [
  127. 'idSubscription' => $id
  128. ]);
  129. }
  130. /**
  131. * Modifie une commande récurrente.
  132. */
  133. public function actionUpdate(int $id)
  134. {
  135. if (\Yii::$app->user->isGuest) {
  136. $producer = $this->getProducerCurrent();
  137. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  138. }
  139. $subscriptionModule = $this->getSubscriptionModule();
  140. $model = new SubscriptionForm;
  141. $subscription = $subscriptionModule->findOneSubscriptionById($id);
  142. if ($subscription) {
  143. $model->id = $id;
  144. $model->id_producer = $subscription->id_producer;
  145. $model->id_user = $subscription->id_user;
  146. $model->username = $subscription->username;
  147. $model->id_point_sale = $subscription->id_point_sale;
  148. $model->date_begin = date('d/m/Y', strtotime($subscription->date_begin));
  149. if (strlen($subscription->date_end)) {
  150. $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
  151. }
  152. $model->monday = $subscription->monday;
  153. $model->tuesday = $subscription->tuesday;
  154. $model->wednesday = $subscription->wednesday;
  155. $model->thursday = $subscription->thursday;
  156. $model->friday = $subscription->friday;
  157. $model->saturday = $subscription->saturday;
  158. $model->sunday = $subscription->sunday;
  159. $model->auto_payment = Subscription::AUTO_PAYMENT_DEDUCTED;
  160. $model->week_frequency = $subscription->week_frequency;
  161. // produits
  162. $arrayProductsSubscription = ProductSubscription::searchAll([
  163. 'id_subscription' => $model->id
  164. ]);
  165. foreach ($arrayProductsSubscription as $productSubscription) {
  166. $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
  167. }
  168. } else {
  169. throw new NotFoundHttpException('L\'abonnement est introuvable.', 404);
  170. }
  171. $productsArray = $this->getProductModule()->findProducts();
  172. if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
  173. if (!strlen($model->date_end)) {
  174. $model->date_end = null;
  175. }
  176. if ($model->save()) {
  177. $this->setFlash('success', 'Abonnement modifié');
  178. $subscription = $subscriptionModule->findOneSubscriptionById($model->id);
  179. $matchedDistributionsArray = $this-> getDistributionModule()->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  180. if (count($matchedDistributionsArray)) {
  181. return $this->redirect(
  182. [
  183. 'subscription/update-distributions',
  184. 'idSubscription' => $subscription->id,
  185. 'update' => true
  186. ]
  187. );
  188. } else {
  189. return $this->redirect(['subscription/index']);
  190. }
  191. }
  192. }
  193. return $this->render('update', [
  194. 'model' => $model,
  195. 'productsArray' => $productsArray
  196. ]);
  197. }
  198. /**
  199. * Supprime un abonnement.
  200. */
  201. public function actionDelete($id)
  202. {
  203. if (\Yii::$app->user->isGuest) {
  204. $producer = $this->getProducerCurrent();
  205. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  206. }
  207. $subscriptionModule = $this->getSubscriptionModule();
  208. $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($id);
  209. if($subscription) {
  210. $subscriptionModule->getBuilder()->deleteSubscription($subscription);
  211. // @TODO : gérer via événements
  212. $this->getOrderModule()->getManager()
  213. ->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());
  214. $this->setFlash('success', "L'abonnement a bien été modifié");
  215. }
  216. else {
  217. $this->setFlash('error', 'Abonnement introuvable');
  218. }
  219. return $this->redirect(['subscription/index']);
  220. }
  221. public function actionAjaxInfos($idSubscription = 0)
  222. {
  223. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  224. $params = [];
  225. $productModule = $this->getProductModule();
  226. $subscriptionModule = $this->getSubscriptionModule();
  227. $user = $this->getUserCurrent();
  228. $userProducer = $this->getUserProducerModule()->findOneUserProducer($this->getUserCurrent());
  229. $pointSale = null;
  230. if ($idSubscription > 0) {
  231. $arrayProductsSubscription = ProductSubscription::searchAll([
  232. 'id_subscription' => $idSubscription
  233. ]);
  234. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  235. if ($subscription && $subscription->id_point_sale) {
  236. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($subscription->id_point_sale);
  237. }
  238. }
  239. // Produits
  240. $productsArray = $productModule->findProducts();
  241. $indexProduct = 0;
  242. foreach ($productsArray as &$product) {
  243. $quantity = 0;
  244. $coefficientUnit = $productModule->getSolver()->getUnitCoefficient($product);
  245. if (isset($arrayProductsSubscription) && count($arrayProductsSubscription)) {
  246. foreach ($arrayProductsSubscription as $productSubscription) {
  247. if ($product->id == $productSubscription->id_product) {
  248. $coefficientUnit = $productModule->getSolver()->getUnitCoefficient($productSubscription->product);
  249. $quantity = $productSubscription->quantity * $coefficientUnit;
  250. }
  251. }
  252. }
  253. $productPointSaleArray = [];
  254. foreach($product->productPointSale as $productPointSale) {
  255. $productPointSaleArray[] = $productPointSale->id_point_sale;
  256. }
  257. $product = array_merge(
  258. $product->getAttributes(),
  259. [
  260. 'index' => $indexProduct++,
  261. 'quantity_form' => $quantity,
  262. 'coefficient_unit' => $coefficientUnit,
  263. 'wording_unit' => $productModule->getSolver()->strUnit($product, UnitDefinition::WORDING_UNIT, true),
  264. 'wording_short' => $productModule->getSolver()->strUnit($product),
  265. 'price_with_tax' => $productModule->getPriceWithTax($product, [
  266. 'user' => $user,
  267. 'user_producer' => $userProducer,
  268. 'point_sale' => $pointSale
  269. ]),
  270. 'product_point_sale_array' => $productPointSaleArray
  271. ]
  272. );
  273. if($product['unit'] == 'piece' && is_null($product['step'])) {
  274. $product['step'] = 1;
  275. }
  276. }
  277. $params['products'] = $productsArray;
  278. $pointsSaleArray = $this->getPointSaleModule()->findPointSalesByUserAccess($user);
  279. foreach ($pointsSaleArray as &$pointSale) {
  280. $pointSale = array_merge($pointSale->getAttributes(), [
  281. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  282. ]);
  283. if ($pointSale['code'] && strlen($pointSale['code'])) {
  284. $pointSale['code'] = '***';
  285. }
  286. }
  287. $params['points_sale'] = $pointsSaleArray;
  288. if ($idSubscription > 0) {
  289. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  290. if (!$subscription || $subscription->id_user != GlobalParam::getCurrentUserId()) {
  291. throw new UserException('Abonnement introuvable');
  292. } else {
  293. $params = array_merge($params, $subscription->getAttributes());
  294. }
  295. }
  296. return $params;
  297. }
  298. /**
  299. * Vérifie le code saisi pour un point de vente.
  300. */
  301. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  302. {
  303. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  304. $pointSaleModule = $this->getPointSaleModule();
  305. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  306. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  307. return 1;
  308. }
  309. return 0;
  310. }
  311. }