]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Добавил интерфейс вывода себестоимости
authorvladfo <fvv2011@gmail.com>
Fri, 11 Oct 2024 07:35:45 +0000 (10:35 +0300)
committervladfo <fvv2011@gmail.com>
Fri, 11 Oct 2024 07:35:45 +0000 (10:35 +0300)
erp24/actions/motivation/TestSelfCostAction.php [new file with mode: 0644]
erp24/controllers/MotivationController.php
erp24/services/MotivationService.php
erp24/views/motivation/test-self-cost.php [new file with mode: 0644]

diff --git a/erp24/actions/motivation/TestSelfCostAction.php b/erp24/actions/motivation/TestSelfCostAction.php
new file mode 100644 (file)
index 0000000..b286e9b
--- /dev/null
@@ -0,0 +1,59 @@
+<?php
+
+namespace yii_app\actions\motivation;
+
+use Yii;
+use yii\base\Action;
+use yii\base\DynamicModel;
+use yii\helpers\ArrayHelper;
+use yii_app\records\CityStore;
+use yii_app\records\Motivation;
+use yii_app\services\MotivationService;
+
+class TestSelfCostAction extends Action
+{
+    public function run() {
+
+        $stores = CityStore::find()
+            ->select(['id', 'name'])
+            ->where(['visible' => 1])
+            ->asArray()
+            ->all();
+
+        $storeList = ArrayHelper::map($stores, 'id', 'name');
+
+        // Создаем модель формы
+        $model = new DynamicModel(['startDate', 'endDate', 'storeId']);
+        $model->addRule(['startDate', 'endDate'], 'date', ['format' => 'php:Y-m-d'])
+            ->addRule(['storeId'], 'integer');
+
+        // Загружаем данные из GET-параметров
+        if ($model->load(Yii::$app->request->get()) && $model->validate()) {
+            $startDate = $model->startDate;
+            $endDate = $model->endDate;
+            $storeId = $model->storeId;
+        } else {
+            $startDate = '';
+            $endDate = '';
+            $storeId = '';
+        }
+
+        $data = [];
+        $totalSum = 0.0;
+
+        if ($startDate && $endDate && $storeId) {
+            $totalSum = MotivationService::getSelfCostSumByStore($startDate, $endDate, $storeId);
+
+            // Получаем данные о продуктах и себестоимости
+            $salesProducts = MotivationService::getSalesProductsDetails($startDate, $endDate, $storeId);
+            $data = $salesProducts;
+        }
+
+        return $this->controller->render('test-self-cost', [
+            'storeList' => $storeList,
+            'model' => $model,
+            'data' => $data,
+            'totalSum' => $totalSum,
+        ]);
+    }
+}
\ No newline at end of file
index 2839c8f9147221586a3e520cbe90f7b0e80730fe..d7a516ee70404c22d20b93cff563d4c2ff2ea465 100644 (file)
@@ -22,6 +22,7 @@ class MotivationController extends Controller
             'mounth-salary' => \yii_app\actions\motivation\SumPreviousMonthSalaryAction::class,
             'sum-salary-by-month' => \yii_app\actions\motivation\SumSalaryByMonthAction::class,
             'test-fact' => \yii_app\actions\motivation\TestFactAction::class,
+            'test-selfcost' => \yii_app\actions\motivation\TestSelfCostAction::class,
         ];
     }
 
index 3ab5b4166f99318d4450f64a12fde55111846297..3b7bdad13a385f3859ed3caf7d2f808fd80f7f01 100644 (file)
@@ -1908,6 +1908,106 @@ class MotivationService
         return $totalSum;
     }
 
