From: JoySystem_v Date: Mon, 26 Aug 2024 14:35:10 +0000 (+0300) Subject: изменение ранжирования, дат и сценариев активных кнопок X-Git-Tag: 1.5~20^2~10 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=08f1ac55a1982fc72b19fe78b23631d1b95c220a;p=erp24_rep%2Fyii-erp24%2F.git изменение ранжирования, дат и сценариев активных кнопок --- diff --git a/erp24/controllers/crud/EmployeePaymentController.php b/erp24/controllers/crud/EmployeePaymentController.php index 175dd832..e886b565 100755 --- a/erp24/controllers/crud/EmployeePaymentController.php +++ b/erp24/controllers/crud/EmployeePaymentController.php @@ -66,11 +66,7 @@ class EmployeePaymentController extends Controller $currentMonth = date('m'); $currentYear = date('Y'); - // Проверяем, сколько записей у сотрудника за текущий месяц - $hasMultipleRecords = EmployeePayment::find() - ->where(['admin_id' => $id]) - ->andWhere(['EXTRACT(MONTH FROM date)' => $currentMonth, 'EXTRACT(YEAR FROM date)' => $currentYear]) - ->count() > 1; + // Получаем данные сотрудника для заголовка $admin = Admin::findOne($id); @@ -80,14 +76,14 @@ class EmployeePaymentController extends Controller } $dataProvider = new ActiveDataProvider([ - 'query' => EmployeePayment::find()->where(['admin_id' => $id]), + 'query' => EmployeePayment::find()->where(['admin_id' => $id])->orderBy(['date' => SORT_DESC]), ]); return $this->render('view', [ 'admin' => $admin, 'user' => $user, 'dataProvider' => $dataProvider, - 'hasMultipleRecords' => $hasMultipleRecords, + ]); } @@ -99,7 +95,7 @@ class EmployeePaymentController extends Controller */ public function actionCreate($admin_id = null) { - $model = new EmployeePayment(); + $model = new EmployeePayment(['scenario' => 'create']); // Если передан admin_id, устанавливаем его в модели if ($admin_id !== null) { @@ -130,6 +126,7 @@ class EmployeePaymentController extends Controller public function actionUpdate($id) { $model = $this->findModel($id); + $model->scenario = 'update'; $admin = Yii::$app->user->identity; // Проверка на group_id и дату записи @@ -159,17 +156,28 @@ class EmployeePaymentController extends Controller $admin = Yii::$app->user->identity; $adminId = $model->admin_id; + // Определяем месяц и год записи, которую пытаемся удалить + $recordMonth = date('Y-m', strtotime($model->date)); + + // Определяем текущий месяц и год + $currentMonth = date('Y-m'); + // Проверка на group_id и дату записи if ($admin->group_id != 81) { - // Проверка, разрешено ли удаление записи текущего месяца - if (date('Y-m') !== date('Y-m', strtotime($model->date))) { - throw new \yii\web\ForbiddenHttpException('Удаление разрешено только для записей текущего месяца.'); + // Проверка, разрешено ли удаление записи текущего месяца или позже + if ($recordMonth < $currentMonth) { + throw new \yii\web\ForbiddenHttpException('Удаление разрешено только для записей текущего месяца и позже.'); } - // Проверка, чтобы осталась хотя бы одна запись после удаления - $remainingRecords = EmployeePayment::find()->where(['admin_id' => $adminId])->count(); - if ($remainingRecords <= 1) { - throw new \yii\web\ForbiddenHttpException('Нельзя удалить последнюю запись. Должна остаться хотя бы одна запись.'); + // Проверка, чтобы осталась хотя бы одна запись за тот же месяц после удаления + $remainingRecordsForMonth = EmployeePayment::find() + ->where(['admin_id' => $adminId]) + ->andWhere(['EXTRACT(MONTH FROM date)' => date('m', strtotime($model->date))]) + ->andWhere(['EXTRACT(YEAR FROM date)' => date('Y', strtotime($model->date))]) + ->count(); + + if ($remainingRecordsForMonth <= 1) { + throw new \yii\web\ForbiddenHttpException('Нельзя удалить последнюю запись за месяц. Должна остаться хотя бы одна запись за месяц.'); } } @@ -178,6 +186,7 @@ class EmployeePaymentController extends Controller return $this->redirect(['view', 'id' => $adminId]); } + /** * Finds the EmployeePayment model based on its primary key value. * If the model is not found, a 404 HTTP exception will be thrown. diff --git a/erp24/records/EmployeePayment.php b/erp24/records/EmployeePayment.php index efdb189a..cee4ede3 100755 --- a/erp24/records/EmployeePayment.php +++ b/erp24/records/EmployeePayment.php @@ -45,6 +45,7 @@ class EmployeePayment extends \yii\db\ActiveRecord [['creator_id'], 'exist', 'skipOnError' => true, 'targetClass' => Admin::class, 'targetAttribute' => ['creator_id' => 'id']], [['daily_payment'], 'validateDailyPayment'], [['date', 'admin_id'], 'validateUniqueDate'], + ['date', 'validateDateForCreate', 'on' => 'create'], ]; } @@ -75,6 +76,18 @@ class EmployeePayment extends \yii\db\ActiveRecord } } + /** + * Кастомная валидация даты при создании новой записи. + */ + public function validateDateForCreate($attribute, $params) + { + $currentMonthStart = date('Y-m-01'); // Первый день текущего месяца + + if ($this->isNewRecord && $this->$attribute < $currentMonthStart) { + $this->addError($attribute, 'Дата не может быть раньше начала текущего месяца.'); + } + } + public function beforeValidate() { if (get_called_class() === self::class) { diff --git a/erp24/views/crud/employee-payment/view.php b/erp24/views/crud/employee-payment/view.php index 9207e3f8..fd9437e4 100755 --- a/erp24/views/crud/employee-payment/view.php +++ b/erp24/views/crud/employee-payment/view.php @@ -3,12 +3,13 @@ use yii\helpers\Html; use yii\grid\GridView; use yii\widgets\DetailView; +use yii_app\records\EmployeePayment; /* @var $this yii\web\View */ /* @var $admin yii_app\records\Admin */ /* @var $user yii_app\records\Admin */ /* @var $dataProvider yii\data\ActiveDataProvider */ -/* @var $hasMultipleRecords boolean */ + $this->title = $admin->name . ' - ' . $admin->adminGroup->name; $this->params['breadcrumbs'][] = ['label' => 'Оклады', 'url' => ['index']]; @@ -53,15 +54,26 @@ $this->params['breadcrumbs'][] = $this->title; return true; } // Для остальных пользователей разрешено редактирование только записей текущего месяца - return date('Y-m') === date('Y-m', strtotime($model->date)); + return date('Y-m') <= date('Y-m', strtotime($model->date)); }, - 'delete' => function ($model) use ($user, $hasMultipleRecords) { + 'delete' => function ($model) use ($user) { // Если пользователь в группе с group_id = 81, разрешить удаление для всех периодов if ($user->group_id == 81) { return true; } + + // Получаем месяц и год текущей записи + $recordMonth = date('m', strtotime($model->date)); + $recordYear = date('Y', strtotime($model->date)); + + + $hasMultipleRecordsForMonth = EmployeePayment::find() + ->where(['admin_id' => $model->admin_id]) + ->andWhere(['EXTRACT(MONTH FROM date)' => $recordMonth, 'EXTRACT(YEAR FROM date)' => $recordYear]) + ->count() > 1; + // Разрешить удаление только для записей текущего месяца, если их больше одной - return $hasMultipleRecords && date('Y-m') === date('Y-m', strtotime($model->date)); + return $hasMultipleRecordsForMonth && date('Y-m') <= date('Y-m', strtotime($model->date)); }, ], 'urlCreator' => function ($action, $model, $key, $index, $column) use ($admin) {