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;
$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',
'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 = [];
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;
}
}
}
}
- 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,
*/
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', 'Не удалось удалить магазин.');
$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', 'Магазин успешно добавлен в куст.');
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) {
$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);
}
}
}
+ 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.