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()
}
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,
+ ]);
+ }
+
}
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;
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,
+ ];
+ }
+
+}
+
--- /dev/null
+<?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>