]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Консольные команды для когорт
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 23 Dec 2024 14:11:46 +0000 (17:11 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Mon, 23 Dec 2024 14:11:46 +0000 (17:11 +0300)
erp24/commands/CronController.php
erp24/records/Users.php
erp24/scripts/tasks/task_35_form_target_kogort.php

index de17fde3ea1ddf5e698ac9e563abe184a08382b4..d57be803047e062963428e4548270507c65f6318 100644 (file)
@@ -4,15 +4,26 @@ namespace yii_app\commands;
 
 use Yii;
 use yii\console\Controller;
+use yii\console\ExitCode;
 use yii\db\Expression;
+use yii\helpers\BaseConsole;
+use yii\helpers\Console;
 use yii_app\records\EqualizationRemains;
 use yii_app\records\Product1cReplacement;
 use yii_app\records\Products1c;
 use yii_app\records\ReplacementInvoice;
 use yii_app\records\ReplacementInvoiceProducts;
+use yii_app\records\SentKogort;
+use yii_app\records\Users;
+use yii_app\records\UsersMessageManagement;
 
 class CronController extends Controller
 {
+    /**
+     * @var int|null Таймштамп текущего времени (принимается через параметр команды --time)
+     */
+    public $time;
+
     public function actions()
     {
         return [
@@ -171,4 +182,129 @@ class CronController extends Controller
         ])->execute();
     }
 
+    public function actionGenerateTargetKogorts($time = null)
+    {
+        date_default_timezone_set('Europe/Moscow');
+
+        if ($time && !is_numeric($time)) {
+            $this->stdout("Некорректный формат времени\n", BaseConsole::FG_RED);
+            return ExitCode::DATAERR;
+        }
+
+        $time = $time ? (int)$time : time();
+
+        $currentYear = date('Y', $time);
+        $currentMonth = date('m', $time);
+
+        if (date('j', $time) == 1) {
+            $startDay = 1;
+            $endDay = cal_days_in_month(CAL_GREGORIAN, $currentMonth, $currentYear);
+        } elseif (date('j', $time) == 21) {
+            $startDay = 1;
+            $endDay = 10;
+            $currentMonth = ($currentMonth == 12) ? 1 : (int)$currentMonth + 1;
+            $currentYear = ($currentMonth == 1) ? (int)$currentYear + 1 : $currentYear;
+        } else {
+            $this->stdout("Формирование когорты в текущий день невозможно. Пропускаю.\n", BaseConsole::FG_YELLOW);
+            return ExitCode::UNAVAILABLE;
+        }
+
+        for ($day = $startDay; $day <= $endDay; $day++) {
+            $currentDate = sprintf('%04d-%02d-%02d', $currentYear, $currentMonth, $day);
+
+            if (SentKogort::find()->where(['kogort_date' => $currentDate, 'kogort_number' => SentKogort::KOGORT_NUMBERS['target']])->exists()) {
+                $this->stdout("Когорта для даты {$currentDate} уже существует. Пропускаю...\n", BaseConsole::FG_YELLOW);
+                continue;
+            }
+
+            $kogortPhones = Users::formKogortByDateAndType($currentDate, 'target');
+
+            if (!empty($kogortPhones)) {
+                Users::saveKogort($kogortPhones, $currentDate, SentKogort::KOGORT_NUMBERS['target']);
+                $this->stdout("Когорта для даты {$currentDate} успешно сохранена.\n", BaseConsole::FG_GREEN);
+            } else {
+                $this->stdout("Нет данных для формирования когорты на дату {$currentDate}.\n", BaseConsole::FG_RED);
+            }
+        }
+
+        $this->stdout("Генерация корорт завершена.\n", BaseConsole::FG_GREEN);
+        return ExitCode::OK;
+    }
+
+    public function actionGenerateWhatsappKogorts()
+    {
+        date_default_timezone_set('Europe/Moscow');
+
+        $currentDate = date('Y-m-d');
+
+        $messagesSettings = UsersMessageManagement::find()
+            ->where(['active' => 1])
+            ->one();
+
+        $step2 = $messagesSettings ? $messagesSettings->day_before_step2 : 4;
+
+        $startDate = date('Y-m-d', strtotime("+$step2 days", strtotime($currentDate)));
+
+        if (
+            SentKogort::find()
+                ->where(['kogort_date' => $startDate, 'kogort_number' => SentKogort::KOGORT_NUMBERS['whatsapp']])
+                ->exists()
+        ) {
+            $this->stdout("Когорта для Вотсапа на данную дату {$startDate} уже существует. Пропустить...\n", Console::FG_YELLOW);
+            return;
+        }
+
+        $kogortPhones = Users::formKogortByDateAndType($startDate, 'whatsapp');
+       // var_dump($kogortPhones); die();
+        if (!empty($kogortPhones)) {
+            Users::saveKogort($kogortPhones, $startDate, SentKogort::KOGORT_NUMBERS['whatsapp']);
+            $this->stdout("Когорта для Вотсапа на данную дату {$startDate} успешно создана.\n", Console::FG_GREEN);
+        } else {
+            $this->stdout("Нет данных для формирования когорты для Ватсапа на дату {$startDate}.\n", Console::FG_RED);
+        }
+    }
+
+    public function actionGenerateCallKogorts()
+    {
+        date_default_timezone_set('Europe/Moscow');
+
+        $currentDate = date('Y-m-d');
+
+        $messagesSettings = UsersMessageManagement::find()
+            ->where(['active' => 1])
+            ->one();
+
+        $step3 = $messagesSettings ? $messagesSettings->day_before_step3 : 2;
+
+        $startDate = date('Y-m-d', strtotime("+$step3 days", strtotime($currentDate)));
+
+        if (
+            SentKogort::find()
+                ->where(['kogort_date' => $startDate, 'kogort_number' => SentKogort::KOGORT_NUMBERS['call']])
+                ->exists()
+        ) {
+            $this->stdout("Когорта для Звонка на данную дату {$startDate} уже существует. Пропустить...\n", Console::FG_YELLOW);
+            return;
+        }
+
+        $kogortPhones = Users::formKogortByDateAndType($startDate, 'call');
+        // var_dump($kogortPhones); die();
+        if (!empty($kogortPhones)) {
+            Users::saveKogort($kogortPhones, $startDate, SentKogort::KOGORT_NUMBERS['call']);
+            $this->stdout("Когорта для Звонка на данную дату {$startDate} успешно создана.\n", Console::FG_GREEN);
+        } else {
+            $this->stdout("Нет данных для формирования когорты для Ватсапа на дату {$startDate}.\n", Console::FG_RED);
+        }
+    }
+
+
+    public function options($actionID)
+    {
+        $options = parent::options($actionID);
+        if ($actionID === 'generate-target-kogorts') {
+            $options[] = 'time';
+        }
+        return array_unique($options);
+    }
+
 }
