]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-58 Задание для начисления бонусов
authorAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Fri, 21 Jun 2024 06:56:35 +0000 (09:56 +0300)
committerAleksey Filippov <Aleksey.Filippov@erp-flowers.ru>
Fri, 21 Jun 2024 06:56:35 +0000 (09:56 +0300)
erp24/commands/BonusController.php
erp24/commands/CronController.php

index a97e053aed699a76d2a056baa89eff07f1ab7032..3e0fe05f7b77534ec3a2c07c7c9d2c38b1dc6430 100644 (file)
@@ -2,15 +2,16 @@
 
 namespace yii_app\commands;
 
-use Yii;
-use yii\base\Exception;
 use yii\console\Controller;
 use yii\helpers\ArrayHelper;
 use yii_app\helpers\ClientHelper;
+use yii_app\records\CityStore;
 use yii_app\records\Sales;
 use yii_app\records\Users;
 use yii_app\records\UsersBonus;
 use yii_app\records\UsersEvents;
+use yii_app\services\ExportImportService;
+use yii_app\services\LogService;
 
 class BonusController extends Controller
 {
@@ -285,4 +286,253 @@ class BonusController extends Controller
             }
         }
     }
+
+    public function actionAddNewUserAndBonus () {
+        self::addUserAndBonus();
+        self::actionBonusRemoveFromReturnSales();
+    }
+
+
+    public static function addUserBonus($row, $percentBonus, $admin_id, $store_id, $daysActiveBonus = 366)
+    {
+        $requiredFields = [
+            'summ',
+            'number',
+            'date',
+            'phone',
+            'id',
+            'store_id_1c',
+            'seller_id',
+        ];
+
+        $requiredFieldsCountValidate = 0;
+
+        foreach ($requiredFields as $field) {
+            if (array_key_exists($field, $row) && (!empty($row[$field]))) {
+                ++$requiredFieldsCountValidate;
+            }
+        }
+
+        if (count($requiredFields) != $requiredFieldsCountValidate) {
+            //TODO add error log
+            return;
+        }
+
+        $coefficientBonus = $percentBonus / 100;
+
+        $back = round($row["summ"] * $coefficientBonus);
+
+        $nm = "Возврат с покупки " . $percentBonus . "% " . $row["number"] . " сумма чека " . $row["summ"] . "";
+
+        echo ("\n\r" . " <br> " . $nm . "  дата покупки " . $row["date"] . "  бонус " . $back . "  " . strval($row["phone"]));
+
+        $userBonus = new UsersBonus;
+        $userBonus->tip = 'plus';
+        $userBonus->tip_sale = 'sale';
+        $userBonus->date = $row["date"];
+        $userBonus->date_start = date('Y-m-d H:i:s', strtotime('+1 day', strtotime($userBonus->date)));
+        $userBonus->date_end = date('Y-m-d H:i:s', strtotime('+' . $daysActiveBonus . ' day', strtotime($userBonus->date)));
+        $userBonus->phone = strval($row["phone"]);
+        $userBonus->name = $nm;
+        $userBonus->check_id = $row["id"];
+        $userBonus->bonus = $back;
+        $userBonus->ip = '127.0.0.1';
+        $userBonus->site_id = 1;
+        $userBonus->store_id = $store_id;
+        $userBonus->referal_id = '';
+        $userBonus->admin_id = $admin_id;
+        $userBonus->price = $row["summ"];
+        $userBonus->store_id_1c = $row["store_id_1c"];
+        $userBonus->seller_id_1c = $row["seller_id"];
+
+        //$userBonus->save();
+        if ($userBonus->getErrors()) {
+            LogService::apiErrorLog(json_encode(["error_id" => 23, "error" => $userBonus->getErrors()], JSON_UNESCAPED_UNICODE));
+        }
+    }
+
+
+    public function addUserAndBonus()
+    {
+        $countSaveNewUser = 0;
+        $countNewUser = 0;
+        $countAddUserBonus10 = 0;
+        $countAddUserBonus20 = 0;
+
+        $days = 5;
+        $days2 = $days + 2;
+        $dateNow = date('Y-m-d');
+        $dateCompare = date('Y-m-d H:i:s', strtotime($dateNow . ' -' . $days2 . ' day'));
+        $usersBonusList = UsersBonus::find()
+            ->select(['phone', 'price', 'bonus', 'name', 'check_id', 'store_id_1c',])
+            ->where(['!=', 'check_id', ''])
+            ->andWhere(['>', 'date', $dateCompare])
+            ->andWhere(['tip' => 'plus'])
+            ->andWhere(['tip_sale' => 'sale'])
+            ->asArray()
+            ->all();
+
+        $usersBonus = [];
+        foreach ($usersBonusList as $row) {
+            $usersBonus[$row["check_id"]] = $row["bonus"];
+        }
+
+        $sales = Sales::find()
+            ->select(['date', 'id', 'phone', 'number', 'summ', 'store_id_1c', 'seller_id'])
+            ->where(['!=', 'phone', 0])
+            ->andWhere(['>', 'date', $dateCompare])
+            ->andWhere(['operation' => Sales::OPERATION_SALE])
+            ->asArray()
+            ->all();
+
+        $salesPhones = ArrayHelper::getColumn($sales, 'phone');
+        $salesIds = ArrayHelper::getColumn($sales, 'id');
+
+        $salesReturn = Sales::find()
+            ->select(['date', 'id', 'phone', 'number', 'summ', 'store_id_1c', 'seller_id'])
+            ->andWhere(['sales_check' => $salesIds])
+            ->andWhere(['operation' => Sales::OPERATION_RETURN])
+            ->asArray()
+            ->all();
+
+        $returnSalesIds = ArrayHelper::getColumn($salesReturn, 'sales_check');
+
+        $usersSalesPhones = Users::find()->select(['phone', 'sale_cnt'])->where(['phone' => $salesPhones])->indexBy('phone')->asArray()->all();
+
+        $entityCityStore = ExportImportService::getEntityByType();
+
+        $storeNames = CityStore::getNames();
+
+        $exportCityStore = array_flip(ArrayHelper::map($entityCityStore, 'entity_id', 'export_val'));
+        $entityAdmin = ExportImportService::getEntityByType('admin');
+
+        $exportAdmin = array_flip(ArrayHelper::map($entityAdmin, 'entity_id', 'export_val'));
+
+        foreach ($sales as $row) {
+            if (array_key_exists($row["id"], $returnSalesIds)) {
+                echo ("\n\r" . "<br> пропуск чека с возвратом " . $row["id"] . " " . $row["number"]);
+                continue;
+            }
+            if (!array_key_exists($row["phone"], $usersSalesPhones)) {
+                $seller_id = ArrayHelper::getValue($exportAdmin, $row["seller_id"]);
+                $store_id = ArrayHelper::getValue($exportCityStore, $row["store_id_1c"]);
+                $sale_store = ArrayHelper::getValue($storeNames, $store_id);
+
+                $pass = rand(1000, 9999);
+                $setka_id = 1;
+
+                echo ("\n\r" . "<br> new User " . strval($row["phone"]));
+                $newUser = new Users();
+
+                $newUser->card = strval(intval($row["phone"]) * 2 + 1608 + $setka_id);
+                $newUser->kod = strval(rand(1000, 9999));
+                $newUser->pol = 'none';
+                $newUser->keycode = strval(rand(1000, 9999));
+                $newUser->phone = strval($row["phone"]);
+                $newUser->name = $name ?? 'Новый';
+                $newUser->name_name = $first_name ?? '';
+                $newUser->name_last = $second_name ?? '';
+                $newUser->password = strval($pass);
+                $newUser->phone_true = '1'; //
+                $newUser->bdate = $birth_day ?? '1971-01-01';
+                $newUser->referral_id = $referral_phone ?? '';
+                $newUser->comment = 'внесен автоматически';
+                $newUser->info = 'внесен автоматически';
+                $newUser->created_id = $seller_id;
+                $newUser->created_name = $created_name ?? '';
+                $newUser->seller_id = strval($seller_id);
+                $newUser->created_store_id = $store_id;
+                $newUser->created_store = $created_store ?? '';
+                $newUser->date = date('Y-m-d H:i:s');//now
+                $newUser->sale_store_id = $store_id;
+                $newUser->sale_store = $sale_store ?? $store_id;
+                $newUser->sms_info = 1;
+                $newUser->reklama_info = 1;
+                $newUser->sale_cnt = 1;
+                $newUser->sale_avg_price = intval($row["summ"]);
+                $newUser->sale_price = intval($row["summ"]);
+                $newUser->store_id = $row["store_id_1c"];
+                $newUser->date_last_sale = $row["date"];
+
+                //$newUser->save();
+                ++$countNewUser;
+                if ($newUser->getErrors()) {
+                    LogService::apiErrorLog(json_encode(["error_id" => 33, "error" => $newUser->getErrors()], JSON_UNESCAPED_UNICODE));
+                } else {
+                    ++$countSaveNewUser;
+                }
+
+            }
+
+            $get_arr = UsersBonus::find()
+                ->select(['bonus'])
+                ->where(['phone' => $row["phone"]])
+                ->andWhere(['check_id' => $row["id"]])
+                ->andWhere(['tip' => 'plus'])
+                ->limit(1)
+                ->scalar();
+
+            if (empty($get_arr)) {
+                $addFirstSaleBonus = false;
+
+                if (!array_key_exists($row["phone"], $usersSalesPhones)) {
+                    $addFirstSaleBonus = true;
+                } else {
+                    if ($usersSalesPhones[$row["phone"]]["sale_cnt"] == 1) {
+                        $addFirstSaleBonus = true;
+                    }
+                }
+
+                // получаем внутренний ID продаца - сотрудника из таблицы admin
+                $admin_id = ArrayHelper::getValue($exportAdmin, $row["seller_id"]);
+                // получаем внутренний ID магазина
+                $store_id = ArrayHelper::getValue($exportCityStore, $row["store_id_1c"]);
+
+                //начисляем кэшбек клиенту 10% от покупки - с базы за вычитом бонусов которые он списывает
+                $percentBonus = 10;
+                $daysActiveBonus = 366;
+                self::addUserBonus($row, $percentBonus, $admin_id, $store_id, $daysActiveBonus);
+                ++$countAddUserBonus10;
+
+                if ($addFirstSaleBonus) {
+                    //начисляем кэшбек клиенту 20% от первой покупки - с базы за вычитом бонусов которые он списывает
+                    $percentFirstBonus = 20;
+                    $daysActiveFirstBonus = 90;
+                    self::addUserBonus($row, $percentFirstBonus, $admin_id, $store_id, $daysActiveFirstBonus);
+                    ++$countAddUserBonus20;
+                }
+            }
+        }
+
+        echo ("\n\r" . "<br> Count new User " . $countNewUser);
+        echo ("\n\r" . "<br> Count Save new User " . $countSaveNewUser);
+        $deltaCounts = $countNewUser - $countSaveNewUser;
+        echo ("\n\r" . "<br> Delta by User " . $deltaCounts);
+
+        echo ("\n\r" . "<br> Count Add User Bonus 10% " . $countAddUserBonus10);
+        echo ("\n\r" . "<br> Count Add User Bonus 20% " . $countAddUserBonus10 . "\n\r");
+    }
+
+    public function actionBonusRemoveFromReturnSales()
+    {
+        $days = 5;
+        $days2 = $days + 2;
+        $dateNow = date('Y-m-d');
+        $dateCompare = date('Y-m-d H:i:s', strtotime($dateNow . ' -' . $days2 . ' day'));
+
+        $salesReturn = Sales::find()
+            ->select(['date', 'id', 'phone', 'number', 'summ', 'store_id_1c', 'seller_id', 'operation'])
+            ->where(['!=', 'phone', 0])
+            ->andWhere(['>', 'date', $dateCompare])
+            ->andWhere(['operation' => Sales::OPERATION_RETURN])
+            ->asArray()
+            ->all();
+
+        foreach($salesReturn as $row) {
+            echo ("\n\r" . "<br> Возврат " .  $row["id"] . " телефон ". $row["phone"]);
+            UsersBonus::deleteAll(
+                ['and', ['check_id' => $row["id"]], ['phone' => $row["phone"]]]
+            );
+        }
+    }
 }
