]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ERP-360 Сборка страницы автопм
authormarina <m.zozirova@gmail.com>
Mon, 16 Jun 2025 08:29:05 +0000 (11:29 +0300)
committermarina <m.zozirova@gmail.com>
Mon, 16 Jun 2025 08:29:05 +0000 (11:29 +0300)
erp24/controllers/AutoPlannogrammaController.php
erp24/views/auto-plannogramma/index.php
erp24/web/js/autoplannogramma/autoplannogramma.js

index 31a8bba5ed834a94e0da15740d44a1daa895490c..feb9caceba11e1d6d1e0e3c66730d0f64a379918 100644 (file)
@@ -346,17 +346,17 @@ class AutoPlannogrammaController extends BaseController
         $filters = [
             'category' => $request->get('category'),
             'store_id' => $request->get('store_id'),
-            'year'     => $request->get('year'),
-            'month'    => $request->get('month'),
-            'type'     => $request->get('type'),
+            'year' => $request->get('year'),
+            'month' => $request->get('month'),
+            'type' => $request->get('type'),
         ];
 
         $categoriesProvider = new ArrayDataProvider([
-            'allModels'  => [],
+            'allModels' => [],
             'pagination' => ['pageSize' => 50],
         ]);
         $productsProvider = new ArrayDataProvider([
-            'allModels'  => [],
+            'allModels' => [],
             'pagination' => ['pageSize' => 100],
         ]);
 
@@ -368,30 +368,30 @@ class AutoPlannogrammaController extends BaseController
             );
 
             $service = new AutoPlannogrammaService();
