Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

SubscriptionController.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  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 backend\controllers;
  38. use common\forms\SubscriptionForm;
  39. use common\helpers\GlobalParam;
  40. use common\logic\Product\Product\Model\Product;
  41. use common\logic\Subscription\Subscription\Model\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->getUserManager()->hasAccessBackend();
  58. }
  59. ]
  60. ],
  61. ],
  62. ];
  63. }
  64. /**
  65. * Liste les commandes récurrente du producteur.
  66. *
  67. * @return string
  68. */
  69. public function actionIndex()
  70. {
  71. $this->checkProductsPointsSale();
  72. $searchModel = new SubscriptionSearch();
  73. $dataProvider = $searchModel->search(\Yii::$app->request->queryParams);
  74. return $this->render('index', [
  75. 'searchModel' => $searchModel,
  76. 'dataProvider' => $dataProvider
  77. ]);
  78. }
  79. /**
  80. * Crée un abonnement.
  81. */
  82. public function actionCreate($idOrder = 0)
  83. {
  84. $orderManager = $this->getOrderManager();
  85. $producerManager = $this->getProducerManager();
  86. $productManager = $this->getProductManager();
  87. $subscriptionManger = $this->getSubscriptionManager();
  88. $distributionManager = $this->getDistributionManager();
  89. $model = new SubscriptionForm();
  90. $model->isAdmin = true;
  91. $model->id_producer = GlobalParam::getCurrentProducerId();
  92. if ($idOrder) {
  93. $order = $orderManager->findOneOrderById($idOrder);
  94. if ($order) {
  95. $model->id_user = $order->id_user;
  96. $model->username = $order->username;
  97. $model->id_point_sale = $order->id_point_sale;
  98. $model->date_begin = date('d/m/Y');
  99. $dateDay = strtolower(date('l', strtotime($order->distribution->date)));
  100. $model->$dateDay = 1;
  101. $model->week_frequency = 1;
  102. if ($model->id_user && $producerManager->getConfig('credit')) {
  103. $model->auto_payment = 1;
  104. }
  105. foreach ($order->productOrder as $productOrder) {
  106. $model->products['product_' . $productOrder->id_product] = $productOrder->quantity;
  107. }
  108. } else {
  109. throw new NotFoundHttpException('La commande est introuvable.', 404);
  110. }
  111. }
  112. // produits
  113. $productsArray = $productManager->findProducts();
  114. if ($model->load(\Yii::$app->request->post()) && $model->validate() && $model->save()) {
  115. $this->setFlash('success', 'Abonnement ajouté');
  116. $subscription = $subscriptionManger->findOneSubscriptionById($model->id);
  117. $matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  118. if (count($matchedDistributionsArray)) {
  119. return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id]);
  120. } else {
  121. return $this->redirect(['subscription/index']);
  122. }
  123. }
  124. return $this->render('create', [
  125. 'model' => $model,
  126. 'productsArray' => $productsArray
  127. ]);
  128. }
  129. /**
  130. * Modifie un abonnement.
  131. */
  132. public function actionUpdate($id)
  133. {
  134. $subscriptionManager = $this->getSubscriptionManager();
  135. $productSubscriptionManager = $this->getProductSubscriptionManager();
  136. $productManager = $this->getProductManager();
  137. $orderManager = $this->getOrderManager();
  138. $distributionManager = $this->getDistributionManager();
  139. $model = new SubscriptionForm;
  140. $model->isAdmin = true;
  141. $subscription = $subscriptionManager->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->monday = $subscription->monday;
  149. $model->tuesday = $subscription->tuesday;
  150. $model->wednesday = $subscription->wednesday;
  151. $model->thursday = $subscription->thursday;
  152. $model->friday = $subscription->friday;
  153. $model->saturday = $subscription->saturday;
  154. $model->sunday = $subscription->sunday;
  155. $model->auto_payment = $subscription->auto_payment;
  156. $model->week_frequency = $subscription->week_frequency;
  157. $model->date_begin = date('d/m/Y', strtotime($subscription->date_begin));
  158. if ($subscription->date_end) {
  159. $model->date_end = date('d/m/Y', strtotime($subscription->date_end));
  160. }
  161. if (strlen($subscription->comment)) {
  162. $model->comment = $subscription->comment;
  163. }
  164. $arrayProductsSubscription = $productSubscriptionManager->findProductSubscriptionsBySubscription($subscription);
  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. // produits
  172. $productsArray = $productManager->findProducts();
  173. if ($model->load(\Yii::$app->request->post()) && $model->validate()) {
  174. if (!$model->date_end) {
  175. $model->date_end = null;
  176. }
  177. if ($model->save()) {
  178. $subscription = $subscriptionManager->findOneSubscriptionById($model->id);
  179. $messageOrdersDeleted = '';
  180. if ($model->date_end) {
  181. $countOrdersDeleted = $orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription, true);
  182. if ($countOrdersDeleted) {
  183. $messageOrdersDeleted = '<br />' . $countOrdersDeleted . ' commandes supprimées';
  184. }
  185. }
  186. $this->setFlash('success', 'Abonnement modifié' . $messageOrdersDeleted);
  187. $matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  188. if (count($matchedDistributionsArray)) {
  189. return $this->redirect(['subscription/update-distributions', 'idSubscription' => $subscription->id, 'update' => true]);
  190. } else {
  191. return $this->redirect(['subscription/index']);
  192. }
  193. }
  194. }
  195. return $this->render('update', [
  196. 'model' => $model,
  197. 'productsArray' => $productsArray
  198. ]);
  199. }
  200. /**
  201. * Supprime une commande récurrente.
  202. */
  203. public function actionDelete(int $id)
  204. {
  205. $subscriptionManager = $this->getSubscriptionManager();
  206. $orderManager = $this->getOrderManager();
  207. $subscription = $subscriptionManager->findOneSubscriptionById($id);
  208. $orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription);
  209. $subscriptionManager->deleteSubscription($subscription);
  210. $this->setFlash('success', 'Abonnement supprimé');
  211. return $this->redirect(['subscription/index']);
  212. }
  213. public function actionUpdateDistributions(int $idSubscription, bool $generate = false, bool $update = false)
  214. {
  215. $subscriptionManager = $this->getSubscriptionManager();
  216. $distributionManager = $this->getDistributionManager();
  217. $orderManager = $this->getOrderManager();
  218. $subscription = $subscriptionManager->findOneSubscriptionById($idSubscription);
  219. $matchedDistributionsArray = $distributionManager->findDistributionsIncomingMatchWithSubscrtiption($subscription);
  220. if ($generate) {
  221. if ($update) {
  222. $orderManager->deleteOrdersIncomingDistributionsFromSubscription($subscription);
  223. }
  224. foreach ($matchedDistributionsArray as $distribution) {
  225. $orderManager->createOrderFromSubscription($subscription, $distribution->date);
  226. }
  227. $this->setFlash('success', 'Commandes ' . ($update ? 're-' : '') . 'générées dans les distributions futures.');
  228. return $this->redirect(['subscription/index']);
  229. }
  230. return $this->render('update_distributions', [
  231. 'matchedDistributionsArray' => $matchedDistributionsArray,
  232. 'idSubscription' => $idSubscription,
  233. 'update' => $update
  234. ]);
  235. }
  236. public function actionAjaxInfos(int $idSubscription = 0)
  237. {
  238. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  239. $productManager = $this->getProductManager();
  240. $productsQuery = Product::find()
  241. ->where(['id_producer' => GlobalParam::getCurrentProducerId(),]);
  242. if ($idSubscription) {
  243. $productsQuery->joinWith(['productSubscription' => function ($query) use ($idSubscription) {
  244. $query->andOnCondition('product_subscription.id_subscription = ' . ((int)$idSubscription));
  245. }]);
  246. }
  247. $productsArray = $productsQuery->asArray()->orderBy('order ASC')->all();
  248. foreach ($productsArray as &$theProduct) {
  249. $theProduct['wording_unit'] = $productManager->strUnit($theProduct['unit'], 'wording_short');
  250. if (isset($theProduct['productSubscription'][0])) {
  251. $theProduct['quantity'] = $theProduct['productSubscription'][0]['quantity'] * Product::$unitsArray[$theProduct['unit']]['coefficient'];
  252. } else {
  253. $theProduct['quantity'] = '';
  254. }
  255. }
  256. return [
  257. 'products' => $productsArray
  258. ];
  259. }
  260. }