]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Редактирование записи
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 24 Oct 2024 14:20:45 +0000 (17:20 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 24 Oct 2024 14:20:45 +0000 (17:20 +0300)
erp24/controllers/crud/ClusterAdminController.php
erp24/records/ClusterAdmin.php
erp24/views/crud/cluster-admin/_form.php

index b0dc4540275cb8baeba0825bb23bb7cb0fcc3b9d..8a674145d60065cca94a67caa1006a5d6379db3e 100644 (file)
@@ -126,14 +126,14 @@ class ClusterAdminController extends Controller
     {
         $model = new ClusterAdmin();
 
-        // Проверяем, существует ли указанный кластер
+
         $cluster = Cluster::findOne($cluster_id);
         if (!$cluster) {
             throw new NotFoundHttpException('Кластер не найден.');
         }
 
         if ($this->request->isPost && $model->load($this->request->post())) {
-            $model->cluster_id = $cluster_id; // Устанавливаем cluster_id
+            $model->cluster_id = $cluster_id;
 
             // Ищем активную запись для данного кластера
             $existingRecord = ClusterAdmin::find()
@@ -190,6 +190,10 @@ class ClusterAdminController extends Controller
     {
         $model = $this->findModel($id);
 
+        $admins = ArrayHelper::map(Admin::find()
+            ->select(['id', 'name'])
+            ->where(['IN', 'group_id', [7]])
+            ->all(), 'id', 'name');
 
         $cluster = Cluster::findOne($model->cluster_id);
         if (!$cluster) {
@@ -197,6 +201,67 @@ class ClusterAdminController extends Controller
         }
 
         if ($this->request->isPost && $model->load($this->request->post())) {
+
+            // Проверяем изменение admin_id
+            if ($model->admin_id) {
+                // Если активность = 1
+                if ($model->active == 1) {
+                    $existingActiveRecords = ClusterAdmin::find()
+                        ->where(['admin_id' => $model->admin_id, 'active' => 1])
+                        ->andWhere(['!=', 'cluster_id', $model->cluster_id])
+                        ->all();
+
+                    if (!empty($existingActiveRecords)) {
+                        $conflictCluster = $existingActiveRecords[0];
+                        Yii::$app->session->setFlash('error', 'Этот пользователь ' . $admins[$model->admin_id] . ' уже привязан к кластеру ' . $conflictCluster->cluster_id . ' с активным статусом.');
+                        return $this->redirect(['update', 'id' => $model->id]);
+                    }
+
+                    // Проверка на конфликт с неактивными записями
+                    $existingInactiveRecords = ClusterAdmin::find()
+                        ->where(['admin_id' => $model->admin_id, 'active' => 0])
+                        ->andWhere(['!=', 'cluster_id', $model->cluster_id])
+                        ->all();
+
+                    foreach ($existingInactiveRecords as $record) {
+                        $modelStart = strtotime($model->date_start);
+                        $recordStart = strtotime($record->date_start);
+                        $recordEnd = strtotime($record->date_end);
+
+                        if ($modelStart < $recordStart && $modelStart < $recordEnd) {
+                            Yii::$app->session->setFlash('error', 'Ошибка: активная запись для ' . $admins[$model->admin_id] . 'не может начинаться раньше, чем неактивная запись (' . $record->date_start . ' - ' . $record->date_end . ') для другого кластера.');
+                            return $this->redirect(['update', 'id' => $model->id]);
+                        }
+                    }
+
+                }
+
+                // Если активность = 0
+                if ($model->active == 0) {
+                    $existingInactiveRecords = ClusterAdmin::find()
+                        ->where(['admin_id' => $model->admin_id,])
+                       // ->andWhere(['!=', 'cluster_id', $model->cluster_id])
+                        ->all();
+
+                    foreach ($existingInactiveRecords as $record) {
+                        $modelStart = strtotime($model->date_start);
+                        $modelEnd = strtotime($model->date_end);
+                        $recordStart = strtotime($record->date_start);
+                        $recordEnd = strtotime($record->date_end);
+
+                        if (
+                            ($modelStart > $recordStart && $modelStart < $recordEnd) ||  // Начало новой записи внутри существующей
+                            ($modelEnd > $recordStart && $modelEnd < $recordEnd) ||      // Конец новой записи внутри существующей
+                            ($modelStart <= $recordStart && $modelEnd >= $recordEnd)     // Новая запись полностью охватывает существующую
+                        ) {
+                            Yii::$app->session->setFlash('error', 'Пересечение дат с записью от ' . $record->date_start . ' до ' . $record->date_end . ' для другого кластера.');
+                            return $this->redirect(['update', 'id' => $model->id]);
+                        }
+                    }
+                }
+            }
+
+            // Сохраняем модель, если нет ошибок
             if ($model->save()) {
                 Yii::$app->session->setFlash('success', 'Запись успешно обновлена.');
                 return $this->redirect(['view', 'id' => $model->cluster_id]);
@@ -205,10 +270,7 @@ class ClusterAdminController extends Controller
             }
         }
 
-        $admins = ArrayHelper::map(Admin::find()
-            ->select(['id', 'name'])
-            ->where(['IN', 'group_id', [7]])
-            ->all(), 'id', 'name');
+
 
         $user = Yii::$app->user->identity;
 
@@ -219,7 +281,6 @@ class ClusterAdminController extends Controller
             'user' => $user,
         ]);
     }
-
     /**
      * Deletes an existing ClusterAdmin model.
      * If deletion is successful, the browser will be redirected to the 'index' page.
index f5bd42abef1cb6ba45438caa2aea559789e24d11..e4d87e951d48bca964b52e3e02a71ac07aa7e295 100644 (file)
@@ -65,14 +65,6 @@ class ClusterAdmin extends \yii\db\ActiveRecord
         return $this->hasOne(Admin::class, ['id' => 'admin_id']);
     }
 
-    /**
-     * Устанавливаем значение активности по умолчанию
-     */
-    public function init()
-    {
-        parent::init();
-        if ($this->isNewRecord) {
-            $this->active = 1; // По умолчанию активная запись
-        }
-    }
+
+
 }
