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.

SubscriptionController.php 13KB

3 months ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  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 backend\controllers;
  38. use common\forms\SubscriptionForm;
  39. use common\helpers\GlobalParam;
  40. use domain\Product\Product\Product;
  41. use domain\Subscription\Subscription\SubscriptionSearch;
  42. use yii\filters\AccessControl;
  43. use yii\web\NotFoundHttpException;
  44. class SubscriptionController extends BackendController
  45. {
  46. var $enableCsrfValidation = false;
  47. public function behaviors()
  48. {
  49. return [
  50. 'access' => [
  51. 'class' => AccessControl::class,
  52. 'rules' => [
  53. [
  54. 'allow' => true,
  55. 'roles' => ['@'],
  56. 'matchCallback' => function ($rule, $action) {
  57. return $this->getUserModule()
  58. ->getAuthorizationChecker()
  59. ->isGrantedAsProducer($this->getUserCurrent());
  60. }
  61. ]
  62. ],
  63. ],
  64. ];
  65. }
  66. /**
  67. * Liste les commandes récurrente du producteur.
  68. *
  69. * @return string
  70. */
  71. public function actionIndex()
  72. {
  73. $this->checkProductsPointsSale();
  74. $searchModel = new SubscriptionSearch();
  75. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  76. return $this->render('index', [
  77. 'searchModel' => $searchModel,
  78. 'dataProvider' => $dataProvider
  79. ]);
  80. }
  81. /**
  82. * Crée un abonnement.
  83. */
  84. public function actionCreate($idOrder = 0)
  85. {
  86. $orderModule = $this->getOrderModule();
  87. $producerModule = $this->getProducerModule();
  88. $productModule = $this->getProductModule();
  89. $subscriptionManger = $this->getSubscriptionModule();
  90. $distributionModule = $this-> getDistributionModule();
  91. $model = new SubscriptionForm();
  92. $model->isAdmin = true;
  93. $model->id_producer = GlobalParam::getCurrentProducerId();
  94. if ($idOrder) {
  95. $order = $orderModule->findOneOrderById($idOrder);
  96. if ($order) {
  97. $model->id_user = $order->id_user;
  98. $model->username = $order->username;
  99. $model->id_point_sale = $order->id_point_sale;
  100. $model->date_begin = date('d/m/Y');
  101. $dateDay = strtolower(date('l', strtotime($order->distribution->date)));
  102. $model->$dateDay = 1;
  103. $model->week_frequency = 1;
  104. if ($model->id_user && $producerModule->getConfig('credit')) {
  105. $model->auto_payment = 1;
  106. }
  107. foreach ($order->productOrder as $productOrder) {
  108. $model->products['product_' . $productOrder->id_product] = $productOrder->quantity;
  109. }
  110. } else {
  111. throw new NotFoundHttpException('La commande est introuvable.', 404);
  112. }
  113. }
  114. // produits
  115. $productsArray = $productModule->findProducts();
  116. if ($model->load(\Yii::$app->request->post()) && $model->validate() && $model->save()) {
  117. $this->setFlash('success', 'Abonnement ajouté');
  118. $subscription = $subscriptionManger->findOneSubscriptionById($model->id);
  119. $matchedDistributionsArray = $distributionModule->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  120. if (count($matchedDistributionsArray)) {
  121. return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]);
  122. } else {
  123. return $this->redirect(['subscription/index']);
  124. }
  125. }
  126. return $this->render('create', [
  127. 'model' => $model,
  128. 'productsArray' => $productsArray
  129. ]);
  130. }
  131. /**
  132. * Modifie un abonnement.
  133. */
  134. public function actionUpdate($id)
  135. {
  136. $orderModule = $this->getOrderModule();
  137. $subscriptionModule = $this->getSubscriptionModule();
  138. $productSubscriptionModule = $this->getProductSubscriptionModule();
  139. $productModule = $this->getProductModule();
  140. $distributionModule = $this-> getDistributionModule();
  141. $model = new SubscriptionForm;
  142. $model->isAdmin = true;
  143. $subscription = $subscriptionModule->findOneSubscriptionById($id);
  144. if ($subscription) {
  145. $model->id = $id;
  146. $model->id_producer = $subscription->id_producer;
  147. $model->id_user = $subscription->id_user;
  148. $model->username = $subscription->username;
  149. $model->id_point_sale = $subscription->id_point_sale;
  150. $model->monday = $subscription->monday;
  151. $model->tuesday = $subscription->tuesday;
  152. $model->wednesday = $subscription->wednesday;
  153. $model->thursday = $subscription->thursday;
  154. $model->friday = $subscription->friday;
  155. $model->saturday = $subscription->saturday;
  156. $model->sunday = $subscription->sunday;
  157. $model->auto_payment = $subscription->auto_payment;
  158. $model->week_frequency = $subscription->week_frequency;
  159. $model->date_begin = date('d/m/Y', strtotime($subscription->date_begin));
  160. if ($subscription->date_end) {
  161. $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
  162. }
  163. if (strlen($subscription->comment)) {
  164. $model->comment = $subscription->comment;
  165. }
  166. $arrayProductsSubscription = $productSubscriptionModule->findProductSubscriptionsBySubscription($subscription);
  167. foreach ($arrayProductsSubscription as $productSubscription) {
  168. $model->products['product_' . $productSubscription->id_product] = $productSubscription->quantity;
  169. }
  170. } else {
  171. throw new NotFoundHttpException('L\'abonnement est introuvable.', 404);
  172. }
  173. // produits
  174. $productsArray = $productModule->findProducts();
  175. if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
  176. if (!$model->date_end) {
  177. $model->date_end = null;
  178. }
  179. if ($model->save()) {
  180. $subscription = $subscriptionModule->findOneSubscriptionById($model->id);
  181. $messageOrdersDeleted = '';
  182. if ($model->date_end) {
  183. $countOrdersDeleted = $orderModule->getManager()
  184. ->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent(), true);
  185. if ($countOrdersDeleted) {
  186. $messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées';
  187. }
  188. }
  189. $this->setFlash('success', 'Abonnement modifié' . $messageOrdersDeleted);
  190. $matchedDistributionsArray = $distributionModule->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  191. if (count($matchedDistributionsArray)) {
  192. return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id, 'update' => true]);
  193. } else {
  194. return $this->redirect(['subscription/index']);
  195. }
  196. }
  197. }
  198. return $this->render('update', [
  199. 'model' => $model,
  200. 'productsArray' => $productsArray
  201. ]);
  202. }
  203. /**
  204. * Supprime une commande récurrente.
  205. */
  206. public function actionDelete(int $id)
  207. {
  208. $orderModule = $this->getOrderModule();
  209. $subscriptionModule = $this->getSubscriptionModule();
  210. $subscription = $subscriptionModule->getRepository()->findOneSubscriptionById($id);
  211. if($subscription) {
  212. $orderModule->getManager()->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());
  213. $subscriptionModule->deleteSubscription($subscription);
  214. $this->setFlash('success', 'Abonnement supprimé');
  215. }
  216. else {
  217. $this->setFlash('danger', 'Abonnement introuvable');
  218. }
  219. return $this->redirect(['subscription/index']);
  220. }
  221. public function actionUpdateDistributions(int $idSubscription, bool $generate = false, bool $update = false)
  222. {
  223. $orderModule = $this->getOrderModule();
  224. $subscriptionModule = $this->getSubscriptionModule();
  225. $distributionModule = $this-> getDistributionModule();
  226. $subscription = $subscriptionModule->findOneSubscriptionById($idSubscription);
  227. if($subscription) {
  228. $matchedDistributionsArray = $distributionModule->findDistributionsIncomingMatchWithSubscrtiption($subscription, true);
  229. if ($generate) {
  230. if ($update) {
  231. $orderModule->getManager()
  232. ->deleteOrdersIncomingDistributionsFromSubscription($subscription, $this->getUserCurrent());
  233. }
  234. foreach ($matchedDistributionsArray as $distribution) {
  235. $orderModule->getManager()->createOrderFromSubscription($subscription, $distribution->date, $this->getUserCurrent());
  236. }
  237. $this->setFlash('success', 'Commandes ' . ($update ? 're-' : '') . 'générées dans les distributions futures.');
  238. return $this->redirect(['subscription/index']);
  239. }
  240. return $this->render('update_distributions', [
  241. 'matchedDistributionsArray' => $matchedDistributionsArray,
  242. 'idSubscription' => $idSubscription,
  243. 'update' => $update
  244. ]);
  245. }
  246. else {
  247. $this->setFlash('error', 'Abonnement introuvable');
  248. return $this->redirect(['subscription/index']);
  249. }
  250. }
  251. public function actionAjaxInfos(int $idSubscription = 0)
  252. {
  253. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  254. $unitModule = $this->getUnitModule();
  255. $productModule = $this->getProductModule();
  256. $productsQuery = Product::find()
  257. ->where(['id_producer' => GlobalParam::getCurrentProducerId()])
  258. ->andWhere('status >= :status')
  259. ->addParams(['status' => Product::STATUS_OFFLINE]);
  260. if ($idSubscription) {
  261. $productsQuery->joinWith(['productSubscription' => function ($query) use ($idSubscription) {
  262. $query->andOnCondition('product_subscription.id_subscription = ' . ((int)$idSubscription));
  263. }]);
  264. }
  265. $productsArray = $productsQuery->asArray()->orderBy('order ASC')->all();
  266. foreach ($productsArray as &$theProduct) {
  267. $theProduct['wording_unit'] = $unitModule->getSolver()->strUnit($theProduct['unit']);
  268. if (isset($theProduct['productSubscription'][0])) {
  269. $theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * Product::$unitsArray[$theProduct['unit']]['coefficient'];
  270. } else {
  271. $theProduct['quantity'] = '';
  272. }
  273. }
  274. return [
  275. 'products' => $productsArray
  276. ];
  277. }
  278. }