No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.

UserController.php 22KB

hace 8 años
hace 8 años
hace 8 años
hace 1 año
hace 8 años
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  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 backend\models\CreditForm;
  39. use common\helpers\GlobalParam;
  40. use backend\models\MailForm;
  41. use common\helpers\MeanPayment;
  42. use common\helpers\Password;
  43. use common\logic\Order\Order\Model\OrderSearch;
  44. use common\logic\PointSale\PointSale\Model\PointSale;
  45. use common\logic\PointSale\UserPointSale\Model\UserPointSale;
  46. use common\logic\Payment\Model\Payment;
  47. use common\logic\User\User\Model\User;
  48. use common\logic\User\User\Model\UserSearch;
  49. use common\logic\User\UserProducer\Model\UserProducer;
  50. use common\logic\User\UserUserGroup\Model\UserUserGroup;
  51. use yii\base\UserException;
  52. use yii\filters\AccessControl;
  53. use \Yii;
  54. use yii\helpers\Html;
  55. use yii\web\NotFoundHttpException;
  56. /**
  57. * UserController implements the CRUD actions for User model.
  58. */
  59. class UserController extends BackendController
  60. {
  61. public function behaviors()
  62. {
  63. return [
  64. 'access' => [
  65. 'class' => AccessControl::class,
  66. 'rules' => [
  67. [
  68. 'allow' => true,
  69. 'roles' => ['@'],
  70. 'matchCallback' => function ($rule, $action) {
  71. return $this->getUserManager()->hasAccessBackend();
  72. }
  73. ]
  74. ],
  75. ],
  76. ];
  77. }
  78. /**
  79. * Liste les utilisateurs.
  80. */
  81. public function actionIndex(
  82. int $idPointSale = 0,
  83. bool $sectionSubscribers = false,
  84. bool $sectionInactiveUsers = false)
  85. {
  86. $pointSaleManager = $this->getPointSaleManager();
  87. $searchModel = new UserSearch();
  88. $dataProvider = $searchModel->search([
  89. 'UserSearch' => array_merge(
  90. [
  91. 'id_point_sale' => $idPointSale,
  92. 'inactive' => (int) $sectionInactiveUsers,
  93. 'subscribers' => (int) $sectionSubscribers
  94. ],
  95. isset(\Yii::$app->request->queryParams['UserSearch']) ?
  96. Yii::$app->request->queryParams['UserSearch'] :
  97. []
  98. )
  99. ]);
  100. $producer = $this->getProducerCurrent();
  101. $pointsSaleArray = $pointSaleManager->findPointSales();
  102. return $this->render('index', [
  103. 'searchModel' => $searchModel,
  104. 'dataProvider' => $dataProvider,
  105. 'producer' => $producer,
  106. 'idPointSaleActive' => $idPointSale,
  107. 'pointsSaleArray' => $pointsSaleArray,
  108. 'sectionInactiveUsers' => $sectionInactiveUsers,
  109. 'sectionSubscribers' => $sectionSubscribers,
  110. ]);
  111. }
  112. public function actionCreate()
  113. {
  114. $userManager = $this->getUserManager();
  115. $producerManager = $this->getProducerManager();
  116. $producerCurrent = $this->getProducerCurrent();
  117. $model = $userManager->instanciateUser();
  118. $posts = Yii::$app->request->post();
  119. $userExist = false;
  120. if ($posts && isset($posts['User']['email']) && strlen($posts['User']['email']) > 0) {
  121. $userExist = $userManager->findOneUserByEmail($posts['User']['email']);
  122. }
  123. if ($userExist) {
  124. $producerManager->addUser($userExist, $producerCurrent);
  125. $this->processLinkPointSale($userExist);
  126. $this->processLinkUserGroup($userExist);
  127. $this->setFlash('success', "L'utilisateur que vous souhaitez créer possède déjà un compte sur la plateforme. Il vient d'être lié à votre établissement.");
  128. } else {
  129. if ($model->load(\Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
  130. $model->id_producer = 0;
  131. $password = Password::generate();
  132. $userManager->setPassword($model, $password);
  133. $userManager->generateAuthKey($model);
  134. $model->username = $model->email;
  135. if (!strlen($model->email)) {
  136. $model->username = 'inconnu@opendistrib.net';
  137. }
  138. $model->save();
  139. // liaison etablissement / user
  140. $useProducer = new UserProducer();
  141. $useProducer->id_user = $model->id;
  142. $useProducer->id_producer = GlobalParam::getCurrentProducerId();
  143. $useProducer->credit = 0;
  144. $useProducer->active = 1;
  145. $useProducer->newsletter = $model->newsletter;
  146. $useProducer->save();
  147. $userManager->sendMailWelcome($model, $password);
  148. $this->processLinkPointSale($model);
  149. $this->processLinkUserGroup($model);
  150. $this->processProductPricePercent($model);
  151. $this->setFlash('success', 'Utilisateur créé.');
  152. $model = $userManager->instanciateUser();
  153. }
  154. }
  155. return $this->render('create', array_merge($this->initForm($model), [
  156. 'model' => $model,
  157. ]));
  158. }
  159. public function actionUpdate($id)
  160. {
  161. $userManager = $this->getUserManager();
  162. $pointSaleManager = $this->getPointSaleManager();
  163. $model = $this->findModel($id);
  164. $previousMail = $model->email;
  165. $user = User::find()->with('userProducer')->where(['id' => $model['id']])->one();
  166. $userBelongToProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]);
  167. if ($userBelongToProducer) {
  168. $model->newsletter = $userBelongToProducer->newsletter;
  169. if ($model->load(\Yii::$app->request->post()) && $model->save()) {
  170. // on envoie le mail de bienvenue si le mail vient d'être défini
  171. if (!strlen($previousMail) && strlen($model->email)) {
  172. $password = Password::generate();
  173. $userManager->setPassword($model, $password);
  174. $model->username = $model->email;
  175. $userManager->sendMailWelcome($model, $password);
  176. }
  177. $this->processLinkPointSale($model);
  178. $this->processLinkUserGroup($model);
  179. $this->processProductPricePercent($model);
  180. if($model->newsletter) {
  181. $userManager->subscribeUserNewsletter($model);
  182. }
  183. else {
  184. $userManager->unsubscribeUserNewsletter($model);
  185. }
  186. $this->setFlash('success', 'Utilisateur <strong>'.Html::encode($userManager->getUsername($model)).'</strong> modifié.');
  187. return $this->redirect(['index']);
  188. }
  189. } else {
  190. throw new UserException("Vous ne pouvez pas modifier cet utilisateur.");
  191. }
  192. // Nouveau mot de passe
  193. $newPassword = Yii::$app->request->post('submit_new_password');
  194. if ($newPassword) {
  195. $password = Password::generate();
  196. $userManager->setPassword($model, $password);
  197. $model->save();
  198. $producer = $this->getProducerCurrent();
  199. \Yii::$app->mailerService->sendFromProducer(
  200. 'Nouveau mot de passe',
  201. 'newPasswordUserAdmin',
  202. [
  203. 'user' => $user,
  204. 'producer' => $producer,
  205. 'password' => $password,
  206. ],
  207. $model->email,
  208. $producer
  209. );
  210. $this->setFlash('success', 'Nouveau mot de passe envoyé à <strong>'.Html::encode($userManager->getUsername($model)).'</strong>.');
  211. return $this->redirect(['index']);
  212. }
  213. return $this->render('update', array_merge($this->initForm($model), [
  214. 'model' => $model,
  215. 'pointSaleBillingArray' => $pointSaleManager->findByBillingUser($model)
  216. ]));
  217. }
  218. public function initForm($model)
  219. {
  220. $userPointSaleManager = $this->getUserPointSaleManager();
  221. $userUserGroupManager = $this->getUserUserGroupManager();
  222. $userProducerManager = $this->getUserProducerManager();
  223. $userGroupManager = $this->getUserGroupManager();
  224. if ($model->id) {
  225. $userPointSaleArray = $userPointSaleManager->findUserPointSalesByUser($model);
  226. if ($userPointSaleArray && count($userPointSaleArray) > 0) {
  227. foreach ($userPointSaleArray as $userPointSale) {
  228. $model->points_sale[] = $userPointSale->id_point_sale;
  229. }
  230. }
  231. $userUserGroupsArray = $userUserGroupManager->findUserUserGroupsByUser($model);
  232. if ($userUserGroupsArray && count($userUserGroupsArray) > 0) {
  233. foreach ($userUserGroupsArray as $userUserGroup) {
  234. $model->user_groups[] = $userUserGroup->id_user_group;
  235. }
  236. }
  237. $userProducer = $userProducerManager->findOneUserProducer($model);
  238. $model->product_price_percent = $userProducer->product_price_percent;
  239. }
  240. $pointsSaleArray = PointSale::find()
  241. ->where([
  242. 'id_producer' => GlobalParam::getCurrentProducerId(),
  243. 'status' => 1
  244. ])
  245. ->joinWith(['userPointSale' => function ($query) use ($model) {
  246. if ($model->id) {
  247. $query->andOnCondition('user_point_sale.id_user = ' . $model->id);
  248. }
  249. }])
  250. ->all();
  251. $userGroupsArray = $userGroupManager->findUserGroups();
  252. return [
  253. 'pointsSaleArray' => $pointsSaleArray,
  254. 'userGroupsArray' => $userGroupsArray,
  255. ];
  256. }
  257. /**
  258. * Lie un utilisateur aux points de vente sélectionnés.
  259. */
  260. public function processLinkPointSale(User $modelUser)
  261. {
  262. $posts = Yii::$app->request->post();
  263. $userPointSaleManager = $this->getUserPointSaleManager();
  264. $pointSaleManager = $this->getPointSaleManager();
  265. UserPointSale::deleteAll([
  266. 'id_user' => $modelUser->id
  267. ]);
  268. if (is_array($modelUser->points_sale) && count($modelUser->points_sale) > 0) {
  269. foreach ($modelUser->points_sale as $pointSaleId) {
  270. $pointSale = $pointSaleManager->findOnePointSaleById($pointSaleId);
  271. $userPointSale = $userPointSaleManager->findOneUserPointSale($modelUser, $pointSale);
  272. if (!$userPointSale) {
  273. $userPointSale = new UserPointSale;
  274. $userPointSale->id_user = $modelUser->id;
  275. $userPointSale->id_point_sale = $pointSaleId;
  276. $userPointSale->comment = isset($posts['User']['comment_point_sale_' . $pointSaleId]) ? $posts['User']['comment_point_sale_' . $pointSaleId] : '';
  277. $userPointSale->save();
  278. }
  279. }
  280. }
  281. }
  282. /**
  283. * Lie un utilisateur aux groupes d'utilisateurs sélectionnés.
  284. */
  285. public function processLinkUserGroup($modelUser)
  286. {
  287. UserUserGroup::deleteAll([
  288. 'id_user' => $modelUser->id
  289. ]);
  290. if (is_array($modelUser->user_groups) && count($modelUser->user_groups) > 0) {
  291. foreach ($modelUser->user_groups as $userGroupId) {
  292. $userUserGroup = UserUserGroup::searchOne([
  293. 'id_user' => $modelUser->id,
  294. 'id_user_group' => $userGroupId
  295. ]);
  296. if (!$userUserGroup) {
  297. $userUserGroup = new UserUserGroup();
  298. $userUserGroup->id_user = $modelUser->id;
  299. $userUserGroup->id_user_group = $userGroupId;
  300. $userUserGroup->save();
  301. }
  302. }
  303. }
  304. }
  305. public function processProductPricePercent($model)
  306. {
  307. $userProducer = UserProducer::searchOne([
  308. 'id_producer' => GlobalParam::getCurrentProducerId(),
  309. 'id_user' => $model->id
  310. ]);
  311. $userProducer->product_price_percent = $model->product_price_percent;
  312. $userProducer->save();
  313. }
  314. /**
  315. * Désactive l'utilisateur de l'établissement.
  316. */
  317. public function actionDelete(int $id)
  318. {
  319. $userManager = $this->getUserManager();
  320. $userProducerManager = $this->getUserProducerManager();
  321. $user = $userManager->findOneUserById($id);
  322. $userProducer = $userProducerManager->findOneUserProducer($user);
  323. if ($userProducer) {
  324. if($userProducerManager->hasOutstandingCredit($userProducer)) {
  325. $this->setFlash('error', "Vous ne pouvez pas supprimer cet utilisateur car il a toujours du crédit en cours.");
  326. }
  327. else {
  328. $userProducerManager->unlinkUserProducer($userProducer);
  329. $this->setFlash('success', 'L\'utilisateur a bien été supprimé de votre établissement.');
  330. }
  331. } else {
  332. throw new \yii\web\NotFoundHttpException('L\'enregistrement UserProducer est introuvable', 404);
  333. }
  334. $params = Yii::$app->getRequest()->getQueryParams();
  335. unset($params['id']);
  336. $this->redirect(array_merge(['index'], $params));
  337. }
  338. /**
  339. * Affiche les données liées au crédit d'un utilisateur (formulaire, historique).
  340. */
  341. public function actionCredit(int $id)
  342. {
  343. $userManager = $this->getUserManager();
  344. $paymentContainer = $this->getPaymentContainer();
  345. $userProducerContainer = $this->getUserProducerContainer();
  346. $user = $userManager->findOneUserById($id);
  347. $userProducer = $userProducerContainer->getRepository()->findOneUserProducer($user);
  348. if ($userProducer) {
  349. $creditForm = new CreditForm();
  350. if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
  351. $paymentContainer->getUtils()
  352. ->creditOrDebitUser($creditForm->type, $user, $creditForm->amount, $creditForm->mean_payment, $this->getUserCurrent(), $creditForm->comment);
  353. if($creditForm->send_mail) {
  354. $paymentContainer->getNotifier()
  355. ->notifyUserCreditMovement($user, $creditForm->type, $creditForm->amount);
  356. if(!$user->email) {
  357. $this->addFlash('error', "L'utilisateur n'a pas pu être prévenu car son adresse email n'est pas définie.");
  358. }
  359. }
  360. $this->addFlash('success', 'Crédit mis à jour.');
  361. return $this->refresh();
  362. }
  363. return $this->render('credit', [
  364. 'user' => $user,
  365. 'userProducer' => $userProducer,
  366. 'creditForm' => $creditForm,
  367. 'dataProvider' => $paymentContainer->getRepository()
  368. ->queryPaymentsCreditHistoryByUser($user)->getDataProvider(20),
  369. ]);
  370. } else {
  371. throw new UserException("Utilisateur introuvable.");
  372. }
  373. }
  374. /**
  375. * Modifie l'option "credit_active" d'un utilisateur pour le producteur courant.
  376. * Redirige vers la page de crédit de l'utilisateur.
  377. */
  378. public function actionStateCredit($idUser, $state)
  379. {
  380. $userManager = $this->getUserManager();
  381. $userProducerManager = $this->getUserProducerManager();
  382. $user = $userManager->findOneUserById($idUser);
  383. $userProducer = $userProducerManager->findOneUserProducer($user);
  384. if ($userProducer) {
  385. $userProducer->credit_active = $state;
  386. $userProducer->save();
  387. }
  388. return $this->redirect(['user/credit', 'id' => $idUser]);
  389. }
  390. /**
  391. * Affiche les commandes d'un utilisateur.
  392. *
  393. * @param integer $id
  394. * @return mixed
  395. */
  396. public function actionOrders($id)
  397. {
  398. $userManager = $this->getUserManager();
  399. $user = $userManager->findOneUserById($id);
  400. $searchModel = new OrderSearch();
  401. $dataProvider = $searchModel->search(array_merge(\Yii::$app->request->queryParams, ['id_user' => $id]));
  402. return $this->render('orders', [
  403. 'user' => $user,
  404. 'searchModel' => $searchModel,
  405. 'dataProvider' => $dataProvider,
  406. ]);
  407. }
  408. /**
  409. * Finds the User model based on its primary key value.
  410. * If the model is not found, a 404 HTTP exception will be thrown.
  411. */
  412. protected function findModel($id)
  413. {
  414. $userManager = $this->getUserManager();
  415. if (($user = $userManager->findOneUserById($id)) !== null) {
  416. return $user;
  417. } else {
  418. throw new NotFoundHttpException("Utilisateur introuvable");
  419. }
  420. }
  421. /**
  422. * Affiche la liste des emails des utilisateurs liés à un point de vente donné.
  423. */
  424. public function actionMail(
  425. $idPointSale = 0,
  426. $sectionSubscribers = 0,
  427. $sectionInactiveUsers = 0,
  428. $usersPointSaleLink = 0,
  429. $usersPointSaleHasOrder = 0)
  430. {
  431. $userManager = $this->getUserManager();
  432. $distributionManager = $this->getDistributionManager();
  433. if ($idPointSale && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
  434. $usersPointSaleLink = 1;
  435. }
  436. $users = $userManager->queryUsersBy([
  437. 'id_producer' => GlobalParam::getCurrentProducerId(),
  438. 'id_point_sale' => $idPointSale,
  439. 'users_point_sale_link' => $usersPointSaleLink,
  440. 'users_point_sale_has_order' => $usersPointSaleHasOrder,
  441. 'subscribers' => $sectionSubscribers,
  442. 'inactive' => $sectionInactiveUsers,
  443. 'newsletter' => true
  444. ])->all();
  445. $usersArray = [];
  446. foreach ($users as $key => $user) {
  447. if (isset($user['email']) && strlen($user['email']) > 0) {
  448. $usersArray[] = $user['email'];
  449. }
  450. else {
  451. unset($users[$key]);
  452. }
  453. }
  454. $pointsSaleArray = PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->all();
  455. $pointSale = null;
  456. if ($idPointSale) {
  457. $pointSale = PointSale::findOne(['id' => $idPointSale]);
  458. }
  459. $mailForm = new MailForm();
  460. if ($mailForm->load(\Yii::$app->request->post()) && $mailForm->validate()) {
  461. $responseSendMail = $mailForm->sendEmail($users);
  462. if ($responseSendMail->success()) {
  463. $this->setFlash('success', 'Votre email a bien été envoyé.');
  464. } else {
  465. $bodyResponseSendMail = $responseSendMail->getBody();
  466. $emailsErrorArray = [];
  467. if (isset($bodyResponseSendMail['Messages'])) {
  468. foreach ($bodyResponseSendMail['Messages'] as $message) {
  469. if ($message['Status'] != 'success') {
  470. $emailsErrorArray[] = $message['Errors'][0]['ErrorMessage'];
  471. }
  472. }
  473. }
  474. $messageError = 'Un problème est survenu lors de l\'envoi de votre email.';
  475. if (count($emailsErrorArray) > 0) {
  476. $messageError .= '<br />Problème détecté : ' . implode(',', $emailsErrorArray);
  477. }
  478. $this->setFlash('error', $messageError);
  479. }
  480. return $this->redirect(['mail', 'idPointSale' => $idPointSale]);
  481. }
  482. $incomingDistributions = $distributionManager->findDistributionsIncoming();
  483. $incomingDistributionsArray = ['0' => '--'];
  484. foreach ($incomingDistributions as $distribution) {
  485. $incomingDistributionsArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date));
  486. }
  487. return $this->render('emails', [
  488. 'usersArray' => $usersArray,
  489. 'pointsSaleArray' => $pointsSaleArray,
  490. 'pointSale' => $pointSale,
  491. 'mailForm' => $mailForm,
  492. 'idPointSaleActive' => $idPointSale,
  493. 'incomingDistributionsArray' => $incomingDistributionsArray,
  494. 'sectionSubscribers' => $sectionSubscribers,
  495. 'sectionInactiveUsers' => $sectionInactiveUsers,
  496. 'usersPointSaleLink' => $usersPointSaleLink,
  497. 'usersPointSaleHasOrder' => $usersPointSaleHasOrder,
  498. ]);
  499. }
  500. public function actionSwitchIdentity(int $id)
  501. {
  502. $userManager = $this->getUserManager();
  503. if($this->isUserCurrentAdmin()) {
  504. $initialId = Yii::$app->user->getId();
  505. if($initialId != $id) {
  506. $user = $userManager->findOneUserById($id);
  507. $duration = 0;
  508. Yii::$app->user->switchIdentity($user, $duration);
  509. Yii::$app->session->set('user.idbeforeswitch',$initialId);
  510. return $this->redirect(['index']);
  511. }
  512. }
  513. else {
  514. throw new NotFoundHttpException('Page introuvable');
  515. }
  516. }
  517. }