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.

580 lines
22KB

  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 Faker\Provider\HtmlLorem;
  52. use yii\base\UserException;
  53. use yii\filters\AccessControl;
  54. use yii\filters\VerbFilter;
  55. use \Yii;
  56. use yii\helpers\Html;
  57. use yii\web\NotFoundHttpException;
  58. /**
  59. * UserController implements the CRUD actions for User model.
  60. */
  61. class UserController extends BackendController
  62. {
  63. public function behaviors()
  64. {
  65. return [
  66. 'verbs' => [
  67. 'class' => VerbFilter::class,
  68. 'actions' => [
  69. ],
  70. ],
  71. 'access' => [
  72. 'class' => AccessControl::class,
  73. 'rules' => [
  74. [
  75. 'allow' => true,
  76. 'roles' => ['@'],
  77. 'matchCallback' => function ($rule, $action) {
  78. return $this->getUserManager()->hasAccessBackend();
  79. }
  80. ]
  81. ],
  82. ],
  83. ];
  84. }
  85. /**
  86. * Liste les utilisateurs.
  87. */
  88. public function actionIndex(
  89. int $idPointSale = 0,
  90. bool $sectionSubscribers = false,
  91. bool $sectionInactiveUsers = false)
  92. {
  93. $pointSaleManager = $this->getPointSaleManager();
  94. $searchModel = new UserSearch();
  95. $dataProvider = $searchModel->search([
  96. 'UserSearch' => array_merge(
  97. [
  98. 'id_point_sale' => $idPointSale,
  99. 'inactive' => (int) $sectionInactiveUsers,
  100. 'subscribers' => (int) $sectionSubscribers
  101. ],
  102. isset(\Yii::$app->request->queryParams['UserSearch']) ?
  103. Yii::$app->request->queryParams['UserSearch'] :
  104. []
  105. )
  106. ]);
  107. $producer = $this->getProducerCurrent();
  108. $pointsSaleArray = $pointSaleManager->findPointSales();
  109. return $this->render('index', [
  110. 'searchModel' => $searchModel,
  111. 'dataProvider' => $dataProvider,
  112. 'producer' => $producer,
  113. 'idPointSaleActive' => $idPointSale,
  114. 'pointsSaleArray' => $pointsSaleArray,
  115. 'sectionInactiveUsers' => $sectionInactiveUsers,
  116. 'sectionSubscribers' => $sectionSubscribers,
  117. ]);
  118. }
  119. public function initForm($model)
  120. {
  121. $userPointSaleManager = $this->getUserPointSaleManager();
  122. $userUserGroupManager = $this->getUserUserGroupManager();
  123. $userProducerManager = $this->getUserProducerManager();
  124. $userGroupManager = $this->getUserGroupManager();
  125. if ($model->id) {
  126. $userPointSaleArray = $userPointSaleManager->findUserPointSalesByUser($model);
  127. if ($userPointSaleArray && count($userPointSaleArray) > 0) {
  128. foreach ($userPointSaleArray as $userPointSale) {
  129. $model->points_sale[] = $userPointSale->id_point_sale;
  130. }
  131. }
  132. $userUserGroupsArray = $userUserGroupManager->findUserUserGroupsByUser($model);
  133. if ($userUserGroupsArray && count($userUserGroupsArray) > 0) {
  134. foreach ($userUserGroupsArray as $userUserGroup) {
  135. $model->user_groups[] = $userUserGroup->id_user_group;
  136. }
  137. }
  138. $userProducer = $userProducerManager->findOneUserProducer($model);
  139. $model->product_price_percent = $userProducer->product_price_percent;
  140. }
  141. $pointsSaleArray = PointSale::find()
  142. ->where([
  143. 'id_producer' => GlobalParam::getCurrentProducerId(),
  144. 'status' => 1
  145. ])
  146. ->joinWith(['userPointSale' => function ($query) use ($model) {
  147. if ($model->id) {
  148. $query->andOnCondition('user_point_sale.id_user = ' . $model->id);
  149. }
  150. }])
  151. ->all();
  152. $userGroupsArray = $userGroupManager->findUserGroups();
  153. return [
  154. 'pointsSaleArray' => $pointsSaleArray,
  155. 'userGroupsArray' => $userGroupsArray,
  156. ];
  157. }
  158. /**
  159. * Creates a new User model.
  160. * If creation is successful, the browser will be redirected to the 'view' page.
  161. */
  162. public function actionCreate()
  163. {
  164. $userManager = $this->getUserManager();
  165. $producerManager = $this->getProducerManager();
  166. $producerCurrent = $this->getProducerCurrent();
  167. $model = $userManager->instanciateUser();
  168. $userExist = false;
  169. $posts = Yii::$app->request->post();
  170. if ($posts && isset($posts['User']['email']) && strlen($posts['User']['email']) > 0) {
  171. $userExist = $userManager->findOneUserByEmail($posts['User']['email']);
  172. }
  173. if ($userExist) {
  174. $producerManager->addUser($userExist, $producerCurrent);
  175. $this->processLinkPointSale($userExist);
  176. $this->processLinkUserGroup($userExist);
  177. $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.");
  178. } else {
  179. if ($model->load(\Yii::$app->request->post()) && $model->validate() && YII_ENV != 'demo') {
  180. $model->id_producer = 0;
  181. $password = Password::generate();
  182. $userManager->setPassword($model, $password);
  183. $userManager->generateAuthKey($model);
  184. $model->username = $model->email;
  185. if (!strlen($model->email)) {
  186. $model->username = 'inconnu@opendistrib.net';
  187. }
  188. $model->save();
  189. // liaison etablissement / user
  190. $useProducer = new UserProducer();
  191. $useProducer->id_user = $model->id;
  192. $useProducer->id_producer = GlobalParam::getCurrentProducerId();
  193. $useProducer->credit = 0;
  194. $useProducer->active = 1;
  195. $useProducer->save();
  196. $userManager->sendMailWelcome($model, $password);
  197. $this->processLinkPointSale($model);
  198. $this->processLinkUserGroup($model);
  199. $this->processProductPricePercent($model);
  200. $this->setFlash('success', 'Utilisateur créé.');
  201. $model = $userManager->instanciateUser();
  202. }
  203. }
  204. return $this->render('create', array_merge($this->initForm($model), [
  205. 'model' => $model,
  206. ]));
  207. }
  208. public function actionUpdate($id)
  209. {
  210. $userManager = $this->getUserManager();
  211. $producerManager = $this->getProducerManager();
  212. $pointSaleManager = $this->getPointSaleManager();
  213. $model = $this->findModel($id);
  214. // Moodification du profil
  215. $previousMail = $model->email;
  216. $user = User::find()->with('userProducer')->where(['id' => $model['id']])->one();
  217. $userBelongToProducer = UserProducer::findOne(['id_user' => $id, 'id_producer' => GlobalParam::getCurrentProducerId()]);
  218. if ($userBelongToProducer) {
  219. if ($model->load(\Yii::$app->request->post()) && $model->save()) {
  220. // on envoie le mail de bienvenue si le mail vient d'être défini
  221. if (!strlen($previousMail) && strlen($model->email)) {
  222. $password = Password::generate();
  223. $userManager->setPassword($model, $password);
  224. $model->username = $model->email;
  225. $userManager->sendMailWelcome($model, $password);
  226. }
  227. $this->processLinkPointSale($model);
  228. $this->processLinkUserGroup($model);
  229. $this->processProductPricePercent($model);
  230. $this->setFlash('success', 'Utilisateur <strong>'.Html::encode($userManager->getUsername($model)).'</strong> modifié.');
  231. return $this->redirect(['index']);
  232. }
  233. } else {
  234. throw new UserException("Vous ne pouvez pas modifier cet utilisateur.");
  235. }
  236. // Nouveau mot de passe
  237. $newPassword = Yii::$app->request->post('submit_new_password');
  238. if ($newPassword) {
  239. $password = Password::generate();
  240. $userManager->setPassword($model, $password);
  241. $model->save();
  242. $producer = $this->getProducerCurrent();
  243. Mailjet::sendMail([
  244. 'from_email' => $producerManager->getEmailOpendistrib($producer),
  245. 'from_name' => $producer->name,
  246. 'to_email' => $model->email,
  247. 'to_name' => $userManager->getUsername($user),
  248. 'subject' => '[' . $producer->name . '] Nouveau mot de passe',
  249. 'content_view_text' => '@common/mail/newPasswordUserAdmin-text.php',
  250. 'content_view_html' => '@common/mail/newPasswordUserAdmin-html.php',
  251. 'content_params' => [
  252. 'user' => $user,
  253. 'producer' => $producer,
  254. 'password' => $password,
  255. ]
  256. ]);
  257. $this->setFlash('success', 'Nouveau mot de passe envoyé à <strong>'.Html::encode($userManager->getUsername($model)).'</strong>.');
  258. return $this->redirect(['index']);
  259. }
  260. return $this->render('update', array_merge($this->initForm($model), [
  261. 'model' => $model,
  262. 'pointSaleBillingArray' => $pointSaleManager->findByBillingUser($model)
  263. ]));
  264. }
  265. /**
  266. * Lie un utilisateur aux points de vente sélectionnés.
  267. */
  268. public function processLinkPointSale(User $modelUser)
  269. {
  270. $posts = Yii::$app->request->post();
  271. $userPointSaleManager = $this->getUserPointSaleManager();
  272. $pointSaleManager = $this->getPointSaleManager();
  273. UserPointSale::deleteAll([
  274. 'id_user' => $modelUser->id
  275. ]);
  276. if (is_array($modelUser->points_sale) && count($modelUser->points_sale) > 0) {
  277. foreach ($modelUser->points_sale as $pointSaleId) {
  278. $pointSale = $pointSaleManager->findOnePointSaleById($pointSaleId);
  279. $userPointSale = $userPointSaleManager->findOneUserPointSale($modelUser, $pointSale);
  280. if (!$userPointSale) {
  281. $userPointSale = new UserPointSale;
  282. $userPointSale->id_user = $modelUser->id;
  283. $userPointSale->id_point_sale = $pointSaleId;
  284. $userPointSale->comment = isset($posts['User']['comment_point_sale_' . $pointSaleId]) ? $posts['User']['comment_point_sale_' . $pointSaleId] : '';
  285. $userPointSale->save();
  286. }
  287. }
  288. }
  289. }
  290. /**
  291. * Lie un utilisateur aux groupes d'utilisateurs sélectionnés.
  292. */
  293. public function processLinkUserGroup($modelUser)
  294. {
  295. UserUserGroup::deleteAll([
  296. 'id_user' => $modelUser->id
  297. ]);
  298. if (is_array($modelUser->user_groups) && count($modelUser->user_groups) > 0) {
  299. foreach ($modelUser->user_groups as $userGroupId) {
  300. $userUserGroup = UserUserGroup::searchOne([
  301. 'id_user' => $modelUser->id,
  302. 'id_user_group' => $userGroupId
  303. ]);
  304. if (!$userUserGroup) {
  305. $userUserGroup = new UserUserGroup();
  306. $userUserGroup->id_user = $modelUser->id;
  307. $userUserGroup->id_user_group = $userGroupId;
  308. $userUserGroup->save();
  309. }
  310. }
  311. }
  312. }
  313. public function processProductPricePercent($model)
  314. {
  315. $userProducer = UserProducer::searchOne([
  316. 'id_producer' => GlobalParam::getCurrentProducerId(),
  317. 'id_user' => $model->id
  318. ]);
  319. $userProducer->product_price_percent = $model->product_price_percent;
  320. $userProducer->save();
  321. }
  322. /**
  323. * Désactive l'utilisateur de l'établissement.
  324. */
  325. public function actionDelete(int $id)
  326. {
  327. $userManager = $this->getUserManager();
  328. $userProducerManager = $this->getUserProducerManager();
  329. $user = $userManager->findOneUserById($id);
  330. $userProducer = $userProducerManager->findOneUserProducer($user);
  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. $userProducer = $userProducerManager->findOneUserProducer($user);
  481. if ($userProducer) {
  482. $userProducer->credit_active = $state;
  483. $userProducer->save();
  484. }
  485. return $this->redirect(['user/credit', 'id' => $idUser]);
  486. }
  487. /**
  488. * Finds the User model based on its primary key value.
  489. * If the model is not found, a 404 HTTP exception will be thrown.
  490. */
  491. protected function findModel($id)
  492. {
  493. $userManager = $this->getUserManager();
  494. if (($user = $userManager->findOneUserById($id)) !== null) {
  495. return $user;
  496. } else {
  497. throw new NotFoundHttpException('The requested page does not exist.');
  498. }
  499. }
  500. }