+
+    /**
+     * Получение информации о продуктах и их себестоимости по магазину за определенный промежуток дат.
+     *
+     * @param string $startDate Дата начала периода (формат Y-m-d).
+     * @param string $endDate Дата конца периода (формат Y-m-d).
+     * @param int $storeId ID магазина.
+     * @return array Массив с данными о товарах, их себестоимости и дате.
+     */
+    public static function getSalesProductsDetails($startDate, $endDate, $storeId)
+    {
+        $storeId = (int)$storeId;
+        $startDate = date('Y-m-d', strtotime($startDate));
+        $endDate = date('Y-m-d 23:59:59', strtotime($endDate));
+
+        // Находим все продажи за указанный период
+        $salesRecords = Sales::find()
+            ->select(['id', 'date'])
+            ->where(['store_id' => $storeId, 'operation' => Sales::OPERATION_SALE])
+            ->andWhere(['>=', 'date', $startDate])
+            ->andWhere(['<=', 'date', $endDate])
+            ->asArray()
+            ->all();
+
+        $endDatePlusThreeWeeks = date('Y-m-d 23:59:59', strtotime($endDate . ' +3 weeks'));
+
+        // Находим возвраты за указанный период + 3 недели
+        $returnedSales = Sales::find()
+            ->select(['sales_check'])
+            ->where(['store_id' => $storeId, 'operation' => Sales::OPERATION_RETURN])
+            ->andWhere(['>=', 'date', $startDate])
+            ->andWhere(['<=', 'date', $endDatePlusThreeWeeks])
+            ->andWhere(['is not', 'sales_check', null])
+            ->asArray()
+            ->all();
+
+        $returnedSalesIds = array_column($returnedSales, 'sales_check');
+
+        // Фильтруем продажи, исключая возвраты
+        $salesRecords = array_filter($salesRecords, function($sale) use ($returnedSalesIds) {
+            return !in_array($sale['id'], $returnedSalesIds);
+        });
+
+        if (empty($salesRecords)) {
+            return [];
+        }
+
+        $salesIds = array_column($salesRecords, 'id');
+        $saleDates = array_column($salesRecords, 'date', 'id');
+
+        // Находим товары, проданные в выбранных продажах
+        $salesProducts = SalesProducts::find()
+            ->select(['check_id', 'product_id', 'quantity'])
+            ->where(['check_id' => $salesIds])
+            ->asArray()
+            ->all();
+
+        $productIds = array_unique(array_column($salesProducts, 'product_id'));
+        $selfCosts = SelfCostProduct::find()
+            ->select(['product_guid', 'price', 'date'])
+            ->where(['store_id' => $storeId, 'product_guid' => $productIds])
+            ->andWhere(['date' => array_map(fn($date) => date('Y-m-d', strtotime($date)), $saleDates)])
+            ->asArray()
+            ->all();
+
+        $selfCostsMap = [];
+        foreach ($selfCosts as $cost) {
+            $selfCostsMap[$cost['product_guid']][$cost['date']] = $cost['price'];
+        }
+
+        // Находим имена продуктов
+        $products = Products1c::find()
+            ->select(['id', 'name'])
+            ->where(['id' => $productIds])
+            ->asArray()
+            ->all();
+
+        $productNamesMap = ArrayHelper::map($products, 'id', 'name');
+
+        $result = [];
+
+        foreach ($salesProducts as $product) {
+            $productId = $product['product_id'];
+            $quantity = (float)$product['quantity'];
+            $checkDate = date('Y-m-d', strtotime($saleDates[$product['check_id']]));
+
+            $price = $selfCostsMap[$productId][$checkDate] ?? 0.0;
+
+            $result[] = [
+                'product_id' => $productId,
+                'product_name' => $productNamesMap[$productId] ?? 'Неизвестный товар',
+                'price' => $price,
+                'date' => $checkDate,
+            ];
+        }
+
+        return $result;
+    }
+
+
     public static function getCostConsumablesSalesSupportByStore($startDate, $endDate, $storeId) {
         $exportImportTable = ExportImportTable::find()->select(['export_val'])->where(['entity' => 'city_store', 'entity_id' => $storeId, 'export_id' => 1])->one();
 
diff --git a/erp24/views/motivation/test-self-cost.php b/erp24/views/motivation/test-self-cost.php
new file mode 100644 (file)
index 0000000..7c964e9
--- /dev/null
@@ -0,0 +1,64 @@
+<?php
+use yii\helpers\Html;
+use yii\widgets\ActiveForm;
+use kartik\select2\Select2;
+
+/* @var $this yii\web\View */
+/* @var $storeList array */
+/* @var $model \yii\base\DynamicModel */
+/* @var $data array */
+/* @var $totalSum float */
+
+$this->title = 'Себестоимость товаров по магазинам';
+?>
+
+<div class="motivation-index">
+    <h1><?= Html::encode($this->title) ?></h1>
+
+    <div class="search-form col-4">
+        <?php $form = ActiveForm::begin(['action' => ['motivation/test-selfcost'], 'method' => 'get']); ?>
+
+        <?= $form->field($model, 'startDate')->input('date') ?>
+
+        <?= $form->field($model, 'endDate')->input('date') ?>
+
+        <?= $form->field($model, 'storeId')->widget(Select2::classname(), [
+            'data' => $storeList,
+            'options' => ['placeholder' => 'Выберите магазин'],
+            'pluginOptions' => [
+                'allowClear' => true,
+            ],
+        ]); ?>
+
+        <div class="form-group">
+            <?= Html::submitButton('Показать', ['class' => 'btn btn-primary']) ?>
+        </div>
+
+        <?php ActiveForm::end(); ?>
+    </div>
+
+    <?php if (!empty($data)): ?>
+        <h2>Результаты</h2>
+        <table class="table table-bordered">
+            <thead>
+            <tr>
+                <th>ID товара</th>
+                <th>Название</th>
+                <th>Цена</th>
+                <th>Дата</th>
+            </tr>
+            </thead>
+            <tbody>
+            <?php foreach ($data as $item): ?>
+                <tr>
+                    <td><?= Html::encode($item['product_id']) ?></td>
+                    <td><?= Html::encode($item['product_name']) ?></td>
+                    <td><?= Html::encode($item['price']) ?></td>
+                    <td><?= Html::encode($item['date']) ?></td>
+                </tr>
+            <?php endforeach; ?>
+            </tbody>
+        </table>
+        <h3>Общая стоимость: <?= Html::encode($totalSum) ?></h3>
+    <?php endif; ?>
+</div>
\ No newline at end of file