]> gitweb.erp-flowers.ru Git - erp24_rep/yii-erp24/.git/commitdiff
Перенос кустовых
authorfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 24 Oct 2024 19:11:05 +0000 (22:11 +0300)
committerfomichev <vladimir.fomichev@erp-flowers.ru>
Thu, 24 Oct 2024 19:11:05 +0000 (22:11 +0300)
erp24/controllers/crud/ClusterAdminController.php
erp24/views/crud/cluster-admin/index.php

index fbe70593559c7e2ad0bb18a191d02bd426a94fbe..fd6b62d0586bfe86d153053bb5123a0e5d85dc90 100644 (file)
@@ -52,6 +52,12 @@ class ClusterAdminController extends Controller
             ->asArray()
             ->all();
 
+        // Получаем список администраторов
+        $admins = ArrayHelper::map(Admin::find()
+            ->select(['id', 'name'])
+            ->where(['IN', 'group_id', [7]])
+            ->all(), 'id', 'name');
+
         // Создаем массив для сопоставления кустов и их статуса
         $clusterMapping = [];
         foreach ($clusters as $cluster) {
@@ -71,13 +77,13 @@ class ClusterAdminController extends Controller
                     if ($adminRecord['active'] == 1) {
                         $clusterMapping[$cluster['id']]['admin'] = $adminRecord['admin']['name'] . ' (' . $adminRecord['admin_id'] . ')';
                         $clusterMapping[$cluster['id']]['status'] = 'Активная запись';
+                        $clusterMapping[$cluster['id']]['admin_id'] = $adminRecord['admin_id']; // Добавляем admin_id
                         $clusterMapping[$cluster['id']]['hasActive'] = true;
                         break;
                     }
                 }
             }
 
-
             if (!$clusterMapping[$cluster['id']]['hasActive'] && $clusterMapping[$cluster['id']]['hasAny']) {
                 $clusterMapping[$cluster['id']]['status'] = 'Нет активных записей';
             }
@@ -85,9 +91,64 @@ class ClusterAdminController extends Controller
 
         return $this->render('index', [
             'clusterMapping' => $clusterMapping,
+            'clustersList' => $clusters,
+            'admins' => $admins, // Передаем список администраторов
         ]);
     }
 
+    public function actionMoveAdmin()
+    {
+        $newAdminId = Yii::$app->request->post('admin_id');
+        $clusterId = Yii::$app->request->post('cluster_id');
+        $currentDate = date('Y-m-d H:i:s');
+
+        $currentClusterAdmin = ClusterAdmin::find()
+            ->where(['cluster_id' => $clusterId, 'active' => 1])
+            ->one();
+
+        $oldClusterAdmin = ClusterAdmin::find()
+            ->where(['admin_id' => $newAdminId, 'active' => 1])
+            ->one();
+
+        if ($currentClusterAdmin) {
+            // Завершаем старую запись
+            $currentClusterAdmin->active = 0;
+            $currentClusterAdmin->date_end = $currentDate;
+
+            if (!$currentClusterAdmin->save(false)) {
+                return $this->asJson(['success' => false, 'message' => 'Администратор не найден или уже не активен.']);
+            }
+            ClusterManagerService::clearClusterManagerStores($currentClusterAdmin->cluster_id, $currentClusterAdmin->admin_id);
+        }
+        if ($oldClusterAdmin) {
+            // Завершаем старую запись
+            $oldClusterAdmin->active = 0;
+            $oldClusterAdmin->date_end = $currentDate;
+
+            if (!$oldClusterAdmin->save(false)) {
+                return $this->asJson(['success' => false, 'message' => 'Администратор не найден или уже не активен.']);
+            }
+            ClusterManagerService::clearClusterManagerStores($oldClusterAdmin->cluster_id, $oldClusterAdmin->admin_id);
+        }
+
+
+            // Создаем новую запись
+            $newClusterAdmin = new ClusterAdmin();
+            $newClusterAdmin->admin_id = $newAdminId;
+            $newClusterAdmin->cluster_id = $clusterId;
+            $newClusterAdmin->date_start = $currentDate;
+            $newClusterAdmin->active = 1;
+
+
+
+            if (!$newClusterAdmin->save(false)) {
+                return $this->asJson(['success' => false, 'message' => 'Администратор не найден или уже не активен.']);
+            }
+        ClusterManagerService::syncClusterManagers($newClusterAdmin->cluster_id, $newClusterAdmin->admin_id);
+        return $this->asJson(['success' => true]);
+
+    }
+
     /**
      * Displays a single ClusterAdmin model.
      * @param int $id ID записи
@@ -268,9 +329,9 @@ 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])
@@ -304,12 +365,12 @@ class ClusterAdminController extends Controller
 
 
                 if ($model->active == 0) {
-                    $existingInactiveRecords = ClusterAdmin::find()
+                    $existingRecords = ClusterAdmin::find()
                         ->where(['admin_id' => $model->admin_id,])
                         ->andWhere(['!=', 'id', $model->id])
                         ->all();
 
-                    foreach ($existingInactiveRecords as $record) {
+                    foreach ($existingRecords as $record) {
                         $modelStart = strtotime($model->date_start);
                         $modelEnd = strtotime($model->date_end);
                         $recordStart = strtotime($record->date_start);
index aacb358a3cbef841a1dfc5511f28c4eeab256eb7..64b6aad55abc7f8f25e594b48d1381fc8c8a399a 100644 (file)
 <?php
 
-use yii\grid\GridView;
+
+use kartik\select2\Select2;
+use yii\helpers\ArrayHelper;
 use yii\helpers\Html;
+use yii\grid\GridView;
 
 /* @var $this yii\web\View */
 /* @var $clusterMapping array */
