]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
изменения в коде - работа с датами, правка код стайл, изменение параметров методов
authorJoySystem_v <fvv2011@gmail.com>
Thu, 15 Aug 2024 08:08:33 +0000 (11:08 +0300)
committerJoySystem_v <fvv2011@gmail.com>
Thu, 15 Aug 2024 08:08:33 +0000 (11:08 +0300)
erp24/actions/motivation/GetSalaryAction.php
erp24/actions/motivation/SumPreviousMonthSalaryAction.php
erp24/actions/motivation/SumSalaryAction.php
erp24/actions/motivation/SumSalaryByMonthAction.php
erp24/services/MotivationService.php

index 3e5b8a27c4aeaa9f50221e9995d0a2087a3b2764..d78eae93f8a0cf3762ba5e1c2a415c53808bec8a 100644 (file)
@@ -50,20 +50,20 @@ class GetSalaryAction extends Action
                 ['start' => 22, 'end' => 28],
             ];
 
-            $lastDayOfMonth = (new DateTime("$year-$month-01"))->format('t');
+            $lastDayOfMonth = date('t', strtotime("$year-$month-01"));
 
             // Проверяем, существует ли 29-е число в текущем месяце (для не високосного года в феврале его не будет)
             if ($lastDayOfMonth > 28) {
                 $weeks[] = ['start' => 29, 'end' => $lastDayOfMonth];
             }
 
