]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
ДобÐавлен расчµт Added mounth sum
authorJoySystem_v <fvv2011@gmail.com>
Wed, 7 Aug 2024 09:54:17 +0000 (12:54 +0300)
committerJoySystem_v <fvv2011@gmail.com>
Wed, 7 Aug 2024 09:54:17 +0000 (12:54 +0300)
erp24/actions/motivation/GetSalaryAction.php
erp24/actions/motivation/SumSalaryAction.php
erp24/services/MotivationService.php

index fcfb743a7fde74d064cf527273fc6dce59827c3a..e03c43b77cdc196eb5ec7d21200534b55b81620a 100644 (file)
@@ -28,7 +28,7 @@ public function run()
     ]);
 
     if (!$model->hasErrors()) {
-        $records = MotivationService::getRecordsByDateAndStore($date, $store_id);
+        $records = MotivationService::getTimetableFactRecordsByDateAndStore($date, $store_id);
         $vacationSum = MotivationService::getVacationsSum($date, $store_id);
     }
 // Определяем начало недели и номер недели в месяце
index f6946f15e80c4a59771dfc1620496eadb2d9b603..aec5b695d14cb75ede3440d0eb6b4facdfedb270 100644 (file)
@@ -21,20 +21,31 @@ class SumSalaryAction extends \yii\base\Action
         $currentYear = $currentDate->format('Y');
         $currentMonth = $currentDate->format('m');
 
+        // Определяем номер недели в месяце и начало недели
+        $weekOfMonth = MotivationService::getWeekOfMonth($currentDate);
+        $startOfWeek = MotivationService::getStartOfWeek($currentDate, $weekOfMonth);
+        $startDate = $startOfWeek->format('Y-m-d');
+        $endDate = $currentDate->format('Y-m-d');
+
         // Найти все записи по текущему месяцу и году
         $motivations = Motivation::find()
             ->where(['year' => $currentYear, 'month' => $currentMonth])
             ->all();
 
+        if (empty($motivations)) {
+            Yii::warning("No motivation records found for the current month and year.");
+            return $this->controller->redirect(['motivation/index']);
+        }
+
         $results = [];
         foreach ($motivations as $motivation) {
             $store_id = $motivation->store_id;
-            $date = $currentDate->format('Y-m-d');
-            $records = MotivationService::getRecordsByDateAndStore($date, $store_id);
-            $vacationSum = MotivationService::getVacationsSum($date, $store_id);
+
+            $records = MotivationService::getRecordsByDateAndStore($startDate, $endDate, $store_id);
+            $vacationSum = MotivationService::getVacationsSum($startDate, $endDate, $store_id);
+
             $totalSalary = 0;
             foreach ($records as $record) {
-
                 $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
                 $dailyPayment = $payment ? $payment->daily_payment : null;
 
@@ -49,12 +60,7 @@ class SumSalaryAction extends \yii\base\Action
             $results[$store_id] = $totalSalary + $vacationSum;
         }
 
-        // Определяем начало недели и номер недели в месяце
-
-        $weekNumberInMonth = ceil($currentDate->format('j') / 7);
-
-        
-        // Записываем информацию в таблицу MotivationValue
+        // Записываем информацию в таблицу MotivationValue за текущую неделю
         foreach ($results as $store_id => $totalSalary) {
             $motivation = Motivation::findOne(['store_id' => $store_id, 'year' => $currentYear, 'month' => $currentMonth]);
 
@@ -63,10 +69,10 @@ class SumSalaryAction extends \yii\base\Action
                 continue;
             }
 
-            // Проверка наличия записи в MotivationValue
+            // Проверка наличия записи в MotivationValue за текущую неделю
             $motivationValue = MotivationValue::findOne([
                 'motivation_id' => $motivation->id,
-                'motivation_group_id' => $weekNumberInMonth,
+                'motivation_group_id' => $weekOfMonth,
                 'value_id' => 11
             ]);
 
@@ -74,7 +80,7 @@ class SumSalaryAction extends \yii\base\Action
                 // Если записи нет, создаем новую
                 $motivationValue = new MotivationValue();
                 $motivationValue->motivation_id = $motivation->id;
-                $motivationValue->motivation_group_id = $weekNumberInMonth;
+                $motivationValue->motivation_group_id = $weekOfMonth;
                 $motivationValue->value_id = 11;
                 $motivationValue->value_type = 'float';
             }
