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.

578 satır
21KB

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