-            $dailyPayments = MotivationService::getEmployeePayments($lastDayOfMonth);
+            $dailyPayments = MotivationService::getEmployeePayments("$year-$month-$lastDayOfMonth");
 
 
             $results = [];
         foreach ($weeks as $weekIndex => $week) {
-            $startDate = sprintf("%s-%02d-%02d", $year, $month, $week['start']);
-            $endDate = sprintf("%s-%02d-%02d", $year, $month, $week['end']);
+            $startDate = date("Y-m-d", strtotime("$year-$month-" . $week['start']));
+            $endDate = date("Y-m-d 23:59:59", strtotime("$year-$month-" . $week['end']));
 
             $weeklyRecords = MotivationService::getTimetableFactRecordsByDateAndStore($startDate, $endDate, $storeId);
             $weeklyVacationSum = MotivationService::getVacationsSum($startDate, $endDate, $storeId);
@@ -100,8 +100,8 @@ class GetSalaryAction extends Action
         ksort($results);
 
         // Вычисление месячных данных
-        $startOfMonth = sprintf("%s-%02d-01", $year, $month);
-        $endOfMonth = (new DateTime("$year-$month-01"))->format('Y-m-t');
+        $startOfMonth = date('Y-m-01', strtotime("$year-$month-01"));
+        $endOfMonth = date('Y-m-t', strtotime("$year-$month-01"));
 
         $monthlyTotalSalary = 0.0;
 
index e57222251bd7d8402ed0113a8ff0515a3bcbea1e..5318f4d669491277e3bdd6d1e0418d36df7f9e8f 100644 (file)
@@ -3,23 +3,23 @@ namespace yii_app\actions\motivation;
 
 use Yii;
 use yii\base\Action;
-use DateTime;
 use yii_app\records\Motivation;
-use yii_app\records\MotivationValue;
-use yii_app\records\EmployeePayment;
 use yii_app\services\MotivationService;
 
 class SumPreviousMonthSalaryAction extends Action
 {
+
+
     public function run()
     {
-        $currentDate = new DateTime();
-        $previousMonthDate = (clone $currentDate)->modify('first day of last month');
-        $year = $previousMonthDate->format('Y');
-        $month = $previousMonthDate->format('m');
 
-        $startOfPreviousMonth = new DateTime("$year-$month-01");
-        $endOfPreviousMonth = new DateTime($startOfPreviousMonth->format('Y-m-t'));
+        $previousMonthDate = date("Y-m-d", strtotime("first day of last month"));
+        $year = date("Y", strtotime($previousMonthDate));
+        $month = date("m", strtotime($previousMonthDate));
+
+        $startOfPreviousMonth = date("Y-m-01", strtotime($previousMonthDate));
+        $endOfPreviousMonth = date("Y-m-t 23:59:59", strtotime($previousMonthDate));
+
 
         $motivations = Motivation::find()
             ->where(['year' => $year, 'month' => $month])
@@ -32,9 +32,9 @@ class SumPreviousMonthSalaryAction extends Action
 
         foreach ($motivations as $motivation) {
             $storeId = $motivation->store_id;
-            $monthlyTotalSalary = MotivationService::calculateTotalSalary($startOfPreviousMonth->format('Y-m-d'), $endOfPreviousMonth->format('Y-m-d'), $storeId);
+            $monthlyTotalSalary = MotivationService::calculateTotalSalary($startOfPreviousMonth, $endOfPreviousMonth, $storeId);
 
-            $idMotivation = MotivationService::saveOrUpdateMotivationValue($motivation->id, 6, 11, "float", $monthlyTotalSalary);
+            $idMotivation = MotivationService::saveOrUpdateMotivationValue($motivation->id, "fact", MotivationService::MCI_FOT, "float", $monthlyTotalSalary);
         }
 
         return $this->controller->redirect(['motivation/index']);
index 135566cd3d597a8d38d6b641e6335a8c7e3369ad..9d55f741c12568ef5ee2624a4c14882cc5e7919c 100644 (file)
@@ -4,28 +4,23 @@ namespace yii_app\actions\motivation;
 
 use Yii;
 use yii\base\Action;
-use yii\db\Expression;
 use yii_app\records\Motivation;
-use yii_app\records\MotivationValue;
-use yii_app\records\MotivationValueGroup;
-use yii_app\records\Admin;
-use yii_app\records\EmployeePayment;
 use yii_app\services\MotivationService;
 use DateTime;
 
-class SumSalaryAction extends \yii\base\Action
+class SumSalaryAction extends Action
 {
     public function run()
     {
-        $currentDate = new DateTime();
-        $currentYear = $currentDate->format('Y');
-        $currentMonth = $currentDate->format('m');
+        $currentDate = date("Y-m-d");
+        $currentYear = date("Y", strtotime($currentDate));
+        $currentMonth = date("m", strtotime($currentDate));
 
         // Определяем номер недели в месяце и начало недели
         $weekOfMonth = MotivationService::getWeekOfMonth($currentDate);
         $startOfWeek = MotivationService::getStartOfWeek($currentDate, $weekOfMonth);
-        $startDate = $startOfWeek->format('Y-m-d');
-        $endDate = $currentDate->format('Y-m-d');
+        $startDate = date("Y-m-d", strtotime($startOfWeek));
+        $endDate = date("Y-m-d", strtotime($currentDate));
 
         // Найти все записи по текущему месяцу и году
         $motivations = Motivation::find()
@@ -54,8 +49,8 @@ class SumSalaryAction extends \yii\base\Action
             if ($motivation === null) {
                 continue;
             }
-
-            MotivationService::saveOrUpdateMotivationValue($motivation->id, $weekOfMonth, 11, "float", $totalSalary);
+            $groupAlias = "week" . $weekOfMonth;
+            MotivationService::saveOrUpdateMotivationValue($motivation->id, $groupAlias, MotivationService::MCI_FOT, "float", $totalSalary);
 
         }
 
index e5d881cf0297674a637670f8a6ff3bcd525851d1..22c62f818525fd429309ffb1f3b8625ce4e9fc7e 100644 (file)
@@ -7,8 +7,6 @@ use yii\base\Action;
 use DateTime;
 use yii_app\models\SumSalaryForm;
 use yii_app\records\Motivation;
-use yii_app\records\MotivationValue;
-use yii_app\records\EmployeePayment;
 use yii_app\services\MotivationService;
 
 class SumSalaryByMonthAction extends Action
@@ -37,7 +35,8 @@ class SumSalaryByMonthAction extends Action
                 ['start' => 22, 'end' => 28],
             ];
 
-            $lastDayOfMonth = (new DateTime("$year-$month-01"))->format('t');
+            $lastDayOfMonth = date('t', strtotime("$year-$month-01"));
+
 
             // Проверяем, существует ли 29-е число в текущем месяце (для не високосного года в феврале его не будет)
             if ($lastDayOfMonth > 28) {
@@ -45,13 +44,13 @@ class SumSalaryByMonthAction extends Action
             }
 
             foreach ($weeks as $weekIndex => $week) {
-                $startDate = sprintf("%s-%02d-%02d", $year, $month, $week['start']);
-                $endDate = sprintf("%s-%02d-%02d", $year, $month, $week['end']);
-
+                $startDate = date("Y-m-d", strtotime("$year-$month-" . $week['start']));
+                $endDate = date("Y-m-d 23:59:59", strtotime("$year-$month-" . $week['end']));
+                $groupAlias = "week" . ($weekIndex + 1);
                 foreach ($motivations as $motivation) {
                     $storeId = $motivation->store_id;
                     $totalSalary = MotivationService::calculateTotalSalary($startDate, $endDate, $storeId);
-                    MotivationService::saveOrUpdateMotivationValue($motivation->id, $weekIndex + 1, 11, "float", $totalSalary);
+                    MotivationService::saveOrUpdateMotivationValue($motivation->id, $groupAlias, MotivationService::MCI_FOT, "float", $totalSalary);
                 }
             }
 
index 24366cccb8e1eba0d604262222feebde0f4725a3..75083ea5923aabd1f6b6157a64f9f3173302b272 100644 (file)
@@ -28,8 +28,8 @@ use yii_app\records\EmployeePayment;
 
 class MotivationService
 {
-
-
+// Код из таблицы MotivationCostsItem строки - Фонд оплаты труда персонала
+    const MCI_FOT = 11;
     /**
      * Получает ассоциативный массив алиасов групп мотивации.
      *
@@ -665,7 +665,7 @@ class MotivationService
      * Если сохранение успешно, возвращается ID записи. В случае ошибки возвращается `false`.
      *
      * @param int $motivationId Идентификатор мотивации.
-     * @param int $groupId Идентификатор группы мотивации.
+     * @param string $groupAlias Алиас группы мотивации.
      * @param int $valueId Идентификатор значения.
      * @param string $valueType Тип значения, который может быть 'float', 'int' или 'string'.
      * @param string $value_string Значение, которое нужно сохранить (string).
@@ -675,8 +675,17 @@ class MotivationService
      * @return int|false Возвращает ID сохраненной или обновленной записи, либо `false` в случае ошибки.
      * @throws \InvalidArgumentException Если передан некорректный тип значения.
      */
-    public static function saveOrUpdateMotivationValue($motivationId, $groupId, $valueId, $valueType, $value)
+    public static function saveOrUpdateMotivationValue($motivationId, $groupAlias, $valueId, $valueType, $value)
     {
+
+        // Найти id по алиасу в таблице MotivationValueGroup
+        $group = MotivationValueGroup::findOne(['alias' => $groupAlias]);
+
+        if ($group === null) {
+            throw new \InvalidArgumentException("Неверный алиас группы: $groupAlias");
+        }
+
+        $groupId = $group->id;
         // Найти существующую запись
         $motivationValue = MotivationValue::findOne([
             'motivation_id' => $motivationId,
@@ -728,13 +737,16 @@ class MotivationService
      * - 4-я неделя: с 22-го по 28-й день месяца.
      * - 5-я неделя: с 29-го дня месяца и до конца месяца.
      *
-     * @param \DateTime $dateTime Объект `DateTime`, для которого нужно определить номер недели.
+     * @param string $date Строка даты в формате 'Y-m-d', для которой нужно определить номер недели.
      *
      * @return int Номер недели в месяце (от 1 до 5).
      */
-    public static function getWeekOfMonth($dateTime)
+    public static function getWeekOfMonth($date)
     {
-        $dayOfMonth = intval($dateTime->format('j'));
+        // Преобразуем строку даты в день месяца
+        $dayOfMonth = intval(date('j', strtotime($date)));
+
+        // Определяем номер недели в месяце
         if ($dayOfMonth <= 7) {
             return 1;
         } elseif ($dayOfMonth <= 14) {
@@ -755,29 +767,30 @@ class MotivationService
      * Возвращается объект `DateTime`, представляющий первый день этой недели. Если номер недели выходит за пределы
      * допустимых значений (1-5), по умолчанию возвращается начало первой недели месяца.
      *
-     * @param \DateTime $dateTime Объект `DateTime`, представляющий дату, для которой определяется неделя.
+     * @param string $date Строка даты в формате 'Y-m-d', представляющая дату, для которой определяется неделя.
      * @param int $weekOfMonth Номер недели в месяце (от 1 до 5).
      *
-     * @return \DateTime Дата начала указанной недели месяца.
+     * @return string Дата начала указанной недели месяца в формате 'Y-m-d'.
      */
-    public static function getStartOfWeek($dateTime, $weekOfMonth)
+    public static function getStartOfWeek($date, $weekOfMonth)
     {
-        $year = $dateTime->format('Y');
-        $month = $dateTime->format('m');
+        // Извлекаем год и месяц из строки даты
+        $year = date('Y', strtotime($date));
+        $month = date('m', strtotime($date));
 
         switch ($weekOfMonth) {
             case 1:
-                return new DateTime("$year-$month-01");
+                return sprintf("%s-%s-01", $year, $month);
             case 2:
-                return new DateTime("$year-$month-08");
+                return sprintf("%s-%s-08", $year, $month);
             case 3:
-                return new DateTime("$year-$month-15");
+                return sprintf("%s-%s-15", $year, $month);
             case 4:
-                return new DateTime("$year-$month-22");
+                return sprintf("%s-%s-22", $year, $month);
             case 5:
-                return new DateTime("$year-$month-29");
+                return sprintf("%s-%s-29", $year, $month);
             default:
-                return new DateTime("$year-$month-01");
+                throw new \InvalidArgumentException("Некорректное значение для недели месяца: $weekOfMonth");
         }
     }