diff --git a/common/components/MailerComponent.php b/common/components/MailerComponent.php index e4baadd..0e76a50 100644 --- a/common/components/MailerComponent.php +++ b/common/components/MailerComponent.php @@ -3,11 +3,16 @@ namespace common\components; use yii\base\Component; +use common\models\Visit; +use backend\models\Mail; +use common\models\Settings; + + /** * ===================================================================================================================== - * Компонент, созданный для того, чтобы обьявлять аналогичные по логике запросы с 1 места + * Компонент, созданный для того, чтобы обьявлять аналогичные по логике письма с 1 места * ===================================================================================================================== */ class MailerComponent extends Component @@ -22,19 +27,21 @@ class MailerComponent extends Component * 1|2|3 ==> используется для site/callback * 4 ==> site/contact */ - public static function sendListToAdminAfterSubmit(int $mode) + public static function sendListToAdminAfterSubmit(int $mode, array $params = []) { $mail = Mail::findOne(1); if ($mail != null) { $time = Visit::getTimeTitles($mode); + $settings = Settings::getInstance(); # если у них всё же почтовые настройки есть, НО письмо не может отправится, # прокидываю сообщение об этом нам обратно try { \Yii::$app->mailer ->compose() - ->setTo($mail->user) + ->setFrom($mail->user) + ->setTo($settings->email) ->setSubject('Запись на прием: обратная связь') - ->setTextBody('Пациент с тел: :' . $model->phone . "
просил перезвонить ему на протяжении " . $time) + ->setTextBody('Контакт пациента: :' . $params['user_data'] . "
просил перезвонить ему на протяжении " . $time) ->send(); } catch (\Exception $e) { \Yii::error($mail->user . " - неполучается отправить письмо за указанным адресом", 'mail_error'); diff --git a/frontend/config/main.php b/frontend/config/main.php index b70b98d..4347f1e 100755 --- a/frontend/config/main.php +++ b/frontend/config/main.php @@ -1,7 +1,8 @@ [ - 'class' => 'artbox\core\forms\Module', + 'class' => 'frontend\modules\forms\Module', 'activeRecord' => "artbox\core\models\Feedback", + 'alternateMailLogic' => true, 'attributes' => [ 'name', 'phone', @@ -349,6 +351,22 @@ use yii\helpers\Url; 'csrfParam' => '_csrf-frontend', 'baseUrl' => '', ], +// 'mailer' => [ +// 'class' => 'yii\swiftmailer\Mailer', +// 'viewPath' => '@frontend/mail', +// 'useFileTransport' => false, +// +// 'transport' => [ +// 'class' => 'Swift_SmtpTransport', +// 'host' => 'smtp.gmail.com', +// # пока что стоят мои данные, потому что я пробивал свою почту +// # для возможности отправки писем +// 'username' => 'alkhonko@gmail.com', +// 'password' => 'jakirothebest123', +// 'port' => '587', +// 'encryption' => 'tls', +// ], +// ], 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, @@ -374,10 +392,15 @@ use yii\helpers\Url; [ 'class' => 'yii\log\EmailTarget', 'categories' => ['mail_error'], + 'levels' => [ + 'error', + 'warning', + ], 'mailer' => [ 'class' => 'yii\swiftmailer\Mailer', 'viewPath' => '@frontend/mail', 'useFileTransport' => false, + 'transport' => [ 'class' => 'Swift_SmtpTransport', 'host' => 'smtp.gmail.com', @@ -391,8 +414,8 @@ use yii\helpers\Url; ], 'logVars' => [], 'message' => [ - 'from' => ['admin@site.com' => 'ABClinic'], - 'to' => [\Yii::$app->params['adminEmail']], + 'from' => ['alkhonko@gmail.com' => 'ABClinic'], + 'to' => [(Settings::getInstance())->artwebAdminMail], 'subject' => 'Ошибка в почтовом адресе. Письма не доставляются после обработки одной из форм', ], ], diff --git a/frontend/controllers/SiteController.php b/frontend/controllers/SiteController.php index 259f541..7ae1f61 100755 --- a/frontend/controllers/SiteController.php +++ b/frontend/controllers/SiteController.php @@ -63,7 +63,7 @@ */ public function actionIndex() { - $slides = Slide::find() + $slides = Slide::find() ->with('language') ->where([ 'status' => true ]) ->orderBy('sort') @@ -184,8 +184,7 @@ $model = new Visit(); if ($model->load(\Yii::$app->request->post()) && $model->save()){ $mode = $model->time; - MailerComponent::sendListToAdminAfterSubmit($mode); - + MailerComponent::sendListToAdminAfterSubmit($mode, ['user_data' => $model->phone]); return ['success' => true]; }else{ return ['success' => false, 'errors' => $model->errors]; diff --git a/frontend/modules/forms/DynamicModel.php b/frontend/modules/forms/DynamicModel.php new file mode 100755 index 0000000..52f7083 --- /dev/null +++ b/frontend/modules/forms/DynamicModel.php @@ -0,0 +1,34 @@ +_labels = $labels; + } + + /** + * @param string $name + * + * @return string + */ + public function getAttributeLabel($name) + { + return $this->_labels[$name] ?? $name; + } +} \ No newline at end of file diff --git a/frontend/modules/forms/Module.php b/frontend/modules/forms/Module.php new file mode 100755 index 0000000..8349ef1 --- /dev/null +++ b/frontend/modules/forms/Module.php @@ -0,0 +1,253 @@ + 'btn']; + + /** + * content for submit button + * + * @var string + */ + public $buttonContent = 'Save'; + + /** + * @var string + */ + public $classForm = 'form'; + + public $id = 'forms'; + + public $buttonTemplate = '{button}'; + + public $locale = 'app'; + + /** + * Свойство, которое заменяет логику для отправки письма, если установлено $this->sendMail=true + * @var null + */ + public $alternateMailLogic = false; + + + /** + * @inheritdoc + * @throws \yii\base\InvalidConfigException + */ + public function init() + { + parent::init(); + + if ($this->activeRecord !== null) { + $this->model = \Yii::createObject($this->activeRecord); + $this->model->scenario = $this->scenario; + } else { + $this->model = new DynamicModel($this->attributes); + $this->model->attributeLabels = $this->labels; + foreach ($this->rules as $rule) { + if (is_array($rule) && isset($rule[0], $rule[1])) { + $attributes = $rule[0]; + $validator = $rule[1]; + unset($rule[0], $rule[1]); + $this->model->addRule($attributes, $validator, $rule); + } else { + throw new InvalidConfigException( + 'Invalid validation rule: a rule must specify both attribute names and validator type.' + ); + } + } + } + } + + /** + * render html form with model + * + * @param \yii\web\View $view + */ + public function renderForm(View $view) + { + if ($this->ajax) { + $js = <<formId}', function(e) { + e.preventDefault(); + e.stopImmediatePropagation(); + $.post( + $(this).attr("action"), $(this).serialize(), {$this->successCallback}).fail({$this->errorCallback}); +}); +JS; + + $view->registerJs($js, View::POS_READY); + } + /** + * @var ActiveForm $form + */ + + $form = ActiveForm::begin( + [ + 'id' => $this->formId, + 'action' => ($this->ajax) ? '/' . $this->id . '/save/ajax' : '/' . $this->id . '/save/no-ajax', + 'class' => $this->classForm, + ] + ); + $content = ''; + # var_dump($this->labels); + # die(var_dump($this->attributes)); + foreach ($this->attributes as $field) { + if (isset($this->inputOptions[$field]['type'])) { + $function = $this->inputOptions[$field]['type']; + $formStr = $form->field($this->model, $field) + ->$function( + isset($this->inputOptions[$field]['options']) ? $this->inputOptions[$field]['options'] : [] + ); + } else { + $formStr = $form->field($this->model, $field); + } + if (isset($this->labels[$field])) { + $formStr->label(\Yii::t($this->locale, $this->labels[$field])); + } + if (isset($this->inputOptions[$field]['template'])) { + $formStr = str_replace('{input}', $formStr, $this->inputOptions[$field]['template']); + } + $content .= $formStr; + } + + $content .= str_replace('{button}', Html::submitButton(\Yii::t($this->locale, $this->buttonContent), $this->buttonOptions), $this->buttonTemplate); + + $content = str_replace('{form}', $content, $this->templateForm); + # die(var_dump(htmlspecialchars($content))); + echo $content; + ActiveForm::end(); + } +} \ No newline at end of file diff --git a/frontend/modules/forms/controllers/SaveController.php b/frontend/modules/forms/controllers/SaveController.php new file mode 100755 index 0000000..a3103fa --- /dev/null +++ b/frontend/modules/forms/controllers/SaveController.php @@ -0,0 +1,112 @@ +request->referrer; + $model = $this->module->model; + if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) { + if ($model instanceof DynamicModel) { + $this->sendEmail($model); + } else { + if ($model->save()) { + if ($this->module->sendEmail) { + $this->sendEmail($model); + return $this->redirect($returnUrl); + } + } else { + return false; + } + } + return $this->redirect($returnUrl); + + } + return $this->redirect($returnUrl); + } + + /** + * Action that saves data submited via AJAX + * + * @return array + * @throws \yii\base\InvalidConfigException + */ + public function actionAjax() + { + \Yii::$app->response->format = Response::FORMAT_JSON; + $model = $this->module->model; + #die(var_dump(\Yii::$app->request->post())); + if (\Yii::$app->request->isPost and $model->load(\Yii::$app->request->post())) { + if ($model instanceof DynamicModel) { + $this->sendEmail($model); + return ['status' => 'success']; + } else { + if ($model->save()) { + if ($this->module->sendEmail) { + if ($this->module->alternateMailLogic) { + MailerComponent::sendListToAdminAfterSubmit(4, ['user_data' => $model->phone]); + } else { + $this->sendEmail($model); + } + + return ['status' => 'success']; + } + return ['status' => 'success']; + } else { + return ['status' => 'error']; + } + } + + } + return ['status' => 'error']; + } + + /** + * @param $model + * + * @return bool + * @throws \yii\base\InvalidConfigException + */ + public function sendEmail($model) + { + + if ($this->module->mailer == null) { + $mailer = \Yii::$app->mailer; + } else { + $mailer = \Yii::$app->get($this->module->mailer); + } + return $mailer->compose( + [ + 'html' => $this->module->emailFile, + 'text' => $this->module->emailFile, + ], + [$model] + ) + ->setFrom([\Yii::$app->params['supportEmail'] => \Yii::$app->name . ' robot']) + ->setTo($this->module->email) + ->setSubject($this->module->subject) + ->send(); + } + +} \ No newline at end of file diff --git a/frontend/modules/forms/views/form/form.php b/frontend/modules/forms/views/form/form.php new file mode 100755 index 0000000..ae616f3 --- /dev/null +++ b/frontend/modules/forms/views/form/form.php @@ -0,0 +1,27 @@ + 'dynamic-form']); +foreach ($this->context->module->attributes as $field) { + + if (isset($types[$field])) { + $function = $types[$field]['type']; + echo $form->field($model, $field) + ->$function( + $types[$field]['options'] + ); + } else { + echo $form->field($model, $field); + } + +} + +echo Html::submitButton(); + +$form = ActiveForm::end(); -- libgit2 0.21.4