Commit 82a18a275cd20c179f2dccad389b455367cc30fb

Authored by alex
1 parent 982be2a8

Mailer 1

common/components/MailerComponent.php
... ... @@ -3,11 +3,16 @@
3 3 namespace common\components;
4 4  
5 5 use yii\base\Component;
  6 +use common\models\Visit;
  7 +use backend\models\Mail;
  8 +use common\models\Settings;
  9 +
  10 +
6 11  
7 12  
8 13 /**
9 14 * =====================================================================================================================
10   - * Компонент, созданный для того, чтобы обьявлять аналогичные по логике запросы с 1 места
  15 + * Компонент, созданный для того, чтобы обьявлять аналогичные по логике письма с 1 места
11 16 * =====================================================================================================================
12 17 */
13 18 class MailerComponent extends Component
... ... @@ -22,19 +27,21 @@ class MailerComponent extends Component
22 27 * 1|2|3 ==> используется для site/callback
23 28 * 4 ==> site/contact
24 29 */
25   - public static function sendListToAdminAfterSubmit(int $mode)
  30 + public static function sendListToAdminAfterSubmit(int $mode, array $params = [])
26 31 {
27 32 $mail = Mail::findOne(1);
28 33 if ($mail != null) {
29 34 $time = Visit::getTimeTitles($mode);
  35 + $settings = Settings::getInstance();
30 36 # если у них всё же почтовые настройки есть, НО письмо не может отправится,
31 37 # прокидываю сообщение об этом нам обратно
32 38 try {
33 39 \Yii::$app->mailer
34 40 ->compose()
35   - ->setTo($mail->user)
  41 + ->setFrom($mail->user)
  42 + ->setTo($settings->email)
36 43 ->setSubject('Запись на прием: обратная связь')
37   - ->setTextBody('Пациент с тел: :' . $model->phone . " <br> просил перезвонить ему на протяжении " . $time)
  44 + ->setTextBody('Контакт пациента: :' . $params['user_data'] . " <br> просил перезвонить ему на протяжении " . $time)
38 45 ->send();
39 46 } catch (\Exception $e) {
40 47 \Yii::error($mail->user . " - неполучается отправить письмо за указанным адресом", 'mail_error');
... ...
frontend/config/main.php
1 1 <?php
2 2 use common\models\SlashRedirect;
3 3 use frontend\components\UrlManager;
4   -use yii\helpers\Url;
  4 +use common\models\Settings;
  5 +
5 6  
6 7  
7 8 $params = array_merge(
... ... @@ -80,8 +81,9 @@ use yii\helpers\Url;
80 81  
81 82 ],
82 83 'contact' => [
83   - 'class' => 'artbox\core\forms\Module',
  84 + 'class' => 'frontend\modules\forms\Module',
84 85 'activeRecord' => "artbox\core\models\Feedback",
  86 + 'alternateMailLogic' => true,
85 87 'attributes' => [
86 88 'name',
87 89 'phone',
... ... @@ -349,6 +351,22 @@ use yii\helpers\Url;
349 351 'csrfParam' => '_csrf-frontend',
350 352 'baseUrl' => '',
351 353 ],
  354 +// 'mailer' => [
  355 +// 'class' => 'yii\swiftmailer\Mailer',
  356 +// 'viewPath' => '@frontend/mail',
  357 +// 'useFileTransport' => false,
  358 +//
  359 +// 'transport' => [
  360 +// 'class' => 'Swift_SmtpTransport',
  361 +// 'host' => 'smtp.gmail.com',
  362 +// # пока что стоят мои данные, потому что я пробивал свою почту
  363 +// # для возможности отправки писем
  364 +// 'username' => 'alkhonko@gmail.com',
  365 +// 'password' => 'jakirothebest123',
  366 +// 'port' => '587',
  367 +// 'encryption' => 'tls',
  368 +// ],
  369 +// ],
352 370 'user' => [
353 371 'identityClass' => 'common\models\User',
354 372 'enableAutoLogin' => true,
... ... @@ -374,10 +392,15 @@ use yii\helpers\Url;
374 392 [
375 393 'class' => 'yii\log\EmailTarget',
376 394 'categories' => ['mail_error'],
  395 + 'levels' => [
  396 + 'error',
  397 + 'warning',
  398 + ],
377 399 'mailer' => [
378 400 'class' => 'yii\swiftmailer\Mailer',
379 401 'viewPath' => '@frontend/mail',
380 402 'useFileTransport' => false,
  403 +
381 404 'transport' => [
382 405 'class' => 'Swift_SmtpTransport',
383 406 'host' => 'smtp.gmail.com',
... ... @@ -391,8 +414,8 @@ use yii\helpers\Url;
391 414 ],
392 415 'logVars' => [],
393 416 'message' => [
394   - 'from' => ['admin@site.com' => 'ABClinic'],
395   - 'to' => [\Yii::$app->params['adminEmail']],
  417 + 'from' => ['alkhonko@gmail.com' => 'ABClinic'],
  418 + 'to' => [(Settings::getInstance())->artwebAdminMail],
396 419 'subject' => 'Ошибка в почтовом адресе. Письма не доставляются после обработки одной из форм',
397 420 ],
398 421 ],
... ...
frontend/controllers/SiteController.php
... ... @@ -63,7 +63,7 @@
63 63 */
64 64 public function actionIndex()
65 65 {
66   - $slides = Slide::find()
  66 + $slides = Slide::find()
67 67 ->with('language')
68 68 ->where([ 'status' => true ])
69 69 ->orderBy('sort')
... ... @@ -184,8 +184,7 @@
184 184 $model = new Visit();
185 185 if ($model->load(\Yii::$app->request->post()) && $model->save()){
186 186 $mode = $model->time;
187   - MailerComponent::sendListToAdminAfterSubmit($mode);
188   -
  187 + MailerComponent::sendListToAdminAfterSubmit($mode, ['user_data' => $model->phone]);
189 188 return ['success' => true];
190 189 }else{
191 190 return ['success' => false, 'errors' => $model->errors];
... ...
frontend/modules/forms/DynamicModel.php 0 → 100755
  1 +<?php
  2 +
  3 +
  4 +namespace frontend\modules\forms;
  5 +/**
  6 + * Class DynamicModel
  7 + *
  8 + * @package artbox\core\forms
  9 + */
  10 +class DynamicModel extends \yii\base\DynamicModel
  11 +{
  12 + /**
  13 + * @var mixed
  14 + */
  15 + protected $_labels;
  16 +
  17 + /**
  18 + * @param $labels
  19 + */
  20 + public function setAttributeLabels($labels)
  21 + {
  22 + $this->_labels = $labels;
  23 + }
  24 +
  25 + /**
  26 + * @param string $name
  27 + *
  28 + * @return string
  29 + */
  30 + public function getAttributeLabel($name)
  31 + {
  32 + return $this->_labels[$name] ?? $name;
  33 + }
  34 +}
0 35 \ No newline at end of file
... ...
frontend/modules/forms/Module.php 0 → 100755
  1 +<?php
  2 +
  3 +namespace frontend\modules\forms;
  4 +
  5 +use yii\base\InvalidConfigException;
  6 +use yii\helpers\Html;
  7 +use yii\web\View;
  8 +use yii\widgets\ActiveForm;
  9 +
  10 +/**
  11 + * Module for generation forms adn saving data from frontend
  12 + *
  13 + * @package artbox\core\forms
  14 + */
  15 +class Module extends \yii\base\Module
  16 +{
  17 + /**
  18 + * ActiveRecord for insert to db
  19 + *
  20 + * @var null
  21 + */
  22 + public $templateForm = '{form}';
  23 +
  24 + public $activeRecord = null;
  25 +
  26 + /**
  27 + * attributes which render in form
  28 + *
  29 + * @var array
  30 + */
  31 + public $attributes = [];
  32 +
  33 + /**
  34 + * validation rules for DynamicModel
  35 + *
  36 + * @var array
  37 + */
  38 + public $rules = [];
  39 +
  40 + /**
  41 + * scenario for ActiveRecord
  42 + *
  43 + * @var string
  44 + */
  45 + public $scenario = 'default';
  46 +
  47 + /**
  48 + * Input types for attributes. textinput default
  49 + *
  50 + * @var array
  51 + */
  52 + public $inputOptions = [];
  53 +
  54 + /**
  55 + * Labels by form (if ActiveRecord is null)
  56 + *
  57 + * @var array
  58 + */
  59 + public $labels = [];
  60 +
  61 + /**
  62 + * Send or not email
  63 + *
  64 + * @var bool
  65 + */
  66 + public $sendEmail = true;
  67 +
  68 + /**
  69 + * Email address
  70 + *
  71 + * @var string
  72 + */
  73 + public $email = 'admin@example.com';
  74 +
  75 + /**
  76 + * Email template
  77 + *
  78 + * @var string
  79 + */
  80 + public $emailFile = 'mail.php';
  81 +
  82 + /**
  83 + * Email subject
  84 + *
  85 + * @var string
  86 + */
  87 + public $subject = '';
  88 +
  89 + /**
  90 + * mailer which send email
  91 + *
  92 + * @var null
  93 + */
  94 + public $mailer = null;
  95 +
  96 + /**
  97 + * @var \yii\db\ActiveRecord $model ;
  98 + */
  99 + public $model = null;
  100 +
  101 + /**
  102 + * send form with ajax
  103 + *
  104 + * @var bool
  105 + */
  106 + public $ajax = false;
  107 +
  108 + /**
  109 + * callback function for ajax script of send form
  110 + *
  111 + * @var string
  112 + */
  113 + public $successCallback = 'function (data) {
  114 + alert("ok");
  115 + }';
  116 +
  117 + /**
  118 + * error function for ajax script of send form
  119 + *
  120 + * @var string
  121 + */
  122 + public $errorCallback = 'function (data) {
  123 + alert("error");
  124 + }';
  125 +
  126 + /**
  127 + * id form
  128 + *
  129 + * @var string
  130 + */
  131 + public $formId = 'dynamic-form';
  132 +
  133 + /**
  134 + * options for submit button
  135 + *
  136 + * @var array
  137 + */
  138 + public $buttonOptions = ['class' => 'btn'];
  139 +
  140 + /**
  141 + * content for submit button
  142 + *
  143 + * @var string
  144 + */
  145 + public $buttonContent = 'Save';
  146 +
  147 + /**
  148 + * @var string
  149 + */
  150 + public $classForm = 'form';
  151 +
  152 + public $id = 'forms';
  153 +
  154 + public $buttonTemplate = '{button}';
  155 +
  156 + public $locale = 'app';
  157 +
  158 + /**
  159 + * Свойство, которое заменяет логику для отправки письма, если установлено $this->sendMail=true
  160 + * @var null
  161 + */
  162 + public $alternateMailLogic = false;
  163 +
  164 +
  165 + /**
  166 + * @inheritdoc
  167 + * @throws \yii\base\InvalidConfigException
  168 + */
  169 + public function init()
  170 + {
  171 + parent::init();
  172 +
  173 + if ($this->activeRecord !== null) {
  174 + $this->model = \Yii::createObject($this->activeRecord);
  175 + $this->model->scenario = $this->scenario;
  176 + } else {
  177 + $this->model = new DynamicModel($this->attributes);
  178 + $this->model->attributeLabels = $this->labels;
  179 + foreach ($this->rules as $rule) {
  180 + if (is_array($rule) && isset($rule[0], $rule[1])) {
  181 + $attributes = $rule[0];
  182 + $validator = $rule[1];
  183 + unset($rule[0], $rule[1]);
  184 + $this->model->addRule($attributes, $validator, $rule);
  185 + } else {
  186 + throw new InvalidConfigException(
  187 + 'Invalid validation rule: a rule must specify both attribute names and validator type.'
  188 + );
  189 + }
  190 + }
  191 + }
  192 + }
  193 +
  194 + /**
  195 + * render html form with model
  196 + *
  197 + * @param \yii\web\View $view
  198 + */
  199 + public function renderForm(View $view)
  200 + {
  201 + if ($this->ajax) {
  202 + $js = <<<JS
  203 +$(document).on('submit', '#{$this->formId}', function(e) {
  204 + e.preventDefault();
  205 + e.stopImmediatePropagation();
  206 + $.post(
  207 + $(this).attr("action"), $(this).serialize(), {$this->successCallback}).fail({$this->errorCallback});
  208 +});
  209 +JS;
  210 +
  211 + $view->registerJs($js, View::POS_READY);
  212 + }
  213 + /**
  214 + * @var ActiveForm $form
  215 + */
  216 +
  217 + $form = ActiveForm::begin(
  218 + [
  219 + 'id' => $this->formId,
  220 + 'action' => ($this->ajax) ? '/' . $this->id . '/save/ajax' : '/' . $this->id . '/save/no-ajax',
  221 + 'class' => $this->classForm,
  222 + ]
  223 + );
  224 + $content = '';
  225 + # var_dump($this->labels);
  226 + # die(var_dump($this->attributes));
  227 + foreach ($this->attributes as $field) {
  228 + if (isset($this->inputOptions[$field]['type'])) {
  229 + $function = $this->inputOptions[$field]['type'];
  230 + $formStr = $form->field($this->model, $field)
  231 + ->$function(
  232 + isset($this->inputOptions[$field]['options']) ? $this->inputOptions[$field]['options'] : []
  233 + );
  234 + } else {
  235 + $formStr = $form->field($this->model, $field);
  236 + }
  237 + if (isset($this->labels[$field])) {
  238 + $formStr->label(\Yii::t($this->locale, $this->labels[$field]));
  239 + }
  240 + if (isset($this->inputOptions[$field]['template'])) {
  241 + $formStr = str_replace('{input}', $formStr, $this->inputOptions[$field]['template']);
  242 + }
  243 + $content .= $formStr;
  244 + }
  245 +
  246 + $content .= str_replace('{button}', Html::submitButton(\Yii::t($this->locale, $this->buttonContent), $this->buttonOptions), $this->buttonTemplate);
  247 +
  248 + $content = str_replace('{form}', $content, $this->templateForm);
  249 + # die(var_dump(htmlspecialchars($content)));
  250 + echo $content;
  251 + ActiveForm::end();
  252 + }
  253 +}
0 254 \ No newline at end of file
... ...
frontend/modules/forms/controllers/SaveController.php 0 → 100755
  1 +<?php
  2 +
  3 +
  4 +namespace frontend\modules\forms\controllers;
  5 +
  6 +
  7 +use artbox\core\forms\DynamicModel;
  8 +use yii\web\Controller;
  9 +use yii\web\Response;
  10 +use common\components\MailerComponent;
  11 +
  12 +/**
  13 + * Class SaveController
  14 + *
  15 + * @property \artbox\core\forms\Module $module
  16 + * @package artbox\core\forms\controllers
  17 + */
  18 +class SaveController extends Controller
  19 +{
  20 + /**
  21 + * Custom data saving via POST
  22 + *
  23 + * @return bool|\yii\web\Response
  24 + * @throws \yii\base\InvalidConfigException
  25 + */
  26 + public function actionNoAjax()
  27 + {
  28 + $returnUrl = \Yii::$app->request->referrer;
  29 + $model = $this->module->model;
  30 + if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) {
  31 + if ($model instanceof DynamicModel) {
  32 + $this->sendEmail($model);
  33 + } else {
  34 + if ($model->save()) {
  35 + if ($this->module->sendEmail) {
  36 + $this->sendEmail($model);
  37 + return $this->redirect($returnUrl);
  38 + }
  39 + } else {
  40 + return false;
  41 + }
  42 + }
  43 + return $this->redirect($returnUrl);
  44 +
  45 + }
  46 + return $this->redirect($returnUrl);
  47 + }
  48 +
  49 + /**
  50 + * Action that saves data submited via AJAX
  51 + *
  52 + * @return array
  53 + * @throws \yii\base\InvalidConfigException
  54 + */
  55 + public function actionAjax()
  56 + {
  57 + \Yii::$app->response->format = Response::FORMAT_JSON;
  58 + $model = $this->module->model;
  59 + #die(var_dump(\Yii::$app->request->post()));
  60 + if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) {
  61 + if ($model instanceof DynamicModel) {
  62 + $this->sendEmail($model);
  63 + return ['status' => 'success'];
  64 + } else {
  65 + if ($model->save()) {
  66 + if ($this->module->sendEmail) {
  67 + if ($this->module->alternateMailLogic) {
  68 + MailerComponent::sendListToAdminAfterSubmit(4, ['user_data' => $model->phone]);
  69 + } else {
  70 + $this->sendEmail($model);
  71 + }
  72 +
  73 + return ['status' => 'success'];
  74 + }
  75 + return ['status' => 'success'];
  76 + } else {
  77 + return ['status' => 'error'];
  78 + }
  79 + }
  80 +
  81 + }
  82 + return ['status' => 'error'];
  83 + }
  84 +
  85 + /**
  86 + * @param $model
  87 + *
  88 + * @return bool
  89 + * @throws \yii\base\InvalidConfigException
  90 + */
  91 + public function sendEmail($model)
  92 + {
  93 +
  94 + if ($this->module->mailer == null) {
  95 + $mailer = \Yii::$app->mailer;
  96 + } else {
  97 + $mailer = \Yii::$app->get($this->module->mailer);
  98 + }
  99 + return $mailer->compose(
  100 + [
  101 + 'html' => $this->module->emailFile,
  102 + 'text' => $this->module->emailFile,
  103 + ],
  104 + [$model]
  105 + )
  106 + ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot'])
  107 + ->setTo($this->module->email)
  108 + ->setSubject($this->module->subject)
  109 + ->send();
  110 + }
  111 +
  112 +}
0 113 \ No newline at end of file
... ...
frontend/modules/forms/views/form/form.php 0 → 100755
  1 +<?php
  2 +/**
  3 + * @var \yii\db\ActiveRecord $model
  4 + * @var array $types
  5 + */
  6 +
  7 +use yii\helpers\Html;
  8 +use yii\widgets\ActiveForm;
  9 +
  10 +$form = ActiveForm::begin(['id' => 'dynamic-form']);
  11 +foreach ($this->context->module->attributes as $field) {
  12 +
  13 + if (isset($types[$field])) {
  14 + $function = $types[$field]['type'];
  15 + echo $form->field($model, $field)
  16 + ->$function(
  17 + $types[$field]['options']
  18 + );
  19 + } else {
  20 + echo $form->field($model, $field);
  21 + }
  22 +
  23 +}
  24 +
  25 +echo Html::submitButton();
  26 +
  27 +$form = ActiveForm::end();
... ...