]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[ERP-100] Добавлена фокус группа services_delivery, сделан подсчёт Услуг по сборке...
authorAlexander Smirnov <fredeom@mail.ru>
Fri, 2 Aug 2024 12:31:50 +0000 (15:31 +0300)
committerAlexander Smirnov <fredeom@mail.ru>
Fri, 2 Aug 2024 12:31:50 +0000 (15:31 +0300)
erp24/actions/motivation/IndexAction.php
erp24/modul/products/ajax_group_config.php
erp24/modul/products/products_1c.php
erp24/services/MotivationService.php
erp24/views/motivation/index.php

index b60157ac6578765cb2edf84f37d88e805b580b6e..aebdbb3af99ae2fd118a611ef48a304c1cdd753f 100644 (file)
@@ -44,7 +44,7 @@ class IndexAction extends Action
         $model = DynamicModel::validateData([
             'store_id' => $currentUser->store_id, // Устанавливаем store_id текущего пользователя
             'year' => $currentDate->format('Y'), // Текущий год
-            'month' => $currentDate->format('n') - 1 // Текущий месяц (0-11)
+            'month' => $currentDate->format('n') // Текущий месяц (1-12)
         ], [
             [['store_id', 'year', 'month'], 'safe']
         ]);
@@ -63,12 +63,12 @@ class IndexAction extends Action
         $years = array_filter(range(2023, 20100), function ($k) use ($possibleYears) {
             return in_array($k, $possibleYears);
         });
+        $years = array_combine($years, $years);
         $possibleMonth = ArrayHelper::getColumn($motivations, 'month');
-        $months = array_filter(['Январь', ' Февраль', 'Март', 'Апрель', 'Май', 'Июнь', 'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь'], function ($k, $v) use ($possibleMonth) {
-            return in_array($v + 1, $possibleMonth);
+        $months = array_filter([1 => 'Январь', 2 => 'Февраль', 3 => 'Март', 4 => 'Апрель', 5 => 'Май', 6 => 'Июнь', 7 => 'Июль', 8 => 'Август', 9 => 'Сентябрь', 10 => 'Октябрь', 11 => 'Ноябрь', 12 => 'Декабрь'], function ($k, $v) use ($possibleMonth) {
+            return in_array($v, $possibleMonth);
         }, ARRAY_FILTER_USE_BOTH);
 
-
         // Загружаем данные из GET-запроса, если они есть
         if (Yii::$app->request->get()) {
             $model->load(Yii::$app->request->get());
@@ -86,6 +86,9 @@ class IndexAction extends Action
             $model->month = intval($model->month);
         }
 
+        // Подсчитываем стоимость услуг по сборке и по доставке. Позже метод будет перенесён в шедулер
+        MotivationService::calculateServiceAssemblyAndDeliveryCost($model->store_id, $model->year, $model->month);
+
         $showTable = false;
         $motivationData = [];
         $daysInMonth = null;
@@ -100,10 +103,10 @@ class IndexAction extends Action
 
 
             // получаем данные из таблицы
-            $motivationDataTableSort = $motivationService->getMotivationDataTableSort($model->store_id, $model->year, $model->month + 1);
+            $motivationDataTableSort = $motivationService->getMotivationDataTableSort($model->store_id, $model->year, $model->month);
 
             // Получаем количество дней в месяце
-            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $model->month + 1, $model->year);
+            $daysInMonth = cal_days_in_month(CAL_GREGORIAN, $model->month, $model->year);
 
             // Определяем, сколько дней в последней неделе
             $daysInLastWeek = $daysInMonth - 28;
@@ -153,7 +156,7 @@ class IndexAction extends Action
 
 
             // Формируем заголовок для 5-й недели
-            if ($model->month == 1) { // Февраль
+            if ($model->month == 2) { // Февраль
                 if ($daysInMonth == 29) {
                     $week5Header = 'Неделя 5<br>(29)';
                 }
@@ -162,15 +165,12 @@ class IndexAction extends Action
             }
         }
 
-        // Подготавливаем данные для Select2 виджета
-        $yearsForSelect = array_combine($years, $years);
-
-
 
 
         return $this->controller->render(
             'index',
-            compact('model', 'stores', 'yearsForSelect', 'months', 'motivationDataTableSort', 'showTable', 'daysInMonth', 'daysInLastWeek', 'week5Header')
+            compact('model', 'stores', 'years', 'months', 'motivationDataTableSort', 'showTable',
+                'daysInMonth', 'daysInLastWeek', 'week5Header')
         );
     }
 
