]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Метод для получения товаров
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 4 Apr 2025 08:03:18 +0000 (11:03 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Fri, 4 Apr 2025 08:03:18 +0000 (11:03 +0300)
erp24/controllers/CategoryPlanController.php
erp24/services/StorePlanService.php
erp24/views/category-plan/show-history-data.php [new file with mode: 0644]

index bec963648c1c2bc84c6b0f45dd46e84fb1e88349..fb7fb5a8272e3142f61e89e232d3daf9872dff28 100644 (file)
@@ -13,11 +13,13 @@ use yii_app\records\CategoryPlan;
 use yii_app\records\CityStore;
 use yii_app\records\CityStoreParams;
 use yii_app\records\ExportImportTable;
+use yii_app\records\Products1cNomenclature;
 use yii_app\records\Sales;
 use yii_app\records\SalesWriteOffsPlan;
 use yii_app\records\StoreDynamic;
 use yii_app\records\WriteOffs;
 use yii_app\records\WriteOffsErp;
+use yii_app\services\StorePlanService;
 
 class CategoryPlanController extends Controller {
     public function actionIndex()
@@ -267,4 +269,95 @@ class CategoryPlanController extends Controller {
         }
         return 'ok';
     }
+
+    public function actionShowHistoryData()
+    {
+        $request = \Yii::$app->request;
+        $result = null;
+
+        $storeList = ArrayHelper::map(
+            CityStore::find()->select(['id', 'name'])->orderBy('name')->asArray()->all(),
+            'id',
+            'name'
+        );
+
+        $monthsList = [
+            '01' => 'Январь',
+            '02' => 'Февраль',
+            '03' => 'Март',
+            '04' => 'Апрель',
+            '05' => 'Май',
+            '06' => 'Июнь',
+            '07' => 'Июль',
+            '08' => 'Август',
+            '09' => 'Сентябрь',
+            '10' => 'Октябрь',
+            '11' => 'Ноябрь',
+            '12' => 'Декабрь',
+        ];
+
+        $categoryList = ArrayHelper::map(
+            Products1cNomenclature::find()->select('category')->distinct()->orderBy('category')->asArray()->all(),
+            'category',
+            'category'
+        );
+
+        $subcategoryList = [];
+        $speciesList = [];
+
+        $model = new DynamicModel(['storeId', 'month', 'category', 'subcategory', 'species']);
+        $model->addRule(['storeId', 'month', 'category'], 'required');
+
+        if ($request->isPost) {
+            $post = $request->post();
+            $model->attributes = $post;
+
+
+            if (!empty($post['category'])) {
+                $subcategoryList = ArrayHelper::map(
+                    Products1cNomenclature::find()
+                        ->select('subcategory')->distinct()
+                        ->where(['category' => $post['category']])
+                        ->orderBy('subcategory')
+                        ->asArray()->all(),
+                    'subcategory',
+                    'subcategory'
+                );
+            }
+
+            if (!empty($post['subcategory'])) {
+                $speciesList = ArrayHelper::map(
+                    Products1cNomenclature::find()
+                        ->select('species')->distinct()
+                        ->where(['subcategory' => $post['subcategory']])
+                        ->orderBy('species')
+                        ->asArray()->all(),
+                    'species',
+                    'species'
+                );
+            }
+
+            if ($model->validate()) {
+                $storeId    = $post['storeId'];
+                $selectedMonth = $post['month'];
+                $category   = $post['category'];
+                $subcategory = !empty($post['subcategory']) ? $post['subcategory'] : null;
+                $species    = !empty($post['species']) ? $post['species'] : null;
+
+
+                $result = StorePlanService::calculateHistoricalShare($storeId, $selectedMonth, $category, $subcategory, $species);
+            }
+        }
+
+        return $this->render('show-history-data', [
+            'result'          => $result,
+            'model'           => $model,
+            'storeList'       => $storeList,
+            'monthsList'      => $monthsList,
+            'categoryList'    => $categoryList,
+            'subcategoryList' => $subcategoryList,
+            'speciesList'     => $speciesList,
+        ]);
+    }
+
 }
index ccc76b8dcce1c53e1c239e187832aff9941317b0..2b7f1477dad88bbb7cdde52b7405ec3f5c630689 100755 (executable)
@@ -5,6 +5,8 @@ namespace yii_app\services;
 use DateTime;
 use yii\db\Expression;
 use yii\helpers\ArrayHelper;
