]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
change weekly
authorJoySystem_v <fvv2011@gmail.com>
Thu, 8 Aug 2024 04:16:13 +0000 (07:16 +0300)
committerJoySystem_v <fvv2011@gmail.com>
Thu, 8 Aug 2024 04:16:13 +0000 (07:16 +0300)
erp24/actions/motivation/GetSalaryAction.php
erp24/actions/motivation/SumPreviousMonthSalaryAction.php
erp24/actions/motivation/SumSalaryByMonthAction.php
erp24/models/SumSalaryForm.php
erp24/services/MotivationService.php
erp24/views/motivation/records.php
erp24/views/motivation/run-sum-salary.php

index e03c43b77cdc196eb5ec7d21200534b55b81620a..858c37caa6ae0ae8b5c37872d91334167f73a6e1 100644 (file)
@@ -8,43 +8,75 @@ use yii\base\DynamicModel;
 use yii_app\services\MotivationService;
 use yii_app\records\TimetableFactModel;
 use DateTime;
-
+use yii_app\records\EmployeePayment;
 
 class GetSalaryAction extends Action
 {
 
-public function run()
-{
-    $request = Yii::$app->request;
-    $store_id = $request->get('store_id', 2);
-    $date = $request->get('date', '2024-08-05');
-    $records = [];
-
-    // Создаем и валидируем модель
-    $model = DynamicModel::validateData(compact('store_id', 'date'), [
-        [['store_id', 'date'], 'required'],
-        ['store_id', 'integer'],
-        ['date', 'date', 'format' => 'php:Y-m-d'],
-    ]);
-
-    if (!$model->hasErrors()) {
-        $records = MotivationService::getTimetableFactRecordsByDateAndStore($date, $store_id);
-        $vacationSum = MotivationService::getVacationsSum($date, $store_id);
+    public function run()
+    {
+        $request = Yii::$app->request;
+        $store_id = $request->get('store_id');
+        $month = $request->get('month');
+        $year = $request->get('year');
+        $records = [];
+        $vacationSum = 0;
+
+        // Создаем и валидируем модель
+        $model = DynamicModel::validateData(compact('store_id', 'month', 'year'), [
+            [['store_id', 'month', 'year'], 'required'],
+            ['store_id', 'integer'],
+            ['month', 'integer', 'min' => 1, 'max' => 12],
+            ['year', 'integer', 'min' => 1900, 'max' => 2100],
+        ]);
+
+        if ($model->hasErrors()) {
+            return $this->controller->render('error', [
+                'model' => $model,
+                'errors' => $model->errors,
+            ]);
+        }
+
+        $weeks = [
+            ['start' => 1, 'end' => 7],
+            ['start' => 8, 'end' => 14],
+            ['start' => 15, 'end' => 21],
+            ['start' => 22, 'end' => 28],
+            ['start' => 29, 'end' => (new DateTime("$year-$month-01"))->format('t')]
+        ];
+
+        $results = [];
+        foreach ($weeks as $weekIndex => $week) {
+            $startDate = sprintf("%s-%02d-%02d", $year, $month, $week['start']);
+            $endDate = sprintf("%s-%02d-%02d", $year, $month, $week['end']);
+
+            $weeklyRecords = MotivationService::getTimetableFactRecordsByDateAndStore($startDate, $endDate, $store_id);
+            $weeklyVacationSum = MotivationService::getVacationsSum($startDate, $endDate, $store_id);
+
+            $weeklyTotalSalary = 0;
+            foreach ($weeklyRecords as $record) {
+                $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
+                $dailyPayment = $payment ? $payment->daily_payment : null;
+
+                if (!empty($record->salary_shift)) {
+                    $weeklyTotalSalary += $record->salary_shift;
+                } else {
+                    $weeklyTotalSalary += $dailyPayment;
+                }
+            }
+
+            $results[$weekIndex + 1] = [
+                'totalSalary' => $weeklyTotalSalary + $weeklyVacationSum,
+                'records' => $weeklyRecords,
+                'vacationSum' => $weeklyVacationSum,
+                'startDate' => $startDate,
+                'endDate' => $endDate
+            ];
+        }
+
+        return $this->controller->render('weekly-salary', [
+            'model' => $model,
+            'results' => $results,
+        ]);
     }
-// Определяем начало недели и номер недели в месяце
-    $currentDate = new DateTime($model->date);
-    $startOfWeek = $currentDate->modify('monday this week')->format('Y-m-d');
-    $endOfWeek = $currentDate->format('Y-m-d');
-
-    $weekNumberInMonth = ceil($currentDate->format('j') / 7);
-
-    return $this->controller->render('records', [
-        'model' => $model,
-        'records' => $records,
-        'startOfWeek' => $startOfWeek,
-        'endOfWeek' => $endOfWeek,
-        'weekNumberInMonth' => $weekNumberInMonth,
-        'vacation'=> $vacationSum,
-    ]);
-}
 }
index 7225f69e7cacd6748b8303554aba58a9920cb7c6..1ac1fa5cf7616007a11ffc274d31afdc913ad7ef 100644 (file)
@@ -16,15 +16,13 @@ class SumPreviousMonthSalaryAction extends Action
         $currentDate = new DateTime();
         $previousMonthDate = (clone $currentDate)->modify('first day of last month');
         $year = $previousMonthDate->format('Y');
-        $mounth = $previousMonthDate->format('m');
+        $month = $previousMonthDate->format('m');
 
-        // Определяем даты начала и конца предыдущего месяца
-        $startOfPreviousMonth = new DateTime("$year-$mounth-01");
+        $startOfPreviousMonth = new DateTime("$year-$month-01");
         $endOfPreviousMonth = new DateTime($startOfPreviousMonth->format('Y-m-t'));
 
-        // Найти все записи по предыдущему месяцу и году
         $motivations = Motivation::find()
-            ->where(['year' => $year, 'month' => $mounth])
+            ->where(['year' => $year, 'month' => $month])
             ->all();
 
         if (empty($motivations)) {
@@ -34,25 +32,8 @@ class SumPreviousMonthSalaryAction extends Action
 
         foreach ($motivations as $motivation) {
             $store_id = $motivation->store_id;
+            $monthlyTotalSalary = MotivationService::calculateTotalSalary($startOfPreviousMonth->format('Y-m-d'), $endOfPreviousMonth->format('Y-m-d'), $store_id);
 
-            $monthlyRecords = MotivationService::getTimetableFactRecordsByDateAndStore($startOfPreviousMonth->format('Y-m-d'), $endOfPreviousMonth->format('Y-m-d'), $store_id);
-            $monthlyVacationSum = MotivationService::getVacationsSum($startOfPreviousMonth->format('Y-m-d'), $endOfPreviousMonth->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;
-            //TODO Проверка записи
             $idMotivation = MotivationService::saveOrUpdateMotivationValue($motivation->id, 6, 11, "float", $monthlyTotalSalary);
         }
 
index 8936ffaa8263d10d27993fb9e5de20e793b205d1..a83c58f304be66949002d496b2ddf0551234f283 100644 (file)
@@ -5,6 +5,7 @@ namespace yii_app\actions\motivation;
 use Yii;
 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;
@@ -14,94 +15,65 @@ class SumSalaryByMonthAction extends Action
 {
     public function run()
     {
-        $request = Yii::$app->request;
-        $inputDate = $request->post('date'); // Получаем дату из формы
-        $selectedDate = new DateTime($inputDate);
-        $year = $selectedDate->format('Y');
-        $month = $selectedDate->format('m');
+        $model = new SumSalaryForm();
 
-        // Найти все записи по выбранному месяцу и году
-        $motivations = Motivation::find()
-            ->where(['year' => $year, 'month' => $month])
-            ->all();
+        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
+            $year = $model->year;
+            $month = $model->month;
 
-        if (empty($motivations)) {
-            Yii::warning("No motivation records found for the selected month and year.");
-            return $this->controller->redirect(['motivation/index']);
-        }
-
-        $weeks = [
-            ['start' => '01', 'end' => '07'],
-            ['start' => '08', 'end' => '14'],
-            ['start' => '15', 'end' => '21'],
-            ['start' => '22', 'end' => '28'],
-            ['start' => '29', 'end' => date('t', strtotime("$year-$month-01"))] // последняя неделя до конца месяца
-        ];
+            $motivations = Motivation::find()
+                ->where(['year' => $year, 'month' => $month])
+                ->all();
 
-        foreach ($weeks as $weekIndex => $week) {
-            $startDate = "$year-$month-" . $week['start'];
-            $endDate = "$year-$month-" . $week['end'];
-
-            $results = [];
-            foreach ($motivations as $motivation) {
-                $store_id = $motivation->store_id;
+            if (empty($motivations)) {
+                Yii::warning("Не найдено ни одной записи для выбранного месяца и года.");
+                return $this->controller->redirect(['motivation/index']);
+            }
 
-                $records = MotivationService::getTimetableFactRecordsByDateAndStore($startDate, $endDate, $store_id);
-                $vacationSum = MotivationService::getVacationsSum($startDate, $endDate, $store_id);
+            $weeks = [
+                ['start' => 1, 'end' => 7],
+                ['start' => 8, 'end' => 14],
+                ['start' => 15, 'end' => 21],
+                ['start' => 22, 'end' => 28],
+                ['start' => 29, 'end' => (new DateTime("$year-$month-01"))->format('t')] // последняя неделя до конца месяца
+            ];
+
+            foreach ($weeks as $weekIndex => $week) {
+                $startDate = sprintf("%s-%02d-%02d", $year, $month, $week['start']);
+                $endDate = sprintf("%s-%02d-%02d", $year, $month, $week['end']);
+
+                foreach ($motivations as $motivation) {
+                    $store_id = $motivation->store_id;
+                    $totalSalary = MotivationService::calculateTotalSalary($startDate, $endDate, $store_id);
+
+                    $motivationValue = MotivationValue::findOne([
+                        'motivation_id' => $motivation->id,
+                        'motivation_group_id' => $weekIndex + 1, // Номер недели
+                        'value_id' => 11
+                    ]);
+
+                    if ($motivationValue === null) {
+                        $motivationValue = new MotivationValue();
+                        $motivationValue->motivation_id = $motivation->id;
+                        $motivationValue->motivation_group_id = $weekIndex + 1;
+                        $motivationValue->value_id = 11;
+                        $motivationValue->value_type = 'float';
+                    }
 
-                $totalSalary = 0;
-                foreach ($records as $record) {
-                    $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
-                    $dailyPayment = $payment ? $payment->daily_payment : null;
+                    $motivationValue->value_float = $totalSalary;
+                    $motivationValue->value_int = null;
+                    $motivationValue->value_string = null;
 
-                    // Если $record->salary_shift имеет значение, учитываем его и не добавляем dailyPayment
-                    if (!empty($record->salary_shift)) {
-                        $totalSalary += $record->salary_shift;
-                    } else {
-                        $totalSalary += $dailyPayment;
+                    if (!$motivationValue->save()) {
+                        Yii::error("Не удалось записать данные для store_id: $store_id");
                     }
                 }
-
-                $results[$store_id] = $totalSalary + $vacationSum;
             }
 
-            // Записываем информацию в таблицу MotivationValue за текущую неделю
-            foreach ($results as $store_id => $totalSalary) {
-                $motivation = Motivation::findOne(['store_id' => $store_id, 'year' => $year, 'month' => $month]);
-
-                // Если не найдено соответствующее мотивационное значение, пропустить этот store_id
-                if ($motivation === null) {
-                    continue;
-                }
-
-                // Проверка наличия записи в MotivationValue за текущую неделю
-                $motivationValue = MotivationValue::findOne([
-                    'motivation_id' => $motivation->id,
-                    'motivation_group_id' => $weekIndex + 1, // Номер недели
-                    'value_id' => 11
-                ]);
-
-                if ($motivationValue === null) {
-                    // Если записи нет, создаем новую
-                    $motivationValue = new MotivationValue();
-                    $motivationValue->motivation_id = $motivation->id;
-                    $motivationValue->motivation_group_id = $weekIndex + 1;
-                    $motivationValue->value_id = 11;
-                    $motivationValue->value_type = 'float';
-                }
-
-                // Обновляем значение
-                $motivationValue->value_float = $totalSalary;
-                $motivationValue->value_int = null;
-                $motivationValue->value_string = null;
-
-                // Сохраняем запись
-                if (!$motivationValue->save()) {
-                    Yii::error("Не удалось записать данные для store_id: $store_id");
-                }
-            }
+            return $this->controller->redirect(['motivation/index']);
+        } else {
+            Yii::warning("Неправильный ввод данных.");
+            return $this->controller->redirect(['motivation/index']);
         }
-
-        return $this->controller->redirect(['motivation/index']);
     }
 }
\ No newline at end of file
index 238d0690c7ec524cc1891ee316310356f1a917a6..55ee9c9f0da72b0a87726de0dabfe15b451bc017 100644 (file)
@@ -6,13 +6,17 @@ use yii\base\Model;
 
 class SumSalaryForm extends Model
 {
-    public $date;
+    public $store_id;
+    public $month;
+    public $year;
 
     public function rules()
     {
         return [
-            [['date'], 'required'],
-            [['date'], 'date', 'format' => 'php:Y-m-d'],
+            [['month', 'year'], 'required'],
+            ['store_id', 'integer'],
+            ['month', 'integer', 'min' => 1, 'max' => 12],
+            ['year', 'integer', 'min' => 1900, 'max' => 2100],
         ];
     }
 }
\ No newline at end of file
index 30b3b78578520ebaea9cce95309346dd26c22294..57f1684c600ac497141dd38025f0184f539d30ec 100644 (file)
@@ -477,4 +477,25 @@ class MotivationService
                 return new DateTime("$year-$month-01");
         }
     }
+
+
+    public static function calculateTotalSalary($startDate, $endDate, $storeId)
+    {
+        $records = self::getTimetableFactRecordsByDateAndStore($startDate, $endDate, $storeId);
+        $vacationSum = self::getVacationsSum($startDate, $endDate, $storeId);
+
+        $totalSalary = 0;
+        foreach ($records as $record) {
+            $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
+            $dailyPayment = $payment ? $payment->daily_payment : null;
+
+            if (!empty($record->salary_shift)) {
+                $totalSalary += $record->salary_shift;
+            } else {
+                $totalSalary += $dailyPayment;
+            }
+        }
+
+        return $totalSalary + $vacationSum;
+    }
 }
index 5c014acc633e45cf2ec0b80db0ddb75ce3f0c490..218775cbdaa1e87442dad02b9bce2b71301d516f 100644 (file)
@@ -1,92 +1,28 @@
 <?php
 use yii\helpers\Html;
 use yii\widgets\ActiveForm;
-use yii_app\records\Admin;
-use yii_app\records\EmployeePayment;
-use yii\base\DynamicModel;
 
-/** @var $model DynamicModel */
-/** @var $records array */
-/** @var $startOfWeek string */
-/** @var $endOfWeek string */
-/** @var $weekNumberInMonth int */
-/** @var $vacation float */
-$this->title = 'Записи';
+/* @var $this yii\web\View */
+/* @var $model yii_app\models\SumSalaryForm */
+
+$this->title = 'Получение зарплат по неделям';
 ?>
 
-<h1><?= Html::encode($this->title) ?></h1>
+<div class="get-salary-action">
+    <h1><?= Html::encode($this->title) ?></h1>
 
-<div class="motivation-form">
     <?php $form = ActiveForm::begin([
         'method' => 'get',
         'action' => ['motivation/get-salary'],
     ]); ?>
 
-    <?= $form->field($model, 'store_id')->textInput(['value' => $model->store_id]) ?>
-    <?= $form->field($model, 'date')->input('date', ['value' => $model->date]) ?>
+    <?= $form->field($model, 'store_id')->textInput() ?>
+    <?= $form->field($model, 'month')->textInput() ?>
+    <?= $form->field($model, 'year')->textInput() ?>
 
     <div class="form-group">
-        <?= Html::submitButton('Ð\97апÑ\80оÑ\81иÑ\82Ñ\8c', ['class' => 'btn btn-primary']) ?>
+        <?= Html::submitButton('Ð\9fолÑ\83Ñ\87иÑ\82Ñ\8c Ð´Ð°Ð½Ð½Ñ\8bе', ['class' => 'btn btn-primary']) ?>
     </div>
 
     <?php ActiveForm::end(); ?>
-</div>
-
-<?php if (!empty($records)): ?>
-    <?php
-    $totalSalary = 0;
-    $weekNumber = (new DateTime($model->date))->format("W");
-
-    foreach ($records as $record) {
-        $admin = Admin::findOne($record->admin_id);
-        $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
-        $dailyPayment = $payment ? $payment->daily_payment : null;
-
-        // Если $record->salary_shift имеет значение, учитываем его и не добавляем dailyPayment
-        if (!empty($record->salary_shift)) {
-            $totalSalary += $record->salary_shift;
-        } else {
-            $totalSalary += $dailyPayment;
-        }
-    }
-    ?>
-
-    <h2>Смены</h2>
-    <table class="table table-bordered">
-        <thead>
-        <tr>
-            <th>Store ID</th>
-            <th>Admin ID</th>
-            <th>Date Shift</th>
-            <th>Salary Shift</th>
-            <th>Name</th>
-            <th>Group</th>
-            <th>ЗП за смену</th>
-        </tr>
-        </thead>
-        <tbody>
-        <?php foreach ($records as $record): ?>
-            <?php
-            $admin = Admin::findOne($record->admin_id);
-            $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
-            $dailyPayment = $payment ? $payment->daily_payment : null;
-            ?>
-            <tr>
-                <td><?= Html::encode($record->store_id) ?></td>
-                <td><?= Html::encode($record->admin_id) ?></td>
-                <td><?= Html::encode($record->date_shift) ?></td>
-                <td><?= Html::encode($record->salary_shift) ?></td>
-                <td><?= Html::encode($admin->name) ?></td>
-                <td><?= Html::encode($admin->group_name) ?></td>
-                <td><?= Html::encode($dailyPayment) ?></td>
-            </tr>
-        <?php endforeach; ?>
-        </tbody>
-    </table>
-
-    <p>Всего смен: <?= count($records) ?></p>
-    <p>ЗП за весь период: <?= Html::encode($totalSalary) ?></p>
-    <p>Отпускные: <?= Html::encode($vacation) ?></p>
-    <p>Период: с <?= Html::encode($startOfWeek) ?> по <?= Html::encode($endOfWeek) ?></p>
-    <p>Номер недели в месяце: <?= Html::encode($weekNumberInMonth) ?></p>
-<?php endif; ?>
+</div>
\ No newline at end of file
index f35a5140e287603d845dfa830c88f562956c086a..b6bf6d260a151dab58642b7a59f0db3929cefe9c 100644 (file)
@@ -10,14 +10,12 @@ $this->title = 'Запуск экшена SumSalary';
 <div class="sum-salary-action">
     <h1><?= Html::encode($this->title) ?></h1>
 
-    <p>Ð\92ведиÑ\82е Ð´Ð°Ñ\82Ñ\83 Ð¸ Ð½Ð°Ð¶Ð¼Ð¸Ñ\82е ÐºÐ½Ð¾Ð¿ÐºÑ\83 Ð½Ð¸Ð¶Ðµ, Ñ\87Ñ\82обÑ\8b Ð·Ð°Ð¿Ñ\83Ñ\81Ñ\82иÑ\82Ñ\8c Ñ\8dкÑ\88н SumSalaryByMonth Ð¸ Ð²Ñ\8bÑ\87иÑ\81лиÑ\82Ñ\8c Ñ\81Ñ\83ммÑ\8b Ð·Ð°Ñ\80плаÑ\82 Ð·Ð° ÐºÐ°Ð¶Ð´Ñ\83Ñ\8e Ð½ÐµÐ´ÐµÐ»Ñ\8e Ð²Ñ\8bбÑ\80анного Ð¼ÐµÑ\81Ñ\8fÑ\86а.</p>
+    <p>Ð\92ведиÑ\82е Ð½Ð¾Ð¼ÐµÑ\80 Ð¼ÐµÑ\81Ñ\8fÑ\86а Ð¸ Ð³Ð¾Ð´ Ð´Ð»Ñ\8f Ñ\80аÑ\81Ñ\87еÑ\82а Ð·Ð°Ñ\80плаÑ\82.</p>
 
-    <?php $form = ActiveForm::begin([
-        'action' => ['motivation/sum-salary-by-month'],
-        'method' => 'post',
-    ]); ?>
+    <?php $form = ActiveForm::begin(['action' => ['motivation/sum-salary-by-month'], 'method' => 'post']); ?>
 
-    <?= $form->field($model, 'date')->input('date') ?>
+    <?= $form->field($model, 'month')->input('number', ['min' => 1, 'max' => 12]) ?>
+    <?= $form->field($model, 'year')->input('number', ['min' => 2000, 'max' => 2100]) ?>
 
     <?= Html::submitButton('Запустить', ['class' => 'btn btn-primary']) ?>