]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
fix vacation method
authorJoySystem_v <fvv2011@gmail.com>
Thu, 8 Aug 2024 09:27:51 +0000 (12:27 +0300)
committerJoySystem_v <fvv2011@gmail.com>
Thu, 8 Aug 2024 09:27:51 +0000 (12:27 +0300)
erp24/actions/motivation/GetSalaryAction.php
erp24/models/SumSalaryForm.php
erp24/services/MotivationService.php
erp24/views/motivation/error.php [new file with mode: 0644]
erp24/views/motivation/records.php
erp24/views/motivation/run-sum-salary.php

index 858c37caa6ae0ae8b5c37872d91334167f73a6e1..6395ffd9a2a5e6ece5c97a3c13d0466a37fd6511 100644 (file)
@@ -9,6 +9,7 @@ use yii_app\services\MotivationService;
 use yii_app\records\TimetableFactModel;
 use DateTime;
 use yii_app\records\EmployeePayment;
+use yii_app\records\Admin;
 
 class GetSalaryAction extends Action
 {
@@ -16,19 +17,17 @@ class GetSalaryAction extends Action
     public function run()
     {
         $request = Yii::$app->request;
-        $store_id = $request->get('store_id');
-        $month = $request->get('month');
-        $year = $request->get('year');
+        $store_id = $request->get('store_id', 1);
+        $month = $request->get('month', 7);
+        $year = $request->get('year', 2024);
         $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],
-        ]);
+        $model = new DynamicModel(compact('store_id', 'month', 'year'));
+        $model->addRule(['store_id', 'month', 'year'], 'required')
+            ->addRule('store_id', 'integer')
+            ->addRule('month', 'integer', ['min' => 1, 'max' => 12])
+            ->addRule('year', 'integer', ['min' => 2000, 'max' => 2100]);
 
         if ($model->hasErrors()) {
             return $this->controller->render('error', [
@@ -37,12 +36,16 @@ class GetSalaryAction extends Action
             ]);
         }
 
+        $store_id = (int)$store_id;
+        $month = (int)$month;
+        $year = (int)$year;
+
         $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')]
+            ['start' => 29, 'end' => (new DateTime("$year-$month-01"))->format('t')],
         ];
 
         $results = [];
@@ -54,29 +57,63 @@ class GetSalaryAction extends Action
             $weeklyVacationSum = MotivationService::getVacationsSum($startDate, $endDate, $store_id);
 
             $weeklyTotalSalary = 0;
+            $recordsWithAdditionalData = [];
             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;
-                }
+                $admin = Admin::findOne(['id' => $record->admin_id]);
+                $adminName = $admin ? $admin->name : 'Unknown';
+
+                $weeklyTotalSalary += !empty($record->salary_shift) ? $record->salary_shift : $dailyPayment;
+
+                $recordsWithAdditionalData[] = [
+                    'admin_id' => $record->admin_id,
+                    'admin_name' => $adminName,
+                    'salary_shift' => $record->salary_shift,
+                    'daily_payment' => $dailyPayment,
+                    'date_shift' => $record->date_shift
+                ];
             }
 
             $results[$weekIndex + 1] = [
                 'totalSalary' => $weeklyTotalSalary + $weeklyVacationSum,
-                'records' => $weeklyRecords,
+                'records' => $recordsWithAdditionalData,
                 'vacationSum' => $weeklyVacationSum,
                 'startDate' => $startDate,
-                'endDate' => $endDate
+                'endDate' => $endDate,
             ];