+use yii_app\records\Motivation;
+use yii_app\records\Sales;
 use yii_app\records\SalesProducts;
 use yii_app\records\StorePlan;
 
@@ -207,4 +209,112 @@ class StorePlanService
         return $enablePlanAdd;
     }
 
-}
\ No newline at end of file
+    public static function calculateHistoricalShare($storeId, $selectedMonth, $category, $subcategory = null, $species = null)
+    {
+        $currentTimestamp = time();
+        $year = date('Y', $currentTimestamp);
+        $periods = [];
+        for ($i = 1; $i <= 3; $i++) {
+            $prevTimestamp = strtotime("-{$i} month", $currentTimestamp);
+            $month = date('m', $prevTimestamp);
+            $periods[$month] = [];
+        }
+       // var_dump($periods); die();
+        foreach ($periods as $monthKey => $month) {
+            for ($weekNumber = 1; $weekNumber <= 4; $weekNumber++) {
+                $range = Motivation::getWeekRange(null, $weekNumber, (int)$monthKey, $year);
+                $periods[$monthKey][$weekNumber - 1] = $range;
+            }
+        }
+       // var_dump($periods); die();
+        $salesHistory = [];
+
+        foreach ($periods as $monthKey => $weeks) {
+            foreach ($weeks as $weekIndex => $week) {
+                $dateStart = $week['start_time'] . ' 00:00:00';
+                $dateEnd = $week['end_time'] . ' 23:59:59';
+
+                $query = Sales::find()->alias('s')
+                    ->select([
+                        'p1c.id as product_guid',
+                        'COUNT(*) as sales_count'
+                    ])
+                    ->innerJoin('sales_products sp', 's.id = sp.check_id')
+                    ->innerJoin('products_1c_nomenclature p1c', 'p1c.id = sp.product_id')
+                    ->where(['s.store_id' => $storeId])
+                    ->andWhere(['between', 's.date', $dateStart, $dateEnd])
+                    // Условие для чеков: order_id равен '' или '0'
+                    ->andWhere(['order_id' => ['', '0']])
+                    ->andWhere(['p1c.category' => $category]);
+
+                if ($subcategory !== null) {
+                    $query->andWhere(['p1c.subcategory' => $subcategory]);
+                }
+                if ($species !== null) {
+                    $query->andWhere(['p1c.species' => $species]);
+                }
+
+                $query->groupBy('p1c.id');
+                $results = $query->asArray()->all();
+
+
+                foreach ($results as $result) {
+                    $guid = $result['product_guid'];
+                    if (!isset($salesHistory[$guid])) {
+                        $salesHistory[$guid] = [];
+                    }
+                    if (!isset($salesHistory[$guid][$monthKey])) {
+                        $salesHistory[$guid][$monthKey] = [];
+                    }
+                    $salesHistory[$guid][$monthKey][$weekIndex] = (int)$result['sales_count'];
+                }
+            }
+        }
+        $productsWithHistory = [];
+        $productsWithoutHistory = [];
+
+        foreach ($salesHistory as $guid => $monthsData) {
+            $hasHistoryInAllMonths = true;
+            $weeklySalesData = [];
+
+            foreach ($periods as $monthKey => $monthData) {
+                if (!isset($monthsData[$monthKey])) {
+                    $hasHistoryInAllMonths = false;
+                    $weekData = [0, 0, 0, 0];
+                } else {
+                    $weekData = [];
+                    $activeWeeks = 0;
+                    for ($weekIndex = 0; $weekIndex < 4; $weekIndex++) {
+                        $salesCount = isset($monthsData[$monthKey][$weekIndex]) ? $monthsData[$monthKey][$weekIndex] : 0;
+                        $weekData[$weekIndex] = $salesCount;
+                        if ($salesCount > 0) {
+                            $activeWeeks++;
+                        }
+                    }
+                    if ($activeWeeks < 2) {
+                        $hasHistoryInAllMonths = false;
+                    }
+                }
+                $weeklySalesData[$monthKey] = $weekData;
+            }
+
+            $productData = [
+                'guid' => $guid,
+                'weekly_sales' => $weeklySalesData,
+            ];
+
+            if ($hasHistoryInAllMonths) {
+                $productsWithHistory[] = $productData;
+            } else {
+                $productsWithoutHistory[] = $productData;
+            }
+        }
+
+        return [
+            'with_history' => $productsWithHistory,
+            'without_history' => $productsWithoutHistory,
+        ];
+    }
+
+}
+
diff --git a/erp24/views/category-plan/show-history-data.php b/erp24/views/category-plan/show-history-data.php
new file mode 100644 (file)
index 0000000..06de4d2
--- /dev/null
@@ -0,0 +1,112 @@
+<?php
+use yii\helpers\Html;
+use yii\helpers\ArrayHelper;
+use yii\widgets\ActiveForm;
+use yii\base\DynamicModel;
+use yii_app\records\CityStore;
+use yii_app\records\Products1cNomenclature;
+
+
+
+/* @var $this yii\web\View */
+/* @var $result array|null */
+/* @var $model DynamicModel */
+/* @var $storeList array */
+/* @var $monthsList array */
+/* @var $categoryList array */
+/* @var $subcategoryList array */
+/* @var $speciesList array */
+?>
+?>
+<div class="show-history-data p-4">
+    <h1>Проверка истории продаж</h1>
+
+    <?php $form = ActiveForm::begin([
+        'method' => 'post',
+    ]); ?>
+
+    <?= $form->field($model, 'storeId')
+        ->dropDownList($storeList, ['prompt' => 'Выберите магазин'])
+        ->label('Магазин') ?>
+
+    <?= $form->field($model, 'month')
+        ->dropDownList($monthsList, ['prompt' => 'Выберите месяц'])
+        ->label('Месяц') ?>
+
+    <?= $form->field($model, 'category')
+        ->dropDownList($categoryList, ['prompt' => 'Выберите категорию'])
+        ->label('Категория') ?>
+
+    <?= $form->field($model, 'subcategory')
+        ->dropDownList($subcategoryList, ['prompt' => 'Выберите подкатегорию'])
+        ->label('Подкатегория') ?>
+
+    <?= $form->field($model, 'species')
+        ->dropDownList($speciesList, ['prompt' => 'Выберите вид товара'])
+        ->label('Вид товара') ?>
+
+    <div class="form-group">
+        <?= Html::submitButton('Отправить', ['class' => 'btn btn-primary']) ?>
+    </div>
+
+    <?php ActiveForm::end(); ?>
+
+
+<?php if ($result !== null): ?>
+
+    <h2>Товары с историей продаж</h2>
+    <?php if (!empty($result['with_history'])): ?>
+        <table class="table table-bordered">
+            <thead>
+            <tr>
+                <th>GUID продукта</th>
+                <th>Недельные продажи</th>
+            </tr>
+            </thead>
+            <tbody>
+            <?php foreach ($result['with_history'] as $product): ?>
+                <tr>
+                    <td><?= Html::encode($product['guid']) ?></td>
+                    <td>
+                        <?php foreach ($product['weekly_sales'] as $month => $weekData): ?>
+                            <strong><?= Html::encode($month) ?>:</strong>
+                            <?= implode(', ', $weekData) ?><br>
+                        <?php endforeach; ?>
+                    </td>
+                </tr>
+            <?php endforeach; ?>
+            </tbody>
+        </table>
+    <?php else: ?>
+        <p>Нет товаров с историей продаж.</p>
+    <?php endif; ?>
+
+    <h2>Товары без истории продаж</h2>
+    <?php if (!empty($result['without_history'])): ?>
+        <table class="table table-bordered">
+            <thead>
+            <tr>
+                <th>GUID продукта</th>
+                <th>Недельные продажи</th>
+            </tr>
+            </thead>
+            <tbody>
+            <?php foreach ($result['without_history'] as $product): ?>
+                <tr>
+                    <td><?= Html::encode($product['guid']) ?></td>
+                    <td>
+                        <?php foreach ($product['weekly_sales'] as $month => $weekData): ?>
+                            <strong><?= Html::encode($month) ?>:</strong>
+                            <?= implode(', ', $weekData) ?><br>
+                        <?php endforeach; ?>
+                    </td>
+                </tr>
+            <?php endforeach; ?>
+            </tbody>
+        </table>
+    <?php else: ?>
+        <p>Нет товаров без истории продаж.</p>
+    <?php endif; ?>
+
+<?php endif; ?>
+</div>