]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-360 Сборка страницы автопм
authormarina <m.zozirova@gmail.com>
Tue, 10 Jun 2025 08:26:43 +0000 (11:26 +0300)
committermarina <m.zozirova@gmail.com>
Tue, 10 Jun 2025 08:26:43 +0000 (11:26 +0300)
erp24/commands/CronController.php
erp24/controllers/AutoPlannogrammaController.php

index 510c6ea4c5de7112297e532a98a714d4ac339f37..70cb2b37e462d9d2faee1f279df283ed2db0726e 100644 (file)
@@ -10,16 +10,20 @@ use DateTimeZone;
 use Yii;
 use yii\console\Controller;
 use yii\console\ExitCode;
+use yii\data\ArrayDataProvider;
 use yii\db\Expression;
 use yii\helpers\ArrayHelper;
 use yii\helpers\BaseConsole;
 use yii\helpers\Json;
 use yii_app\helpers\ClientHelper;
 use yii_app\helpers\DataHelper;
+use yii_app\records\Autoplannogramma;
 use yii_app\records\BonusLevels;
+use yii_app\records\CityStore;
 use yii_app\records\EqualizationRemains;
 use yii_app\records\KogortStopList;
 use yii_app\records\LPTrackerApi;
+use yii_app\records\MatrixBouquetForecast;
 use yii_app\records\Product1cReplacement;
 use yii_app\records\Products1c;
 use yii_app\records\ReplacementInvoice;
@@ -33,6 +37,8 @@ use yii_app\records\UsersBonusLevels;
 use yii_app\records\UsersMessageManagement;
 use yii_app\records\UsersTelegram;
 use yii_app\records\UsersTelegramLog;
+use yii_app\services\AutoPlannogrammaService;
+use yii_app\services\StorePlanService;
 use yii_app\services\TelegramService;
 use yii_app\services\WhatsAppService;
 
@@ -76,7 +82,8 @@ class CronController extends Controller
     }
 
     //cron/marketplace-order-one-c-statuses
