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.

SiteController.php 17KB

8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
1 year ago
8 years ago
8 years ago
1 year ago
8 years ago
1 year ago
1 year ago
1 year ago
8 years ago
8 years ago
8 years ago
8 years ago
1 year ago
1 year ago
8 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 frontend\controllers;
  38. use common\helpers\GlobalParam;
  39. use frontend\forms\ProducerCodeForm;
  40. use GuzzleHttp\Client;
  41. use Yii;
  42. use frontend\forms\PasswordResetRequestForm;
  43. use frontend\forms\ResetPasswordForm;
  44. use frontend\forms\SignupForm;
  45. use common\forms\ContactForm;
  46. use yii\base\InvalidParamException;
  47. use yii\base\UserException;
  48. use yii\data\ActiveDataProvider;
  49. use yii\helpers\Html;
  50. use yii\web\BadRequestHttpException;
  51. use yii\filters\VerbFilter;
  52. use yii\filters\AccessControl;
  53. use common\forms\LoginForm;
  54. use yii\web\NotFoundHttpException;
  55. /**
  56. * Site controller
  57. */
  58. class SiteController extends FrontendController
  59. {
  60. /**
  61. * @inheritdoc
  62. */
  63. public function behaviors()
  64. {
  65. return [
  66. 'access' => [
  67. 'class' => AccessControl::class,
  68. 'only' => ['logout', 'signup'],
  69. 'rules' => [
  70. [
  71. 'actions' => ['signup'],
  72. 'allow' => true,
  73. 'roles' => ['?'],
  74. ],
  75. [
  76. 'actions' => ['logout'],
  77. 'allow' => true,
  78. 'roles' => ['@'],
  79. ],
  80. ],
  81. ],
  82. 'verbs' => [
  83. 'class' => VerbFilter::class,
  84. 'actions' => [
  85. 'logout' => ['get'],
  86. ],
  87. ],
  88. ];
  89. }
  90. /**
  91. * @inheritdoc
  92. */
  93. public function actions()
  94. {
  95. return [
  96. 'captcha' => [
  97. 'class' => 'yii\captcha\CaptchaAction',
  98. 'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
  99. ],
  100. ];
  101. }
  102. /**
  103. * Affiche la page d'erreur.
  104. *
  105. * @return mixed
  106. */
  107. public function actionError()
  108. {
  109. $exception = \Yii::$app->errorHandler->exception;
  110. if ($exception->getMessage() == 'Producteur introuvable'
  111. || \Yii::$app->getRequest()->getQueryParam('producer_not_found')) {
  112. return $this->render('error-404-producer', ['exception' => $exception]);
  113. }
  114. if ($exception !== null) {
  115. return $this->render('error', ['exception' => $exception]);
  116. }
  117. }
  118. /**
  119. * Affiche la page d'accueil.
  120. */
  121. public function actionIndex()
  122. {
  123. return $this->render('index');
  124. }
  125. public function actionService()
  126. {
  127. return $this->render('service', [
  128. 'producerDemoAccount' => $this->getProducerManager()->findOneProducerDemoAccount(),
  129. 'dataProviderPrices' => $this->getDataProviderPrices()
  130. ]);
  131. }
  132. public function getDataProviderPrices()
  133. {
  134. return new ActiveDataProvider([
  135. 'query' => $this->getProducerPriceRangeManager()->queryProducerPriceRanges()->query(),
  136. 'pagination' => [
  137. 'pageSize' => 100,
  138. ],
  139. ]);
  140. }
  141. /**
  142. * Liste les producteurs utilisant la plateforme.
  143. */
  144. public function actionProducers()
  145. {
  146. $dataProviderProducers = new ActiveDataProvider([
  147. 'query' => $this->getProducerManager()->queryProducersActive()->query(),
  148. 'pagination' => [
  149. 'pageSize' => 100,
  150. ],
  151. ]);
  152. return $this->render('producers', [
  153. 'dataProviderProducers' => $dataProviderProducers,
  154. 'producersArray' => $this->getProducerManager()->findProducersActive()
  155. ]);
  156. }
  157. public function actionAbout()
  158. {
  159. $aboutFewNumbers = Yii::$app->cache->getOrSet('about_few_numbers7', function () {
  160. $producerManager = $this->getProducerManager();
  161. $pointSaleManager = $this->getPointSaleManager();
  162. $userManager = $this->getUserManager();
  163. $orderManager = $this->getOrderManager();
  164. $countProducersActive = $producerManager->countProducersActiveWithTurnover();
  165. $timeSavedByProducersAverage = $producerManager->getTimeSavedByProducersAverage();
  166. $countProducersWithOptionTimeSaved = $producerManager->countProducersWithTimeSaved();
  167. $countPointSalesActive = $pointSaleManager->countPointSalesActiveLastThreeMonths();
  168. $countUsersActive = $userManager->countUsersActiveLastThreeMonths();
  169. $averageOrdersPerDay = $orderManager->countGlobalUserOrdersAverageLastSevenDays();
  170. $averageTurnover = $orderManager->getAverageTurnoverLastThreeMonths();
  171. $resultMatomoApiVisitSummary = json_decode(file_get_contents(Yii::$app->params['matomoApiVisitSummaryUrl']));
  172. $numberVisitsMonth = $resultMatomoApiVisitSummary->nb_uniq_visitors;
  173. return $this->renderPartial('_about_few_numbers', [
  174. 'countProducersActive' => $countProducersActive,
  175. 'countPointSalesActive' => $countPointSalesActive,
  176. 'countUsersActive' => $countUsersActive,
  177. 'averageOrdersPerDay' => $averageOrdersPerDay,
  178. 'averageTurnover' => $averageTurnover,
  179. 'numberVisitsMonth' => $numberVisitsMonth,
  180. 'timeSavedByProducersAverage' => $timeSavedByProducersAverage,
  181. 'countProducersWithOptionTimeSaved' => $countProducersWithOptionTimeSaved
  182. ]);
  183. }, 60 * 60 * 24);
  184. $producerManager = $this->getProducerManager();
  185. return $this->render('about', [
  186. 'countProducers' => $producerManager->countProducersActiveWithTurnover(),
  187. 'producersWithTestimonials' => $producerManager->findProducersWithTestimonials(),
  188. 'aboutFewNumbers' => $aboutFewNumbers
  189. ]);
  190. }
  191. public function actionSourceCode()
  192. {
  193. return $this->render('source_code');
  194. }
  195. /**
  196. * Liste les producteurs utilisant la plateforme.
  197. */
  198. public function actionAjaxProducers()
  199. {
  200. \Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
  201. $producersArray = $this->getProducerManager()->findProducersActive();
  202. $producersArrayReturn = [];
  203. foreach($producersArray as $producer) {
  204. $producersArrayReturn[] = [
  205. 'id' => $producer->id,
  206. 'name' => Html::encode($producer->name),
  207. 'type' => Html::encode($producer->type),
  208. 'address' => Html::encode($producer->postcode.' '.$producer->city),
  209. 'latitude' => $producer->latitude,
  210. 'longitude' => $producer->longitude,
  211. 'link' => $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug])
  212. ];
  213. }
  214. return $producersArrayReturn;
  215. }
  216. /**
  217. * Affiche la page de connexion et traite le formulaire de connexion.
  218. */
  219. public function actionLogin()
  220. {
  221. if (!\Yii::$app->user->isGuest) {
  222. return \Yii::$app->getResponse()->redirect(['site/index']);
  223. }
  224. $model = new LoginForm();
  225. if ($model->load(Yii::$app->request->post()) && $model->login()) {
  226. $returnUrl = \Yii::$app->request->get('return_url');
  227. if ($returnUrl) {
  228. return $this->redirect($returnUrl);
  229. }
  230. else {
  231. $userProducerArray = $this->getUserProducerManager()->findUserProducersByUser(GlobalParam::getCurrentUser());
  232. if ($userProducerArray
  233. && is_array($userProducerArray)
  234. && count($userProducerArray) == 1) {
  235. $urlRedirect = $this->getUrlManagerProducer()
  236. ->createAbsoluteUrl([
  237. 'site/index',
  238. 'slug_producer' => $userProducerArray[0]->producer->slug
  239. ]);
  240. return $this->redirect($urlRedirect);
  241. }
  242. else {
  243. return $this->goBack();
  244. }
  245. }
  246. } else {
  247. return $this->render('@frontend/views/site/login', [
  248. 'model' => $model,
  249. ]);
  250. }
  251. }
  252. /**
  253. * Déconnecte l'utilisateur.
  254. */
  255. public function actionLogout()
  256. {
  257. \Yii::$app->user->logout();
  258. return $this->goHome();
  259. }
  260. /**
  261. * Affiche la page de contact et traite le formulaire s'il est soumis.
  262. */
  263. public function actionContact()
  264. {
  265. $model = new ContactForm();
  266. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  267. if ($model->sendEmail(Yii::$app->params['adminEmail'])) {
  268. $this->setFlash('success', 'Votre message a bien été envoyé. Nous vous répondrons dès que possible.');
  269. }
  270. else {
  271. $this->setFlash('error', 'Il y a eu une erreur lors de l\'envoi de votre message.');
  272. }
  273. return $this->refresh();
  274. }
  275. else {
  276. return $this->render('contact', [
  277. 'model' => $model,
  278. ]);
  279. }
  280. }
  281. /**
  282. * Affiche la page d'inscription et traite son formulaire.
  283. */
  284. public function actionSignup()
  285. {
  286. $model = new SignupForm();
  287. $producerManager = $this->getProducerManager();
  288. if ($model->load(Yii::$app->request->post())) {
  289. $user = $model->signup();
  290. if ($user && Yii::$app->getUser()->login($user)) {
  291. if ($model->isProducer()) {
  292. $this->redirect(['site/signup-confirm']);
  293. }
  294. else {
  295. $producer = $producerManager->findOneProducerById($model->id_producer);
  296. if ($producer) {
  297. $this->redirect(['site/signup-confirm', 'idProducerRedirect' => $producer->id]);
  298. }
  299. else {
  300. $this->redirect(['site/index']);
  301. }
  302. }
  303. }
  304. }
  305. // Liste des producteurs disponibles
  306. $producersArray = $producerManager->populateProducerDropdown();
  307. $dataProducers = $producersArray['data'];
  308. $optionsProducers = $producersArray['options'];
  309. return $this->render('signup', [
  310. 'model' => $model,
  311. 'dataProducers' => $dataProducers,
  312. 'dataProviderPrices' => $this->getDataProviderPrices(),
  313. 'optionsProducers' => $optionsProducers,
  314. ]);
  315. }
  316. public function actionSignupConfirm($idProducerRedirect = null)
  317. {
  318. $producerManager = $this->getProducerManager();
  319. $user = $this->getUserCurrent();
  320. $producerRedirect = $idProducerRedirect ? $producerManager->findOneProducerById($idProducerRedirect) : null ;
  321. if(!$user) {
  322. throw new NotFoundHttpException('Page introuvable');
  323. }
  324. return $this->render('signup_confirm', [
  325. 'user' => $user,
  326. 'producerRedirect' => $producerRedirect
  327. ]);
  328. }
  329. /**
  330. * Affiche la page de demande de nouveau mot de passe.
  331. * Traitement du formulaire.
  332. */
  333. public function actionRequestPasswordReset()
  334. {
  335. $model = new PasswordResetRequestForm();
  336. if ($model->load(Yii::$app->request->post()) && $model->validate()) {
  337. if ($model->sendEmail()) {
  338. $this->setFlash('success', 'Un lien vous permettant de réinitialiser votre mot de passe
  339. vient d\'être envoyé sur votre boîte mail.');
  340. return $this->goHome();
  341. }
  342. else {
  343. $this->setFlash('error', 'Sorry, we are unable to reset password for email provided.');
  344. }
  345. }
  346. return $this->render('requestPasswordResetToken', [
  347. 'model' => $model,
  348. ]);
  349. }
  350. /**
  351. * Met à jour le mot de passe de l'utilisateur.
  352. */
  353. public function actionResetPassword($token)
  354. {
  355. try {
  356. $model = new ResetPasswordForm($token);
  357. } catch (InvalidParamException $e) {
  358. throw new BadRequestHttpException($e->getMessage());
  359. }
  360. if ($model->load($this->getRequest()->post())
  361. && $model->validate()
  362. && $model->resetPassword()) {
  363. $this->setFlash('success', 'Votre nouveau mot de passe vient d\'être sauvegardé.');
  364. return $this->goHome();
  365. }
  366. return $this->render('resetPassword', [
  367. 'model' => $model,
  368. ]);
  369. }
  370. /**
  371. * Affiche le formulaire de demande de code pour accéder à certains producteurs.
  372. */
  373. public function actionProducerCode(int $id)
  374. {
  375. $producerManager = $this->getProducerManager();
  376. $producer = $producerManager->findOneProducerById($id);
  377. if (!$producer) {
  378. throw new \yii\web\HttpException(404, 'Producteur introuvable');
  379. }
  380. $producerCodeForm = new ProducerCodeForm();
  381. $producerCodeForm->id_producer = $id;
  382. if ($producerCodeForm->load($this->getRequest()->post())
  383. && $producerCodeForm->validate()) {
  384. $this->getLogic()->setProducerContext($producer);
  385. $producerManager->addUser(GlobalParam::getCurrentUser(), $producer);
  386. $this->redirect($this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  387. }
  388. return $this->render('producer_code', [
  389. 'producer' => $producer,
  390. 'producerCodeForm' => $producerCodeForm,
  391. ]);
  392. }
  393. /**
  394. * Affiche la page de connexion / inscription pour accéder notamment au
  395. * formulaire de commande des producteurs.
  396. */
  397. public function actionProducer(int $id)
  398. {
  399. $loginForm = new LoginForm();
  400. $signupForm = new SignupForm();
  401. $producerManager = $this->getProducerManager();
  402. $producer = $producerManager->findOneProducerById($id);
  403. $this->getLogic()->setProducerContext($producer);
  404. $loginForm->id_producer = $id;
  405. $signupForm->id_producer = $id;
  406. $signupForm->option_user_producer = 'user';
  407. $returnUrl = $this->getRequest()->get('returnUrl', $this->getUrlManagerProducer()->createAbsoluteUrl(['site/index', 'slug_producer' => $producer->slug]));
  408. if (Yii::$app->user->isGuest) {
  409. if ($loginForm->load($this->getRequest()->post()) && $loginForm->login()) {
  410. if (!strlen($producer->code)) {
  411. $producerManager->addUser(GlobalParam::getCurrentUser(), $producer);
  412. }
  413. $this->redirect($returnUrl);
  414. }
  415. if ($signupForm->load($this->getRequest()->post())
  416. && ($user = $signupForm->signup())
  417. && Yii::$app->user->login($user)) {
  418. $this->redirect($returnUrl);
  419. }
  420. }
  421. else {
  422. $this->redirect($returnUrl);
  423. }
  424. return $this->render('producer', [
  425. 'loginForm' => $loginForm,
  426. 'signupForm' => $signupForm,
  427. 'producer' => $producer,
  428. ]);
  429. }
  430. /**
  431. * Indique à l'utilisateur que l'espace d'un producteur est hors ligne.
  432. */
  433. public function actionProducerOffline(int $id)
  434. {
  435. return $this->render('producer_offline', [
  436. 'producer' => $this->getProducerManager()->findOneProducerById($id),
  437. ]);
  438. }
  439. /**
  440. * Affiche les mentions légales.
  441. */
  442. public function actionMentions()
  443. {
  444. return $this->render('mentions');
  445. }
  446. /**
  447. * Affiche les conditions générale de service.
  448. */
  449. public function actionCgv()
  450. {
  451. return $this->render('cgv');
  452. }
  453. /**
  454. * Affiche les précisions concernant l'utilisation du crédit.
  455. */
  456. public function actionCredit()
  457. {
  458. return $this->render('credit');
  459. }
  460. }