use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii_app\records\PlanStore;
+use yii_app\records\StoreDynamic;
/**
* ClusterController implements the CRUD actions for Cluster model.
*/
public function actionIndex()
{
+ // Поиск моделей кустов
$searchModel = new ClusterSearch();
$dataProvider = $searchModel->search($this->request->queryParams);
+ // Получаем кустовых директоров из таблицы Admin
+ $clusterManagers = Admin::find()
+ ->select(['name', 'id', 'store_arr'])
+ ->where(['group_id' => 7, 'group_name' => 'Кустовой директор']) // Условия для группы кустовых директоров
+ ->indexBy('id') // Индексируем по идентификатору
+ ->all();
+
+ // Данные по динамике магазинов, связанных с кустами
+ $storeData = StoreDynamic::find()
+ ->select([
+ 'value_int AS cluster_id',
+ 'string_agg(store_id::text, \',\') AS stores', // Используем string_agg для PostgreSQL
+ 'COUNT(store_id) AS store_count',
+ 'MAX(date_from) AS last_update'
+ ])
+ ->where(['active' => 1])
+ ->groupBy('value_int') // Группируем по идентификатору куста
+ ->asArray()
+ ->all();
+
+ // Преобразуем данные о магазинах в удобный формат
+ $storeLists = ArrayHelper::map($storeData, 'cluster_id', 'stores'); // Список магазинов для каждого куста
+
+ // Инициализируем массив соответствий кустов и менеджеров
+ $clusterToManager = [];
+ $matchedManagers = [];
+
+ // Сопоставляем менеджеров и кусты по спискам магазинов
+ foreach ($storeData as $store) {
+ $clusterId = $store['cluster_id'];
+ $storeIds = explode(',', $store['stores']); // Магазины, прикрепленные к кусту
+ $assignedManager = null;
+
+ foreach ($clusterManagers as $manager) {
+ if (!empty($manager->store_arr)) {
+ $managerStores = explode(',', $manager->store_arr); // Магазины, прикрепленные к менеджеру
+ $intersection = array_intersect($storeIds, $managerStores); // Находим пересечение
+
+ // Если большинство магазинов совпадают, то менеджер сопоставляется с кустом
+ if (count($intersection) >= count($storeIds) / 2) {
+ $assignedManager = $manager->name;
+ $matchedManagers[] = $manager->id; // Добавляем менеджера в список использованных
+ break; // Останавливаем поиск для этого куста
+ }
+ }
+ }
+
+ // Если менеджер не найден по магазину, оставляем его "не назначенным"
+ $clusterToManager[$clusterId] = $assignedManager ?? 'Не назначен';
+ }
+
+ // Проверка на оставшегося менеджера и куст
+ $unassignedClusters = array_filter($clusterToManager, fn($manager) => $manager === 'Не назначен'); // Кусты без менеджера
+ $unassignedManagers = array_filter($clusterManagers, fn($manager) => !in_array($manager->id, $matchedManagers)); // Менеджеры без кластера
+
+ // Если остался один менеджер и один куст, их нужно сопоставить
+ if (count($unassignedClusters) === 1 && count($unassignedManagers) === 1) {
+ $unassignedClusterId = array_key_first($unassignedClusters); // ID куста без менеджера
+ $unassignedManager = reset($unassignedManagers); // Менеджер без куста
+ $clusterToManager[$unassignedClusterId] = $unassignedManager->name; // Назначаем последнего менеджера на куст
+
+
+ }
+
+ // Передача данных в представление
return $this->render('/cluster_link_edit/index', [
'searchModel' => $searchModel,
'dataProvider' => $dataProvider,
+ 'clusterManagers' => $clusterManagers,
+ 'storeCounts' => ArrayHelper::map($storeData, 'cluster_id', 'store_count'),
+ 'lastUpdates' => ArrayHelper::map($storeData, 'cluster_id', 'last_update'),
+ 'storeLists' => $storeLists,
+ 'clusterToManager' => $clusterToManager, // Передаем соответствия куста и менеджера
]);
}
*/
public function actionViewAll($id)
{
- return $this->render('view', [
+ return $this->render('/cluster_link_edit/view-all', [
'model' => $this->findModel($id),
]);
}
<?php
-use yii_app\records\Cluster;
use yii\helpers\Html;
use yii\helpers\Url;
-use yii\grid\ActionColumn;
use yii\grid\GridView;
use yii\widgets\Pjax;
+
/** @var yii\web\View $this */
/** @var yii_app\records\ClusterSearch $searchModel */
/** @var yii\data\ActiveDataProvider $dataProvider */
+/** @var array $clusterManagers */
+/** @var array $storeCounts */
+/** @var array $lastUpdates */
+/** @var array $storeLists */
+/** @var array $clusterToManager */
$this->title = 'Кусты';
$this->params['breadcrumbs'][] = $this->title;
<h1><?= Html::encode($this->title) ?></h1>
<p>
- <?= Html::a('Create Cluster', ['create'], ['class' => 'btn btn-success']) ?>
+ <?= Html::a('Создать Куст', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<?php Pjax::begin(); ?>
- <?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<?= GridView::widget([
'dataProvider' => $dataProvider,
'id',
'name',
[
- 'class' => ActionColumn::className(),
- 'urlCreator' => function ($action, Cluster $model, $key, $index, $column) {
- return Url::toRoute([$action, 'id' => $model->id]);
- }
+ 'label' => 'Количество магазинов',
+ 'value' => function ($model) use ($storeCounts) {
+ // Отображаем количество магазинов из маппинга $storeCounts
+ return isset($storeCounts[$model->id]) ? $storeCounts[$model->id] : 0;
+ },
+ ],
+ [
+ 'label' => 'Шеф кустовой',
+ 'value' => function ($model) use ($clusterToManager) {
+ return $clusterToManager[$model->id] ?? 'Не назначен';
+ },
+ ],
+ [
+ 'label' => 'Дата обновления',
+ 'value' => function ($model) use ($lastUpdates) {
+ // Отображаем дату последнего обновления из маппинга $lastUpdates
+ return isset($lastUpdates[$model->id]) ? date('d.m.Y', strtotime($lastUpdates[$model->id])) : 'Неизвестно';
+ },
+ ],
+ [
+ 'class' => 'yii\grid\ActionColumn',
+ 'template' => '{view-all} {update}',
+ 'buttons' => [
+ 'view-all' => function ($url, $model, $key) {
+ return Html::a('Просмотр', $url, ['class' => 'btn btn-primary']);
+ },
+ 'update' => function ($url, $model, $key) {
+ return Html::a('Редактировать', $url, ['class' => 'btn btn-warning']);
+ },
+ ],
],
],
]); ?>
<?php Pjax::end(); ?>
</div>
+
+<?php
+print_r($clusterManagers);
+?>
\ No newline at end of file
--- /dev/null
+<?php
+
+use yii\helpers\Html;
+use yii\widgets\DetailView;
+
+/** @var yii\web\View $this */
+/** @var yii_app\records\Cluster $model */
+
+$this->title = $model->name;
+$this->params['breadcrumbs'][] = ['label' => 'Clusters', 'url' => ['index']];
+$this->params['breadcrumbs'][] = $this->title;
+\yii\web\YiiAsset::register($this);
+?>
+<div class="cluster-view">
+
+ <h1><?= Html::encode($this->title) ?></h1>
+
+ <p>
+ <?= Html::a('К списку', ['index'], ['class' => 'btn btn-primary']) ?>
+ <?= Html::a('Изменить', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
+ <?= Html::a('Удалить', ['delete', 'id' => $model->id], [
+ 'class' => 'btn btn-danger',
+ 'data' => [
+ 'confirm' => 'Are you sure you want to delete this item?',
+ 'method' => 'post',
+ ],
+ ]) ?>
+ </p>
+
+ <?= DetailView::widget([
+ 'model' => $model,
+ 'attributes' => [
+ 'id',
+ 'name',
+ ],
+ ]) ?>
+<p>Просмотр куста 1</p>
+</div>
+++ /dev/null
-<?php
-
-use yii\helpers\Html;
-use yii\widgets\DetailView;
-
-/** @var yii\web\View $this */
-/** @var yii_app\records\Cluster $model */
-
-$this->title = $model->name;
-$this->params['breadcrumbs'][] = ['label' => 'Clusters', 'url' => ['index']];
-$this->params['breadcrumbs'][] = $this->title;
-\yii\web\YiiAsset::register($this);
-?>
-<div class="cluster-view">
-
- <h1><?= Html::encode($this->title) ?></h1>
-
- <p>
- <?= Html::a('К списку', ['index'], ['class' => 'btn btn-primary']) ?>
- <?= Html::a('Изменить', ['update', 'id' => $model->id], ['class' => 'btn btn-primary']) ?>
- <?= Html::a('Удалить', ['delete', 'id' => $model->id], [
- 'class' => 'btn btn-danger',
- 'data' => [
- 'confirm' => 'Are you sure you want to delete this item?',
- 'method' => 'post',
- ],
- ]) ?>
- </p>
-
- <?= DetailView::widget([
- 'model' => $model,
- 'attributes' => [
- 'id',
- 'name',
- ],
- ]) ?>
-
-</div>