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.

UserController.php 23KB

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