index 775bf6e83eceffac88cafe668bcf43da05c25ba1..fede2932f85a78ce461cc2f806954c5ebdcdcaa1 100644 (file)
@@ -12,16 +12,16 @@ class CronController extends Controller
     {
         return [
             //'1c' => \app\actions\cron\OneCAction::class,
-            'amo142' => \app\actions\cron\Amo142Action::class,
-            'cloudpayments' => \app\actions\cron\CloudPaymentsAction::class,
-            'import-amo-in-crm' => \app\actions\cron\ImportAmoInCrmAction::class,
+//            'amo142' => \app\actions\cron\Amo142Action::class,
+//            'cloudpayments' => \app\actions\cron\CloudPaymentsAction::class,
+//            'import-amo-in-crm' => \app\actions\cron\ImportAmoInCrmAction::class,
 //            'domru-cams' => \app\actions\cron\DomRuCamsAction::class,
 //            '1c-sellers' => \app\actions\cron\OneCSellersAction::class,
 //            'custom-1c-cron' => \app\actions\cron\Custom1cCronAction::class,
 //            'balances-history' => \app\actions\cron\BalanceHistoryAction::class,
 //            'export-catalog' => \app\actions\cron\ExportCatalogAction::class,
-            'cloudpayments-region' => \app\actions\cron\CloudpaymentsRegionAction::class,
-            'bonus-users-sale-update' => \app\actions\cron\BonusUsersSaleUpdateAction::class,
+//            'cloudpayments-region' => \app\actions\cron\CloudpaymentsRegionAction::class,
+//            'bonus-users-sale-update' => \app\actions\cron\BonusUsersSaleUpdateAction::class,
           //  '1c-check-1day' => \app\actions\cron\OneCCheckOneDayAction::class,
         ];
     }