+
+        }
+        // Сортировка по дате начала недели
+        ksort($results);
+
+        // Вычисление месячных данных
+        $startOfMonth = sprintf("%s-%02d-01", $year, $month);
+        $endOfMonth = (new DateTime("$year-$month-01"))->format('Y-m-t');
+
+        $monthlyTotalSalary = 0;
+        $monthlyVacationSum = 0;
+
+        $monthlyRecords = MotivationService::getTimetableFactRecordsByDateAndStore($startOfMonth, $endOfMonth, $store_id);
+        $monthlyVacationSum = MotivationService::getVacationsSum($startOfMonth, $endOfMonth, $store_id);
+
+        foreach ($monthlyRecords as $record) {
+            $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
+            $dailyPayment = $payment ? $payment->daily_payment : null;
+
+            $monthlyTotalSalary += !empty($record->salary_shift) ? $record->salary_shift : $dailyPayment;
         }
 
-        return $this->controller->render('weekly-salary', [
+        // Подсчет зарплаты без отпускных
+        $monthlySalaryWithoutVacation = $monthlyTotalSalary - $monthlyVacationSum;
+
+        return $this->controller->render('records', [
             'model' => $model,
             'results' => $results,
+            'monthlyTotalSalary' => $monthlyTotalSalary,
+            'monthlyVacationSum' => $monthlyVacationSum,
+            'monthlySalaryWithoutVacation' => $monthlySalaryWithoutVacation,
         ]);
     }
 }
