]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Таблица с письмами
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 21 Mar 2025 14:52:47 +0000 (17:52 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 21 Mar 2025 14:52:47 +0000 (17:52 +0300)
erp24/controllers/MarketplaceFlowwowEmailsController.php [new file with mode: 0644]
erp24/migrations/m250321_134458_create_marketplace_flowwow_emails_table.php [new file with mode: 0644]
erp24/records/MarketplaceFlowwowEmails.php [new file with mode: 0644]
erp24/records/MarketplaceFlowwowEmailsSearch.php [new file with mode: 0644]
erp24/services/MarketplaceService.php
erp24/views/marketplace-flowwow-emails/_form.php [new file with mode: 0644]
erp24/views/marketplace-flowwow-emails/_search.php [new file with mode: 0644]
erp24/views/marketplace-flowwow-emails/index.php [new file with mode: 0644]
erp24/views/marketplace-flowwow-emails/update.php [new file with mode: 0644]
erp24/views/marketplace-flowwow-emails/view.php [new file with mode: 0644]

diff --git a/erp24/controllers/MarketplaceFlowwowEmailsController.php b/erp24/controllers/MarketplaceFlowwowEmailsController.php
new file mode 100644 (file)
index 0000000..c40d9c8
--- /dev/null
@@ -0,0 +1,134 @@
+<?php
+
+namespace app\controllers;
+
+use yii_app\records\MarketplaceFlowwowEmails;
+use yii_app\records\MarketplaceFlowwowEmailsSearch;
+use yii\web\Controller;
+use yii\web\NotFoundHttpException;
+use yii\filters\VerbFilter;
+
+/**
+ * MarketplaceFlowwowEmailsController implements the CRUD actions for MarketplaceFlowwowEmails model.
+ */
+class MarketplaceFlowwowEmailsController extends Controller
+{
+    /**
+     * @inheritDoc
+     */
+    public function behaviors()
+    {
+        return array_merge(
+            parent::behaviors(),
+            [
+                'verbs' => [
+                    'class' => VerbFilter::className(),
+                    'actions' => [
+                        'delete' => ['POST'],
+                    ],
+                ],
+            ]
+        );
+    }
+
+    /**
+     * Lists all MarketplaceFlowwowEmails models.
+     *
+     * @return string
+     */
+    public function actionIndex()
+    {
+        $searchModel = new MarketplaceFlowwowEmailsSearch();
+        $dataProvider = $searchModel->search($this->request->queryParams);
+
+        return $this->render('index', [
+            'searchModel' => $searchModel,
+            'dataProvider' => $dataProvider,
+        ]);
+    }
+
+    /**
+     * Displays a single MarketplaceFlowwowEmails model.
+     * @param int $id ID
+     * @return string
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionView($id)
+    {
+        return $this->render('view', [
+            'model' => $this->findModel($id),
+        ]);
+    }
+
+    /**
+     * Creates a new MarketplaceFlowwowEmails model.
+     * If creation is successful, the browser will be redirected to the 'view' page.
+     * @return string|\yii\web\Response
+     */
+    public function actionCreate()
+    {
+        $model = new MarketplaceFlowwowEmails();
+
+        if ($this->request->isPost) {
+            if ($model->load($this->request->post()) && $model->save()) {
+                return $this->redirect(['view', 'id' => $model->id]);
+            }
+        } else {
+            $model->loadDefaultValues();
+        }
+
+        return $this->render('create', [
+            'model' => $model,
+        ]);
+    }
+
+    /**
+     * Updates an existing MarketplaceFlowwowEmails model.
+     * If update is successful, the browser will be redirected to the 'view' page.
+     * @param int $id ID
+     * @return string|\yii\web\Response
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionUpdate($id)
+    {
+        $model = $this->findModel($id);
+
+        if ($this->request->isPost && $model->load($this->request->post()) && $model->save()) {
+            return $this->redirect(['view', 'id' => $model->id]);
+        }
+
+        return $this->render('update', [
+            'model' => $model,
+        ]);
+    }
+
+    /**
+     * Deletes an existing MarketplaceFlowwowEmails model.
+     * If deletion is successful, the browser will be redirected to the 'index' page.
+     * @param int $id ID
+     * @return \yii\web\Response
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    public function actionDelete($id)
+    {
+        $this->findModel($id)->delete();
+
+        return $this->redirect(['index']);
+    }
+
+    /**
+     * Finds the MarketplaceFlowwowEmails model based on its primary key value.
+     * If the model is not found, a 404 HTTP exception will be thrown.
+     * @param int $id ID
+     * @return MarketplaceFlowwowEmails the loaded model
+     * @throws NotFoundHttpException if the model cannot be found
+     */
+    protected function findModel($id)
+    {
+        if (($model = MarketplaceFlowwowEmails::findOne(['id' => $id])) !== null) {
+            return $model;
+        }
+
+        throw new NotFoundHttpException('The requested page does not exist.');
+    }
+}
diff --git a/erp24/migrations/m250321_134458_create_marketplace_flowwow_emails_table.php b/erp24/migrations/m250321_134458_create_marketplace_flowwow_emails_table.php
new file mode 100644 (file)
index 0000000..15deea5
--- /dev/null
@@ -0,0 +1,44 @@
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Handles the creation of table `{{%marketplace_flowwow_emails}}`.
+ */
+class m250321_134458_create_marketplace_flowwow_emails_table extends Migration
+{
+    const TABLE_NAME = 'erp24.marketplace_flowwow_emails';
+    /**
+     * {@inheritdoc}
+     */
+    public function safeUp()
+    {
+        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+
+        if (!isset($tableSchema)) {
+            $this->createTable(self::TABLE_NAME, [
+                'id' => $this->bigPrimaryKey()->comment('ID'),
+                'subject' => $this->string()->notNull()->comment('Тема письма'),
+                'subject_pattern' => $this->string()->null()->comment('Шаблон темы письма'),
+                'from' => $this->string(255)->notNull()->comment('Отправитель письма'),
+                'to' => $this->string()->notNull()->comment('Получатель письма'),
+                'date' => $this->dateTime()->notNull()->comment('Дата письма'),
+                'body' => $this->text()->notNull()->comment('Тело письма'),
+                'created_at' => $this->timestamp()
+                    ->defaultExpression('CURRENT_TIMESTAMP')
+                    ->comment('Дата создания записи'),
+            ]);
+        }
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function safeDown()
+    {
+        $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+        if (isset($tableSchema)) {
+            $this->dropTable(self::TABLE_NAME);
+        }
+    }
+}
diff --git a/erp24/records/MarketplaceFlowwowEmails.php b/erp24/records/MarketplaceFlowwowEmails.php
new file mode 100644 (file)
index 0000000..e148ff5
--- /dev/null
@@ -0,0 +1,62 @@
+<?php
+
+namespace yii_app\records;
+
+use Yii;
+
+/**
+ * This is the model class for table "marketplace_flowwow_emails".
+ *
+ * @property int $id ID
+ * @property string $subject Тема письма
+ * @property string|null $subject_pattern Шаблон темы письма
+ * @property string $from Отправитель письма
+ * @property string $to Получатель письма
+ * @property string $date Дата письма
+ * @property string $body Тело письма
+ * @property string|null $created_at Дата создания записи
+ */
+class MarketplaceFlowwowEmails extends \yii\db\ActiveRecord
+{
+
+
+    /**
+     * {@inheritdoc}
+     */
+    public static function tableName()
+    {
+        return 'marketplace_flowwow_emails';
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['subject_pattern'], 'default', 'value' => null],
+            [['subject', 'from', 'to', 'date', 'body'], 'required'],
+            [['date', 'created_at'], 'safe'],
+            [['body'], 'string'],
+            [['subject', 'subject_pattern', 'from', 'to'], 'string', 'max' => 255],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function attributeLabels()
+    {
+        return [
+            'id' => 'ID',
+            'subject' => 'Тема письма',
+            'subject_pattern' => 'Шаблон темы письма',
+            'from' => 'Отправитель письма',
+            'to' => 'Получатель письма',
+            'date' => 'Дата письма',
+            'body' => 'Тело письма',
+            'created_at' => 'Дата создания записи',
+        ];
+    }
+
+}
diff --git a/erp24/records/MarketplaceFlowwowEmailsSearch.php b/erp24/records/MarketplaceFlowwowEmailsSearch.php
new file mode 100644 (file)
index 0000000..a0426ab
--- /dev/null
@@ -0,0 +1,75 @@
+<?php
+
+namespace yii_app\records;
+
+use yii\base\Model;
+use yii\data\ActiveDataProvider;
+use yii_app\records\MarketplaceFlowwowEmails;
+
+/**
+ * MarketplaceFlowwowEmailsSearch represents the model behind the search form of `yii_app\records\MarketplaceFlowwowEmails`.
+ */
+class MarketplaceFlowwowEmailsSearch extends MarketplaceFlowwowEmails
+{
+    /**
+     * {@inheritdoc}
+     */
+    public function rules()
+    {
+        return [
+            [['id'], 'integer'],
+            [['subject', 'subject_pattern', 'from', 'to', 'date', 'body', 'created_at'], 'safe'],
+        ];
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function scenarios()
+    {
+        // bypass scenarios() implementation in the parent class
+        return Model::scenarios();
+    }
+
+    /**
+     * Creates data provider instance with search query applied
+     *
+     * @param array $params
+     * @param string|null $formName Form name to be used into `->load()` method.
+     *
+     * @return ActiveDataProvider
+     */
+    public function search($params, $formName = null)
+    {
+        $query = MarketplaceFlowwowEmails::find();
+
+        // add conditions that should always apply here
+
+        $dataProvider = new ActiveDataProvider([
+            'query' => $query,
+        ]);
+
+        $this->load($params, $formName);
+
+        if (!$this->validate()) {
+            // uncomment the following line if you do not want to return any records when validation fails
+            // $query->where('0=1');
+            return $dataProvider;
+        }
+
+        // grid filtering conditions
+        $query->andFilterWhere([
+            'id' => $this->id,
+            'date' => $this->date,
+            'created_at' => $this->created_at,
+        ]);
+
+        $query->andFilterWhere(['ilike', 'subject', $this->subject])
+            ->andFilterWhere(['ilike', 'subject_pattern', $this->subject_pattern])
+            ->andFilterWhere(['ilike', 'from', $this->from])
+            ->andFilterWhere(['ilike', 'to', $this->to])
+            ->andFilterWhere(['ilike', 'body', $this->body]);
+
+        return $dataProvider;
+    }
+}
index 5af8ebaa72269ffdedcc09b74a759ac15dbc3152..a2d48528ba6a93c216e799615be7a5a62fc87f82 100644 (file)
@@ -17,6 +17,7 @@ use yii_app\helpers\DataHelper;
 use yii_app\helpers\File;
 use yii_app\records\Balances;
 use yii_app\records\Images;
+use yii_app\records\MarketplaceFlowwowEmails;
 use yii_app\records\MarketplaceOrderDelivery;
 use yii_app\records\MarketplaceOrderItems;
 use yii_app\records\MarketplaceOrders;
@@ -1444,18 +1445,23 @@ class MarketplaceService
                     $from = mb_decode_mimeheader($overview[0]->from);
                     $to = mb_decode_mimeheader($overview[0]->to);
                     $date = date('Y-m-d H:i:s', strtotime(mb_decode_mimeheader($overview[0]->date)));
+                    if (isset($structure->parts) && count($structure->parts)) {
+                        foreach ($structure->parts as $partNum => $part) {
+                            if ($part->subtype == 'HTML') {
+                                $htmlMessage = imap_fetchbody($inbox, $email_number, $partNum + 1);
+                                break;
+                            }
+                        }
+                    }
+                    $savedEmail = self::saveEmailIfNotExists($subject, null, $from, $to, $date, $htmlMessage);
+
                     foreach ($subjectPatterns as $pattern) {
                         if (preg_match($pattern, $subject)) {
                             $subjectIndex = self::SUBJECT_INDEX[$pattern];
-                            if (isset($structure->parts) && count($structure->parts)) {
-                                foreach ($structure->parts as $partNum => $part) {
-                                    if ($part->subtype == 'HTML') {
-                                        $htmlMessage = imap_fetchbody($inbox, $email_number, $partNum + 1);
-                                        break;
-                                    }
-                                }
+                            if ($savedEmail !== null) {
+                                $savedEmail->subject_pattern = $pattern;
+                                $savedEmail->save();
                             }
-
                             $messages[] = [
                                 'subject' => $subject,
                                 'subject_index' => $subjectIndex,
@@ -1464,27 +1470,27 @@ class MarketplaceService
                                 'date' => $date,
                                 'body' => $htmlMessage,
                             ];
-                        }
-                    }
-                    self::imap_debug_log("Установка флага SEEN для сообшения #" . $email_number, $debugMode, $progressCallback);
-                    $result = imap_setflag_full($inbox, $email_number, "\\Seen");
-                    if (!$result) {
-                        self::imap_debug_log("Не удалось установить SEEN flag: " . imap_last_error(), $debugMode, $progressCallback);
-                    } else {
-                        self::imap_debug_log("SEEN установлен успешно", $debugMode, $progressCallback);
-                    }
-                    self::check_imap_errors($debugMode, $progressCallback);
+                            self::imap_debug_log("Установка флага SEEN для сообшения #" . $email_number, $debugMode, $progressCallback);
+                            $result = imap_setflag_full($inbox, $email_number, "\\Seen");
+                            if (!$result) {
+                                self::imap_debug_log("Не удалось установить SEEN flag: " . imap_last_error(), $debugMode, $progressCallback);
+                            } else {
+                                self::imap_debug_log("SEEN установлен успешно", $debugMode, $progressCallback);
+                            }
+                            self::check_imap_errors($debugMode, $progressCallback);
 
-                    $overview_after = imap_fetch_overview($inbox, $email_number, 0);
-                    if (isset($overview_after[0]->seen) && $overview_after[0]->seen) {
-                        self::imap_debug_log("Сообщение #" . $email_number . "  помечено SEEN", $debugMode, $progressCallback);
-                    } else {
-                        self::imap_debug_log("WARNING: Сообщение #" . $email_number . " не удалось пометить как  SEEN", $debugMode, $progressCallback);
-                    }
+                            $overview_after = imap_fetch_overview($inbox, $email_number, 0);
+                            if (isset($overview_after[0]->seen) && $overview_after[0]->seen) {
+                                self::imap_debug_log("Сообщение #" . $email_number . "  помечено SEEN", $debugMode, $progressCallback);
+                            } else {
+                                self::imap_debug_log("WARNING: Сообщение #" . $email_number . " не удалось пометить как  SEEN", $debugMode, $progressCallback);
+                            }
 
-                    if ($progressCallback) {
-                        call_user_func($progressCallback, "От: " . $from . " тема " . $subject . " от " . $date);
-                        call_user_func($progressCallback, "Обработано писем: " . ($index + 1) . " из " . count($emails));
+                            if ($progressCallback) {
+                                call_user_func($progressCallback, "От: " . $from . " тема " . $subject . " от " . $date);
+                                call_user_func($progressCallback, "Обработано писем: " . ($index + 1) . " из " . count($emails));
+                            }
+                        }
                     }
                 }
             } else {
@@ -1506,6 +1512,36 @@ class MarketplaceService
         return $messages;
     }
 
+    public static function saveEmailIfNotExists($subject, $subjectPattern, $from, $to, $date, $body)
+    {
+        if (strpos($from, 'info@flowwow.com') === false) {
+            return;
+        }
+
+        $exists = MarketplaceFlowwowEmails::find()
+            ->where(['subject' => $subject, 'from' => $from, 'date' => $date])
+            ->exists();
+
+        if (!$exists) {
+            $email = new MarketplaceFlowwowEmails();
+            $email->subject = $subject;
+            $email->subject_pattern = $subjectPattern;
+            $email->from = $from;
+            $email->to = $to;
+            $email->date = $date;
+            $email->body = $body;
+            $email->created_at = date('Y-m-d H:i:s');
+            
+            if ($email->save()) {
+                return $email;
+            } else {
+                Yii::error('Письмо не сохранено' . json_encode($email->errors), __METHOD__);
+                return null;
+            }
+
+        }
+    }
+
 
     public static function imap_debug_log($message, $debugMode, $progressCallback) {
 
diff --git a/erp24/views/marketplace-flowwow-emails/_form.php b/erp24/views/marketplace-flowwow-emails/_form.php
new file mode 100644 (file)
index 0000000..9bc491a
--- /dev/null
@@ -0,0 +1,35 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceFlowwowEmails $model */
+/** @var yii\widgets\ActiveForm $form */
+?>
+
+<div class="marketplace-flowwow-emails-form">
+
+    <?php $form = ActiveForm::begin(); ?>
+
+    <?= $form->field($model, 'subject')->textInput(['maxlength' => true]) ?>
+
+    <?= $form->field($model, 'subject_pattern')->textInput(['maxlength' => true]) ?>
+
+    <?= $form->field($model, 'from')->textInput(['maxlength' => true]) ?>
+
+    <?= $form->field($model, 'to')->textInput(['maxlength' => true]) ?>
+
+    <?= $form->field($model, 'date')->textInput() ?>
+
+    <?= $form->field($model, 'body')->textarea(['rows' => 6]) ?>
+
+    <?= $form->field($model, 'created_at')->textInput() ?>
+
+    <div class="form-group">
+        <?= Html::submitButton('Save', ['class' => 'btn btn-success']) ?>
+    </div>
+
+    <?php ActiveForm::end(); ?>
+
+</div>
diff --git a/erp24/views/marketplace-flowwow-emails/_search.php b/erp24/views/marketplace-flowwow-emails/_search.php
new file mode 100644 (file)
index 0000000..dbae395
--- /dev/null
@@ -0,0 +1,41 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceFlowwowEmailsSearch $model */
+/** @var yii\widgets\ActiveForm $form */
+?>
+
+<div class="marketplace-flowwow-emails-search">
+
+    <?php $form = ActiveForm::begin([
+        'action' => ['index'],
+        'method' => 'get',
+    ]); ?>
+
+    <?= $form->field($model, 'id') ?>
+
+    <?= $form->field($model, 'subject') ?>
+
+    <?= $form->field($model, 'subject_pattern') ?>
+
+    <?= $form->field($model, 'from') ?>
+
+    <?= $form->field($model, 'to') ?>
+
+    <?php // echo $form->field($model, 'date') ?>
+
+    <?php // echo $form->field($model, 'body') ?>
+
+    <?php // echo $form->field($model, 'created_at') ?>
+
+    <div class="form-group">
+        <?= Html::submitButton('Search', ['class' => 'btn btn-primary']) ?>
+        <?= Html::resetButton('Reset', ['class' => 'btn btn-outline-secondary']) ?>
+    </div>
+
+    <?php ActiveForm::end(); ?>
+
+</div>
diff --git a/erp24/views/marketplace-flowwow-emails/index.php b/erp24/views/marketplace-flowwow-emails/index.php
new file mode 100644 (file)
index 0000000..07861ce
--- /dev/null
@@ -0,0 +1,50 @@
+<?php
+
+use yii_app\records\MarketplaceFlowwowEmails;
+use yii\helpers\Html;
+use yii\helpers\Url;
+use yii\grid\ActionColumn;
+use yii\grid\GridView;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceFlowwowEmailsSearch $searchModel */
+/** @var yii\data\ActiveDataProvider $dataProvider */
+
+$this->title = 'Marketplace Flowwow Emails';
+$this->params['breadcrumbs'][] = $this->title;
+?>
+<div class="marketplace-flowwow-emails-index">
+
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <p>
+        <?= Html::a('Create Marketplace Flowwow Emails', ['create'], ['class' => 'btn btn-success']) ?>
+    </p>
+
+    <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
+
+    <?= GridView::widget([
+        'dataProvider' => $dataProvider,
+        'filterModel' => $searchModel,
+        'columns' => [
+            ['class' => 'yii\grid\SerialColumn'],
+
+            'id',
+            'subject',
+            'subject_pattern',
+            'from',
+            'to',
+            //'date',
+            //'body:ntext',
+            //'created_at',
+            [
+                'class' => ActionColumn::className(),
+                'urlCreator' => function ($action, MarketplaceFlowwowEmails $model, $key, $index, $column) {
+                    return Url::toRoute([$action, 'id' => $model->id]);
+                 }
+            ],
+        ],
+    ]); ?>
+
+
+</div>
diff --git a/erp24/views/marketplace-flowwow-emails/update.php b/erp24/views/marketplace-flowwow-emails/update.php
new file mode 100644 (file)
index 0000000..5a5e5f4
--- /dev/null
@@ -0,0 +1,21 @@
+<?php
+
+use yii\helpers\Html;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceFlowwowEmails $model */
+
+$this->title = 'Update Marketplace Flowwow Emails: ' . $model->id;
+$this->params['breadcrumbs'][] = ['label' => 'Marketplace Flowwow Emails', 'url' => ['index']];
+$this->params['breadcrumbs'][] = ['label' => $model->id, 'url' => ['view', 'id' => $model->id]];
+$this->params['breadcrumbs'][] = 'Update';
+?>
+<div class="marketplace-flowwow-emails-update">
+
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <?= $this->render('_form', [
+        'model' => $model,
+    ]) ?>
+
+</div>
diff --git a/erp24/views/marketplace-flowwow-emails/view.php b/erp24/views/marketplace-flowwow-emails/view.php
new file mode 100644 (file)
index 0000000..2e94d5d
--- /dev/null
@@ -0,0 +1,43 @@
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\DetailView;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\MarketplaceFlowwowEmails $model */
+
+$this->title = $model->id;
+$this->params['breadcrumbs'][] = ['label' => 'Marketplace Flowwow Emails', 'url' => ['index']];
+$this->params['breadcrumbs'][] = $this->title;
+\yii\web\YiiAsset::register($this);
+?>
+<div class="marketplace-flowwow-emails-view">
+
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <p>
+        <?= Html::a('Update', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
+        <?= Html::a('Delete', ['delete', 'id' => $model->id], [
+            'class' => 'btn btn-danger',
+            'data' => [
+                'confirm' => 'Are you sure you want to delete this item?',
+                'method' => 'post',
+            ],
+        ]) ?>
+    </p>
+
+    <?= DetailView::widget([
+        'model' => $model,
+        'attributes' => [
+            'id',
+            'subject',
+            'subject_pattern',
+            'from',
+            'to',
+            'date',
+            'body:ntext',
+            'created_at',
+        ],
+    ]) ?>
+
+</div>