]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
[ERP-140] Добавлен частично факт мотивации
authorAlexander Smirnov <fredeom@mail.ru>
Tue, 13 Aug 2024 13:16:38 +0000 (16:16 +0300)
committerAlexander Smirnov <fredeom@mail.ru>
Tue, 13 Aug 2024 13:16:38 +0000 (16:16 +0300)
erp24/scripts/tasks/task_32_motivation_fact.php [new file with mode: 0644]
erp24/services/MotivationService.php

diff --git a/erp24/scripts/tasks/task_32_motivation_fact.php b/erp24/scripts/tasks/task_32_motivation_fact.php
new file mode 100644 (file)
index 0000000..7c99a10
--- /dev/null
@@ -0,0 +1,104 @@
+<?php
+
+/* @var $time integer */
+
+use yii_app\records\CityStore;
+use yii\helpers\ArrayHelper;
+use yii_app\records\SchedulerTaskLog;
+use yii_app\services\MotivationService;
+
+ini_set('max_execution_time', (string)(60 * 60 * 1)); // 1 час
+ini_set('display_errors', 'on');
+ini_set('display_errors', 1);
+ini_set('display_startup_errors', 1);
+error_reporting(E_ALL);
+
+echo "time_" . $time . "_time ";
+$taskNum = 32;
+$dateTask = date('Y-m-d H:i:s');
+$dateTaskStart = null;
+$dateTaskStop = null;
+$log = '';
+$error = '';
+$infoError = '';
+$infoText = '';
+$description = '';
+$result = 0;
+
+$enable = true;
+$start = false;
+$force = false;
+
+$minuetTimeInTask = date('i', $time);
+$fullTimeInTask = date('Y-m-d H:i:s', $time);
+
+try {
+    if (
+        (
+            (date('dHi', $time) == '010300')
+            || $force
+        )
+        && $enable
+    ) {
+        $dateTaskStart = date('Y-m-d H:i:s');
+        $info = ' ================ test Task 0' . $taskNum . ' start ================';
+        echo $info;
+        $log .= $info;
+        $log .= $time;
+        // все флористы и администраторы
+
+        $infoText .= ' test ';
+
+        //////////////////////////////////////////////
+        $year = date('Y', strtotime("-1 month", time()));
+        $month = date('m', strtotime("-1 month", time()));
+
+        MotivationService::calculateMonthSales($year, $month);
+
+        MotivationService::calculateMonthServices($year, $month);
+
+        MotivationService::calculateMonthDefect($year, $month);
+
+
+        //////////////////////////////////////////////
+
+
+        $info = ' ================ test Task 0' . $taskNum . ' stop ================';
+        echo $info;
+        $log .= $info;
+        $dateTaskStop = date('Y-m-d H:i:s');
+    } else {
+        $info = '   Task 0' . $taskNum . ' skip   ';
+        echo $info;
+        $log .= $info;
+    }
+} catch (Exception $e) {
+    $error = 'Exception: ' . $e->getMessage() . ' >>> ' . $e->getLine();
+}
+
+
+
+if (empty($schedulerTaskLog)) {
+    $schedulerTaskLog = new SchedulerTaskLog();
+    $schedulerTaskLog->setTaskNum($taskNum)
+        ->setName('Task 0' . $taskNum)
+        ->setDate($dateTask)
+        ->setDateStart($dateTaskStart)
+        ->setDateStop($dateTaskStop)
+        ->setDescription($description)
+        ->setError($error)
+        ->setInfo($infoText)
+        ->setLog($log)
+    ;
+} else {
+    $schedulerTaskLog->setDateStop($dateTaskStop)
+        ->setDescription($description)
+        ->setError($error)
+        ->setInfo($infoText)
+        ->setLog($log)
+    ;
+}
+$validate = $schedulerTaskLog->validate();
+if ($validate) {
+    $schedulerTaskLog->save();
+}
index 0ada3d5e52587793fd22291d954eac4179dee154..66a665ca31a3e9497b7a2b149a3fe20e9347881d 100644 (file)
@@ -519,4 +519,251 @@ class MotivationService
             }
         }
     }
