Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

SubscriptionController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  1. <?php
  2. /**
  3. * Copyright distrib (2018)
  4. *
  5. * contact@opendistrib.net
  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 common\logic\Product\Product\Model\Product;
  41. use common\logic\Subscription\ProductSubscription\Model\ProductSubscription;
  42. use common\logic\Subscription\Subscription\Model\Subscription;
  43. use common\logic\Subscription\Subscription\Model\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. $subscriptionManager = $this->getSubscriptionManager();
  84. $model = new SubscriptionForm();
  85. $model->id_producer = GlobalParam::getCurrentProducerId();
  86. $model->id_user = GlobalParam::getCurrentUserId();
  87. $posts = \Yii::$app->request->post();
  88. $idSubscription = (int)$posts['idSubscription'];
  89. $isUpdate = false;
  90. if ($idSubscription) {
  91. $subscription = $subscriptionManager->findOneSubscriptionById($idSubscription);
  92. if ($subscription) {
  93. $model->id = $idSubscription;
  94. $isUpdate = true;
  95. }
  96. }
  97. if ($model->load($posts) && $model->validate() && $model->save()) {
  98. $subscription = $subscriptionManager->findOneSubscriptionById($model->id);
  99. $this->getOrderManager()->updateOrdersIncomingDistributionsFromSubscription($subscription, $isUpdate);
  100. if ($isUpdate) {
  101. $this->setFlash('success', 'Abonnement modifié');
  102. } else {
  103. $this->setFlash('success', 'Abonnement ajouté');
  104. }
  105. }
  106. }
  107. /**
  108. * Crée une commande récurrente.
  109. */
  110. public function actionForm(int $id = 0)
  111. {
  112. if (\Yii::$app->user->isGuest) {
  113. $producer = $this->getProducerCurrent();
  114. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  115. }
  116. return $this->render('form', [
  117. 'idSubscription' => $id
  118. ]);
  119. }
  120. /**
  121. * Modifie une commande récurrente.
  122. */
  123. public function actionUpdate(int $id)
  124. {
  125. if (\Yii::$app->user->isGuest) {
  126. $producer = $this->getProducerCurrent();
  127. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  128. }
  129. $subscriptionManager = $this->getSubscriptionManager();
  130. $model = new SubscriptionForm;
  131. $subscription = $subscriptionManager->findOneSubscriptionById($id);
  132. if ($subscription) {
  133. $model->id = $id;
  134. $model->id_producer = $subscription->id_producer;
  135. $model->id_user = $subscription->id_user;
  136. $model->username = $subscription->username;
  137. $model->id_point_sale = $subscription->id_point_sale;
  138. $model->date_begin = date('d/m/Y', strtotime($subscription->date_begin));
  139. if (strlen($subscription->date_end)) {
  140. $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
  141. }
  142. $model->monday = $subscription->monday;
  143. $model->tuesday = $subscription->tuesday;
  144. $model->wednesday = $subscription->wednesday;
  145. $model->thursday = $subscription->thursday;
  146. $model->friday = $subscription->friday;
  147. $model->saturday = $subscription->saturday;
  148. $model->sunday = $subscription->sunday;
  149. $model->auto_payment = Subscription::AUTO_PAYMENT_DEDUCTED;
  150. $model->week_frequency = $subscription->week_frequency;
  151. // produits
  152. $arrayProductsSubscription = ProductSubscription::searchAll([
  153. 'id_subscription' => $model->id
  154. ]);
  155. foreach ($arrayProductsSubscription as $productSubscription) {
  156. $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
  157. }
  158. } else {
  159. throw new NotFoundHttpException('L\'abonnement est introuvable.', 404);
  160. }
  161. $productsArray = $this->getProductManager()->findProducts();
  162. if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
  163. if (!strlen($model->date_end)) {
  164. $model->date_end = null;
  165. }
  166. if ($model->save()) {
  167. $this->setFlash('success', 'Abonnement modifié');
  168. $subscription = $subscriptionManager->findOneSubscriptionById($model->id);
  169. $matchedDistributionsArray = $this->getDistributionManager()->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  170. if (count($matchedDistributionsArray)) {
  171. return $this->redirect(
  172. [
  173. 'subscription/update-distributions',
  174. 'idSubscription' => $subscription->id,
  175. 'update' => true
  176. ]
  177. );
  178. } else {
  179. return $this->redirect(['subscription/index']);
  180. }
  181. }
  182. }
  183. return $this->render('update', [
  184. 'model' => $model,
  185. 'productsArray' => $productsArray
  186. ]);
  187. }
  188. /**
  189. * Supprime un abonnement.
  190. */
  191. public function actionDelete($id)
  192. {
  193. if (\Yii::$app->user->isGuest) {
  194. $producer = $this->getProducerCurrent();
  195. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  196. }
  197. $subscriptionManager = $this->getSubscriptionManager();
  198. $subscription = $subscriptionManager->findOneSubscriptionById($id);
  199. $subscriptionManager->deleteSubscription($subscription);
  200. // @TODO : gérer via événements
  201. $this->getOrderManager()->deleteOrdersIncomingDistributionsFromSubscription($subscription);
  202. $this->setFlash('success', 'Abonnement supprimé');
  203. return $this->redirect(['subscription/index']);
  204. }
  205. public function actionAjaxInfos($idSubscription = 0)
  206. {
  207. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  208. $params = [];
  209. $productManager = $this->getProductManager();
  210. $subscriptionManager = $this->getSubscriptionManager();
  211. $user = GlobalParam::getCurrentUser();
  212. $userProducer = $this->getUserProducerManager()->findOneUserProducer($this->getUserCurrent());
  213. $pointSale = null;
  214. if ($idSubscription > 0) {
  215. $arrayProductsSubscription = ProductSubscription::searchAll([
  216. 'id_subscription' => $idSubscription
  217. ]);
  218. $subscription = $subscriptionManager->findOneSubscriptionById($idSubscription);
  219. if ($subscription && $subscription->id_point_sale) {
  220. $pointSale = $this->getPointSaleManager()->findOnePointSaleById($subscription->id_point_sale);
  221. }
  222. }
  223. // Produits
  224. $productsArray = $productManager->findProducts();
  225. $indexProduct = 0;
  226. foreach ($productsArray as &$product) {
  227. $quantity = 0;
  228. $coefficientUnit = Product::$unitsArray[$product->unit]['coefficient'];
  229. if (isset($arrayProductsSubscription) && count($arrayProductsSubscription)) {
  230. foreach ($arrayProductsSubscription as $productSubscription) {
  231. if ($product->id == $productSubscription->id_product) {
  232. $coefficientUnit = Product::$unitsArray[$productSubscription->product->unit]['coefficient'];
  233. $quantity = $productSubscription->quantity * $coefficientUnit;
  234. }
  235. }
  236. }
  237. $productPointSaleArray = [];
  238. foreach($product->productPointSale as $productPointSale) {
  239. $productPointSaleArray[] = $productPointSale->id_point_sale;
  240. }
  241. $product = array_merge(
  242. $product->getAttributes(),
  243. [
  244. 'index' => $indexProduct++,
  245. 'quantity_form' => $quantity,
  246. 'coefficient_unit' => $coefficientUnit,
  247. 'wording_unit' => $productManager->strUnit($product->unit, 'wording_unit', true),
  248. 'wording_short' => $productManager->strUnit($product->unit, 'wording_short'),
  249. 'price_with_tax' => $productManager->getPriceWithTax($product, [
  250. 'user' => $user,
  251. 'user_producer' => $userProducer,
  252. 'point_sale' => $pointSale
  253. ]),
  254. 'product_point_sale_array' => $productPointSaleArray
  255. ]
  256. );
  257. if($product['unit'] == 'piece' && is_null($product['step'])) {
  258. $product['step'] = 1;
  259. }
  260. }
  261. $params['products'] = $productsArray;
  262. $pointsSaleArray = $this->getPointSaleManager()->findPointSales();
  263. foreach ($pointsSaleArray as &$pointSale) {
  264. $pointSale = array_merge($pointSale->getAttributes(), [
  265. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  266. ]);
  267. if ($pointSale['code'] && strlen($pointSale['code'])) {
  268. $pointSale['code'] = '***';
  269. }
  270. }
  271. $params['points_sale'] = $pointsSaleArray;
  272. if ($idSubscription > 0) {
  273. $subscription = $subscriptionManager->findOneSubscriptionById($idSubscription);
  274. if (!$subscription || $subscription->id_user != GlobalParam::getCurrentUserId()) {
  275. throw new UserException('Abonnement introuvable');
  276. } else {
  277. $params = array_merge($params, $subscription->getAttributes());
  278. }
  279. }
  280. return $params;
  281. }
  282. /**
  283. * Vérifie le code saisi pour un point de vente.
  284. */
  285. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  286. {
  287. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  288. $pointSaleManager = $this->getPointSaleManager();
  289. $pointSale = $pointSaleManager->findOnePointSaleById($idPointSale);
  290. if ($pointSale && $pointSaleManager->validateCode($pointSale, $code)) {
  291. return 1;
  292. }
  293. return 0;
  294. }
  295. }