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,
- ]);
-}
}
$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)) {
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);
}
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;
{
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
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
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;
+ }
}
<?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
<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']) ?>