@@ -90,6 +96,59 @@ class SumSalaryAction extends \yii\base\Action
             }
         }
 
+        // Определяем даты начала и конца текущего месяца
+        $startOfMonth = new DateTime("$currentYear-$currentMonth-01");
+        $endOfMonth = new DateTime($startOfMonth->format('Y-m-t'));
+
+        // Записываем информацию в таблицу MotivationValue за текущий месяц
+        foreach ($motivations as $motivation) {
+            $store_id = $motivation->store_id;
+
+            $monthlyRecords = MotivationService::getRecordsByDateAndStore($startOfMonth->format('Y-m-d'), $endOfMonth->format('Y-m-d'), $store_id);
+            $monthlyVacationSum = MotivationService::getVacationsSum($startOfMonth->format('Y-m-d'), $endOfMonth->format('Y-m-d'), $store_id);
+
+            $monthlyTotalSalary = 0;
+            foreach ($monthlyRecords as $record) {
+                $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
+                $dailyPayment = $payment ? $payment->daily_payment : null;
+
+                // Если $record->salary_shift имеет значение, учитываем его и не добавляем dailyPayment
+                if (!empty($record->salary_shift)) {
+                    $monthlyTotalSalary += $record->salary_shift;
+                } else {
+                    $monthlyTotalSalary += $dailyPayment;
+                }
+            }
+
+            $monthlyTotalSalary += $monthlyVacationSum;
+
+            // Проверка наличия записи в MotivationValue за текущий месяц
+            $motivationValue = MotivationValue::findOne([
+                'motivation_id' => $motivation->id,
+                'motivation_group_id' => 6, // 6 для обозначения всего месяца
+                'value_id' => 11
+            ]);
+
+            if ($motivationValue === null) {
+                // Если записи нет, создаем новую
+                $motivationValue = new MotivationValue();
+                $motivationValue->motivation_id = $motivation->id;
+                $motivationValue->motivation_group_id = 6;
+                $motivationValue->value_id = 11;
+                $motivationValue->value_type = 'float';
+            }
+
+            // Обновляем значение
+            $motivationValue->value_float = $monthlyTotalSalary;
+            $motivationValue->value_int = null;
+            $motivationValue->value_string = null;
+
+            // Сохраняем запись
+            if (!$motivationValue->save()) {
+                Yii::error("Не удалось записать данные для store_id: $store_id");
+            }
+        }
+
         return $this->controller->redirect(['motivation/index']);
     }
 }
index 1447894dc2f3a143e78f730cdba2dcadd27498cb..671285254f78ed3b721f531554b2b02777a72bb1 100644 (file)
@@ -333,40 +333,31 @@ class MotivationService
     }
 
 
-    public static function getRecordsByDateAndStore($date, $store_id)
+    public static function getTimetableFactRecordsByDateAndStore($startDate, $endDate, $store_id)
     {
-        // Преобразуем дату в объект DateTime
-        $dateTime = new DateTime($date);
-    
-        // Получаем номер недели в месяце и начало недели
-        $weekOfMonth = self::getWeekOfMonth($dateTime);
-        $startOfWeek = self::getStartOfWeek($dateTime, $weekOfMonth);
-    
-        // Определяем конец текущей недели (до текущей даты)
-        $endOfWeek = clone $dateTime;
-    
+        // Преобразуем начальную и конечную дату в объекты DateTime
+        $startDateTime = new DateTime($startDate);
+        $endDateTime = new DateTime($endDate);
+
         // Делаем запрос к TimetableFactModel
         $records = TimetableFactModel::find()
             ->where(['store_id' => $store_id])
-            ->andWhere(['between', 'date_shift', $startOfWeek->format('Y-m-d'), $endOfWeek->format('Y-m-d')])
+            ->andWhere(['between', 'date_shift', $startDateTime->format('Y-m-d'), $endDateTime->format('Y-m-d')])
             ->all();
-    
+
         return $records;
     }
 
