Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

SubscriptionController.php 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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\Config\Unit\Service\UnitDefinition;
  41. use common\logic\Product\Product\Model\Product;
  42. use common\logic\Subscription\ProductSubscription\Model\ProductSubscription;
  43. use common\logic\Subscription\Subscription\Model\Subscription;
  44. use common\logic\Subscription\Subscription\Model\SubscriptionSearch;
  45. use yii\base\UserException;
  46. use yii\filters\AccessControl;
  47. use yii\web\NotFoundHttpException;
  48. class SubscriptionController extends ProducerBaseController
  49. {
  50. var $enableCsrfValidation = false;
  51. public function behaviors()
  52. {
  53. return [
  54. 'access' => [
  55. 'class' => AccessControl::class,
  56. 'rules' => [
  57. [
  58. 'allow' => true,
  59. 'roles' => ['@'],
  60. ]
  61. ],
  62. ],
  63. ];
  64. }
  65. /**
  66. * Liste les abonnements de l'utilisateur.
  67. */
  68. public function actionIndex()
  69. {
  70. if (\Yii::$app->user->isGuest) {
  71. $producer = $this->getProducerCurrent();
  72. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  73. }
  74. $searchModel = new SubscriptionSearch();
  75. $searchModel->id_user = GlobalParam::getCurrentUserId();
  76. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  77. return $this->render('index', [
  78. 'searchModel' => $searchModel,
  79. 'dataProvider' => $dataProvider
  80. ]);
  81. }
  82. public function actionAjaxProcess()
  83. {
  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. $subscriptionModule->getOrderManager()
  101. ->updateOrdersIncomingDistributionsFromSubscription($subscription, $isUpdate);
  102. if ($isUpdate) {
  103. $this->setFlash('success', 'Abonnement modifié');
  104. } else {
  105. $this->setFlash('success', 'Abonnement ajouté');
  106. }
  107. }
  108. }
  109. /**
  110. * Crée une commande récurrente.
  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. return $this->render('form', [
  119. 'idSubscription' => $id
  120. ]);
  121. }
  122. /**
  123. * Modifie une commande récurrente.
  124. */
  125. public function actionUpdate(int $id)
  126. {
  127. if (\Yii::$app->user->isGuest) {
  128. $producer = $this->getProducerCurrent();
  129. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  130. }
  131. $subscriptionModule = $this->getSubscriptionModule();
  132. $model = new SubscriptionForm;
  133. $subscription = $subscriptionModule->findOneSubscriptionById($id);
  134. if ($subscription) {
  135. $model->id = $id;
  136. $model->id_producer = $subscription->id_producer;
  137. $model->id_user = $subscription->id_user;
  138. $model->username = $subscription->username;
  139. $model->id_point_sale = $subscription->id_point_sale;
  140. $model->date_begin = date('d/m/Y', strtotime($subscription->date_begin));
  141. if (strlen($subscription->date_end)) {
  142. $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
  143. }
  144. $model->monday = $subscription->monday;
  145. $model->tuesday = $subscription->tuesday;
  146. $model->wednesday = $subscription->wednesday;
  147. $model->thursday = $subscription->thursday;
  148. $model->friday = $subscription->friday;
  149. $model->saturday = $subscription->saturday;
  150. $model->sunday = $subscription->sunday;
  151. $model->auto_payment = Subscription::AUTO_PAYMENT_DEDUCTED;
  152. $model->week_frequency = $subscription->week_frequency;
  153. // produits
  154. $arrayProductsSubscription = ProductSubscription::searchAll([
  155. 'id_subscription' => $model->id
  156. ]);
  157. foreach ($arrayProductsSubscription as $productSubscription) {
  158. $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
  159. }
  160. } else {
  161. throw new NotFoundHttpException('L\'abonnement est introuvable.', 404);
  162. }
  163. $productsArray = $this->getProductModule()->findProducts();
  164. if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
  165. if (!strlen($model->date_end)) {
  166. $model->date_end = null;
  167. }
  168. if ($model->save()) {
  169. $this->setFlash('success', 'Abonnement modifié');
  170. $subscription = $subscriptionModule->findOneSubscriptionById($model->id);
  171. $matchedDistributionsArray = $this-> getDistributionModule()->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  172. if (count($matchedDistributionsArray)) {
  173. return $this->redirect(
  174. [
  175. 'subscription/update-distributions',
  176. 'idSubscription' => $subscription->id,
  177. 'update' => true
  178. ]
  179. );
  180. } else {
  181. return $this->redirect(['subscription/index']);
  182. }
  183. }
  184. }
  185. return $this->render('update', [
  186. 'model' => $model,
  187. 'productsArray' => $productsArray
  188. ]);
  189. }
  190. /**
  191. * Supprime un abonnement.
  192. */
  193. public function actionDelete($id)
  194. {
  195. if (\Yii::$app->user->isGuest) {
  196. $producer = $this->getProducerCurrent();
  197. return $this->redirect($this->getUrlManagerFrontend()->createAbsoluteUrl(['site/producer', 'id' => $producer->id]));
  198. }
  199. $subscriptionModule = $this->getSubscriptionModule();
  200. $subscription = $subscriptionModule->findOneSubscriptionById($id);
  201. $subscriptionModule->deleteSubscription($subscription);
  202. // @TODO : gérer via événements
  203. $this->getSubscriptionModule()->getOrderManager()
  204. ->deleteOrdersIncomingDistributionsFromSubscription($subscription);
  205. $this->setFlash('success', 'Abonnement supprimé');
  206. return $this->redirect(['subscription/index']);
  207. }
  208. public function actionAjaxInfos($idSubscription = 0)
  209. {
  210. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  211. $params = [];
  212. $productModule = $this->getProductModule();
  213. $subscriptionModule = $this->getSubscriptionModule();
  214. $user = GlobalParam::getCurrentUser();
  215. $userProducer = $this->getUserProducerModule()->findOneUserProducer($this->getUserCurrent());
  216. $pointSale = null;
  217. if ($idSubscription > 0) {
  218. $arrayProductsSubscription = ProductSubscription::searchAll([
  219. 'id_subscription' => $idSubscription
  220. ]);
  221. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  222. if ($subscription && $subscription->id_point_sale) {
  223. $pointSale = $this->getPointSaleModule()->findOnePointSaleById($subscription->id_point_sale);
  224. }
  225. }
  226. // Produits
  227. $productsArray = $productModule->findProducts();
  228. $indexProduct = 0;
  229. foreach ($productsArray as &$product) {
  230. $quantity = 0;
  231. $coefficientUnit = $productModule->getSolver()->getUnitCoefficient($product);
  232. if (isset($arrayProductsSubscription) && count($arrayProductsSubscription)) {
  233. foreach ($arrayProductsSubscription as $productSubscription) {
  234. if ($product->id == $productSubscription->id_product) {
  235. $coefficientUnit = $productModule->getSolver()->getUnitCoefficient($productSubscription->product);
  236. $quantity = $productSubscription->quantity * $coefficientUnit;
  237. }
  238. }
  239. }
  240. $productPointSaleArray = [];
  241. foreach($product->productPointSale as $productPointSale) {
  242. $productPointSaleArray[] = $productPointSale->id_point_sale;
  243. }
  244. $product = array_merge(
  245. $product->getAttributes(),
  246. [
  247. 'index' => $indexProduct++,
  248. 'quantity_form' => $quantity,
  249. 'coefficient_unit' => $coefficientUnit,
  250. 'wording_unit' => $productModule->getSolver()->strUnit($product, UnitDefinition::WORDING_UNIT, true),
  251. 'wording_short' => $productModule->getSolver()->strUnit($product),
  252. 'price_with_tax' => $productModule->getPriceWithTax($product, [
  253. 'user' => $user,
  254. 'user_producer' => $userProducer,
  255. 'point_sale' => $pointSale
  256. ]),
  257. 'product_point_sale_array' => $productPointSaleArray
  258. ]
  259. );
  260. if($product['unit'] == 'piece' && is_null($product['step'])) {
  261. $product['step'] = 1;
  262. }
  263. }
  264. $params['products'] = $productsArray;
  265. $pointsSaleArray = $this->getPointSaleModule()->findPointSales();
  266. foreach ($pointsSaleArray as &$pointSale) {
  267. $pointSale = array_merge($pointSale->getAttributes(), [
  268. 'userPointSale' => ($pointSale->userPointSale ? $pointSale->userPointSale[0] : '')
  269. ]);
  270. if ($pointSale['code'] && strlen($pointSale['code'])) {
  271. $pointSale['code'] = '***';
  272. }
  273. }
  274. $params['points_sale'] = $pointsSaleArray;
  275. if ($idSubscription > 0) {
  276. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  277. if (!$subscription || $subscription->id_user != GlobalParam::getCurrentUserId()) {
  278. throw new UserException('Abonnement introuvable');
  279. } else {
  280. $params = array_merge($params, $subscription->getAttributes());
  281. }
  282. }
  283. return $params;
  284. }
  285. /**
  286. * Vérifie le code saisi pour un point de vente.
  287. */
  288. public function actionAjaxValidateCodePointSale($idPointSale, $code)
  289. {
  290. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  291. $pointSaleModule = $this->getPointSaleModule();
  292. $pointSale = $pointSaleModule->findOnePointSaleById($idPointSale);
  293. if ($pointSale && $pointSaleModule->validateCode($pointSale, $code)) {
  294. return 1;
  295. }
  296. return 0;
  297. }
  298. }