\ No newline at end of file
index 54b9f3bad572b9316d8b83e91b581bc525dcdec9..a2135ed2c007afc3b396f320ec74f8b3badbda9e 100644 (file)
@@ -15,60 +15,96 @@ use yii_app\records\ClusterAdmin;
 
 ?>
 
-<div class="cluster-admin-form">
-    <?php if (Yii::$app->session->hasFlash('error')) { ?>
-        <div class="alert alert-danger" role="alert">
-            <?= Yii::$app->session->getFlash('error') ?>
-        </div>
-    <?php } ?>
+    <div class="cluster-admin-form">
+        <?php if (Yii::$app->session->hasFlash('error')) { ?>
+            <div class="alert alert-danger" role="alert">
+                <?= Yii::$app->session->getFlash('error') ?>
+            </div>
+        <?php } ?>
 
-    <div class="col-6">
-        <?php $form = ActiveForm::begin(); ?>
+        <div class="col-6">
+            <?php $form = ActiveForm::begin(); ?>
+
+
+            <div class="form-group">
+                <label>Куст</label>
+                <input type="text" class="form-control" value="<?= Html::encode($cluster->name) ?>" readonly>
+                <?= $form->field($model, 'cluster_id')->hiddenInput(['value' => $cluster->id])->label(false) ?>
+            </div>
+
+            <?= $form->field($model, 'admin_id')->widget(Select2::class, [
+                'data' => $admins,
+                'options' => ['placeholder' => 'Выберите кустового...'],
+                'pluginOptions' => [
+                    'allowClear' => true
+                ],
+            ]); ?>
+
+
+            <?= $form->field($model, 'active')->checkbox([
+                'label' => 'Активность',
+                'checked' => $model->isNewRecord ? true : boolval($model->active),
+                'id' => 'active-checkbox',
+            ]) ?>
 
