use yii_app\records\SentKogort;
use yii_app\records\Users;
use yii_app\records\UsersMessageManagement;
+use yii_app\records\UsersTelegramLog;
class CronController extends Controller
{
);
}
}
+ return ExitCode::OK;
}
public function options($actionID)
return $options;
}
+ public function actionSyncTelegramUsers()
+ {
+ $remoteDb = Yii::$app->dbRemote;
+ $batchSize = 500;
+ $offset = 0;
+
+ while (true) {
+ $chatbotUsers = $remoteDb
+ ->createCommand('SELECT * FROM chatbot_telegram_users LIMIT :limit OFFSET :offset', [
+ ':limit' => $batchSize,
+ ':offset' => $offset,
+ ])->queryAll();
+
+ if (empty($chatbotUsers)) {
+ break;
+ }
+
+ foreach ($chatbotUsers as $remoteUser) {
+ $phone = $remoteUser['phone'];
+ $chatId = $remoteUser['chat_id'];
+ $username = $remoteUser['username'];
+ $isBlocked = (int)$remoteUser['is_blocked'];
+ $isRegistered = (int)$remoteUser['is_registered'];
+
+ $user = Users::findOne(['phone' => $phone]);
+
+ if (!$user) {
+ $user = new Users([
+ 'phone' => $phone,
+ 'name' => $username ?: 'Клиент из чатбота',
+ 'date' => date('Y-m-d H:i:s'),
+ 'password' => '00000',
+ 'keycode' => '00000',
+ ]);
+ $user->save(false);
+ }
+
+ if (empty($user->telegram_chat_id)) {
+ $user->telegram_chat_id = $chatId;
+ }
+
+ if ($isRegistered && $user->telegram_is_subscribed == 0) {
+ $user->telegram_is_subscribed = 1;
+ } elseif (!$isRegistered && $user->telegram_is_subscribed == 1) {
+ $user->telegram_is_subscribed = 0;
+ $user->telegram_unsubscribed_at = date('Y-m-d H:i:s');
+ }
+
+ $user->save(false);
+
+ $existingLog = UsersTelegramLog::find()
+ ->where(['phone' => $phone, 'date_end' => null])
+ ->one();
+
+ if ($existingLog) {
+ if (
+ $existingLog->is_blocked != $isBlocked ||
+ $existingLog->is_registered != $isRegistered
+ ) {
+ $existingLog->date_end = date('Y-m-d H:i:s');
+ $existingLog->save(false);
+
+ $this->createTelegramLog($phone, $isBlocked, $isRegistered);
+ }
+ } else {
+ $this->createTelegramLog($phone, $isBlocked, $isRegistered);
+ }
+ }
+
+ $offset += $batchSize;
+
+ $this->stdout("Обработано записей: {$offset}\n", Console::FG_GREEN);
+ }
+
+ $this->stdout("Синхронизация завершена успешно.\n", Console::FG_GREEN);
+ return ExitCode::OK;
+ }
+
+ /**
+ * Создает новую запись в таблице users_telegram_log.
+ *
+ * @param string $phone
+ * @param int $isBlocked
+ * @param int $isRegistered
+ */
+ protected function createTelegramLog($phone, $isBlocked, $isRegistered)
+ {
+ $log = new UsersTelegramLog([
+ 'phone' => $phone,
+ 'is_blocked' => $isBlocked,
+ 'is_registered' => $isRegistered,
+ 'active' => ($isBlocked == 0 && $isRegistered == 1) ? 1 : 0,
+ ]);
+ $log->save(false);
+ }
}
--- /dev/null
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Class m241224_140248_add_telegram_chat_id_to_users_table
+ */
+class m241224_140248_add_column_telegram_chat_id_to_users_table extends Migration
+{
+ const TABLE_NAME = 'erp24.users';
+ const COLUMN_NAME = 'telegram_chat_id';
+ /**
+ * {@inheritdoc}
+ */
+ public function safeUp()
+ {
+ if (!$this->db->getTableSchema(self::TABLE_NAME, true)->getColumn(self::COLUMN_NAME)) {
+ $this->addColumn(self::TABLE_NAME, self::COLUMN_NAME, $this->string()->comment('Telegram Chat ID'));
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function safeDown()
+ {
+ if ($this->db->getTableSchema(self::TABLE_NAME, true)->getColumn(self::COLUMN_NAME)) {
+ $this->dropColumn(self::TABLE_NAME, self::COLUMN_NAME);
+ }
+ }
+
+ /*
+ // Use up()/down() to run migration code without a transaction.
+ public function up()
+ {
+
+ }
+
+ public function down()
+ {
+ echo "m241224_140248_add_telegram_chat_id_to_users_table cannot be reverted.\n";
+
+ return false;
+ }
+ */
+}
--- /dev/null
+<?php
+
+use yii\db\Migration;
+
+/**
+ * Handles the creation of table `{{%users_telegram_log}}`.
+ */
+class m241224_145213_create_users_telegram_log_table extends Migration
+{
+ const TABLE_NAME = 'erp24.users_telegram_log';
+ /**
+ * {@inheritdoc}
+ */
+ public function safeUp()
+ {
+ $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+
+ if (!isset($tableSchema)) {
+ $this->createTable(self::TABLE_NAME, [
+ 'phone' => $this->string()->notNull()->unique()->comment('Телефон'),
+ 'is_blocked' => $this->integer(1)->notNull()->defaultValue(0)->comment(
+ 'Заблокирован: 0 - нет, 1 - да'
+ ),
+ 'is_registered' => $this->integer(1)->notNull()->defaultValue(0)->comment(
+ 'Зарегистрирован: 0 - нет, 1 - да'
+ ),
+ 'active' => $this->integer(1)->notNull()->defaultValue(0)->comment(
+ 'Активный: 0 - нет, 1 - да'
+ ),
+ 'date_end' => $this->date()->null()->comment('Дата окончания активности'),
+
+ ]);
+ }
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function safeDown()
+ {
+ $tableSchema = $this->db->getTableSchema(self::TABLE_NAME);
+ if (isset($tableSchema)) {
+ $this->dropTable(self::TABLE_NAME);
+ }
+ }
+}
* @property int $events Импортированы ли события
* @property string|null $first_minus_balance
* @property string $info
+ * @property string $telegram_chat_id
*/
class Users extends \yii\db\ActiveRecord
{
'seller_id',
'store_id',
'first_minus_balance',
- 'telegram_unsubscribed_at'
+ 'telegram_unsubscribed_at',
+ 'telegram_chat_id'
],
'safe'
],
- [['pol', 'info', 'telegram_created_at'], 'string'],
+ [['pol', 'info', 'telegram_created_at', 'telegram_chat_id'], 'string'],
[
[
'forgot',
[['name_name', 'name_last', 'kod'], 'string', 'max' => 20],
[['name_family'], 'string', 'max' => 25],
[['comment', 'sale_store'], 'string', 'max' => 200],
- [['email'], 'string', 'max' => 70],
+ [['email', 'telegram_chat_id'], 'string', 'max' => 70],
[['phone_old'], 'string', 'max' => 250],
[['card', 'check_id'], 'string', 'max' => 35],
[['password', 'keycode', 'seller_id'], 'string', 'max' => 36],
'black_list' => 'Black List',
'events' => 'Events',
'telegram_unsubscribed_at' => 'Telegram Unsubscribed At',
+ 'telegram_chat_id' => 'Telegram ChatID'
];
}
//TODO: Проверка что он уже участвовал в когорте раннее
$phonesSent = SentKogort::find()
->select('phone')
- ->where(['between', 'kogort_date', date('Y-m-d', strtotime("$startDate -$step1 days")), date('Y-m-d', strtotime("$startDate -1 days"))])
+ ->where(['between', 'kogort_date',
+ date('Y-m-d', strtotime("$startDate -$step1 days")),
+ date('Y-m-d', strtotime("$startDate -1 days"))])
->column();
$filteredUsers = array_diff($usersArray, $phonesSent);
->where(['kogort_date' => $startDate])
->column();
foreach ($kogortData as $phone) {
- if($phone) {
- if (!in_array($phone, $kogortPhones) ) {
- $sentKogort = new SentKogort;
+ if ($phone) {
+ if (!in_array($phone, $kogortPhones)) {
+ $sentKogort = new SentKogort();
$sentKogort->phone = $phone;
$sentKogort->kogort_date = $startDate;
$sentKogort->kogort_unixtime = (int)strtotime($startDate . ' 00:00:00');
}
}
- // Если тип call, проверяем наличие whatsapp выборки
if ($type === 'call') {
$existingWhatsappKogort = SentKogort::find()
->select('phone')
$usersArray = array_unique(array_merge($salesPhone, $memorableDate));
-
$phonesSent = SentKogort::find()
->select('phone')
->where(['between', 'kogort_date',
$filteredUsers = array_diff($usersArray, $phonesSent);
$kogortData = array_values($filteredUsers);
-
if ($type === 'target') {
return $kogortData;
}
-
return $type === 'whatsapp'
? self::processWhatsappKogort($kogortData, $startDate)
: self::processCallKogort($kogortData, $startDate);
--- /dev/null
+<?php
+
+namespace yii_app\records;
+
+use Yii;
+
+/**
+ * This is the model class for table "users_telegram_log".
+ *
+ * @property string $phone Телефон
+ * @property int $is_blocked Заблокирован: 0 - нет, 1 - да
+ * @property int $is_registered Зарегистрирован: 0 - нет, 1 - да
+ * @property int $active Активный: 0 - нет, 1 - да
+ * @property string|null $date_end Дата окончания активности
+ */
+class UsersTelegramLog extends \yii\db\ActiveRecord
+{
+ /**
+ * {@inheritdoc}
+ */
+ public static function tableName()
+ {
+ return 'users_telegram_log';
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function rules()
+ {
+ return [
+ [['phone'], 'required'],
+ [['is_blocked', 'is_registered', 'active'], 'default', 'value' => null],
+ [['is_blocked', 'is_registered', 'active'], 'integer'],
+ [['date_end'], 'safe'],
+ [['phone'], 'string', 'max' => 255],
+ [['phone'], 'unique'],
+ ];
+ }
+
+ /**
+ * {@inheritdoc}
+ */
+ public function attributeLabels()
+ {
+ return [
+ 'phone' => 'Телефон',
+ 'is_blocked' => 'Заблокирован: 0 - нет, 1 - да',
+ 'is_registered' => 'Зарегистрирован: 0 - нет, 1 - да',
+ 'active' => 'Активный: 0 - нет, 1 - да',
+ 'date_end' => 'Дата окончания активности',
+ ];
+ }
+}