Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

UserController.php 22KB

8 лет назад
6 лет назад
8 лет назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
8 лет назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
1 год назад
8 лет назад
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  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. $user = User::find()->with('userProducer')->where(['id' => $id])->one();
  344. $userProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]);
  345. if (($userProducer) || $this->isUserCurrentAdmin()) {
  346. $creditForm = new CreditForm();
  347. if ($creditForm->load(\Yii::$app->request->post()) && $creditForm->validate()) {
  348. $creditForm->id_user = $id;
  349. $creditForm->save();
  350. $creditForm = new CreditForm;
  351. }
  352. $history = Payment::find()
  353. ->with(['order', 'userAction'])
  354. ->where([
  355. 'id_user' => $user->id,
  356. 'id_producer' => GlobalParam::getCurrentProducerId(),
  357. 'mean_payment' => MeanPayment::CREDIT
  358. ])
  359. ->orderBy('date DESC')
  360. ->all();
  361. return $this->render('credit', [
  362. 'user' => $user,
  363. 'userProducer' => $userProducer,
  364. 'creditForm' => $creditForm,
  365. 'history' => $history
  366. ]);
  367. } else {
  368. throw new UserException("Vous ne pouvez pas créditer un utilisateur qui n'est pas associé à votre établissement.");
  369. }
  370. }
  371. /**
  372. * Modifie l'option "credit_active" d'un utilisateur pour le producteur courant.
  373. * Redirige vers la page de crédit de l'utilisateur.
  374. */
  375. public function actionStateCredit($idUser, $state)
  376. {
  377. $userManager = $this->getUserManager();
  378. $userProducerManager = $this->getUserProducerManager();
  379. $user = $userManager->findOneUserById($idUser);
  380. $userProducer = $userProducerManager->findOneUserProducer($user);
  381. if ($userProducer) {
  382. $userProducer->credit_active = $state;
  383. $userProducer->save();
  384. }
  385. return $this->redirect(['user/credit', 'id' => $idUser]);
  386. }
  387. /**
  388. * Affiche les commandes d'un utilisateur.
  389. *
  390. * @param integer $id
  391. * @return mixed
  392. */
  393. public function actionOrders($id)
  394. {
  395. $userManager = $this->getUserManager();
  396. $user = $userManager->findOneUserById($id);
  397. $searchModel = new OrderSearch();
  398. $dataProvider = $searchModel->search(array_merge(\Yii::$app->request->queryParams, ['id_user' => $id]));
  399. return $this->render('orders', [
  400. 'user' => $user,
  401. 'searchModel' => $searchModel,
  402. 'dataProvider' => $dataProvider,
  403. ]);
  404. }
  405. /**
  406. * Finds the User model based on its primary key value.
  407. * If the model is not found, a 404 HTTP exception will be thrown.
  408. */
  409. protected function findModel($id)
  410. {
  411. $userManager = $this->getUserManager();
  412. if (($user = $userManager->findOneUserById($id)) !== null) {
  413. return $user;
  414. } else {
  415. throw new NotFoundHttpException("Utilisateur introuvable");
  416. }
  417. }
  418. /**
  419. * Affiche la liste des emails des utilisateurs liés à un point de vente donné.
  420. */
  421. public function actionMail(
  422. $idPointSale = 0,
  423. $sectionSubscribers = 0,
  424. $sectionInactiveUsers = 0,
  425. $usersPointSaleLink = 0,
  426. $usersPointSaleHasOrder = 0)
  427. {
  428. $userManager = $this->getUserManager();
  429. $distributionManager = $this->getDistributionManager();
  430. if ($idPointSale && !$usersPointSaleLink && !$usersPointSaleHasOrder) {
  431. $usersPointSaleLink = 1;
  432. }
  433. $users = $userManager->queryUsersBy([
  434. 'id_producer' => GlobalParam::getCurrentProducerId(),
  435. 'id_point_sale' => $idPointSale,
  436. 'users_point_sale_link' => $usersPointSaleLink,
  437. 'users_point_sale_has_order' => $usersPointSaleHasOrder,
  438. 'subscribers' => $sectionSubscribers,
  439. 'inactive' => $sectionInactiveUsers,
  440. 'newsletter' => true
  441. ])->all();
  442. $usersArray = [];
  443. foreach ($users as $key => $user) {
  444. if (isset($user['email']) && strlen($user['email']) > 0) {
  445. $usersArray[] = $user['email'];
  446. }
  447. else {
  448. unset($users[$key]);
  449. }
  450. }
  451. $pointsSaleArray = PointSale::find()->where(['id_producer' => GlobalParam::getCurrentProducerId()])->all();
  452. $pointSale = null;
  453. if ($idPointSale) {
  454. $pointSale = PointSale::findOne(['id' => $idPointSale]);
  455. }
  456. $mailForm = new MailForm();
  457. if ($mailForm->load(\Yii::$app->request->post()) && $mailForm->validate()) {
  458. $responseSendMail = $mailForm->sendEmail($users);
  459. if ($responseSendMail->success()) {
  460. $this->setFlash('success', 'Votre email a bien été envoyé.');
  461. } else {
  462. $bodyResponseSendMail = $responseSendMail->getBody();
  463. $emailsErrorArray = [];
  464. if (isset($bodyResponseSendMail['Messages'])) {
  465. foreach ($bodyResponseSendMail['Messages'] as $message) {
  466. if ($message['Status'] != 'success') {
  467. $emailsErrorArray[] = $message['Errors'][0]['ErrorMessage'];
  468. }
  469. }
  470. }
  471. $messageError = 'Un problème est survenu lors de l\'envoi de votre email.';
  472. if (count($emailsErrorArray) > 0) {
  473. $messageError .= '<br />Problème détecté : ' . implode(',', $emailsErrorArray);
  474. }
  475. $this->setFlash('error', $messageError);
  476. }
  477. return $this->redirect(['mail', 'idPointSale' => $idPointSale]);
  478. }
  479. $incomingDistributions = $distributionManager->findDistributionsIncoming();
  480. $incomingDistributionsArray = ['0' => '--'];
  481. foreach ($incomingDistributions as $distribution) {
  482. $incomingDistributionsArray[$distribution->id] = strftime('%A %d %B %Y', strtotime($distribution->date));
  483. }
  484. return $this->render('emails', [
  485. 'usersArray' => $usersArray,
  486. 'pointsSaleArray' => $pointsSaleArray,
  487. 'pointSale' => $pointSale,
  488. 'mailForm' => $mailForm,
  489. 'idPointSaleActive' => $idPointSale,
  490. 'incomingDistributionsArray' => $incomingDistributionsArray,
  491. 'sectionSubscribers' => $sectionSubscribers,
  492. 'sectionInactiveUsers' => $sectionInactiveUsers,
  493. 'usersPointSaleLink' => $usersPointSaleLink,
  494. 'usersPointSaleHasOrder' => $usersPointSaleHasOrder,
  495. ]);
  496. }
  497. public function actionSwitchIdentity(int $id)
  498. {
  499. $userManager = $this->getUserManager();
  500. if($this->isUserCurrentAdmin()) {
  501. $initialId = Yii::$app->user->getId();
  502. if($initialId != $id) {
  503. $user = $userManager->findOneUserById($id);
  504. $duration = 0;
  505. Yii::$app->user->switchIdentity($user, $duration);
  506. Yii::$app->session->set('user.idbeforeswitch',$initialId);
  507. return $this->redirect(['index']);
  508. }
  509. }
  510. else {
  511. throw new NotFoundHttpException('Page introuvable');
  512. }
  513. }
  514. }