index 05a246e85d325062536670d0941707c3de640006..dd62da5ef961f4590ed3cfc7b50a181070182860 100644 (file)
@@ -11,7 +11,7 @@ $data = $db::getRows($q,[$id]);
  foreach ($data as $row)  $data2[$row["tip"]] = $id;   
 
 
-$array=["wrap"=>"Упаковка","potted"=>"Горшечка", "services"=>"Услуги", "salut"=>"Пиротехника", "matrix"=>"Матрица", "related"=>"Сопутка", "other_items"=>"Номенклатура 1%"];
+$array=["wrap"=>"Упаковка","potted"=>"Горшечка", "services"=>"Услуги", "services_delivery"=>"Услуги по доставке", "salut"=>"Пиротехника", "matrix"=>"Матрица", "related"=>"Сопутка", "other_items"=>"Номенклатура 1%"];
 echo'<table class=""><tbody>';
 
   foreach($array as $k => $arr) {
index c505ec1616b4fe75b46db2a3a36fa214ca38114d..a205bcafbc22518c43e85b84978c98f2bc58c5bd 100644 (file)
@@ -21,7 +21,7 @@ foreach ($data as $row) $prices[$row['product_id']]= $row['price'];
 
 function build_tree($cats,$parent_id,$only_parent = false){
     global $ahref,$group_tpl, $products_class_row;
-  $products_class=["wrap"=>"Упаковка","potted"=>"Горшечка", "services"=>"Услуги", "salut"=>"Пиротехника", "matrix"=>"Матрица", "related"=>"Сопутка", "other_items"=>"Номенклатура 1%"];
+  $products_class=["wrap"=>"Упаковка","potted"=>"Горшечка", "services"=>"Услуги", "services_delivery"=>"Услуги по доставке", "salut"=>"Пиротехника", "matrix"=>"Матрица", "related"=>"Сопутка", "other_items"=>"Номенклатура 1%"];
    
     
  //   if(is_array($cats) and isset($cats[$parent_id])){
index 06e071aa8c8fedcbb9658b000d963de733d1dc08..58270cde65df1639ec8bfb2a56c841b67e7f0de7 100644 (file)
@@ -3,11 +3,16 @@
 namespace yii_app\services;
 
 use PhpOffice\PhpSpreadsheet\IOFactory;
+use yii\helpers\ArrayHelper;
 use yii_app\records\Motivation;
 use yii_app\records\MotivationValue;
 use yii_app\records\MotivationValueGroup;
 use yii_app\records\CityStore;
 use yii_app\records\MotivationCostsItem;
+use yii_app\records\Products1c;
+use yii_app\records\ProductsClass;
+use yii_app\records\Sales;
+use yii_app\records\SalesProducts;
 
 
 class MotivationService
@@ -326,4 +331,128 @@ class MotivationService
 
         return compact('errors');
     }
+
+    public static function calculateServiceAssemblyAndDeliveryCost($store_id, $year, $month) {
+        $monthStart = date("Y-m-d 00:00:00", strtotime($year . '-' . $month . '-1'));
+        $monthEnd = date("Y-m-t 23:59:59", strtotime($year . '-' . $month . '-1'));
+
+        foreach (range(1, 5) as $ind) {
+            $weekStart = date("Y-m-d 00:00:00", strtotime("+" . (($ind - 1) * 7) . ' days', strtotime($monthStart)));
+            $weekEnd = date("Y-m-d 23:50:50", strtotime("+" . ($ind * 7 - 1) . ' days', strtotime($monthStart)));
+            if ($weekEnd > $monthEnd) {
+                $weekEnd = $monthEnd;
+            }
+
+            // Ищем каталог-гуиды категории services
+            $productsClass = ProductsClass::find()->select(['category_id', 'tip'])
+                ->where(['tip' => 'services'])
+                ->indexBy('category_id')
+                ->asArray()->all();
+
+            // Ищем продуктовые гуиды по каталог-гуидам категории service
+            $products1c = Products1c::find()->select(['id', 'parent_id', 'name'])
+                ->where(['parent_id' => array_keys($productsClass), 'tip' => 'products'])
+                ->indexBy(['id'])
+                ->asArray()->all();
+
+            // Ищем продажи по продуктовым гуидам по каталог-гуидам категории service
+            $sales = Sales::find()->alias('s')
+                ->leftJoin('sales_products p', 'p.check_id = s.id')
+                ->where(['between', 's.date', $weekStart, $weekEnd])
+                ->andWhere(['p.product_id' => array_keys($products1c)])
+                ->andWhere(['s.store_id' => $store_id])
+                ->andWhere(['s.operation' => Sales::OPERATION_SALE])
+                ->asArray()->all();
+            $salesIds = ArrayHelper::getColumn($sales, 'id');
+
+            // Ищем чеки-возврат на текущие чеки
+            $returnSales = Sales::find()->where(['operation' => Sales::OPERATION_RETURN, 'sales_check' => $salesIds])->all();
+            $returnSalesIds = ArrayHelper::getColumn($returnSales, 'sales_check');
+
+            // Ищем продукты из категории services
+            $salesProduct = SalesProducts::find()
+                ->select(['SUM(summ) as total'])
+                ->where(['check_id' => $salesIds])
+                ->andWhere(['NOT IN', 'check_id', $returnSalesIds])
+                ->andWhere(['product_id' => array_keys($products1c)])
+                ->asArray()->one();
+
+            $motivationValueGroup = MotivationValueGroup::find()->where(['alias' => 'week' . $ind])->one();
+            $motivationCostsItem = MotivationCostsItem::find()->where(['name' => 'Услуги по сборке'])->one();
+            /** @var $motivationCostsItem MotivationCostsItem */
+            $motivation = Motivation::find()->where(['store_id' => $store_id, 'year' => $year, 'month' => $month])->one();
+            if ($motivation) {
+                $motivationValue = MotivationValue::find()->where(['motivation_id' => $motivation->id,
+                    'motivation_group_id' => $motivationValueGroup->id, 'value_id' => $motivationCostsItem->id])->one();
+                if (!$motivationValue) {
+                    $motivationValue = new MotivationValue;
+                    $motivationValue->motivation_id = $motivation->id;
+                    $motivationValue->motivation_group_id = $motivationValueGroup->id;
+                    $motivationValue->value_id = $motivationCostsItem->id;
+                    $motivationValue->value_type = $motivationCostsItem->data_type;
+                }
+                $motivationValue->value_float = $salesProduct['total'];
+                $motivationValue->save();
+                //var_dump($motivationValue); die;
+                if ($motivationValue->getErrors()) {
+                    var_dump($motivationValue->getErrors());
+                    die;
+                }
+            }
+
+            // Ищем каталог-гуиды категории services_delivery
+            $productsClass = ProductsClass::find()->select(['category_id', 'tip'])
+                ->where(['tip' => 'services_delivery'])
+                ->indexBy('category_id')
+                ->asArray()->all();
+
+            // Ищем продуктовые гуиды по каталог-гуидам категории service_delivery
+            $products1c = Products1c::find()->select(['id', 'parent_id', 'name'])
+                ->where(['parent_id' => array_keys($productsClass), 'tip' => 'products'])
+                ->indexBy(['id'])
+                ->asArray()->all();
+
+            // Ищем продажи по продуктовым гуидам по каталог-гуидам категории service_delivery
+            $sales = Sales::find()->alias('s')
+                ->leftJoin('sales_products p', 'p.check_id = s.id')
+                ->where(['between', 's.date', $weekStart, $weekEnd])
+                ->andWhere(['p.product_id' => array_keys($products1c)])
+                ->andWhere(['s.store_id' => $store_id])
+                ->andWhere(['s.operation' => Sales::OPERATION_SALE])
+                ->asArray()->all();
+            $salesIds = ArrayHelper::getColumn($sales, 'id');
+
+            // Ищем чеки-возврат на текущие чеки
+            $returnSales = Sales::find()->where(['operation' => Sales::OPERATION_RETURN, 'sales_check' => $salesIds])->all();
+            $returnSalesIds = ArrayHelper::getColumn($returnSales, 'sales_check');
+
+            // Ищем продукты из категории services_delivery
+            $salesProduct = SalesProducts::find()
+                ->select(['SUM(summ) as total'])
+                ->where(['check_id' => $salesIds])
+                ->andWhere(['NOT IN', 'check_id', $returnSalesIds])
+                ->andWhere(['product_id' => array_keys($products1c)])
+                ->asArray()->one();
+
+            $motivationCostsItem = MotivationCostsItem::find()->where(['name' => 'Услуги по доставке'])->one();
+            /** @var $motivationCostsItem MotivationCostsItem */
+            if ($motivation) {
+                $motivationValue = MotivationValue::find()->where(['motivation_id' => $motivation->id,
+                    'motivation_group_id' => $motivationValueGroup->id, 'value_id' => $motivationCostsItem->id])->one();
+                if (!$motivationValue) {
+                    $motivationValue = new MotivationValue;
+                    $motivationValue->motivation_id = $motivation->id;
+                    $motivationValue->motivation_group_id = $motivationValueGroup->id;
+                    $motivationValue->value_id = $motivationCostsItem->id;
+                    $motivationValue->value_type = $motivationCostsItem->data_type;
+                }
+                $motivationValue->value_float = $salesProduct['total'];
+                $motivationValue->save();
+                if ($motivationValue->getErrors()) {
+                    var_dump($motivationValue->getErrors());
+                    die;
+                }
+            }
+        }
+    }
 }