+
+    public static function calculateMonthSales($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'));
+
+        $sales = Sales::find()->where(['between', 'date', $monthStart, $monthEnd])
+            ->andWhere(['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');
+
+        $salesOffline = Sales::find()->select(['SUM(summ) as total'])
+            ->where(['between', 'date', $monthStart, $monthEnd])
+            ->andWhere(['operation' => Sales::OPERATION_SALE])
+            ->andWhere(['order_id' => ['', '0']])
+            ->andWhere(['NOT IN', 'check_id', $returnSalesIds])
+            ->groupBy(['store_id'])
+            ->indexBy('store_id')
+            ->asArray()->all();
+
+        $salesOnline = Sales::find()->select(['SUM(summ) as total'])
+            ->where(['between', 'date', $monthStart, $monthEnd])
+            ->andWhere(['operation' => Sales::OPERATION_SALE])
+            ->andWhere(['NOT IN', 'order_id', ['', '0']])
+            ->andWhere(['NOT IN', 'check_id', $returnSalesIds])
+            ->groupBy(['store_id'])
+            ->indexBy('store_id')
+            ->asArray()->all();
+
+        $motivations = Motivation::find()->where(['year' => $year, 'month' => $month])->indexBy('store_id')->all();
+
+        $motivationValueGroupFact = MotivationValueGroup::find()->where(['alias' => 'fact'])->one();
+        $motivationCostsItemOffline = MotivationCostsItem::find()->where(['name' => 'Оффлайн продажи'])->one();
+        $motivationCostsItemOnline = MotivationCostsItem::find()->where(['name' => 'Онлайн продажи'])->one();
+        /** @var $motivationCostsItemOffline MotivationCostsItem */
+        /** @var $motivationCostsItemOnline MotivationCostsItem */
+
+
+        $storeIds = ArrayHelper::getColumn(CityStore::find()->where(['visible' => '1'])->all(), 'id');
+        foreach ($storeIds as $store_id) {
+            if (isset($motivations[$store_id])) {
+                if (isset($salesOffline[$store_id])) {
+                    $motivationValueOffline = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
+                        'motivation_group_id' => $motivationValueGroupFact->id, 'value_id' => $motivationCostsItemOffline->code])->one();
+                    if (!$motivationValueOffline) {
+                        $motivationValueOffline = new MotivationValue;
+                        $motivationValueOffline->motivation_id = $motivations[$store_id]->id;
+                        $motivationValueOffline->motivation_group_id = $motivationValueGroupFact->id;
+                        $motivationValueOffline->value_id = $motivationCostsItemOffline->code;
+                        $motivationValueOffline->value_type = $motivationCostsItemOffline->data_type;
+                    }
+                    $motivationValueOffline->value_float = $salesOffline[$store_id]['total'];
+                    $motivationValueOffline->save();
+                    if ($motivationValueOffline->getErrors()) {
+                        throw new \Exception(Json::encode($motivationValueOffline->getErrors()));
+                    }
+                }
+                if (isset($salesOnline[$store_id])) {
+                    $motivationValueOnline = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
+                        'motivation_group_id' => $motivationValueGroupFact->id, 'value_id' => $motivationCostsItemOnline->code])->one();
+                    if (!$motivationValueOnline) {
+                        $motivationValueOnline = new MotivationValue;
+                        $motivationValueOnline->motivation_id = $motivations[$store_id]->id;
+                        $motivationValueOnline->motivation_group_id = $motivationValueGroupFact->id;
+                        $motivationValueOnline->value_id = $motivationCostsItemOnline->code;
+                        $motivationValueOnline->value_type = $motivationCostsItemOnline->data_type;
+                    }
+                    $motivationValueOnline->value_float = $salesOnline[$store_id]['total'];
+                    $motivationValueOnline->save();
+                    if ($motivationValueOnline->getErrors()) {
+                        throw new \Exception(Json::encode($motivationValueOnline->getErrors()));
+                    }
+                }
+            }
+        }
+    }
+
+    public static function calculateMonthServices($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'));
+
+        // Ищем каталог-гуиды категории 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();
+
+        // Ищем каталог-гуиды категории services_delivery
+        $productsClassDelivery = ProductsClass::find()->select(['category_id', 'tip'])
+            ->where(['tip' => 'services_delivery'])
+            ->indexBy('category_id')
+            ->asArray()->all();
+
+        // Ищем продуктовые гуиды по каталог-гуидам категории service_delivery
+        $products1cDelivery = Products1c::find()->select(['id', 'parent_id', 'name'])
+            ->where(['parent_id' => array_keys($productsClassDelivery), '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', $monthStart, $monthEnd])
+            ->andWhere(['p.product_id' => array_keys($products1c)])
+            ->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()->alias('p')
+            ->select(['SUM(summ) as total'])
+            ->leftJoin('sales s', 's.id = p.check_id')
+            ->where(['check_id' => $salesIds])
+            ->andWhere(['NOT IN', 'check_id', $returnSalesIds])
+            ->andWhere(['product_id' => array_keys($products1c)])
+            ->groupBy(['s.store_id'])
+            ->indexBy('s.store_id')
+            ->asArray()->one();
+
+        // Ищем продажи по продуктовым гуидам по каталог-гуидам категории services_delivery
+        $salesDelivery = Sales::find()->alias('s')
+            ->leftJoin('sales_products p', 'p.check_id = s.id')
+            ->where(['between', 's.date', $monthStart, $monthEnd])
+            ->andWhere(['p.product_id' => array_keys($products1cDelivery)])
+            ->andWhere(['s.operation' => Sales::OPERATION_SALE])
+            ->asArray()->all();
+        $salesIdsDelivery = ArrayHelper::getColumn($salesDelivery, 'id');
+
+        // Ищем чеки-возврат на текущие чеки
+        $returnSalesDelivery = Sales::find()->where(['operation' => Sales::OPERATION_RETURN, 'sales_check' => $salesIdsDelivery])->all();
+        $returnSalesIdsDelivery = ArrayHelper::getColumn($returnSalesDelivery, 'sales_check');
+
+        // Ищем продукты из категории services_delivery
+        $salesProductDelivery = SalesProducts::find()->alias('p')
+            ->select(['SUM(summ) as total'])
+            ->leftJoin('sales s', 's.id = p.check_id')
+            ->where(['check_id' => $salesIdsDelivery])
+            ->andWhere(['NOT IN', 'check_id', $returnSalesIdsDelivery])
+            ->andWhere(['product_id' => array_keys($products1cDelivery)])
+            ->groupBy(['s.store_id'])
+            ->indexBy('s.store_id')
+            ->asArray()->one();
+
+        $motivations = Motivation::find()->where(['year' => $year, 'month' => $month])->indexBy('store_id')->all();
+
+        $motivationValueGroupFact = MotivationValueGroup::find()->where(['alias' => 'fact'])->one();
+        $motivationCostsItemServices = MotivationCostsItem::find()->where(['name' => 'Услуги по сборке'])->one();
+        $motivationCostsItemServicesDelivery = MotivationCostsItem::find()->where(['name' => 'Услуги по доставке'])->one();
+        /** @var $motivationCostsItemServices MotivationCostsItem */
+        /** @var $motivationCostsItemServicesDelivery MotivationCostsItem */
+
+        $storeIds = ArrayHelper::getColumn(CityStore::find()->where(['visible' => '1'])->all(), 'id');
+        foreach ($storeIds as $store_id) {
+            if (isset($motivations[$store_id])) {
+                if (isset($salesProduct[$store_id])) {
+                    $motivationValueService = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
+                        'motivation_group_id' => $motivationValueGroupFact->id, 'value_id' => $motivationCostsItemServices->code])->one();
+                    if (!$motivationValueService) {
+                        $motivationValueService = new MotivationValue;
+                        $motivationValueService->motivation_id = $motivations[$store_id]->id;
+                        $motivationValueService->motivation_group_id = $motivationValueGroupFact->id;
+                        $motivationValueService->value_id = $motivationCostsItemServices->code;
+                        $motivationValueService->value_type = $motivationCostsItemServices->data_type;
+                    }
+                    $motivationValueService->value_float = $salesProduct[$store_id]['total'];
+                    $motivationValueService->save();
+                    if ($motivationValueService->getErrors()) {
+                        throw new \Exception(Json::encode($motivationValueService->getErrors()));
+                    }
+                }
+                if (isset($salesProductDelivery[$store_id])) {
+                    $motivationValueServiceDelivery = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
+                        'motivation_group_id' => $motivationValueGroupFact->id, 'value_id' => $motivationCostsItemServicesDelivery->code])->one();
+                    if (!$motivationValueServiceDelivery) {
+                        $motivationValueServiceDelivery = new MotivationValue;
+                        $motivationValueServiceDelivery->motivation_id = $motivations[$store_id]->id;
+                        $motivationValueServiceDelivery->motivation_group_id = $motivationValueGroupFact->id;
+                        $motivationValueServiceDelivery->value_id = $motivationCostsItemServicesDelivery->code;
+                        $motivationValueServiceDelivery->value_type = $motivationCostsItemServicesDelivery->data_type;
+                    }
+                    $motivationValueServiceDelivery->value_float = $salesProductDelivery[$store_id]['total'];
+                    $motivationValueServiceDelivery->save();
+                    if ($motivationValueServiceDelivery->getErrors()) {
+                        throw new \Exception(Json::encode($motivationValueServiceDelivery->getErrors()));
+                    }
+                }
+            }
+        }
+    }
+
+    public static function calculateMonthDefect($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'));
+
+        $motivations = Motivation::find()->where(['year' => $year, 'month' => $month])->indexBy('store_id')->all();
+        $motivationValueGroup = MotivationValueGroup::find()->where(['alias' => 'fact'])->one();
+        $exportImportTables = ExportImportTable::find()->select(['export_val'])->where(['entity' => 'city_store',
+            'entity_id' => array_keys($motivations), 'export_id' => 1])->indexBy('entity_id')->all();
+        /** @var $exportImportTables ExportImportTable[] */
+
+        foreach ($exportImportTables as $store_id => $store_guid) {
+            $writeOffs = WriteOffs::find()->select(['sum(summ) as total', 'type'])
+                ->where(['between', 'date', $monthStart, $monthEnd])
+                ->andWhere(['store_id' => $store_guid])
+                ->groupBy(['type'])
+                ->indexBy('type')
+                ->asArray()->all();
+
+            foreach ($writeOffs as $key => $data) {
+                $motivationItemType = MotivationCostsItem::writeOffsToMotivationItemMap($key);
+                if (empty($motivationItemType)) {
+                    continue;
+                }
+                $motivationCostsItem = MotivationCostsItem::find()->where(['name' => $motivationItemType])->one();
+                /** @var $motivationCostsItem MotivationCostsItem */
+                if (isset($motivations[$store_id])) {
+                    $motivationValue = MotivationValue::find()->where(['motivation_id' => $motivations[$store_id]->id,
+                        'motivation_group_id' => $motivationValueGroup->id, 'value_id' => $motivationCostsItem->code])->one();
+                    if (!$motivationValue) {
+                        $motivationValue = new MotivationValue;
+                        $motivationValue->motivation_id = $motivations[$store_id]->id;
+                        $motivationValue->motivation_group_id = $motivationValueGroup->id;
+                        $motivationValue->value_id = $motivationCostsItem->code;
+                        $motivationValue->value_type = $motivationCostsItem->data_type;
+                    }
+                    $motivationValue->value_float = $data['total'];
+                    $motivationValue->save();
+                    if ($motivationValue->getErrors()) {
+                        throw new \Exception(Json::encode($motivationValue->getErrors()));
+                    }
+                }
+            }
+        }
+    }
 }