-    public static function getVacationsSum($currentDate, $store_id)
+    public static function getVacationsSum($startDate, $endDate, $store_id)
     {
-        // Преобразуем дату в объект DateTime
-        $dateTime = new DateTime($currentDate);
-
-        // Определяем номер недели в месяце и начало недели
-        $weekOfMonth = self::getWeekOfMonth($dateTime);
-        $startOfWeek = self::getStartOfWeek($dateTime, $weekOfMonth);
+        // Преобразуем начальную и конечную дату в объекты DateTime
+        $startDateTime = new DateTime($startDate);
+        $endDateTime = new DateTime($endDate);
 
         // Делаем запрос к таблице Timetable для получения записей с slot_type_id = 2
         $records = Timetable::find()
             ->where(['store_id' => $store_id])
-            ->andWhere(['between', 'date', $startOfWeek->format('Y-m-d'), $dateTime->format('Y-m-d')])
+            ->andWhere(['between', 'date', $startDateTime->format('Y-m-d'), $endDateTime->format('Y-m-d')])
             ->andWhere(['slot_type_id' => 2])
             ->all();
 
@@ -378,16 +369,78 @@ class MotivationService
             ->where(['admin_id' => $adminIds])
             ->all();
 
-        // Получаем массив стоимости каждого дня отпуска
-        $dailyPayments = ArrayHelper::getColumn($payments, 'daily_payment');
-
         // Вычисляем сумму отпускных выплат
-        $vacationsSum = array_sum($dailyPayments);
+        $vacationsSum = 0;
+        foreach ($payments as $payment) {
+            $vacationsSum += $payment->daily_payment;
+        }
 
         return $vacationsSum;
     }
+
+
+    public static function getMonthSalarySum($id)
+    {
+        // Запрос к модели MotivationValue для получения записей с заданными условиями
+        $records = MotivationValue::find()
+            ->where(['motivation_id' => $id, 'value_id' => 11])
+            ->andWhere(['in', 'motivation_group_id', [1, 2, 3, 4, 5]])
+            ->all();
+
+        // Получаем массив значений value_float
+        $values = array_map(function($record) {
+            return $record->value_float;
+        }, $records);
+
+        // Суммируем значения value_float
+        $totalSum = array_sum($values);
+
+        return $totalSum;
+    }
+
+    public static function saveOrUpdateMotivationValue($motivation_id, $group_id, $value_id, $value_type, $value)
+    {
+        // Найти существующую запись
+        $motivationValue = MotivationValue::findOne([
+            'motivation_id' => $motivation_id,
+            'motivation_group_id' => $group_id,
+            'value_id' => $value_id,
+        ]);
+
+        // Если запись не найдена, создать новую
+        if ($motivationValue === null) {
+            $motivationValue = new MotivationValue();
+            $motivationValue->motivation_id = $motivation_id;
+            $motivationValue->motivation_group_id = $group_id;
+            $motivationValue->value_id = $value_id;
+            $motivationValue->value_type = $value_type;
+        }
+
+        // Установить значение в зависимости от типа
+        switch ($value_type) {
+            case 'float':
+                $motivationValue->value_float = $value;
+                break;
+            case 'int':
+                $motivationValue->value_int = $value;
+                break;
+            case 'string':
+                $motivationValue->value_string = $value;
+                break;
+            default:
+                throw new \InvalidArgumentException("Invalid value type: $value_type");
+        }
+
+        // Сохранить запись и вернуть id или false
+        if ($motivationValue->save()) {
+            return $motivationValue->id;
+        } else {
+            Yii::error("Failed to save MotivationValue: " . json_encode($motivationValue->errors));
+            return false;
+        }
+    }
     
-    private static function getWeekOfMonth($dateTime)
+    public static function getWeekOfMonth($dateTime)
     {
         $dayOfMonth = intval($dateTime->format('j'));
         if ($dayOfMonth <= 7) {
@@ -403,7 +456,7 @@ class MotivationService
         }
     }
     
-    private static function getStartOfWeek($dateTime, $weekOfMonth)
+    public static function getStartOfWeek($dateTime, $weekOfMonth)
     {
         $year = $dateTime->format('Y');
         $month = $dateTime->format('m');