index e0a72540501fe5c7ea99a8023f67496e07135cc4..ebe374abb05312ceaaa9687822ac76343d7eeb14 100755 (executable)
@@ -429,13 +429,13 @@ class Users extends \yii\db\ActiveRecord
     {
         $startDate = $startDate ?? date('Y-m-d');
 
-        // Если тип whatsapp, проверяем наличие target выборки
+
         if ($type === 'whatsapp') {
             $existingTargetKogort = SentKogort::find()
                 ->select('phone')
                 ->where([
                     'kogort_date' => $startDate,
-                    'number_kogort' => SentKogort::KOGORT_NUMBERS['target']
+                    'kogort_number' => SentKogort::KOGORT_NUMBERS['target']
                 ])
                 ->column();
 
@@ -450,7 +450,7 @@ class Users extends \yii\db\ActiveRecord
                 ->select('phone')
                 ->where([
                     'kogort_date' => $startDate,
-                    'number_kogort' => SentKogort::KOGORT_NUMBERS['whatsapp']
+                    'kogort_number' => SentKogort::KOGORT_NUMBERS['whatsapp']
                 ])
                 ->column();
 
@@ -514,15 +514,11 @@ class Users extends \yii\db\ActiveRecord
 
         $step1 = $messagesSettings ? $messagesSettings->day_before_step1 : 10;
         $step2 = $messagesSettings ? $messagesSettings->day_before_step2 : 4;
+        $usersQuery = Users::find()->andWhere(['phone' => $phones]);
+
+        $usersQuery->andWhere(['telegram_is_subscribed' => 0]);
 
-        // Подзапрос базы пользователей с учетом подписки на телеграм
-        $usersQuery = (new \yii\db\Query())
-            ->select(['phone'])
-            ->from('users')
-            ->where(['phone' => $phones])
-            ->andWhere(['telegram_is_subscribed' => 0]);
 
-        // Исключаем телефоны с продажами в период от 10 до 4 дней до даты
         $excludeSalesPhone = Sales::find()
             ->where(['>=', 'date', date('Y-m-d', strtotime("$startDate -$step1 days"))])
             ->andWhere(['<=', 'date', date('Y-m-d', strtotime("$startDate -$step2 days"))])
@@ -530,8 +526,9 @@ class Users extends \yii\db\ActiveRecord
             ->select('phone')
             ->column();
 
-        $usersQuery->andWhere(['not in', 'phone', $excludeSalesPhone]);
-
+        $usersQuery->andWhere(['not in', 'phone', $excludeSalesPhone])
+        ->distinct('phone')
+        ->select('phone');
         return $usersQuery->column();
     }
 
@@ -572,7 +569,7 @@ class Users extends \yii\db\ActiveRecord
         $data = [];
         $kogortPhones = SentKogort::find()
             ->select('phone')
-            ->where(['kogort_date' => $startDate])
+            ->where(['kogort_date' => $startDate, 'kogort_number' => $kogort_number])
             ->column();
 
         foreach ($phones as $phone) {
index 26ad26b8239d0404792e57e3e0732fead6b1c88d..0ff348a22347e7e409ec70186fa8b04ce3ef2eb3 100644 (file)
@@ -85,7 +85,7 @@ try {
 
 
             if (SentKogort::find()->where(['kogort_date' => $currentDate])->exists()) {
-                $info = "Kogort for date {$currentDate} already exists. Skipping...\n";
+                $info = "Когорта для даты {$currentDate} уже существует. Пропускаю...\n";
                 echo $info;
                 $log .= $info;
                 continue;
@@ -95,11 +95,11 @@ try {
 
             if (!empty($kogortPhones)) {
                 Users::saveKogort($kogortPhones, $currentDate, SentKogort::KOGORT_NUMBERS['target']);
-                $info = "Kogort for date {$currentDate} saved successfully.\n";
+                $info = "Когорта для даты {$currentDate} успешно сохранена.\n";
                 echo $info;
                 $log .= $info;
             } else {
-                $info = "No phones found for kogort on date {$currentDate}.\n";
+                $info = "Нет данных для формирования когрты на дату {$currentDate}.\n";
                 echo $info;
                 $log .= $info;
             }