-        <!-- Отображаем только имя кластера и скрытое поле для передачи cluster_id -->
-        <div class="form-group">
-            <label>Куст</label>
-            <input type="text" class="form-control" value="<?= Html::encode($cluster->name) ?>" readonly>
-            <?= $form->field($model, 'cluster_id')->hiddenInput(['value' => $cluster->id])->label(false) ?>
-        </div>
 
-        <?= $form->field($model, 'admin_id')->widget(Select2::class, [
-            'data' => $admins,
-            'options' => ['placeholder' => 'Выберите кустового...'],
-            'pluginOptions' => [
-                'allowClear' => true
-            ],
-        ]); ?>
-
-        <!-- Чекбокс для активности -->
-        <?= $form->field($model, 'active')->checkbox([
-            'label' => 'Активность',
-            'checked' => $model->isNewRecord ? true : boolval($model->active),
-        ]) ?>
-
-    <!--    <?php /*if (in_array($user->group_id, [81])): */?>
-            <?php /*= $form->field($model, 'date_start')->input('date', [
+            <?= $form->field($model, 'date_start')->input('date', [
                 'value' => $model->date_start ?? date('Y-m-d'),
-            ]) */?>
-        <?php /*else: */?>
-            <?php /*= $form->field($model, 'date_start')->hiddenInput(['value' => date('Y-m-d')])->label(false) */?>
-        --><?php /*endif; */?>
-
-        <?= $form->field($model, 'date_start')->input('date', [
-            'value' => $model->date_start ?? date('Y-m-d'),
-        ]) ?>
-
-        <?= $form->field($model, 'date_end')->input('date', [
-            'value' => $model->date_end ?? date('Y-m-d'),
-        ]) ?>
-
-        <div class="form-group">
-            <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
-            <?= Html::a('Отмена', ['index'], ['class' => 'btn btn-danger my-2']) ?>
-        </div>
+            ]) ?>
+
 
-        <?php ActiveForm::end(); ?>
+            <?= $form->field($model, 'date_end')->input('date', [
+                'value' => $model->date_end ?? date('Y-m-d'),
+                'id' => 'date-end-field',
+                'style' => $model->active ? 'display: none;' : '',
+            ]) ?>
 
+            <div class="form-group">
+                <?= Html::submitButton('Сохранить', ['class' => 'btn btn-success']) ?>
+                <?= Html::a('Отмена', ['index'], ['class' => 'btn btn-danger my-2']) ?>
+            </div>
 
+            <?php ActiveForm::end(); ?>
+
+        </div>
     </div>
-</div>
\ No newline at end of file
+
+<?php
+
+$js = <<<JS
+    function toggleDateEndField() {
+        var isChecked = $('#active-checkbox').is(':checked');
+        var currentDate = new Date().toISOString().split('T')[0]; 
+
+        if (isChecked) {
+            $('#date-end-field').val('2100-01-01'); 
+            $('#date-end-field').hide(); 
+            $('label[for="date-end-field"]').hide(); 
+        } else {
+            $('#date-end-field').val(currentDate); 
+            $('#date-end-field').show(); 
+            $('label[for="date-end-field"]').show(); 
+        }
+    }
+    
+    function initDateEndField() {
+    var isChecked = $('#active-checkbox').is(':checked');
+    if (isChecked) {
+           
+            $('label[for="date-end-field"]').hide(); 
+        } else {
+           
+            $('label[for="date-end-field"]').show(); 
+        }
+    }
+
+    
+    $('#active-checkbox').on('change', function() {
+        toggleDateEndField();
+    });
+
+    initDateEndField();
+JS;
+
+$this->registerJs($js);
+?>
\ No newline at end of file