+/* @var $clustersList array */
+/* @var $admins array */
 
-$this->title = 'Привязка Куст-Кустовой';
-$this->params['breadcrumbs'][] = $this->title;
 ?>
-<div class="cluster-admin-index p-4">
 
-    <h1><?= Html::encode($this->title) ?></h1>
+    <div class="cluster-admin-index p-4">
 
-    <?= GridView::widget([
-        'dataProvider' => new \yii\data\ArrayDataProvider([
-            'allModels' => $clusterMapping,
-            'pagination' => [
-                'pageSize' => 20,
-            ],
-        ]),
-        'columns' => [
-            [
-                'attribute' => 'name',
-                'label' => 'Куст',
-                'value' => function ($model) {
-                    return Html::encode($model['name']);
-                },
-                'format' => 'raw',
-            ],
-            [
-                'attribute' => 'admin',
-                'label' => 'Кустовой',
-                'value' => function ($model) {
-                    if ($model['status'] === 'Нет записей') {
-                        return Html::tag('span', 'Нет записей', ['style' => 'color: red;']);
-                    } elseif ($model['status'] === 'Нет активных записей') {
-                        return Html::tag('span', 'Нет активных записей', ['style' => 'color: orange;']);
-                    } else {
-                        return Html::encode($model['admin']);
-                    }
-                },
-                'format' => 'raw',
-            ],
-            [
-                'class' => 'yii\grid\ActionColumn',
-                'template' => '{view} {create}',
-                'buttons' => [
-                    'view' => function ($url, $model, $key) {
-                        return Html::a('Просмотреть', ['view', 'id' => $key], ['class' => 'btn btn-primary']);
+        <h1><?= Html::encode($this->title) ?></h1>
+
+        <?= GridView::widget([
+            'dataProvider' => new \yii\data\ArrayDataProvider([
+                'allModels' => $clusterMapping,
+                'pagination' => [
+                    'pageSize' => 20,
+                ],
+            ]),
+            'columns' => [
+                [
+                    'attribute' => 'name',
+                    'label' => 'Куст',
+                    'value' => function ($model) {
+                        return Html::encode($model['name']);
                     },
-                    'create' => function ($url, $model, $key) {
-                        // Показываем кнопку только если нет записей для кластера
+                    'format' => 'raw',
+                ],
+                [
+                    'attribute' => 'admin',
+                    'label' => 'Кустовой',
+                    'value' => function ($model) {
                         if ($model['status'] === 'Нет записей') {
-                            return Html::a('Создать новую привязку', ['create', 'cluster_id' => $key], ['class' => 'btn btn-success']);
+                            return Html::tag('span', 'Нет записей', ['style' => 'color: red;']);
+                        } elseif ($model['status'] === 'Нет активных записей') {
+                            return Html::tag('span', 'Нет активных записей', ['style' => 'color: orange;']);
+                        } else {
+                            return Html::encode($model['admin']);
+                        }
+                    },
+                    'format' => 'raw',
+                ],
+                [
+                    'attribute' => 'transfer',
+                    'label' => 'Назначить кустового',
+                    'format' => 'raw',
+                    'value' => function ($model, $key) use ($admins) {
+                        // Проверяем, существует ли admin_id в массиве
+                        $adminId = isset($model['admin_id']) ? $model['admin_id'] : null;
+
+                        // Если есть привязка, показываем имя, иначе показываем Select2
+                        if ($model['status'] !== 'Нет записей') {
+                            return Select2::widget([
+                                'name' => 'admin_id_' . ($adminId ?? 'new'),  // Если admin_id не задан, используем 'new'
+                                'data' => $admins,  // Список администраторов
+                                'value' => $adminId,  // Текущий привязанный администратор или null
+                                'options' => [
+                                    'placeholder' => 'Выберите администратора...',
+                                    'class' => 'form-control transfer-select',
+                                    'data-id' => $key,
+                                ],
+                                'pluginOptions' => [
+                                    'allowClear' => true,
+                                ],
+                            ]);
                         }
                         return null;
                     },
                 ],
+                [
+                    'class' => 'yii\grid\ActionColumn',
+                    'template' => '{view} {create}',
+                    'buttons' => [
+                        'view' => function ($url, $model, $key) {
+                            return Html::a('Просмотреть', ['view', 'id' => $key], ['class' => 'btn btn-primary']);
+                        },
+                        'create' => function ($url, $model, $key) {
+                            // Показываем кнопку только если нет записей для кластера
+                            if ($model['status'] === 'Нет записей') {
+                                return Html::a('Создать новую привязку', ['create', 'cluster_id' => $key], ['class' => 'btn btn-success']);
+                            }
+                            return null;
+                        },
+                    ],
+                ],
             ],
-        ],
-    ]); ?>
+        ]); ?>
+
+    </div>
+
+<?php
+
+$this->registerJs("
+    $('.transfer-select').on('change', function () {
+    let adminId = $(this).val();
+    let clusterId = $(this).data('id');
 
-</div>
\ No newline at end of file
+    if (adminId) {
+        $.post({
+            url: 'move-admin',  // Укажите правильный маршрут для назначения администратора
+            data: { admin_id: adminId, cluster_id: clusterId },
+            success: function(response) {
+                if (response.success) {
+                    alert('Администратор успешно назначен');
+                   window.location.reload();
+                } else {
+                    alert('Ошибка при назначении администратора');
+                }
+            },
+            error: function() {
+                alert('Ошибка при запросе');
+            }
+        });
+    }
+});
+");
+?>
\ No newline at end of file