-    public function actionMarketplaceOrderOneCStatuses() {
+    public function actionMarketplaceOrderOneCStatuses()
+    {
         $req_id = time();
 
         $marketplaces = [
@@ -90,13 +97,13 @@ class CronController extends Controller
             $statusesData = [];
             foreach ($statuses as $status) {
                 /* @var $status MarketplaceOrder1cStatuses */
-                $statusesData []= [
+                $statusesData [] = [
                     'status_name' => $status->status,
                     'hint' => $status->status_instruction,
                     'status_id' => $status->status_id,
                 ];
             }
-            $data []= [
+            $data [] = [
                 'id' => $marketplaceGuid,
                 'name' => $marketplaceName,
                 'statuses' => $statusesData
@@ -293,7 +300,7 @@ class CronController extends Controller
             $kogortPhones = Users::formKogortByDateAndType($targetDate, 'target');
 
             if (!empty($kogortPhones)) {
-               $dataSaved = Users::saveKogort($kogortPhones, $kogortDate, $targetDate, SentKogort::KOGORT_NUMBERS['target'], $testActive);
+                $dataSaved = Users::saveKogort($kogortPhones, $kogortDate, $targetDate, SentKogort::KOGORT_NUMBERS['target'], $testActive);
                 $this->stdout(
                     "Когорта таргета на {$kogortDate} для целевой даты {$targetDate} успешно сохранена.\n",
                     BaseConsole::FG_GREEN
@@ -441,17 +448,17 @@ class CronController extends Controller
                     $targetDate
                 );
                 foreach ($toSend as $telegramUser) {
-                        $messageData = [];
-                        $messageData['chat_id'] = $telegramUser['chat_id'];
-                        $messageData['phone'] = $telegramUser['phone'];
-                        $messageData['kogort_date'] = $kogortDate;
-                        $messageData['target_date'] = $targetDate;
-                        $messageData['type'] = 1;
-                        $messageData['message'] = $messageText;
-
-                        Yii::$app->queue->push(new SendTelegramMessageJob([
-                            'messageData' => $messageData,
-                        ]));
+                    $messageData = [];
+                    $messageData['chat_id'] = $telegramUser['chat_id'];
+                    $messageData['phone'] = $telegramUser['phone'];
+                    $messageData['kogort_date'] = $kogortDate;
+                    $messageData['target_date'] = $targetDate;
+                    $messageData['type'] = 1;
+                    $messageData['message'] = $messageText;
+
+                    Yii::$app->queue->push(new SendTelegramMessageJob([
+                        'messageData' => $messageData,
+                    ]));
                 }
                 //TODO - перенос в отправку
                 $updatedCount = SentKogort::updateAll(
@@ -729,17 +736,17 @@ class CronController extends Controller
                 $messageText = $messagesSettings
                     ->replaceShortcodes($messagesSettings->offer_2, $targetDate);
                 foreach ($toSend as $telegramUser) {
-                        $messageData = [];
-                        $messageData['chat_id'] = $telegramUser['chat_id'];
-                        $messageData['phone'] = $telegramUser['phone'];
-                        $messageData['kogort_date'] = $kogortDate;
-                        $messageData['target_date'] = $targetDate;
-                        $messageData['type'] = 2;
-                        $messageData['message'] = $messageText;
-
-                        Yii::$app->queue->push(new SendTelegramMessageJob([
-                            'messageData' => $messageData,
-                        ]));
+                    $messageData = [];
+                    $messageData['chat_id'] = $telegramUser['chat_id'];
+                    $messageData['phone'] = $telegramUser['phone'];
+                    $messageData['kogort_date'] = $kogortDate;
+                    $messageData['target_date'] = $targetDate;
+                    $messageData['type'] = 2;
+                    $messageData['message'] = $messageText;
+
+                    Yii::$app->queue->push(new SendTelegramMessageJob([
+                        'messageData' => $messageData,
+                    ]));
 
                 }
                 //TODO - перенос в отправку
@@ -807,7 +814,7 @@ class CronController extends Controller
         date_default_timezone_set('Europe/Moscow');
 
         $step2 = $messagesSettings ? $messagesSettings->day_before_step2 : 4;
-        $limit =  $messagesSettings ? $messagesSettings->channel_limit : 250;
+        $limit = $messagesSettings ? $messagesSettings->channel_limit : 250;
         $cascadeId = $messagesSettings ? $messagesSettings->cascade_id : 5686;
 
         $kogortDate = date('Y-m-d');
@@ -912,19 +919,19 @@ class CronController extends Controller
         $currentDate = date('Y-m-d');
 
         $params = [
-            "offset"       => 0,
-            "limit"        => 1000,
+            "offset" => 0,
+            "limit" => 1000,
             "channelTypes" => ["WHATSAPP"],
-            "direction"    => "OUT",
-            "dateFrom"     => $currentDate . "T00:00:00Z",
-            "dateTo"       => $currentDate . "T23:59:59Z",
-            "sort"         => [
+            "direction" => "OUT",
+            "dateFrom" => $currentDate . "T00:00:00Z",
+            "dateTo" => $currentDate . "T23:59:59Z",
+            "sort" => [
                 [
-                    "property"  => "messageId",
+                    "property" => "messageId",
                     "direction" => "DESC"
                 ]
             ],
-            "subjectId"    => 11374
+            "subjectId" => 11374
         ];
 
         $done = WhatsAppService::processMessagesHistoryAndUpdateStatuses($params);
@@ -1096,7 +1103,7 @@ class CronController extends Controller
             $users = Users::find()->select(['phone', 'name'])->where(['phone' => $phonesArray])->asArray()->all();
             $usersNames = ArrayHelper::map($users, 'phone', 'name');
             foreach ($phonesArray as $phone) {
-                if (isset($usersNames[$phone]) && !empty(trim($usersNames[$phone ])) ) {
+                if (isset($usersNames[$phone]) && !empty(trim($usersNames[$phone]))) {
                     $name = $usersNames[$phone];
                 } else {
                     $name = 'Клиент';
@@ -1131,7 +1138,7 @@ class CronController extends Controller
                     ? SentKogort::SUCCESS_UPLOAD_TO_LPTRACKER_STATUS
                     : SentKogort::ERROR_UPLOAD_TO_LPTRACKER_STATUS;
 
-                $matches = array_filter($numbers, function($item) use ($phone) {
+                $matches = array_filter($numbers, function ($item) use ($phone) {
                     return $item->phone === $phone;
                 });
 
@@ -1285,7 +1292,7 @@ class CronController extends Controller
 
         while (true) {
             $usersTelegram = UsersTelegram::find()
-                ->select(['phone','is_blocked','is_registered'])
+                ->select(['phone', 'is_blocked', 'is_registered'])
                 ->where('phone IS NOT NULL')
                 ->limit($batchSize)
                 ->offset($offset)
@@ -1342,7 +1349,7 @@ class CronController extends Controller
         }
 
         $time_end = microtime(true);
-        $execution_time = ($time_end - $time_start)/60;
+        $execution_time = ($time_end - $time_start) / 60;
         $this->stdout("Total Execution Time: {$execution_time} Mins \n", BaseConsole::FG_GREEN);
     }
 
@@ -1552,114 +1559,30 @@ class CronController extends Controller
         }
 
 
-
-
         return ExitCode::OK;
     }
-/**
-    public function actionMarinaAutoplannogrammaTest()
+
+    public function actionAutoplannogrammaCalculate()
     {
         $month = date('m');
         $year = date('Y');
-
-        $plan_date = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-01';
+        $planDate = $year . '-' . str_pad($month, 2, '0', STR_PAD_LEFT) . '-01';
         $service = new AutoPlannogrammaService();
-        $monthCategoryShare = $service->getMonthCategoryShareOrWriteOff($plan_date);
-        $monthCategoryGoal = $service->getMonthCategoryGoal($monthCategoryShare, $plan_date);
-        $monthSubcategoryShare = $service->getMonthSubcategoryShareOrWriteOff($plan_date);
-        $monthSubcategoryGoal = $service->getMonthSubcategoryGoal($monthSubcategoryShare, $monthCategoryGoal);
-        $monthSpeciesShare = $service->getMonthSpeciesShareOrWriteOff($plan_date);
-        $goals = $service->getMonthSpeciesGoalDirty($monthSpeciesShare, $monthSubcategoryGoal);
-
-        $result = StorePlanService::calculateHistoricalShare(
-            $filters['store_id'],
-            $filters['month'],
-            $filters['year'],
-            $filters['category'],
-            $filters['subcategory'],
-            $filters['species']
-        );
-
-        $noHistoryProductData = $service->calculateSpeciesForecastForProductsWithoutHistory($plan_date);
-
-        $productSalesShare = StorePlanService::calculateProductSalesShareProductsWithHistory(
-            $filters['store_id'],
-            $filters['month'],
-            $result['with_history']
-        );
-
-        $productSalesForecast = $service->calculateProductForecastInPiecesProductsWithHistory(
-            $filters['store_id'],
-            $filters['month'],
-            $productSalesShare,
-            $goals,
-            $filters['subcategory'],
-            $filters['category'],
-            $filters['species']
-        );
-
-        $matrixForecast = MatrixBouquetForecast::find()
-            ->where(['year' => $year, 'month' => $month])
-            ->asArray()
-            ->all();
-        $matrixGroups = array_unique(ArrayHelper::getColumn($matrixForecast, 'group'));
-        $bouquetForecast = StorePlanService::getBouquetSpiecesMonthGoalFromForecast($filters['month'], $filters['year'], $filters['store_id'], $matrixGroups);
-        $speciesData = $bouquetForecast['final'];
-        foreach ($speciesData as $store_id  => $categoryData) {
-            foreach ($categoryData as $category => $subcategoryData) {
-                foreach ($subcategoryData as $subcategory => $species) {
-                    foreach ($species as $speciesInd => $row) {
-                        $bouquetSpeciesForecast[] = [
-                            'category' => $category,
-                            'subcategory' => $subcategory,
-                            'store_id' => $store_id,
-                            'species' => $speciesInd,
-                            'goal' => $row
-                        ];
-                    }
-                }
-            }
+        $stores = CityStore::findAll(['visible' => CityStore::IS_VISIBLE]);
+        foreach ($stores as $store) {
+            $forecast = $service->calculateFullForecastForWeek(['month' => $month, 'year' => $year, 'store_id' => $store->id, 'plan_date' => $planDate]);
+            Yii::error("Рассчитана автопланограмма для магазина  $store->id");
 
-        }
-        $cleanedSpeciesGoals = $service->subtractSpeciesGoals($goals, $bouquetSpeciesForecast, $noHistoryProductData);
-
-
-        $salesProductForecastShare = $service->calculateProductForecastShare($noHistoryProductData, $productSalesForecast);
-
-        $productForecastSpecies = $service->calculateProductSalesBySpecies($salesProductForecastShare, $cleanedSpeciesGoals);
-
-
-        $weeklySales = $service->getHistoricalSpeciesShareByWeek($plan_date);
-
-        $weeklySalesForecast = $service->calculateWeeklyProductForecastPieces($productForecastSpecies, $weeklySales);
-
-
-        $weeklySalesForecastFormated = $service->pivotWeeklyForecast($weeklySalesForecast);
-
-        $flatData = array_filter($weeklySalesForecastFormated, function ($row) use ($filters) {
-            foreach ($filters as $key => $value) {
-                if (empty($value)) continue;
-                if (!isset($row[$key])) continue;
-
-                if (stripos((string)$row[$key], (string)$value) === false) {
-                    return false;
-                }
-            }
-            return true;
-        });
-
-        foreach ($flatData as $item) {
-            foreach ($weeks as $weekKey => $weekNumber) {
+            foreach ($forecast as $item) {
                 $model = new Autoplannogramma();
-                $model->week = $weekNumber;
+//                    $model->week = $weekNumber;
                 $model->month = $month;
                 $model->year = $year;
                 $model->product_id = $item['product_id'];
                 $model->store_id = $item['store_id'];
-                $model->quantity = round($item[$weekKey]);
+//                    $model->quantity = round($item[$weekKey]);
                 $model->quantity_forecast = round($item[$weekKey]);
                 $model->is_archive = false;
-                $model->auto_forecast = true;
 
                 if (!$model->save()) {
                     Yii::error("Ошибка сохранения: " . json_encode($model->errors), __METHOD__);
@@ -1667,10 +1590,7 @@ class CronController extends Controller
                     Yii::error("Ошибка сохранения: " . json_encode($model->errors), __METHOD__);
                 }
             }
+            Yii::error("Сохранена автопланограмма для магазина $store->name");
         }
-
-
     }
- **/
-
 }
index ad2fa16d614cd871a852de4a73f3c152b1e03b66..31a8bba5ed834a94e0da15740d44a1daa895490c 100644 (file)
@@ -1384,10 +1384,6 @@ class AutoPlannogrammaController extends BaseController
                 return true;
             });
 
-
-            echo '<pre>';
-            var_dump($flatData);
-            echo '</pre>';die();
             $dataProvider = new ArrayDataProvider([
                 'allModels' => $flatData,
                 'pagination' => ['pageSize' => 1000],