index 55ee9c9f0da72b0a87726de0dabfe15b451bc017..72954f2b05f7b04164c92cbf25afedbb25bcd356 100644 (file)
@@ -13,7 +13,7 @@ class SumSalaryForm extends Model
     public function rules()
     {
         return [
-            [['month', 'year'], 'required'],
+            [['store_id','month', 'year'], 'required'],
             ['store_id', 'integer'],
             ['month', 'integer', 'min' => 1, 'max' => 12],
             ['year', 'integer', 'min' => 1900, 'max' => 2100],
index 57f1684c600ac497141dd38025f0184f539d30ec..1acf981ed2214d8ccb0a1a00f1568786f3f29920 100644 (file)
@@ -10,10 +10,11 @@ use yii_app\records\MotivationValueGroup;
 use yii_app\records\CityStore;
 use yii_app\records\MotivationCostsItem;
 use yii_app\records\TimetableFactModel;
+use yii_app\records\Timetable;
 use DateTime;
 
 use yii\helpers\ArrayHelper;
-use yii_app\records\Timetable;
+
 use yii_app\records\EmployeePayment;
 
 
@@ -336,14 +337,12 @@ class MotivationService
 
     public static function getTimetableFactRecordsByDateAndStore($startDate, $endDate, $store_id)
     {
-        // Преобразуем начальную и конечную дату в объекты DateTime
-        $startDateTime = new DateTime($startDate);
-        $endDateTime = new DateTime($endDate);
+
 
         // Делаем запрос к TimetableFactModel
         $records = TimetableFactModel::find()
             ->where(['store_id' => $store_id])
-            ->andWhere(['between', 'date_shift', $startDateTime->format('Y-m-d'), $endDateTime->format('Y-m-d')])
+            ->andWhere(['between', 'date_shift', $startDate, $endDate])
             ->all();
 
         return $records;
@@ -351,31 +350,33 @@ class MotivationService
 
     public static function getVacationsSum($startDate, $endDate, $store_id)
     {
-        // Преобразуем начальную и конечную дату в объекты 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', $startDateTime->format('Y-m-d'), $endDateTime->format('Y-m-d')])
+            ->andWhere(['between', 'date', $startDate, $endDate])
             ->andWhere(['slot_type_id' => 2])
             ->all();
 
-        // Получаем массив admin_id
-        $adminIds = ArrayHelper::getColumn($records, 'admin_id');
+        // Проверяем, есть ли записи
+        if (empty($records)) {
+            return 0; // Возвращаем 0, если записей нет
+        }
+
 
-        // Делаем запрос к таблице EmployeePayment для получения daily_payment
-        $payments = EmployeePayment::find()
-            ->where(['admin_id' => $adminIds])
-            ->all();
 
-        // Вычисляем сумму отпускных выплат
         $vacationsSum = 0;
-        foreach ($payments as $payment) {
-            $vacationsSum += $payment->daily_payment;
+        foreach ($records as $record) {
+            $payment = EmployeePayment::findOne(['admin_id' => $record->admin_id]);
+            $dailyPayment = $payment ? $payment->daily_payment : null;
+
+
+            $vacationsSum += $dailyPayment;
+
         }
 
+
+
         return $vacationsSum;
     }
 
diff --git a/erp24/views/motivation/error.php b/erp24/views/motivation/error.php
new file mode 100644 (file)
index 0000000..ddd1122
--- /dev/null
@@ -0,0 +1,25 @@
+<?php
+use yii\helpers\Html;
+
+/* @var $this yii\web\View */
+/* @var $model yii\base\DynamicModel */
+/* @var $errors array */
+
+$this->title = 'Ошибка валидации данных';
+?>
+
+<div class="validation-error">
+    <h1><?= Html::encode($this->title) ?></h1>
+    <p>Произошли следующие ошибки:</p>
+    <ul>
+        <?php foreach ($errors as $attribute => $messages): ?>
+            <li><strong><?= Html::encode($attribute) ?>:</strong>
+                <ul>
+                    <?php foreach ($messages as $message): ?>
+                        <li><?= Html::encode($message) ?></li>
+                    <?php endforeach; ?>
+                </ul>
+            </li>
+        <?php endforeach; ?>
+    </ul>
+</div>
index 218775cbdaa1e87442dad02b9bce2b71301d516f..1a82cd6dc712acd6d03e022dad5d722293e0cb3b 100644 (file)
@@ -2,27 +2,74 @@
 use yii\helpers\Html;
 use yii\widgets\ActiveForm;
 
+
 /* @var $this yii\web\View */
 /* @var $model yii_app\models\SumSalaryForm */
+/* @var $results array */
+/* @var $monthlyTotalSalary float */
+/* @var $monthlyVacationSum float */
+/* @var $monthlySalaryWithoutVacation float */
 
-$this->title = 'Ð\9fолÑ\83Ñ\87ение зарплат по неделям';
+$this->title = 'РезÑ\83лÑ\8cÑ\82аÑ\82Ñ\8b Ñ\80аÑ\81Ñ\87еÑ\82а зарплат по неделям';
 ?>
 
-<div class="get-salary-action">
+<div class="weekly-salary-results">
     <h1><?= Html::encode($this->title) ?></h1>
 
-    <?php $form = ActiveForm::begin([
-        'method' => 'get',
-        'action' => ['motivation/get-salary'],
-    ]); ?>
+    <p>Магазин: <?= Html::encode($model->store_id) ?>, Месяц: <?= Html::encode($model->month) ?>, Год: <?= Html::encode($model->year) ?></p>
+
+    <?php
+    // Инициализируем переменные для подсчета общих сумм
+    $totalSalaryMonth = 0;
+    $totalVacationSumMonth = 0;
+    $totalSalaryWithoutVacationMonth = 0;
+
+    // Подсчитываем общие суммы
+    foreach ($results as $weekData) {
+        $totalSalaryMonth += $weekData['totalSalary'];
+        $totalVacationSumMonth += $weekData['vacationSum'];
+    }
+    $totalSalaryWithoutVacationMonth = $totalSalaryMonth - $totalVacationSumMonth;
+    ?>
+
+    <h2>Итого за месяц</h2>
+    <p>Общая зарплата с отпускными: <?= Html::encode($totalSalaryMonth) ?></p>
+    <p>Сумма отпускных: <?= Html::encode($totalVacationSumMonth) ?></p>
+    <p>Сумма зарплат без отпускных: <?= Html::encode($totalSalaryWithoutVacationMonth) ?></p>
 
-    <?= $form->field($model, 'store_id')->textInput() ?>
-    <?= $form->field($model, 'month')->textInput() ?>
-    <?= $form->field($model, 'year')->textInput() ?>
+    <?php foreach ($results as $week => $data): ?>
+        <h3>Неделя <?= Html::encode($week) ?> (с <?= Html::encode($data['startDate']) ?> по <?= Html::encode($data['endDate']) ?>)</h3>
+        <p>Общая зарплата с отпускными: <?= Html::encode($data['totalSalary']) ?></p>
+        <p>Общая зарплата без отпускных: <?= Html::encode($data['totalSalary'] - $data['vacationSum']) ?></p>
+        <p>Сумма отпускных: <?= Html::encode($data['vacationSum']) ?></p>
 
-    <div class="form-group">
-        <?= Html::submitButton('Получить данные', ['class' => 'btn btn-primary']) ?>
-    </div>
+        <h4>Записи:</h4>
+        <table class="table table-bordered">
+            <thead>
+            <tr>
+                <th>Admin ID</th>
+                <th>Admin Name</th>
+                <th>Salary Shift</th>
+                <th>Daily Payment</th>
+                <th>Date Shift</th>
+            </tr>
+            </thead>
+            <tbody>
+            <?php foreach ($data['records'] as $record): ?>
+                <tr>
+                    <td><?= Html::encode($record['admin_id']) ?></td>
+                    <td><?= Html::encode($record['admin_name']) ?></td>
+                    <td><?= Html::encode($record['salary_shift']) ?></td>
+                    <td><?= Html::encode($record['daily_payment']) ?></td>
+                    <td><?= Html::encode($record['date_shift']) ?></td>
+                </tr>
+            <?php endforeach; ?>
+            </tbody>
+        </table>
+    <?php endforeach; ?>
+</div>
 
-    <?php ActiveForm::end(); ?>
-</div>
\ No newline at end of file
+<h2>Итого за месяц</h2>
+<p>Общая зарплата с отпускными: <?= Html::encode($monthlyTotalSalary) ?></p>
+<p>Сумма отпускных: <?= Html::encode($monthlyVacationSum) ?></p>
+<p>Сумма зарплат без отпускных: <?= Html::encode($monthlySalaryWithoutVacation) ?></p>
index b6bf6d260a151dab58642b7a59f0db3929cefe9c..554db4025919bfd7899687b9cd58057e6ac9d700 100644 (file)
@@ -13,7 +13,7 @@ $this->title = 'Запуск экшена SumSalary';
     <p>Введите номер месяца и год для расчета зарплат.</p>
 
     <?php $form = ActiveForm::begin(['action' => ['motivation/sum-salary-by-month'], 'method' => 'post']); ?>
-
+    <?= $form->field($model, 'store_id')->input('number', ['min' => 1, 'max' => 12]) ?>
     <?= $form->field($model, 'month')->input('number', ['min' => 1, 'max' => 12]) ?>
     <?= $form->field($model, 'year')->input('number', ['min' => 2000, 'max' => 2100]) ?>
 
@@ -33,4 +33,24 @@ $this->title = 'Запуск экшена SumSalary';
     <?= Html::submitButton('Запустить', ['class' => 'btn btn-primary']) ?>
     <?= Html::endForm() ?>
 
+    <!--<p>Получить данные по сменам.</p>
+    <div class="get-salary-action">
+        <h1><?/*= Html::encode($this->title) */?></h1>
+
+        <?php /*$form = ActiveForm::begin([
+            'method' => 'get',
+            'action' => ['motivation/get-salary'],
+        ]); */?>
+
+        <?/*= $form->field($model, 'store_id')->textInput() */?>
+        <?/*= $form->field($model, 'month')->textInput() */?>
+        <?/*= $form->field($model, 'year')->textInput() */?>
+
+        <div class="form-group">
+            <?/*= Html::submitButton('Получить данные', ['class' => 'btn btn-primary']) */?>
+        </div>
+
+        <?php /*ActiveForm::end(); */?>
+    </div>-->
+
 </div>