From: JoySystem_v Date: Thu, 15 Aug 2024 08:08:33 +0000 (+0300) Subject: изменения в коде - работа с датами, правка код стайл, изменение параметров методов X-Git-Tag: 1.4~35^2~4 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=4d3d9db269454121ba1d4483a6ba490d5f108c5a;p=erp24_rep%2Fyii-erp24%2F.git изменения в коде - работа с датами, правка код стайл, изменение параметров методов --- diff --git a/erp24/actions/motivation/GetSalaryAction.php b/erp24/actions/motivation/GetSalaryAction.php index 3e5b8a27..d78eae93 100644 --- a/erp24/actions/motivation/GetSalaryAction.php +++ b/erp24/actions/motivation/GetSalaryAction.php @@ -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; diff --git a/erp24/actions/motivation/SumPreviousMonthSalaryAction.php b/erp24/actions/motivation/SumPreviousMonthSalaryAction.php index e5722225..5318f4d6 100644 --- a/erp24/actions/motivation/SumPreviousMonthSalaryAction.php +++ b/erp24/actions/motivation/SumPreviousMonthSalaryAction.php @@ -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']); diff --git a/erp24/actions/motivation/SumSalaryAction.php b/erp24/actions/motivation/SumSalaryAction.php index 135566cd..9d55f741 100644 --- a/erp24/actions/motivation/SumSalaryAction.php +++ b/erp24/actions/motivation/SumSalaryAction.php @@ -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); } diff --git a/erp24/actions/motivation/SumSalaryByMonthAction.php b/erp24/actions/motivation/SumSalaryByMonthAction.php index e5d881cf..22c62f81 100644 --- a/erp24/actions/motivation/SumSalaryByMonthAction.php +++ b/erp24/actions/motivation/SumSalaryByMonthAction.php @@ -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); } } diff --git a/erp24/services/MotivationService.php b/erp24/services/MotivationService.php index 24366ccc..75083ea5 100644 --- a/erp24/services/MotivationService.php +++ b/erp24/services/MotivationService.php @@ -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"); } }