-            $data    = $service->getMonthCategoryShareOrWriteOff(
+            $data = $service->getMonthCategoryShareOrWriteOff(
                 $filters['plan_date'],
                 $filters,
                 $filters['type']
             );
 
-            $allProdIds   = [];
+            $allProdIds = [];
             $categoryRows = [];
             $storeNames = CityStore::find()->select(['id', 'name'])->indexBy('id')->asArray()->all();
             foreach ($data as $storeId => $categories) {
                 foreach ($categories as $row) {
-                    $prodIds     = array_filter(explode(',', $row['products_list'] ?? ''), fn($v)=>$v!=='');
-                    $prodCompIds = array_filter(explode(',', $row['products_components_list'] ?? ''), fn($v)=>$v!=='');
-                    $rowProdIds  = array_merge($prodIds, $prodCompIds);
+                    $prodIds = array_filter(explode(',', $row['products_list'] ?? ''), fn($v) => $v !== '');
+                    $prodCompIds = array_filter(explode(',', $row['products_components_list'] ?? ''), fn($v) => $v !== '');
+                    $rowProdIds = array_merge($prodIds, $prodCompIds);
 
                     $categoryRows[] = [
-                        'store_id'         => (string)$storeId,
-                        'store_name'       => $storeNames[$storeId]['name'] ?? null,
-                        'category'         => $row['category'],
+                        'store_id' => (string)$storeId,
+                        'store_name' => $storeNames[$storeId]['name'] ?? null,
+                        'category' => $row['category'],
                         'base_total_store' => $row['base_total_store'],
-                        'new_total_store'  => $row['new_total_store'],
-                        'total_sum'        => $row['total_sum'],
-                        'percent'          => $row['percent'],
-                        'product_ids'      => $rowProdIds,
+                        'new_total_store' => $row['new_total_store'],
+                        'total_sum' => $row['total_sum'],
+                        'percent' => $row['percent'],
+                        'product_ids' => $rowProdIds,
                     ];
 
                     $allProdIds = array_merge($allProdIds, $rowProdIds);
@@ -401,8 +401,8 @@ class AutoPlannogrammaController extends BaseController
 
             $allProdIds = array_values(array_unique($allProdIds));
             $products = Products1c::find()
-                ->select(['id','name','type','components'])
-                ->andWhere(['id'=>$allProdIds])
+                ->select(['id', 'name', 'type', 'components'])
+                ->andWhere(['id' => $allProdIds])
                 ->asArray()
                 ->indexBy('id')
                 ->all();
@@ -422,22 +422,22 @@ class AutoPlannogrammaController extends BaseController
                         ->andWhere(['region_id' => 52])
                         ->andWhere(['active' => 1])
                         ->one()->price ?? null;
-                    $productsRows[]   = $prod;
+                    $productsRows[] = $prod;
                 }
             }
             if (!empty($filters['category'])) {
-                $productsRows = array_filter($productsRows, function($prod) use ($filters) {
+                $productsRows = array_filter($productsRows, function ($prod) use ($filters) {
                     return $prod['category'] === $filters['category'];
                 });
             }
 
 
             $productsProvider = new ArrayDataProvider([
-                'allModels'  => $productsRows,
-                'pagination' => ['pageSize'=>500],
+                'allModels' => $productsRows,
+                'pagination' => ['pageSize' => 500],
             ]);
 
-            $categoryRows = array_filter($categoryRows, function($row) use ($filters) {
+            $categoryRows = array_filter($categoryRows, function ($row) use ($filters) {
                 foreach ($filters as $key => $value) {
                     if (!$value || !isset($row[$key])) {
                         continue;
@@ -451,7 +451,7 @@ class AutoPlannogrammaController extends BaseController
 
 
             $categoriesProvider = new ArrayDataProvider([
-                'allModels'  => array_values($categoryRows),
+                'allModels' => array_values($categoryRows),
                 'pagination' => ['pageSize' => 500],
             ]);
 
@@ -459,8 +459,8 @@ class AutoPlannogrammaController extends BaseController
 
         return $this->render('1_2', [
             'categoriesProvider' => $categoriesProvider,
-            'productsProvider'   => $productsProvider,
-            'filters'            => $filters,
+            'productsProvider' => $productsProvider,
+            'filters' => $filters,
         ]);
     }
 
@@ -765,7 +765,7 @@ class AutoPlannogrammaController extends BaseController
             $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 ($speciesData as $store_id => $categoryData) {
                 foreach ($categoryData as $category => $subcategoryData) {
                     foreach ($subcategoryData as $subcategory => $species) {
                         foreach ($species as $speciesInd => $row) {
@@ -928,35 +928,35 @@ class AutoPlannogrammaController extends BaseController
                 $filters['species']
             );
 
-/*            $matrixForecast = MatrixBouquetForecast::find()
-                ->where(['year' => $filters['year'], 'month' => $filters['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
-                            ];
-                        }
-                    }
-                }
+            /*            $matrixForecast = MatrixBouquetForecast::find()
+                            ->where(['year' => $filters['year'], 'month' => $filters['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
+                                        ];
+                                    }
+                                }
+                            }
 
-            }
-            $cleanedSpeciesGoals = $service->subtractSpeciesGoals($goals, $bouquetSpeciesForecast, $noHistoryProductData);*/
+                        }
+                        $cleanedSpeciesGoals = $service->subtractSpeciesGoals($goals, $bouquetSpeciesForecast, $noHistoryProductData);*/
 
 
             $salesProductForecastShare = $service->calculateProductForecastShare($noHistoryProductData, $productSalesForecast);
 
-           // $productForecastSpecies = $service->calculateProductSalesBySpecies($salesProductForecastShare, $cleanedSpeciesGoals);
+            // $productForecastSpecies = $service->calculateProductSalesBySpecies($salesProductForecastShare, $cleanedSpeciesGoals);
 
             $flatData = array_filter($salesProductForecastShare, function ($row) use ($filters) {
                 foreach ($filters as $key => $value) {
@@ -1062,7 +1062,7 @@ class AutoPlannogrammaController extends BaseController
             $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 ($speciesData as $store_id => $categoryData) {
                 foreach ($categoryData as $category => $subcategoryData) {
                     foreach ($subcategoryData as $subcategory => $species) {
                         foreach ($species as $speciesInd => $row) {
@@ -1083,7 +1083,7 @@ class AutoPlannogrammaController extends BaseController
 
             $salesProductForecastShare = $service->calculateProductForecastShare($noHistoryProductData, $productSalesForecast);
 
-             $productForecastSpecies = $service->calculateProductSalesBySpecies($salesProductForecastShare, $cleanedSpeciesGoals);
+            $productForecastSpecies = $service->calculateProductSalesBySpecies($salesProductForecastShare, $cleanedSpeciesGoals);
 
             $flatData = array_filter($productForecastSpecies, function ($row) use ($filters) {
                 foreach ($filters as $key => $value) {
@@ -1158,7 +1158,7 @@ class AutoPlannogrammaController extends BaseController
             $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 ($speciesData as $store_id => $categoryData) {
                 foreach ($categoryData as $category => $subcategoryData) {
                     foreach ($subcategoryData as $subcategory => $species) {
                         foreach ($species as $speciesInd => $row) {
@@ -1230,14 +1230,9 @@ class AutoPlannogrammaController extends BaseController
             $service = new AutoPlannogrammaService();
 
 
-
             $weeklySales = $service->getHistoricalSpeciesShareByWeek($filters['plan_date'], $filters);
 
 
-
-
-
-
             $flatData = array_filter($weeklySales, function ($row) use ($filters) {
                 foreach ($filters as $key => $value) {
                     if (empty($value)) continue;
@@ -1307,33 +1302,33 @@ class AutoPlannogrammaController extends BaseController
             }
 
 
-           /* $result = StorePlanService::calculateHistoricalShare(
-                $filters['store_id'],
-                $filters['month'],
-                $filters['year'],
-                null,
-                null,
-                null
-            );*/
+            /* $result = StorePlanService::calculateHistoricalShare(
+                 $filters['store_id'],
+                 $filters['month'],
+                 $filters['year'],
+                 null,
+                 null,
+                 null
+             );*/
 
             $noHistoryProductData = $service->calculateSpeciesForecastForProductsWithoutHistory($filters['plan_date'], $filters);
             $historyProductData = $service->calculateSpeciesForecastForProductsWithHistory($filters['plan_date'], $filters, $goals);
 
-           /* $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']
-            );*/
+            /* $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' => $filters['year'], 'month' => $filters['month']])
@@ -1342,7 +1337,7 @@ class AutoPlannogrammaController extends BaseController
             $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 ($speciesData as $store_id => $categoryData) {
                 foreach ($categoryData as $category => $subcategoryData) {
                     foreach ($subcategoryData as $subcategory => $species) {
                         foreach ($species as $speciesInd => $row) {
@@ -1396,8 +1391,6 @@ class AutoPlannogrammaController extends BaseController
     }
 
 
-
-
     public function actionControlSpeciesOld()
     {
         $model = new DynamicModel([
@@ -1408,7 +1401,7 @@ class AutoPlannogrammaController extends BaseController
             ->addRule('storeId', 'integer');
 
         $storeList = CityStore::find()
-            ->select(['name','id'])
+            ->select(['name', 'id'])
             ->where(['visible' => CityStore::IS_VISIBLE])
             ->indexBy('id')
             ->column();
@@ -1434,7 +1427,7 @@ class AutoPlannogrammaController extends BaseController
 
             list($m, $y) = explode('-', $model->month);
             $dateFrom = date("Y-m-d 00:00:00", strtotime(sprintf('%04d-%02d-01', $y, $m)));
-            $dateTo   = date("Y-m-t 23:59:59", strtotime($dateFrom));
+            $dateTo = date("Y-m-t 23:59:59", strtotime($dateFrom));
 
             if ($model->storeId) {
                 $filters['store_id'] = $model->storeId;
@@ -1460,24 +1453,24 @@ class AutoPlannogrammaController extends BaseController
                 $monthSpeciesGoalsMap[$monthSpeciesGoal['store_id']]
                 [$monthSpeciesGoal['category']]
                 [$monthSpeciesGoal['subcategory']]
-                [$monthSpeciesGoal['species']] = $monthSpeciesGoal['goal'] ;
+                [$monthSpeciesGoal['species']] = $monthSpeciesGoal['goal'];
             }
 
             $weeksShareResult = $service->getHistoricalWeeklySpeciesShare($model->month, $filters, null, 'writeOffs');
-            $weeksData = $service->calculateWeeklySpeciesGoals($weeksShareResult['weeksData'], $monthSpeciesGoals) ;
+            $weeksData = $service->calculateWeeklySpeciesGoals($weeksShareResult['weeksData'], $monthSpeciesGoals);
 
             $datePlan = $filters['plan_date'];
             $monthCategoryShare = $service->getMonthCategoryShareOrWriteOffWeighted($datePlan, $filters, null, $filters['type']);
             $monthCategoryGoal = $service->getMonthCategoryGoal($monthCategoryShare, $datePlan, $filters['type']);
             foreach ($monthCategoryShare as $sid => $cats) {
-                foreach($cats as $cat) {
+                foreach ($cats as $cat) {
                     $monthCategoryShareResult[$sid][$cat['category']]['total_sum_cat'] = $cat['total_sum_cat'];
                     $monthCategoryShareResult[$sid][$cat['category']]['share_of_total'] = $cat['share_of_total'];
                 }
 
             }
             foreach ($monthCategoryGoal as $cats) {
-                    $monthCategoryShareResult[$cats['store_id']][$cats['category']]['goal'] = $cats['goal'];
+                $monthCategoryShareResult[$cats['store_id']][$cats['category']]['goal'] = $cats['goal'];
 
             }
 
@@ -1485,8 +1478,8 @@ class AutoPlannogrammaController extends BaseController
             $monthSubcategoryGoal = $service->getMonthSubcategoryGoal($monthSubcategoryShare, $monthCategoryGoal);
 
             if ($filters['type'] === 'writeOffs') {
-                $salesSubShare        = $service->getMonthSubcategoryShareOrWriteOffWeighted($datePlan, $filters, null, 'sales');
-                $salesSubGoal         = $service->getMonthSubcategoryGoal($salesSubShare, $monthCategoryGoal);
+                $salesSubShare = $service->getMonthSubcategoryShareOrWriteOffWeighted($datePlan, $filters, null, 'sales');
+                $salesSubGoal = $service->getMonthSubcategoryGoal($salesSubShare, $monthCategoryGoal);
 
                 $catGoalMap = [];
                 foreach ($monthCategoryGoal as $row) {
@@ -1504,8 +1497,8 @@ class AutoPlannogrammaController extends BaseController
 
                     $writeShare = $row['percent_of_month'];
 
-                    $writeGoal  = ($catGoalMap[$cat] ?? 0) * $writeShare;
-                    $saleGoal   = $salesSubGoalMap[$cat][$sub] ?? 0;
+                    $writeGoal = ($catGoalMap[$cat] ?? 0) * $writeShare;
+                    $saleGoal = $salesSubGoalMap[$cat][$sub] ?? 0;
 
                     if ($saleGoal > 0 && $writeGoal > 0.1 * $saleGoal) {
                         $row['share'] = 0.1;
@@ -1516,8 +1509,8 @@ class AutoPlannogrammaController extends BaseController
             }
 
             foreach ($monthSubcategoryShare as $subcat) {
-                    $monthCategoryShareResult[$subcat['store_id']][$subcat['category']][$subcat['subcategory']]['total_sum'] = $subcat['total_sum'];
-                    $monthCategoryShareResult[$subcat['store_id']][$subcat['category']][$subcat['subcategory']]['percent_of_month'] = $subcat['percent_of_month'];
+                $monthCategoryShareResult[$subcat['store_id']][$subcat['category']][$subcat['subcategory']]['total_sum'] = $subcat['total_sum'];
+                $monthCategoryShareResult[$subcat['store_id']][$subcat['category']][$subcat['subcategory']]['percent_of_month'] = $subcat['percent_of_month'];
             }
             foreach ($monthSubcategoryGoal as $cats) {
                 $monthCategoryShareResult[$cats['store_id']][$cats['category']][$cats['subcategory']]['goal'] = $cats['goal'];
@@ -1527,7 +1520,7 @@ class AutoPlannogrammaController extends BaseController
             $monthSpeciesGoal = $service->getMonthSpeciesGoalDirty($monthSpeciesShare, $monthSubcategoryGoal);
             if ($filters['type'] === 'writeOffs') {
                 $salesSpecShare = $service->getMonthSpeciesShareOrWriteOffWeighted($datePlan, $datePlan, $filters, null, 'sales');
-                $salesSpecGoal  = $service->getMonthSpeciesGoalDirty($salesSpecShare, $monthSubcategoryGoal);
+                $salesSpecGoal = $service->getMonthSpeciesGoalDirty($salesSpecShare, $monthSubcategoryGoal);
 
                 $subGoalMap = [];
                 foreach ($monthSubcategoryGoal as $row) {
@@ -1539,13 +1532,13 @@ class AutoPlannogrammaController extends BaseController
                 }
 
                 foreach ($monthSpeciesShare as &$row) {
-                    $cat  = $row['category'];
-                    $sub  = $row['subcategory'];
+                    $cat = $row['category'];
+                    $sub = $row['subcategory'];
                     $spec = $row['species'];
 
                     $writeShare = $row['percent_of_month'];
-                    $writeGoal  = ($subGoalMap[$cat][$sub] ?? 0) * $writeShare;
-                    $saleGoal   = $salesSpecGoalMap[$cat][$sub][$spec] ?? 0;
+                    $writeGoal = ($subGoalMap[$cat][$sub] ?? 0) * $writeShare;
+                    $saleGoal = $salesSpecGoalMap[$cat][$sub][$spec] ?? 0;
 
                     if ($saleGoal > 0 && $writeGoal > 0.1 * $saleGoal) {
                         $row['share'] = 0.1;
@@ -1570,25 +1563,25 @@ class AutoPlannogrammaController extends BaseController
                 $forecasts = $service->calculateWeekForecastSpeciesProducts($r['category'], $r['subcategory'], $r['species'], $r['store_id'], $r['weekly_goal']);
                 foreach ($forecasts as $forecast) {
                     $weeksProductForecast[] = [
-                        'category'    => $forecast['category']    ?? '',
+                        'category' => $forecast['category'] ?? '',
                         'subcategory' => $forecast['subcategory'] ?? '',
-                        'species'     => $forecast['species']     ?? '',
-                        'product_id'  => $forecast['product_id']  ?? '',
-                        'name'        => $forecast['name']        ?? '',
-                        'price'       => $forecast['price']       ?? '',
-                        'goal'        => $forecast['goal']        ?? 0,
-                        'forecast'    => $forecast['forecast']    ?? 0,
-                        'week'        => $r['week'],
+                        'species' => $forecast['species'] ?? '',
+                        'product_id' => $forecast['product_id'] ?? '',
+                        'name' => $forecast['name'] ?? '',
+                        'price' => $forecast['price'] ?? '',
+                        'goal' => $forecast['goal'] ?? 0,
+                        'forecast' => $forecast['forecast'] ?? 0,
+                        'week' => $r['week'],
                     ];
                 }
             }
 
-            usort($weeksProductForecast, function($a, $b) {
-                foreach (['category','subcategory','species','name','week'] as $key) {
+            usort($weeksProductForecast, function ($a, $b) {
+                foreach (['category', 'subcategory', 'species', 'name', 'week'] as $key) {
                     $va = $a[$key];
                     $vb = $b[$key];
                     if ($va < $vb) return -1;
-                    if ($va > $vb) return  1;
+                    if ($va > $vb) return 1;
                 }
                 return 0;
             });
@@ -1596,14 +1589,14 @@ class AutoPlannogrammaController extends BaseController
         }
 
         return $this->render('control-species-old', [
-            'model'           => $model,
-            'result'          => $monthResult,
-            'weeksData'       => $weeksData,
+            'model' => $model,
+            'result' => $monthResult,
+            'weeksData' => $weeksData,
             'monthCategoryShare' => $monthCategoryShareResult,
             'weeksProductForecast' => $weeksProductForecast,
-            'totals'          => $totals,
-            'storeList'       => $storeList,
-            'monthsList'      => $monthsList,
+            'totals' => $totals,
+            'storeList' => $storeList,
+            'monthsList' => $monthsList,
 
         ]);
     }
@@ -1619,7 +1612,7 @@ class AutoPlannogrammaController extends BaseController
             ->addRule('storeId', 'integer');
 
         $storeList = CityStore::find()
-            ->select(['name','id'])
+            ->select(['name', 'id'])
             ->where(['visible' => CityStore::IS_VISIBLE])
             ->indexBy('id')
             ->column();
@@ -1645,7 +1638,7 @@ class AutoPlannogrammaController extends BaseController
 
             list($m, $y) = explode('-', $model->month);
             $dateFrom = date("Y-m-d 00:00:00", strtotime(sprintf('%04d-%02d-01', $y, $m)));
-            $dateTo   = date("Y-m-t 23:59:59", strtotime($dateFrom));
+            $dateTo = date("Y-m-t 23:59:59", strtotime($dateFrom));
 
             if ($model->storeId) {
                 $filters['store_id'] = $model->storeId;
@@ -1666,17 +1659,17 @@ class AutoPlannogrammaController extends BaseController
 
 
             $weeksShareResult = $service->getHistoricalWeeklySpeciesShare($model->month, $filters, null, 'writeOffs');
-            $weeksData = $service->calculateWeeklySpeciesGoals($weeksShareResult, $monthSpeciesGoals) ;
+            $weeksData = $service->calculateWeeklySpeciesGoals($weeksShareResult, $monthSpeciesGoals);
 
             $datePlan = $filters['plan_date'];
-            $monthCategoryShare = $service->getMonthCategoryShareOrWriteOff($datePlan, $filters,  $filters['type']);
-            $monthCategoryGoal = $service->getMonthCategoryGoal($monthCategoryShare, $datePlan,  $filters['type']);
+            $monthCategoryShare = $service->getMonthCategoryShareOrWriteOff($datePlan, $filters, $filters['type']);
+            $monthCategoryGoal = $service->getMonthCategoryGoal($monthCategoryShare, $datePlan, $filters['type']);
 
             $monthCategorySalesShare = $service->getMonthCategoryShareOrWriteOff($datePlan, $filters);
             $monthCategorySalesGoal = $service->getMonthCategoryGoal($monthCategorySalesShare, $datePlan);
 
             foreach ($monthCategoryShare as $sid => $cats) {
-                foreach($cats as $cat) {
+                foreach ($cats as $cat) {
                     $monthCategoryShareResult[$sid][$cat['category']]['total_sum'] = $cat['total_sum'];
                     $monthCategoryShareResult[$sid][$cat['category']]['percent'] = $cat['percent'];
                 }
@@ -1689,8 +1682,8 @@ class AutoPlannogrammaController extends BaseController
             $monthSubcategorySalesShare = $service->getMonthSubcategoryShareOrWriteOff($datePlan, $filters);
             $monthSubcategorySalesGoal = $service->getMonthSubcategoryGoal($monthSubcategorySalesShare, $monthCategorySalesGoal);
 
-            $monthSubcategoryShare = $service->getMonthSubcategoryShareOrWriteOff($datePlan, $filters,  $filters['type']);
-            $monthSubcategoryGoal = $service->getMonthSubcategoryGoal($monthSubcategoryShare, $monthCategoryGoal,  $filters['type'], $monthSubcategorySalesGoal);
+            $monthSubcategoryShare = $service->getMonthSubcategoryShareOrWriteOff($datePlan, $filters, $filters['type']);
+            $monthSubcategoryGoal = $service->getMonthSubcategoryGoal($monthSubcategoryShare, $monthCategoryGoal, $filters['type'], $monthSubcategorySalesGoal);
 
             foreach ($monthSubcategoryShare as $subcat) {
                 $monthCategoryShareResult[$subcat['store_id']][$subcat['category']][$subcat['subcategory']]['total_sum'] = $subcat['total_sum'];
@@ -1725,25 +1718,25 @@ class AutoPlannogrammaController extends BaseController
                 $forecasts = $service->calculateWeekForecastSpeciesProducts($r['category'], $r['subcategory'], $r['species'], $r['store_id'], $r['weekly_goal']);
                 foreach ($forecasts as $forecast) {
                     $weeksProductForecast[] = [
-                        'category'    => $forecast['category']    ?? '',
+                        'category' => $forecast['category'] ?? '',
                         'subcategory' => $forecast['subcategory'] ?? '',
-                        'species'     => $forecast['species']     ?? '',
-                        'product_id'  => $forecast['product_id']  ?? '',
-                        'name'        => $forecast['name']        ?? '',
-                        'price'       => $forecast['price']       ?? '',
-                        'goal'        => $forecast['goal']        ?? 0,
-                        'forecast'    => $forecast['forecast']    ?? 0,
-                        'week'        => $r['week'],
+                        'species' => $forecast['species'] ?? '',
+                        'product_id' => $forecast['product_id'] ?? '',
+                        'name' => $forecast['name'] ?? '',
+                        'price' => $forecast['price'] ?? '',
+                        'goal' => $forecast['goal'] ?? 0,
+                        'forecast' => $forecast['forecast'] ?? 0,
+                        'week' => $r['week'],
                     ];
                 }
             }
 
-            usort($weeksProductForecast, function($a, $b) {
-                foreach (['category','subcategory','species','name','week'] as $key) {
+            usort($weeksProductForecast, function ($a, $b) {
+                foreach (['category', 'subcategory', 'species', 'name', 'week'] as $key) {
                     $va = $a[$key];
                     $vb = $b[$key];
                     if ($va < $vb) return -1;
-                    if ($va > $vb) return  1;
+                    if ($va > $vb) return 1;
                 }
                 return 0;
             });
@@ -1751,18 +1744,36 @@ class AutoPlannogrammaController extends BaseController
         }
 
         return $this->render('control-species', [
-            'model'           => $model,
-            'result'          => $monthResult,
-            'weeksData'       => $weeksData,
+            'model' => $model,
+            'result' => $monthResult,
+            'weeksData' => $weeksData,
             'monthCategoryShare' => $monthCategoryShareResult,
             'weeksProductForecast' => $weeksProductForecast,
-            'totals'          => $totals,
-            'storeList'       => $storeList,
-            'monthsList'      => $monthsList,
+            'totals' => $totals,
+            'storeList' => $storeList,
+            'monthsList' => $monthsList,
 
         ]);
     }
 
+    public function actionGetSubcategories(string $category, int $year, int $week): array
+    {
+        Yii::$app->response->format = Response::FORMAT_JSON;
 
+        $data = Autoplannogramma::find()
+            ->alias('a')
+            ->leftJoin('products_1c_nomenclature p', 'a.product_id = p.id')
+            ->where(['p.category' => $category])
+            ->andWhere(['a.year' => $year])
+            ->andWhere(['a.week' => $week])
+            ->select([
+                'p.subcategory as name',
+                new \yii\db\Expression("CASE WHEN COUNT(a.id) > 0 THEN 1 ELSE 0 END AS hasData")
+            ])
+            ->groupBy('p.subcategory')
+            ->asArray()
+            ->all();
 
+        return $data;
+    }
 }
index 68cb03e865723621aba7208b1f8bb4a2084751dc..c260ab8e6ae15346817416ce59f31186022a9239 100644 (file)
@@ -54,9 +54,11 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
                 </div>
                 <div class="col-md d-flex">
                     <?= Select2::widget([
+
                         'name' => 'store-type-filter',
+                        'class' => 'w-110',
                         'data' => ArrayHelper::map(StoreType::find()->orderBy('sequence_number')->all(), 'id', 'name'),
-                        'options' => ['placeholder' => 'Тип магазина', 'id' => 'store-type', 'style' => 'width: 110%;'],
+                        'options' => ['placeholder' => 'Тип магазина', 'id' => 'store-type'],
                         'pluginOptions' => ['allowClear' => true],
                     ]) ?>
                 </div>
@@ -84,7 +86,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
                     ]) ?>
                 </div>
                 <div class="col-md d-flex">
-                    <?= Html::submitButton('Применить', ['class' => 'btn btn-apply btn-primary', 'style' => 'width:100%']); ?>
+                    <?= Html::submitButton('Применить', ['class' => 'btn btn-apply btn-primary w-100']); ?>
                 </div>
             </div>
             <div class="row py-3">
@@ -130,7 +132,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
                 <div class="col-md d-flex">
                 </div>
                 <div class="col-md d-flex">
-                    <?= Html::submitButton('Сбросить', ['class' => 'btn btn-reset btn-warning', 'style' => 'width:100%']); ?>
+                    <?= Html::submitButton('Сбросить', ['class' => 'btn btn-reset btn-warning w-100']); ?>
                 </div>
             </div>
             <div class="row">
@@ -149,7 +151,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
                 <div class="col-md d-flex"></div>
                 <div class="col-md d-flex"></div>
                 <div class="col-md d-flex">
-                    <?= Html::button('Сохранить', ['class' => 'btn btn-success btn-save', 'style' => 'width:100%']); ?>
+                    <?= Html::button('Сохранить', ['class' => 'btn btn-success btn-save w-100']); ?>
                 </div>
             </div>
         </div>
@@ -171,7 +173,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
         <table class="table">
             <thead>
             <tr class="head">
-                <th scope="col" style="text-align: left !important; display: inline-block; justify-content: flex-end;">
+                <th scope="col" class="info-column">
                     <?= Html::label("Год: Неделя: ", null, ['class' => 'label-year-week']) ?><br>
                     <?= Html::label("Месяц", null, ['class' => 'label-month-range']) ?><br>
                     <?= Html::label("Тип п-ма:", null, ['class' => 'label-capacity-type']) ?><br>
@@ -189,9 +191,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
                 </th>
                 <?php foreach ($stores as $storeId => $storeName): ?>
                     <th scope="col" class="store-label" data-store-id="<?= $storeId ?>">
-                        <?= Html::label($storeName, null, [
-                            'style' => 'display: block; white-space: nowrap; margin: auto; font-weight: bold; text-align: center; writing-mode: sideways-lr;'
-                        ]) ?>
+                        <?= Html::label($storeName, null, ['class' => 'store-cell']) ?>
                     </th>
                 <?php endforeach; ?>
             </tr>
@@ -206,26 +206,28 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
 
             <?php foreach ($groupedCategories as $category => $subcategories): ?>
                 <tr>
-                    <td class="category" style="display: flex; justify-content: flex-end;">
+                    <td class="category category-cell">
                         <span class="list-group-item list-group-item-action">
                             <?= Html::encode($category) ?>
                         </span>
                     </td>
                     <?php foreach ($stores as $id => $storeName): ?>
-                        <td data-store-id="<?= $id ?>" data-category="<?=$category?>"></td>
+                        <td data-store-id="<?= $id ?>" data-category="<?= $category ?>"></td>
                     <?php endforeach; ?>
                 </tr>
 
                 <?php foreach ($subcategories as $subcategory): ?>
-
                     <tr>
-                        <td class="subcategory" style="display: flex; justify-content: flex-end;">
-                            <span class="list-group-item list-group-item-action" style="width: 95%" data-category="<?= Html::encode($category) ?>" data-subcategory="<?= Html::encode($subcategory) ?>">
+                        <td class="subcategory subcategory-cell">
+                            <span class="list-group-item list-group-item-action subcategory-label"
+                                  data-category="<?= Html::encode($category) ?>"
+                                  data-subcategory="<?= Html::encode($subcategory) ?>">
                                 <?= Html::encode($subcategory) ?>
                             </span>
                         </td>
                         <?php foreach ($stores as $id => $storeName): ?>
-                            <td data-store-id="<?= $id ?>" data-category="<?= $category?>" data-subcategory="<?= $subcategory ?>"></td>
+                            <td data-store-id="<?= $id ?>" data-category="<?= $category ?>"
+                                data-subcategory="<?= $subcategory ?>"></td>
                         <?php endforeach; ?>
                     </tr>
                 <?php endforeach; ?>
@@ -281,7 +283,7 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
     }
 
     .list-group-item-action {
-        color:black;
+        color: black;
     }
 
     .loader-overlay {
@@ -297,4 +299,59 @@ $this->registerJsFile('/js/autoplannogramma/autoplannogramma.js', ['position' =>
         z-index: 999;
     }
 
+    .category-cell {
+        display: flex;
+        justify-content: flex-end;
+    }
+
+    .subcategory-cell {
+        display: flex;
+        justify-content: flex-end;
+    }
+
+    .subcategory-label {
+        width: 95%;
+    }
+
+    th[scope="col"][style*="text-align: left"] {
+        display: inline-block !important;
+        justify-content: flex-end;
+    }
+
+    .buttons {
+        display: flex;
+        justify-content: flex-end;
+    }
+
+    .store-label > label {
+        display: block;
+        white-space: nowrap;
+        margin: auto;
+        font-weight: bold;
+        text-align: center;
+        writing-mode: sideways-lr;
+    }
+
+    .info-column {
+        text-align: left !important;
+        display: inline-block;
+        justify-content: flex-end;
+    }
+
+    .store-cell {
+        display: block;
+        white-space: nowrap;
+        margin: auto;
+        font-weight: bold;
+        text-align: center;
+        writing-mode: sideways-lr;
+    }
+
+    .input {
+        padding: .375rem .75rem;
+        font-size: 1rem;
+        line-height: 1.5;
+        border-radius: .375rem;
+        border: 1px solid #0d6efd;
+    }
 </style>
\ No newline at end of file
index a5ed14b009a73a273bbddecd7e268fa0c3aaf8f1..e1b77ff2153f0c73c4265293b77183fd12988e4b 100644 (file)
@@ -73,9 +73,8 @@ $('.subcategory .list-group-item').on('click', function (e) {
             const tr = $('<tr class="inserted-row"></tr>');
 
             const subcategoryTd = $(`
-                <td class="subcategory" style="display: flex; justify-content: flex-end;">
-                    <span class="list-group-item list-group-item-action subcategory-link"
-                          style="width: 90%;"
+                <td class="subcategory d-flex justify-content-end">
+                    <span class="list-group-item list-group-item-action subcategory-link w-90"
                           data-category="${category}" data-subcategory="${subcategory}">
                         ${item.name}
                     </span>
@@ -104,16 +103,16 @@ $('.subcategory .list-group-item').on('click', function (e) {
 
                 const td = $(`
                     <td data-store-id="${storeId}">
-                        <div style="display: flex; align-items: center;">
-                            <input type="number" class="btn btn-primary input "
+                        <div class="d-flex align-items-center">
+                            <input type="number" class="btn btn-primary input w-100"
                                    value="${val.quantity}"
                                    data-id="${val.id}"
                                    data-guid="${item.product_id}"
                                    data-store_id="${storeId}"
                                    data-bs-toggle="tooltip" data-bs-placement="top"
                                    data-original-value="${val.quantity}"
-                                   style="width: 100%; padding: .375rem .75rem; font-size: 1rem; line-height: 1.5; border-radius: .375rem; border: 1px solid #0d6efd;">
-                            <button class="reject-btn" style="border: none; background: transparent; cursor: pointer;">
+                                   >
+                            <button class="reject-btn border-0 bg-transparent cursor-pointer">
                                 <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24">
                                     <path d="M20 11v5a1 1 0 0 1-2 0v-4H7.414l1.293 1.293a1 1 0 0 1-1.414 1.414l-3-3a1 1 0 0 1 0-1.416l3-3a1 1 0 1 1 1.414 1.416L7.414 10H19a1 1 0 0 1 1 1z"
                                           fill="grey" stroke="none"/>
@@ -134,54 +133,36 @@ $('.subcategory .list-group-item').on('click', function (e) {
             $('.loader-overlay').addClass('d-none');
         });
 });
-//
-// $('.category .list-group-item').on('click', function () {
-//     let $categorySpan = $(this);
-//     let category = $categorySpan.text().trim();
-//
-//     $.get('/path/to/subcategories', { category: category }, function (subcategories) {
-//         // пример: subcategories = ["Зелень", "Овощи", "Фрукты"]
-//
-//         // удалим уже существующие строки подкатегорий
-//         $categorySpan.closest('tr').nextAll('tr').each(function () {
-//             if ($(this).find('.subcategory').length > 0) {
-//                 $(this).remove();
-//             } else {
-//                 return false; // как только наткнулись на следующую категорию — останавливаемся
-//             }
-//         });
-//
-//         // вставим строки
-//         let $categoryRow = $categorySpan.closest('tr');
-//         $.each(subcategories, function (i, subcategory) {
-//             let row = $('<tr style="display: table-row;"></tr>');
-//             let td = $('<td class="subcategory" style="display: flex; justify-content: flex-end;"></td>');
-//             let span = $('<span>', {
-//                 class: 'list-group-item list-group-item-action subcategory-link',
-//                 style: 'width: 95%',
-//                 'data-category': category,
-//                 'data-subcategory': subcategory,
-//                 text: subcategory
-//             });
-//             td.append(span);
-//             row.append(td);
-//
-//             // Добавим по колонке на каждый магазин
-//             <?php foreach ($stores as $id => $storeName): ?>
-//             row.append(
-//                 $('<td>', {
-//                     'data-store-id': '<?= $id ?>',
-//                     'data-category': category,
-//                     'data-subcategory': subcategory
-//                 })
-//             );
-//             <?php endforeach; ?>
-//
-//             $categoryRow.after(row);
-//             $categoryRow = row; // чтобы следующий вставлялся после предыдущего
-//         });
-//     });
-// });
+
+$('.category .list-group-item').on('click', function () {
+    const $categorySpan = $(this);
+    const category = $categorySpan.text().trim();
+    const year = $('#year').val();
+    const week = $('#week').val();
+    $('.loader-overlay').removeClass('d-none');
+    $.get('/auto-plannogramma/get-subcategories', { category, year, week }, function (subcategories) {
+        const subMap = {};
+        subcategories.forEach(sub => {
+            subMap[sub.name] = sub.hasdata;
+        });
+
+        $(`span.list-group-item[data-category="${category}"]`).each(function () {
+            const $span = $(this);
+            const subName = $span.data('subcategory');
+
+            if (subMap.hasOwnProperty(subName)) {
+                if (subMap[subName]) {
+                    $span.text(subName);
+                } else {
+                    $span.text(`${subName} (нет данных)`);
+                }
+            } else {
+                $span.text(`${subName} (нет данных)`);
+            }
+        });
+    });
+    $('.loader-overlay').addClass('d-none');
+});
 
 
 $('#autoplannogramma').on('input', '.input', function () {