]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Исправления и настройка
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Wed, 5 Feb 2025 09:27:15 +0000 (12:27 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Wed, 5 Feb 2025 09:27:15 +0000 (12:27 +0300)
erp24/api2/controllers/BonusController.php
erp24/commands/CronController.php
erp24/controllers/BonusLevelsController.php

index 05a074f13b5744bff342a714bf78f6edcc45c0d1..e80fbbe21b4b953a491c898801672714b3adce91 100644 (file)
@@ -6,6 +6,7 @@ use Yii;
 use yii\helpers\ArrayHelper;
 use yii\helpers\Json;
 use yii_app\helpers\ClientHelper;
+use yii_app\records\BonusLevels;
 use yii_app\records\Contest001;
 use yii_app\records\ExportImportTable;
 use yii_app\records\MessagerUser;
@@ -17,6 +18,7 @@ use yii_app\records\UniversalCatalogItem;
 use yii_app\records\Users;
 use yii_app\records\UsersAuthCallLog;
 use yii_app\records\UsersBonus;
+use yii_app\records\UsersBonusLevels;
 use yii_app\records\UsersEvents;
 use yii_app\records\UsersPhones;
 use yii_app\records\UsersStopList;
@@ -38,8 +40,8 @@ class BonusController extends BaseController
     private static $CREDIT_HIGH_PROCENT = 0.3;
     private static $CREDIT_HIGH_PROCENT_PART20 = 0.2;
 
-    const OUT_DIR =
-        "/var/www/erp24/api2/json";
+    const OUT_DIR = "/var/www/erp24/api2/json"; // "/www/api2/json";
+
 
     public function actionGetBonuses()
     {
@@ -698,6 +700,32 @@ class BonusController extends BaseController
         $auth_code = $result['auth_code'] ?? 0;
         $write_off_bonuses = intval($result["write_off_bonuses"] ?? 0); // только при продаже
 
+        $userBonusLevel = UsersBonusLevels::find()->where(['phone' => $phone])->andWhere(['active' => 1])->one();
+        $bonusLevels = BonusLevels::find()->where(['active' => 1])->indexBy('alias')->asArray()->all();
+        $bonusLevel = null;
+        if ($userBonusLevel) {
+            $bonusLevel = $userBonusLevel->bonus_level;
+        } else {
+            foreach ($bonusLevels as $bonusLevelArr) {
+                if ($bonusLevelArr['threshold'] == 0) {
+                    $bonusLevel = $bonusLevelArr['alias'];
+                }
+            }
+        }
+
+        $cashback_rate = isset($bonusLevels[$bonusLevel]['cashback_rate'])
+            ? $bonusLevels[$bonusLevel]['cashback_rate'] / 100
+            : self::$FIRST_SALE_PROCENT;
+
+        $referal_rate = isset($bonusLevels[$bonusLevel]['referal_rate'])
+            ? $bonusLevels[$bonusLevel]['referal_rate'] / 100
+            : self::$CREDIT_HIGH_PROCENT;
+
+        $bonus_rate = isset($bonusLevels[$bonusLevel]['bonus_rate'])
+            ? $bonusLevels[$bonusLevel]['bonus_rate'] / 100
+            : self::$FIRST_SALE_PROCENT;
+
+
         file_put_contents(self::OUT_DIR . '/sale_bonuses_' . $fl . '.json', PHP_EOL . '--' . __LINE__, FILE_APPEND);
         $amount_real = 0;
         $items_arr_no = array_values(ArrayHelper::map(
@@ -722,8 +750,8 @@ class BonusController extends BaseController
         $cnt = intval(Sales::find()->where(['phone' => $result['phone'], 'operation' => Sales::OPERATION_SALE])->count());
 
         file_put_contents(self::OUT_DIR . '/sale_bonuses_' . $fl . '.json', PHP_EOL . '--' . __LINE__, FILE_APPEND);
-        $max_procent = $cnt == 0 ? self::$FIRST_SALE_PROCENT : ($cnt == 1 ? self::$SECOND_SALE_PROCENT : self::$MAX_PROCENT);
-
+       // $max_procent = $cnt == 0 ? self::$FIRST_SALE_PROCENT : ($cnt == 1 ? self::$SECOND_SALE_PROCENT : self::$MAX_PROCENT);
+        $max_procent = $bonus_rate;
         file_put_contents(self::OUT_DIR . '/sale_bonuses_' . $fl . '.json', PHP_EOL . '--' . __LINE__, FILE_APPEND);
         // если списывается в попытке больше бонусов чем может списаться -
         $percent = $phone == "79049031399" ? 0.9 : $max_procent;
@@ -876,8 +904,8 @@ class BonusController extends BaseController
         }
         $credit_procent_index = $userFound && $userFound->source > 0 && $salesCount == 0 ? 1 : 0;
 
-        $back1 = $back = round($baza_back * self::$CREDIT_PROCENT);
-        $nm = "Возврат с покупки " . (100 * self::$CREDIT_PROCENT) . "% $check_name сумма чека $check_amount";
+        $back1 = $back = round($baza_back * $cashback_rate);
+        $nm = "Возврат с покупки " . (100 * $cashback_rate) . "% $check_name сумма чека $check_amount";
 
         file_put_contents(self::OUT_DIR . '/sale_bonuses_' . $fl . '.json', PHP_EOL . '--' . __LINE__, FILE_APPEND);
         $userBonus2 = UsersBonus::find()->where(['phone' => $phone])->andWhere(['check_id' => $check_id])->andWhere(['site_id' => $site_id])
@@ -932,8 +960,8 @@ class BonusController extends BaseController
             if ($credit_procent_index) {
 
                 file_put_contents(self::OUT_DIR . '/sale_bonuses_' . $fl . '.json', PHP_EOL . '--' . __LINE__, FILE_APPEND);
-                $back = round($baza_back * self::$CREDIT_HIGH_PROCENT_PART20);
-                $nm = "Возврат с покупки " . (100 * self::$CREDIT_HIGH_PROCENT_PART20) . "% $check_name сумма чека $check_amount";
+                $back = round($baza_back * $cashback_rate);
+                $nm = "Возврат с покупки " . (100 * $cashback_rate) . "% $check_name сумма чека $check_amount";
 
                 $user_balans_new += $back;
 
@@ -1087,6 +1115,7 @@ class BonusController extends BaseController
         $user->sale_store_id = $store_id;
         $user->sale_price = $sale_price;
         $user->sale_avg_price = $sale_avg_price;
+        $user->check_id_last_sale = $check_id;
 //        $user->email_old = "example@example.ru"; // Поле не заполнялось в старом апи, но без него бд выдаёт ошибку при сохранении
 //        $user->phone_old = "71111111111";        // Поле не заполнялось в старом апи, но без него бд выдаёт ошибку при сохранении
 //        $user->check_id_forgot = "???";          // Поле не заполнялось в старом апи, но без него бд выдаёт ошибку при сохранении
@@ -1109,6 +1138,8 @@ class BonusController extends BaseController
                 FILE_APPEND | LOCK_EX);
 
             return $this->asJson(["error_id" => 6, "error" => $user->getErrors()]);
+        } else {
+            $this->updateUserBonusLevel($user, $sale_price, $check_id, $check_name);
         }
         file_put_contents(self::$USERS_AUTH_CALL_LOG2,
             "" . date("d.m.Y H:i:s", time()) . " BEFORE END \n",
@@ -1151,6 +1182,98 @@ class BonusController extends BaseController
         return $this->asJson($mess);
     }
 
+    /**
+     * Обновляет бонусный уровень пользователя.
+     *
+     * @param Users  $user      Модель пользователя.
+     * @param float  $sale_price Текущая сумма покупок.
+     * @param string $check_id   Идентификатор чека.
+     * @param string $check_name Имя (номер) чека.
+     */
+    protected function updateUserBonusLevel($user, $sale_price, $check_id, $check_name)
+    {
+        $bonusLevels = BonusLevels::find()
+            ->where(['active' => 1])
+            ->orderBy(['threshold' => SORT_ASC])
+            ->all();
+
+        $newBonusLevel = null;
+
+        foreach ($bonusLevels as $level) {
+            if ($sale_price > $level->threshold) {
+                $newBonusLevel = $level->alias;
+            }
+        }
+
+        if (empty($user->bonus_level)) {
+            $existingLevel = UsersBonusLevels::find()
+                ->where(['or', ['phone' => $user->phone], ['user_id' => $user->id]])
+                ->andWhere(['active' => 1])
+                ->one();
+
+            if (!$existingLevel && $newBonusLevel) {
+                $user->bonus_level = $newBonusLevel;
+                if (!$user->save()) {
+                    LogService::apiErrorLog(
+                        json_encode(["error_id" => 6.1, "error" => $user->getErrors()], JSON_UNESCAPED_UNICODE)
+                    );
+                }
+
+                $bonusRecord = new UsersBonusLevels();
+                $bonusRecord->phone = $user->phone;
+                $bonusRecord->user_id = $user->id;
+                $bonusRecord->bonus_level = $newBonusLevel;
+                $bonusRecord->created_at = date('Y-m-d H:i:s');
+                $bonusRecord->check_id = $check_id;       // используем значения из запроса
+                $bonusRecord->check_name = $check_name;     // используем значения из запроса
+                $bonusRecord->active = 1;
+
+                if (!$bonusRecord->save()) {
+                    LogService::apiErrorLog(
+                        json_encode(["error_id" => 7.1, "error" => $bonusRecord->getErrors()], JSON_UNESCAPED_UNICODE)
+                    );
+                }
+            }
+        } else {
+            $activeLevel = UsersBonusLevels::find()
+                ->where(['or', ['phone' => $user->phone], ['user_id' => $user->id]])
+                ->andWhere(['active' => 1])
+                ->one();
+
+            if ($newBonusLevel && $activeLevel && $activeLevel->bonus_level !== $newBonusLevel) {
+                $activeLevel->active = 0;
+                $activeLevel->updated_at = date('Y-m-d H:i:s');
+                if (!$activeLevel->save()) {
+                    LogService::apiErrorLog(
+                        json_encode(["error_id" => 6.2, "error" => $activeLevel->getErrors()], JSON_UNESCAPED_UNICODE)
+                    );
+                }
+
+                $bonusRecord = new UsersBonusLevels();
+                $bonusRecord->phone = $user->phone;
+                $bonusRecord->user_id = $user->id;
+                $bonusRecord->bonus_level = $newBonusLevel;
+                $bonusRecord->created_at = date('Y-m-d H:i:s');
+                $bonusRecord->check_id = $check_id;
+                $bonusRecord->check_name = $check_name;
+                $bonusRecord->active = 1;
+
+                if (!$bonusRecord->save()) {
+                    LogService::apiErrorLog(
+                        json_encode(["error_id" => 6.3, "error" => $bonusRecord->getErrors()], JSON_UNESCAPED_UNICODE)
+                    );
+                }
+
+                $user->bonus_level = $newBonusLevel;
+                if (!$user->save()) {
+                    LogService::apiErrorLog(
+                        json_encode(["error_id" => 6.4, "error" => $user->getErrors()], JSON_UNESCAPED_UNICODE)
+                    );
+                }
+            }
+        }
+    }
+
     public function actionGetClientInfo()
     {
         Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
index d3524d77ddeb5b778a38c3979ea35e0fed370858..26618ada6f81333cbde9ed29587489b006421232 100644 (file)
@@ -4,6 +4,8 @@ namespace yii_app\commands;
 
 use app\jobs\SendTelegramMessageDBJob;
 use app\jobs\SendTelegramMessageJob;
+use DateTime;
+use DateTimeZone;
 use Yii;
 use yii\console\Controller;
 use yii\console\ExitCode;
@@ -927,9 +929,13 @@ class CronController extends Controller
                 continue;
             }
 
+            $baseDateRounded = date('Y-m-d H:i:00', strtotime($baseDate));
+
             $newSales = Sales::find()
                 ->where(['phone' => $user->phone, 'operation' => Sales::OPERATION_SALE])
-                ->andWhere(['>', 'date', $baseDate])
+                ->andWhere(new \yii\db\Expression("DATE_TRUNC('minute', date) > CAST(:baseDate AS timestamp)", [
+                    ':baseDate' => $baseDateRounded,
+                ]))
                 ->all();
 
             if (empty($newSales)) {
@@ -952,14 +958,19 @@ class CronController extends Controller
                 }
             }
 
-            $user->sale_price = $user->sale_price + $newSalesSum;
+            $user->sale_price = intval($user->sale_price + $newSalesSum);
             $user->sale_cnt = $user->sale_cnt + $newSalesCount;
             $user->sale_avg_price = $user->sale_cnt > 0
                 ? round($user->sale_price / $user->sale_cnt)
                 : 0;
             $user->date_last_sale = $newDateLastSale;
             $user->check_id_last_sale = $newCheckId; // обновляем идентификатор последнего обработанного чека
-
+            if (!$user->date) {
+                $user->date = (new DateTime('now', new DateTimeZone('Europe/Moscow')))->format('Y-m-d H:i:sP');
+            }
+            if (!$user->password) {
+                $user->password = '1111';
+            }
             if (!$user->save()) {
                 $this->stdout(
                     "Ошибка обновления данных пользователя (ID: {$user->id}): " . json_encode($user->getErrors()) . "\n",
@@ -1039,109 +1050,4 @@ class CronController extends Controller
         return ExitCode::OK;
     }
 
-    // Обновление уровня и заполнение таблицы users_bonus_levels
-    public function actionUpdateUsersLevels()
-    {
-        $users = Users::find()->all();
-
-        $bonusLevelsList = BonusLevels::find()
-            ->where(['active' => 1])
-            ->orderBy(['threshold' => SORT_ASC])
-            ->asArray()
-            ->all();
-
-        if (empty($bonusLevelsList)) {
-            $this->stdout(
-                "Нет активных бонус уровней для обработки.\n",
-                BaseConsole::FG_RED
-            );
-            return ExitCode::UNAVAILABLE;
-        }
-
-        foreach ($users as $user) {
-            $newBonusLevel = null;
-            foreach ($bonusLevelsList as $level) {
-                if ($user->sale_price > $level['threshold']) {
-                    $newBonusLevel = $level['alias'];
-                }
-            }
-
-            if ($user->bonus_level !== $newBonusLevel) {
-                $oldBonusLevel = $user->bonus_level;
-                $user->bonus_level = $newBonusLevel;
-                if (!$user->save()) {
-                    $this->stdout(
-                        "Ошибка обновления бонусного уровня пользователя (ID: {$user->id}): " . json_encode($user->getErrors()) . "\n",
-                        BaseConsole::FG_RED
-                    );
-                    continue;
-                }
-                $this->stdout(
-                    "Пользователю (ID: {$user->id}) изменён бонусный уровень с \"{$oldBonusLevel}\" на \"{$newBonusLevel}\".\n",
-                    BaseConsole::FG_GREEN
-                );
-
-                $activeBonusRecord = UsersBonusLevels::find()
-                    ->where(['active' => 1])
-                    ->andWhere(['or', ['phone' => $user->phone], ['user_id' => $user->id]])
-                    ->one();
-                if ($activeBonusRecord) {
-                    $activeBonusRecord->active = 0;
-                    $activeBonusRecord->updated_at = date('Y-m-d H:i:s');
-                    if (!$activeBonusRecord->save()) {
-                        $this->stdout(
-                            "Ошибка деактивации старой записи бонусного уровня для пользователя (ID: {$user->id}).\n",
-                            BaseConsole::FG_RED
-                        );
-                    }
-                }
-
-                $newBonusRecord = new UsersBonusLevels();
-                $newBonusRecord->phone = $user->phone;
-                $newBonusRecord->user_id = $user->id;
-                $newBonusRecord->bonus_level = $newBonusLevel;
-                $newBonusRecord->created_at = date('Y-m-d H:i:s');
-                if ($user->check_id_last_sale) {
-                    $newBonusRecord->check_id = $user->check_id_last_sale;
-                    $sale = Sales::find()->where(['phone' => $user->phone])
-                        ->andWhere(['id' => $user->check_id_last_sale])->one();
-                    $check_name = $sale->number ?? null;
-                    $newBonusRecord->check_name = $check_name;
-                } else {
-                    $sale = Sales::find()
-                        ->where(['phone' => $user->phone])
-                        ->andWhere(
-                            new \yii\db\Expression("date::DATE = :date"),
-                            [':date' => date('Y-m-d', strtotime($user->date_last_sale))]
-                        )
-                        ->one();
-                    if (!empty($sale)) {
-                        $newBonusRecord->check_id = $sale->id;
-                        $newBonusRecord->check_name = $sale->number;
-                    }
-                }
-
-
-                
-                $newBonusRecord->active = 1;
-                if (!$newBonusRecord->save()) {
-                    $this->stdout(
-                        "Ошибка создания новой записи бонусного уровня для пользователя (ID: {$user->id}): " . json_encode($newBonusRecord->getErrors()) . "\n",
-                        BaseConsole::FG_RED
-                    );
-                } else {
-                    $this->stdout(
-                        "Создана новая запись бонусного уровня для пользователя (ID: {$user->id}).\n",
-                        BaseConsole::FG_GREEN
-                    );
-                }
-            }
-        }
-
-        $this->stdout(
-            "Обновление бонусных уровней завершено.\n",
-            BaseConsole::FG_GREEN
-        );
-        return ExitCode::OK;
-    }
 }
index 6be6584d9664f8e09dbbb6b8bdb2f1c37679432d..fa05d79514d1e35d2d6ed4aad2357c4f0c8034f8 100644 (file)
@@ -84,7 +84,7 @@ class BonusLevelsController extends Controller
             $model->load($this->request->post());
             $model->created_by = Yii::$app->user->id;
             $model->date_start = date('Y-m-d');
-
+            $model->date_end = date('Y-m-d', strtotime('2100-01-01'));
             if (BonusLevels::find()->where(['name' => $model->name])->exists()) {
                 Yii::$app->session->setFlash('error', 'Запись с таким именем уже существует.');
             } else if ($model->save()) {
@@ -139,14 +139,14 @@ class BonusLevelsController extends Controller
                 try {
                     // Деактивируем старую запись
                     $oldModel->active = 0;
-                    $oldModel->date_end = date('Y-m-d H:i:s');
+                    $oldModel->date_end = date('Y-m-d');
                     $oldModel->updated_by = Yii::$app->user->id;
                     $oldModel->save();
 
                     // Создаём новую запись с данными из формы
                     $newModel->active = 1;
-                    $newModel->date_start = date('Y-m-d H:i:s');
-                    $newModel->date_end = null;
+                    $newModel->date_start = date('Y-m-d');
+                    $newModel->date_end = date('Y-m-d', strtotime('2100-01-01'));
                     $newModel->created_by = Yii::$app->user->id;
                     $newModel->save();