index a6bdb8b4566598a242170a5c86b14ed47d89f050..38386efcadefcf479a0a223c760884edfa182d43 100644 (file)
@@ -10,7 +10,11 @@ use yii_app\records\MotivationCostsItem;
 /** @var $stores array */
 /** @var $years array */
 /** @var $months array */
-/** @var $daysInMonth integer */
+/** @var $motivationDataTableSort array */
+/** @var $showTable bool */
+/** @var $daysInMonth int */
+/** @var $daysInLastWeek int */
+/** @var $week5Header string */
 
 
 $this->registerJsFile('/js/motivation/index.js', ['position' => \yii\web\View::POS_END]);
@@ -19,7 +23,7 @@ $this->registerJsFile('/js/motivation/index.js', ['position' => \yii\web\View::P
 
 <div class="motivationIndex m-5">
 
-    <?php $form = ActiveForm::begin(['method' => 'GET']) ?>
+    <?php $form = ActiveForm::begin(['method' => 'GET', 'action' => '/motivation/index']) ?>
 
     <div class="row">
         <div class="col-4 d-flex justify-content-between align-items-center gap-4">
@@ -40,7 +44,7 @@ $this->registerJsFile('/js/motivation/index.js', ['position' => \yii\web\View::P
                 <div class="mb-3">Год:</div>
                 <div style="display: inline-block">
                     <?= $form->field($model, 'year')->widget(Select2::class, [
-                        'data' => $yearsForSelect,
+                        'data' => $years,
                         'language' => 'ru',
                         'options' => ['placeholder' => 'Год...'],
                         'pluginOptions' => [