From: vladfo Date: Fri, 27 Sep 2024 09:46:12 +0000 (+0300) Subject: Изменения в actionViewAll X-Git-Tag: 1.5~1^2~11 X-Git-Url: https://gitweb.erp-flowers.ru/?a=commitdiff_plain;h=83be81caccbee1d67a5285b8c7e45804deab0b6d;p=erp24_rep%2Fyii-erp24%2F.git Изменения в actionViewAll --- diff --git a/erp24/controllers/ClusterLinkEditController.php b/erp24/controllers/ClusterLinkEditController.php index 13447637..42be4a7b 100644 --- a/erp24/controllers/ClusterLinkEditController.php +++ b/erp24/controllers/ClusterLinkEditController.php @@ -4,6 +4,7 @@ namespace app\controllers; use Yii; use yii\data\ArrayDataProvider; +use yii\debug\models\search\Log; use yii\filters\AccessControl; use yii\helpers\ArrayHelper; use yii_app\helpers\DateHelper; @@ -97,23 +98,14 @@ class ClusterLinkEditController extends Controller $currentDate = Yii::$app->request->get('ClusterSearch')['date'] ?? date('Y-m-d'); + $earliestDateFrom = '2023-05-19'; - $storeData = StoreDynamic::find() - ->select([ - 'value_int AS cluster_id', - 'string_agg(store_id::text, \',\') AS stores', - 'COUNT(store_id) AS store_count', - 'MAX(date_from) AS last_update' - ]) - ->where(['active' => 1]) - ->andWhere(['<=', 'date_from', $currentDate]) - ->groupBy('value_int') - ->asArray() - ->all(); + $specialDate = '2024-09-12'; + + if (strtotime($currentDate) < strtotime($earliestDateFrom)) { - if (empty($storeData)) { $storeData = StoreDynamic::find() ->select([ 'value_int AS cluster_id', @@ -121,16 +113,39 @@ class ClusterLinkEditController extends Controller 'COUNT(store_id) AS store_count', 'MIN(date_from) AS first_update' ]) + ->where(['<', 'date_from', $specialDate]) + ->andWhere(['>', 'date_to', $specialDate]) + ->andWhere(['category' => 1]) + ->groupBy('value_int') + ->asArray() + ->all(); + $lastUpdates = array_fill_keys(array_column($storeData, 'cluster_id'), $earliestDateFrom); + } else { + + $storeData = StoreDynamic::find() + ->select([ + 'value_int AS cluster_id', + 'string_agg(store_id::text, \',\') AS stores', + 'COUNT(store_id) AS store_count', + 'MAX(date_from) AS last_update' + ]) + ->where(['active' => 1]) + ->andWhere(['category' => 1]) + ->andWhere(['<=', 'date_from', $currentDate]) + ->andWhere(['>', 'date_to', $currentDate]) ->groupBy('value_int') ->asArray() ->all(); + + $lastUpdates = ArrayHelper::map($storeData, 'cluster_id', 'last_update'); + } $storeLists = ArrayHelper::map($storeData, 'cluster_id', 'stores'); // List of stores for each cluster $storeCounts = ArrayHelper::map($storeData, 'cluster_id', 'store_count'); - $lastUpdates = ArrayHelper::map($storeData, 'cluster_id', 'last_update'); + $clusterToManager = []; @@ -139,19 +154,19 @@ class ClusterLinkEditController extends Controller foreach ($storeData as $store) { $clusterId = $store['cluster_id']; - $storeIds = explode(',', $store['stores']); // Stores attached to cluster + $storeIds = explode(',', $store['stores']); $assignedManager = null; foreach ($clusterManagers as $manager) { if (!empty($manager->store_arr)) { - $managerStores = explode(',', $manager->store_arr); // Stores attached to manager - $intersection = array_intersect($storeIds, $managerStores); // Find intersection + $managerStores = explode(',', $manager->store_arr); + $intersection = array_intersect($storeIds, $managerStores); if (count($intersection) >= count($storeIds) / 2) { $assignedManager = $manager->name; - $matchedManagers[] = $manager->id; // Add manager to list of used - break; // Stop searching for this cluster + $matchedManagers[] = $manager->id; + break; } } } @@ -177,18 +192,6 @@ class ClusterLinkEditController extends Controller } - foreach ($storeData as $store) { - $clusterId = $store['cluster_id']; - $calendar = StoreDynamic::find() - ->where(['value_int' => $clusterId]) - ->andWhere(['<=', 'date_from', $currentDate]) - ->orderBy(['date_from' => SORT_DESC]) - ->one(); - - if ($calendar) { - $lastUpdates[$clusterId] = $calendar->date_from; - } - } return $this->render('/cluster_link_edit/index', [ 'searchModel' => $searchModel, @@ -267,113 +270,155 @@ class ClusterLinkEditController extends Controller */ public function actionViewAll($id, $manager = null, $date = null) { - // Получаем модель кластера по ID + $model = $this->findModel($id); - // Если $date не передан в запросе, используем текущую дату - $currentDate = $date ?? date('Y-m-d'); - // Ограничение на минимальную дату для выборки - $minDate = '2024-09-12'; + $requestDate = $date ?? date('Y-m-d'); - // Проверка, если выбранная дата меньше 12 сентября 2024 года - if (strtotime($currentDate) < strtotime($minDate)) { - $currentDate = $minDate; // Присваиваем минимально допустимую дату - } - // Поиск записей в ClusterCalendar для указанного кластера - $stores = ClusterCalendar::find() - ->where(['cluster_id' => $id]) - ->andWhere(['<=', 'date_from', $currentDate]) - ->andWhere(['>', 'date_to', $currentDate]) - ->andWhere(['>=', 'date_from', $minDate]) - ->all(); + $specialDate = '2024-09-12'; + $earliestDateFrom = '2023-05-19'; + + + + if (strtotime($requestDate) < strtotime($earliestDateFrom)) { + + $stores = StoreDynamic::find() + ->select([ + 'id', + 'store_id', + 'value_int AS cluster_id', + 'date_from', + 'date_to', + 'active', + 'category' + ]) + ->where(['value_int' => $id]) + ->andWhere(['>', 'date_to', $specialDate]) + ->andWhere(['<', 'date_from', $specialDate]) + ->andWhere(['category' => 1]) + ->asArray() + ->all(); + } else { + + $stores = StoreDynamic::find() + ->select([ + 'id', + 'store_id', + 'value_int AS cluster_id', + 'date_from', + 'date_to', + 'active', + 'category' + ]) + ->where(['value_int' => $id]) + ->andWhere(['<=', 'date_from', $requestDate]) + ->andWhere(['>', 'date_to', $requestDate]) + ->andWhere(['active' => 1]) + ->andWhere(['category' => 1]) + ->asArray() + ->all(); + } - // Получаем список всех кустов для перевода + //var_dump($stores); $clustersList = ArrayHelper::map(Cluster::find()->all(), 'id', 'name'); - // Получение всех магазинов из таблицы CityStore + $storesData = CityStore::find() ->select(['id', 'name']) ->indexBy('id') ->asArray() ->all(); - // Создание справочника: id магазина => имя магазина + $storeNames = ArrayHelper::map($storesData, 'id', 'name'); - // Формируем провайдер данных для отображения магазинов + $dataProvider = new ArrayDataProvider([ 'allModels' => $stores, ]); - // Передача данных в представление + return $this->render('/cluster_link_edit/view-all', [ 'model' => $model, 'dataProvider' => $dataProvider, 'clustersList' => $clustersList, - 'currentDate' => $currentDate, + 'currentDate' => $requestDate, 'clusterManager' => $manager, 'storeNames' => $storeNames, ]); } public function actionMoveStore() { - $storeId = Yii::$app->request->post('store_id'); + $recordId = Yii::$app->request->post('id'); $newClusterId = Yii::$app->request->post('new_cluster_id'); $currentDate = date('Y-m-d'); - // Найти запись в ClusterCalendar по store_id и актуальной дате - $calendarEntry = ClusterCalendar::find() - ->where(['id' => $storeId]) - ->andWhere(['>=', 'date_from', '2024-09-12']) - ->andWhere(['date_to' => '2100-01-01']) + + $dynamicEntry = StoreDynamic::find() + ->select([ + 'id', + 'store_id', + 'value_int AS cluster_id', + 'date_from', + 'date_to', + 'active', + 'category' + ]) + ->where(['id' => $recordId]) + ->andWhere(['<=', 'date_from', $currentDate]) + ->andWhere(['>', 'date_to', $currentDate]) + ->andWhere(['active' => 1]) + ->one(); - if ($calendarEntry) { - // Обновляем текущую запись — закрываем ее с текущей датой - $calendarEntry->date_to = $currentDate; - $calendarEntry->save(false); - - // Создаем новую запись для нового кластера - $newCalendarEntry = new ClusterCalendar(); - $newCalendarEntry->cluster_id = $newClusterId; - $newCalendarEntry->value_type = 'int'; - $newCalendarEntry->value_int = $calendarEntry->value_int; - $newCalendarEntry->date_from = $currentDate; - $newCalendarEntry->category_id = 1; - $newCalendarEntry->date_to = '2100-01-01'; - $newCalendarEntry->created_admin_id = Yii::$app->user->id; - $newCalendarEntry->save(false); - - // Синхронизируем данные менеджеров после переноса - $this->syncClusterManagers(); + if ($dynamicEntry) { + + $dynamicEntry->date_to = $currentDate; + $dynamicEntry->active = 0; + $dynamicEntry->save(false); + + + $newDynamicEntry = new StoreDynamic(); + $newDynamicEntry->value_type = 'integer'; + $newDynamicEntry->value_int = $newClusterId; + $newDynamicEntry->store_id = $dynamicEntry->store_id; + $newDynamicEntry->date_from = $currentDate; + $newDynamicEntry->date_to = '2100-01-01'; + $newDynamicEntry->active = 1; + $newDynamicEntry->category = 1; + $newDynamicEntry->save(false); + + // $this->syncClusterManagers(); + $this->updateStoreCluster($dynamicEntry->store_id, $newClusterId); return $this->asJson(['success' => true]); } - return $this->asJson(['success' => false]); + return $this->asJson(['success' => false, 'message' => 'Record not found']); } public function actionDeleteStore($id, $cluster_id) { $currentDate = date('Y-m-d'); - // Найти запись в ClusterCalendar по store_id и актуальной дате - $calendarEntry = ClusterCalendar::find() - ->where(['id' => $id, 'cluster_id' => $cluster_id]) - ->andWhere(['>=', 'date_from', '2024-09-12']) - ->andWhere(['date_to' => '2100-01-01']) + + $dynamicEntry = StoreDynamic::find() + ->where(['id' => $id, 'value_int' => $cluster_id]) + ->andWhere(['<=', 'date_from', $currentDate]) + ->andWhere(['>', 'date_to', $currentDate]) ->one(); - if ($calendarEntry) { - // Закрываем текущую запись - $calendarEntry->date_to = $currentDate; - $calendarEntry->save(false); + if ($dynamicEntry) { + + $dynamicEntry->date_to = $currentDate; + $dynamicEntry->active = 0; + $dynamicEntry->save(false); - // Синхронизируем данные менеджеров после удаления - $this->syncClusterManagers(); + // $this->syncClusterManagers(); + $this->updateStoreCluster($dynamicEntry->store_id); Yii::$app->session->setFlash('success', 'Магазин успешно удален из куста.'); } else { Yii::$app->session->setFlash('error', 'Не удалось удалить магазин.'); @@ -387,32 +432,34 @@ class ClusterLinkEditController extends Controller $storeId = Yii::$app->request->post('store_id'); $currentDate = date('Y-m-d'); - // Проверить, есть ли уже активная запись для данного магазина - $existingEntry = ClusterCalendar::find() - ->where(['value_int' => $storeId]) - ->andWhere(['>=', 'date_from', '2024-09-12']) - ->andWhere(['date_to' => '2100-01-01']) + + $existingEntry = StoreDynamic::find() + ->where(['store_id' => $storeId]) + ->andWhere(['<=', 'date_from', $currentDate]) + ->andWhere(['>', 'date_to', $currentDate]) + ->andWhere(['active' => 1]) ->one(); if ($existingEntry) { - // Если есть активная запись, закрываем ее, установив date_to текущей датой + $existingEntry->date_to = $currentDate; + $existingEntry->active = 0; $existingEntry->save(false); } - // Создаем новую запись для кластера - $newCalendarEntry = new ClusterCalendar(); - $newCalendarEntry->cluster_id = $id; - $newCalendarEntry->value_type = 'int'; - $newCalendarEntry->value_int = $storeId; - $newCalendarEntry->date_from = $currentDate; - $newCalendarEntry->date_to = '2100-01-01'; - $newCalendarEntry->category_id = 1; - $newCalendarEntry->created_admin_id = Yii::$app->user->id; - $newCalendarEntry->save(false); - // Синхронизируем данные менеджеров после добавления - $this->syncClusterManagers(); + $newDynamicEntry = new StoreDynamic(); + $newDynamicEntry->value_int = $id; + $newDynamicEntry->value_type = 'integer'; + $newDynamicEntry->store_id = $storeId; + $newDynamicEntry->date_from = $currentDate; + $newDynamicEntry->date_to = '2100-01-01'; + $newDynamicEntry->active = 1; + $newDynamicEntry->category = 1; + $newDynamicEntry->save(false); + + $this->updateStoreCluster($storeId,$id); + // $this->syncClusterManagers(); Yii::$app->session->setFlash('success', 'Магазин успешно добавлен в куст.'); @@ -421,25 +468,25 @@ class ClusterLinkEditController extends Controller protected function syncClusterManagers() { - // Получаем кустовых директоров из таблицы Admin + $clusterManagers = Admin::find() ->select(['id', 'store_arr']) ->where(['group_id' => 7, 'group_name' => 'Кустовой директор']) ->indexBy('id') ->all(); - // Делаем выборку данных из ClusterCalendar - $storeData = ClusterCalendar::find() - ->select(['cluster_id', "string_agg(value_int::text, ',') AS stores"]) - ->where(['date_to' => '2100-01-01']) - ->groupBy('cluster_id') + + $storeData = StoreDynamic::find() + ->select(['value_int AS cluster_id', "string_agg(store_id::text, ',') AS stores"]) + ->where(['active' => 1]) + ->groupBy('value_int') ->asArray() ->all(); - // Преобразуем данные о магазинах в удобный формат + $storeLists = ArrayHelper::map($storeData, 'cluster_id', 'stores'); - // Сопоставляем менеджеров и кусты по спискам магазинов + foreach ($storeLists as $clusterId => $stores) { $storeIds = explode(',', $stores); foreach ($clusterManagers as $manager) { @@ -447,9 +494,9 @@ class ClusterLinkEditController extends Controller $managerStores = explode(',', $manager->store_arr); $intersection = array_intersect($storeIds, $managerStores); - // Если большинство магазинов совпадают, менеджер назначается на куст + if (count($intersection) >= count($storeIds) / 2) { - // Обновляем список магазинов менеджера + $manager->store_arr = implode(',', array_unique(array_merge($managerStores, $storeIds))); $manager->save(false); } @@ -458,6 +505,26 @@ class ClusterLinkEditController extends Controller } } + protected function updateStoreCluster($storeId, $clusterId = 0) + { + + $storeRecord = CityStore::findOne(['id' => $storeId]); + + if (!$storeRecord) { + return false; + } + + + $storeRecord->cluster_id = $clusterId; + + + if ($storeRecord->save(false)) { + return true; + } else { + return false; + } + } + /** * Updates an existing Cluster model. diff --git a/erp24/views/charts-for-management/index.php b/erp24/views/charts-for-management/index.php index f8827536..157dbc41 100644 --- a/erp24/views/charts-for-management/index.php +++ b/erp24/views/charts-for-management/index.php @@ -733,8 +733,9 @@ $this->registerJs(<< { diff --git a/erp24/views/cluster_link_edit/view-all.php b/erp24/views/cluster_link_edit/view-all.php index f0671f3f..dc4289e1 100644 --- a/erp24/views/cluster_link_edit/view-all.php +++ b/erp24/views/cluster_link_edit/view-all.php @@ -62,7 +62,7 @@ $availableStores = array_filter($storeNames, function ($storeId) use ($storesInC 'attribute' => 'name', 'label' => 'Наименование магазина', 'value' => function ($store) use ($storeNames) { - return $storeNames[$store['value_int']] ?? 'Магазин не найден'; + return $storeNames[$store['store_id']] ?? 'Магазин не найден'; }, ], [ @@ -82,7 +82,7 @@ $availableStores = array_filter($storeNames, function ($storeId) use ($storesInC } return Html::dropDownList('cluster_id', $store['cluster_id'], $clustersList, [ 'class' => 'form-control', - 'data-store-id' => $store['id'], + 'data-id' => $store['id'], 'options' => [ $model->id => ['Selected' => true], // Текущий куст ], diff --git a/erp24/web/js/cluster-link-edit/view-all.js b/erp24/web/js/cluster-link-edit/view-all.js index 3fba472a..1d4a63bc 100644 --- a/erp24/web/js/cluster-link-edit/view-all.js +++ b/erp24/web/js/cluster-link-edit/view-all.js @@ -1,5 +1,5 @@ $('select[name="cluster_id"]').change(function() { - let storeId = $(this).data('store-id'); + let storeId = $(this).data('id'); let newClusterId = $(this).val(); // Получаем имя магазина из первого столбца той же строки @@ -10,10 +10,10 @@ $('select[name="cluster_id"]').change(function() { // Отправляем данные на сервер после подтверждения $.post({ url: 'move-store', - data: { store_id: storeId, new_cluster_id: newClusterId }, + data: { id: storeId, new_cluster_id: newClusterId }, success: function() { // Если магазин был успешно перемещен, удаляем его строку из таблицы - $('select[name="cluster_id"][data-store-id="' + storeId + '"]').closest('tr').remove(); + $('select[name="cluster_id"][data-id="' + storeId + '"]').closest('tr').remove(); alert('Магазин успешно переведен в новый куст'); }, error: function() {