Корзина, массовые действия в списках и история записи в карточке
This commit is contained in:
1 parent
20f3d79552
commit
00bba5abfa
23 files changed
+936
No files matched your search
@@ -97,6 +97,9 @@ EXPORT_MAX_ROWS=20000
|
||||
# Загрузка списков из CSV: сколько строк принимаем за раз
|
||||
IMPORT_MAX_ROWS=5000
|
||||
|
||||
# Корзина: через сколько дней удалённое добивается окончательно (0 — никогда)
|
||||
TRASH_KEEP_DAYS=30
|
||||
|
||||
# Безопасность: закрытые адреса, автоблокировка перебора, журнал событий
|
||||
SECURITY_BLOCKLIST=true
|
||||
SECURITY_AUTOBLOCK_ATTEMPTS=30
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Controllers\Admin;
|
||||
|
||||
use Rsgrinko\Proton\Access\AccessDenied;
|
||||
use Rsgrinko\Proton\Access\Viewer;
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Http\Controller;
|
||||
use Rsgrinko\Proton\Http\Request;
|
||||
use Rsgrinko\Proton\Http\Response;
|
||||
use Rsgrinko\Proton\Support\Audit;
|
||||
use Rsgrinko\Proton\Support\Trash;
|
||||
|
||||
/**
|
||||
* Корзина: удалённое, но ещё живое.
|
||||
*
|
||||
* Разделы объявляет реестр (`config/trash.php`), поэтому свой раздел появляется
|
||||
* здесь сам, без правки контроллера. Каждый закрыт своим правом: право видеть
|
||||
* пользователей и право видеть вебхуки — разные вещи и в корзине тоже.
|
||||
*/
|
||||
final class TrashController extends Controller
|
||||
{
|
||||
public function index(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
$kinds = $this->allowed($viewer);
|
||||
|
||||
if ($kinds === []) {
|
||||
throw new AccessDenied('Корзина пуста для вашей роли');
|
||||
}
|
||||
|
||||
$key = (string) $request->query('kind', '');
|
||||
$key = isset($kinds[$key]) ? $key : (string) array_key_first($kinds);
|
||||
$kind = $kinds[$key];
|
||||
|
||||
$page = Trash::query($key)
|
||||
?->orderBy(Model::DELETED_AT, 'desc')
|
||||
->paginate($this->page($request), $this->perPage());
|
||||
|
||||
return $this->view('admin/trash', [
|
||||
'active' => 'trash',
|
||||
'kinds' => $kinds,
|
||||
'counts' => $this->counts($kinds),
|
||||
'kind' => $key,
|
||||
'label' => $kind['label'],
|
||||
'title' => $kind['title'],
|
||||
'page' => $page ?? ['items' => [], 'total' => 0, 'page' => 1, 'pages' => 1, 'per_page' => 0],
|
||||
], 'Корзина');
|
||||
}
|
||||
|
||||
/**
|
||||
* Вернуть запись из корзины.
|
||||
*/
|
||||
public function restore(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
[$kind, $record] = $this->find($request, $viewer);
|
||||
|
||||
$record->restore();
|
||||
|
||||
Audit::action(Trash::kind($kind)['entity'] ?? $kind, $record->id(), 'запись возвращена из корзины');
|
||||
|
||||
$this->flash('Запись возвращена');
|
||||
|
||||
return $this->redirect('admin.trash', ['kind' => $kind]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Добить окончательно. Обратной дороги нет, поэтому отдельное действие
|
||||
* и отдельная запись в журнале.
|
||||
*/
|
||||
public function destroy(Request $request, Viewer $viewer): Response
|
||||
{
|
||||
[$kind, $record] = $this->find($request, $viewer);
|
||||
|
||||
$record->forceDelete();
|
||||
|
||||
Audit::deleted(Trash::kind($kind)['entity'] ?? $kind, $record->id(), 'запись удалена окончательно');
|
||||
|
||||
$this->flash('Запись удалена окончательно');
|
||||
|
||||
return $this->redirect('admin.trash', ['kind' => $kind]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Раздел и запись из запроса — с проверкой права на этот раздел.
|
||||
*
|
||||
* @return array{0: string, 1: Model}
|
||||
*/
|
||||
private function find(Request $request, Viewer $viewer): array
|
||||
{
|
||||
$key = (string) $request->input('kind', '');
|
||||
$kinds = $this->allowed($viewer);
|
||||
|
||||
if (!isset($kinds[$key])) {
|
||||
throw new AccessDenied('Этот раздел корзины вам не доступен');
|
||||
}
|
||||
|
||||
/** @var class-string<Model> $model */
|
||||
$model = $kinds[$key]['model'];
|
||||
|
||||
/** @var Model|null $record */
|
||||
$record = $model::query()->onlyTrashed()->where('id', (int) $request->input('id', 0))->first();
|
||||
|
||||
/** @var Model $found */
|
||||
$found = $this->require($record, 'admin.trash', 'Записи в корзине нет');
|
||||
|
||||
return [$key, $found];
|
||||
}
|
||||
|
||||
/**
|
||||
* Разделы, доступные этому человеку.
|
||||
*
|
||||
* @return array<string, array{model: class-string<Model>, label: string, title: callable, permission: string}>
|
||||
*/
|
||||
private function allowed(Viewer $viewer): array
|
||||
{
|
||||
$allowed = [];
|
||||
|
||||
foreach (Trash::kinds() as $key => $kind) {
|
||||
if ($kind['permission'] === '' || $viewer->can($kind['permission'])) {
|
||||
$allowed[$key] = $kind;
|
||||
}
|
||||
}
|
||||
|
||||
return $allowed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array<string, array<string, mixed>> $kinds
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
private function counts(array $kinds): array
|
||||
{
|
||||
$counts = [];
|
||||
|
||||
foreach (array_keys($kinds) as $key) {
|
||||
$counts[$key] = Trash::query($key)?->count() ?? 0;
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
}
|
||||
@@ -230,6 +230,76 @@ final class UsersController extends Controller
|
||||
return $this->redirect('admin.users');
|
||||
}
|
||||
|
||||
/**
|
||||
* Массовое действие над отмеченными: включить, выключить, удалить.
|
||||
*
|
||||
* Себя в список не берём ни при каком действии: выключить или удалить
|
||||
* самого себя — верный способ остаться без панели.
|
||||
*/
|
||||
public function bulk(Request $request, User $user): Response
|
||||
{
|
||||
$data = $this->validate($request, [
|
||||
'action' => 'required|in:enable,disable,delete',
|
||||
], ['action' => 'Действие']);
|
||||
|
||||
$ids = array_values(array_filter(array_map('intval', (array) $request->input('ids', []))));
|
||||
$ids = array_values(array_diff($ids, [$user->id()]));
|
||||
|
||||
if ($ids === []) {
|
||||
$this->flash('Не отмечено ни одной записи (себя массовые действия не трогают)', 'error');
|
||||
|
||||
return $this->redirect('admin.users');
|
||||
}
|
||||
|
||||
$action = (string) $data['action'];
|
||||
$done = 0;
|
||||
|
||||
/** @var User $target */
|
||||
foreach (User::query()->whereIn('id', $ids)->get() as $target) {
|
||||
// Последнего активного не выключаем и не удаляем: войти станет некому
|
||||
if ($action !== 'enable' && $target->isActive() && User::query()->where('active', 1)->count() <= 1) {
|
||||
continue;
|
||||
}
|
||||
|
||||
match ($action) {
|
||||
'enable' => $target->forceFill(['active' => 1])->save(),
|
||||
'disable' => $this->disable($target),
|
||||
default => $this->remove($target),
|
||||
};
|
||||
|
||||
$done++;
|
||||
}
|
||||
|
||||
$labels = ['enable' => 'включено', 'disable' => 'выключено', 'delete' => 'удалено'];
|
||||
|
||||
Audit::action('user', 0, 'массовое действие: ' . $labels[$action] . ' ' . $done);
|
||||
|
||||
$this->flash(
|
||||
$done > 0 ? 'Готово, ' . $labels[$action] . ': ' . $done : 'Ничего не изменилось',
|
||||
$done > 0 ? 'ok' : 'error'
|
||||
);
|
||||
|
||||
return $this->redirect('admin.users');
|
||||
}
|
||||
|
||||
/**
|
||||
* Выключить: по старой куке отключённый доходить до страниц не должен.
|
||||
*/
|
||||
private function disable(User $target): void
|
||||
{
|
||||
$target->forceFill(['active' => 0])->save();
|
||||
$target->logoutEverywhere();
|
||||
}
|
||||
|
||||
/**
|
||||
* Удалить мягко — запись уходит в корзину.
|
||||
*/
|
||||
private function remove(User $target): void
|
||||
{
|
||||
$target->logoutEverywhere();
|
||||
$target->delete();
|
||||
}
|
||||
|
||||
/**
|
||||
* Роли для списка: id => название.
|
||||
*
|
||||
|
||||
@@ -193,6 +193,12 @@ return [
|
||||
'max_rows' => Env::int('EXPORT_MAX_ROWS', 20000),
|
||||
],
|
||||
|
||||
'trash' => [
|
||||
// Сколько держать удалённое, прежде чем добить окончательно.
|
||||
// 0 — не добивать никогда, корзина растёт
|
||||
'keep_days' => Env::int('TRASH_KEEP_DAYS', 30),
|
||||
],
|
||||
|
||||
'security' => [
|
||||
// Закрытые адреса проверяются на каждом заходе; выключается, если
|
||||
// блокировки делает что-то снаружи (nginx, файрвол)
|
||||
|
||||
@@ -24,6 +24,7 @@ return [
|
||||
['key' => 'settings', 'label' => 'Настройки', 'route' => 'admin.settings', 'permission' => Permission::SETTINGS_MANAGE],
|
||||
['key' => 'backups', 'label' => 'Копии', 'route' => 'admin.backups', 'permission' => Permission::SYSTEM_MANAGE],
|
||||
['key' => 'reports', 'label' => 'Отчёты', 'route' => 'admin.reports', 'permission' => Permission::SYSTEM_VIEW],
|
||||
['key' => 'trash', 'label' => 'Корзина', 'route' => 'admin.trash', 'permission' => ''],
|
||||
['key' => 'security', 'label' => 'Безопасность', 'route' => 'admin.security', 'permission' => Permission::SYSTEM_MANAGE],
|
||||
['key' => 'audit', 'label' => 'Журнал', 'route' => 'admin.audit', 'permission' => Permission::AUDIT_VIEW],
|
||||
['key' => 'logs', 'label' => 'Логи', 'route' => 'admin.logs', 'permission' => Permission::LOGS_VIEW],
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Что показывать в «Корзине».
|
||||
*
|
||||
* Модель попадает сюда, только если у неё включено мягкое удаление
|
||||
* (`protected bool $softDelete = true`) — иначе возвращать нечего.
|
||||
* Право ограничивает раздел: чужие удалённые записи видит не каждый.
|
||||
*/
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Models\Role;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Models\Webhook;
|
||||
use Rsgrinko\Proton\Support\Trash;
|
||||
|
||||
Trash::register(
|
||||
'users',
|
||||
User::class,
|
||||
'Пользователи',
|
||||
static fn (User $user): string => (string) $user->login . ' (' . (string) $user->email . ')',
|
||||
Permission::USERS_MANAGE,
|
||||
'user'
|
||||
);
|
||||
|
||||
Trash::register(
|
||||
'roles',
|
||||
Role::class,
|
||||
'Роли',
|
||||
static fn (Role $role): string => (string) $role->name,
|
||||
Permission::ROLES_MANAGE,
|
||||
'role'
|
||||
);
|
||||
|
||||
Trash::register(
|
||||
'webhooks',
|
||||
Webhook::class,
|
||||
'Вебхуки',
|
||||
static fn (Webhook $webhook): string => (string) $webhook->name . ' → ' . (string) $webhook->url,
|
||||
Permission::WEBHOOKS_MANAGE,
|
||||
'webhook'
|
||||
);
|
||||
|
||||
Trash::register(
|
||||
'notes',
|
||||
Note::class,
|
||||
'Заметки',
|
||||
static fn (Note $note): string => (string) $note->title,
|
||||
'notes.manage',
|
||||
'note'
|
||||
);
|
||||
@@ -23,6 +23,9 @@ final class Role extends Model
|
||||
'is_system' => 'bool',
|
||||
];
|
||||
|
||||
/** Мягкое удаление: роль возвращается из корзины вместе с правами */
|
||||
protected bool $softDelete = true;
|
||||
|
||||
/**
|
||||
* Права роли.
|
||||
*
|
||||
|
||||
@@ -30,6 +30,9 @@ final class User extends Model
|
||||
'role_id' => 'int',
|
||||
];
|
||||
|
||||
/** Мягкое удаление: человека возвращают из корзины, пока его не добили */
|
||||
protected bool $softDelete = true;
|
||||
|
||||
public function role(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(Role::class, 'role_id');
|
||||
|
||||
@@ -29,6 +29,9 @@ final class Webhook extends Model
|
||||
|
||||
protected array $casts = ['active' => 'bool', 'events' => 'json', 'failures' => 'int', 'last_status' => 'int'];
|
||||
|
||||
/** Мягкое удаление: подписку можно вернуть, журнал доставок остаётся */
|
||||
protected bool $softDelete = true;
|
||||
|
||||
/** Все события сразу: новое событие реестра подписка получит без правки */
|
||||
public const ALL_EVENTS = '*';
|
||||
|
||||
|
||||
@@ -16,6 +16,7 @@ use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\Trash;
|
||||
use Rsgrinko\Proton\Support\RequestId;
|
||||
use Throwable;
|
||||
|
||||
@@ -237,6 +238,7 @@ final class Worker
|
||||
WebhookDelivery::purge((int) Config::get('webhooks.keep_days', 14));
|
||||
SecurityEvent::purge((int) Config::get('security.keep_days', 60));
|
||||
BlockedIp::purgeExpired();
|
||||
Trash::purge((int) Config::get('trash.keep_days', 30));
|
||||
Notify::purge();
|
||||
|
||||
(new Logger('app'))->purge();
|
||||
|
||||
@@ -0,0 +1,159 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Support;
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\Query;
|
||||
|
||||
/**
|
||||
* Корзина: что можно вернуть после удаления.
|
||||
*
|
||||
* Мягкое удаление у моделей было всегда (`$softDelete = true`), но добраться
|
||||
* до удалённого можно было только кодом. Реестр говорит, какие модели
|
||||
* показывать в разделе «Корзина» и как их подписывать.
|
||||
*
|
||||
* Trash::register('notes', Note::class, 'Заметки', static fn (Note $n): string => (string) $n->title);
|
||||
*
|
||||
* Свои модели приложение дописывает в `config/trash.php`.
|
||||
*/
|
||||
final class Trash
|
||||
{
|
||||
/** @var array<string, array{model: class-string<Model>, label: string, title: callable, permission: string, entity: string}>|null */
|
||||
private static ?array $kinds = null;
|
||||
|
||||
/**
|
||||
* Показать модель в корзине.
|
||||
*
|
||||
* @param class-string<Model> $model
|
||||
* @param callable(Model): string $title как назвать запись в списке
|
||||
*/
|
||||
public static function register(
|
||||
string $key,
|
||||
string $model,
|
||||
string $label,
|
||||
callable $title,
|
||||
string $permission = '',
|
||||
string $entity = ''
|
||||
): void {
|
||||
self::boot();
|
||||
|
||||
self::$kinds[$key] = [
|
||||
'model' => $model,
|
||||
'label' => $label,
|
||||
'title' => $title,
|
||||
'permission' => $permission,
|
||||
// Как раздел называется в журнале действий: там единственное число
|
||||
// (user, role), а ключ раздела — множественное
|
||||
'entity' => $entity !== '' ? $entity : $key,
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* Все разделы корзины.
|
||||
*
|
||||
* @return array<string, array{model: class-string<Model>, label: string, title: callable, permission: string}>
|
||||
*/
|
||||
public static function kinds(): array
|
||||
{
|
||||
self::boot();
|
||||
|
||||
return self::$kinds ?? [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Описание раздела или null, если такого нет.
|
||||
*
|
||||
* @return array{model: class-string<Model>, label: string, title: callable, permission: string}|null
|
||||
*/
|
||||
public static function kind(string $key): ?array
|
||||
{
|
||||
return self::kinds()[$key] ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Запрос к удалённым записям раздела.
|
||||
*/
|
||||
public static function query(string $key): ?Query
|
||||
{
|
||||
$kind = self::kind($key);
|
||||
|
||||
if ($kind === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @var class-string<Model> $model */
|
||||
$model = $kind['model'];
|
||||
|
||||
return $model::query()->onlyTrashed();
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько удалённого лежит в каждом разделе.
|
||||
*
|
||||
* @return array<string, int>
|
||||
*/
|
||||
public static function counts(): array
|
||||
{
|
||||
$counts = [];
|
||||
|
||||
foreach (array_keys(self::kinds()) as $key) {
|
||||
$counts[$key] = self::query($key)?->count() ?? 0;
|
||||
}
|
||||
|
||||
return $counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Добить всё, что лежит в корзине дольше стольких дней. Зовётся уборкой
|
||||
* воркера: корзина не архив, вечно держать удалённое незачем.
|
||||
*/
|
||||
public static function purge(int $days): int
|
||||
{
|
||||
if ($days <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
$edge = date('Y-m-d H:i:s', time() - $days * 86400);
|
||||
$removed = 0;
|
||||
|
||||
foreach (array_keys(self::kinds()) as $key) {
|
||||
$query = self::query($key);
|
||||
|
||||
if ($query === null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$removed += $query->where(Model::DELETED_AT, '<', $edge)->forceDelete();
|
||||
}
|
||||
|
||||
return $removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Забыть реестр — нужно тестам.
|
||||
*/
|
||||
public static function reset(): void
|
||||
{
|
||||
self::$kinds = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Реестр ядра плюс config/trash.php приложения.
|
||||
*/
|
||||
private static function boot(): void
|
||||
{
|
||||
if (self::$kinds !== null) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$kinds = [];
|
||||
|
||||
$file = APP_ROOT . '/config/trash.php';
|
||||
|
||||
if (is_file($file)) {
|
||||
require $file;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Панель массовых действий над списком.
|
||||
*
|
||||
* Работает в паре с формой вокруг таблицы: в каждой строке галочка
|
||||
* `ids[]` с атрибутом data-check-item, здесь — «отметить все» и выбор действия.
|
||||
* Отметить все и посчитать отмеченное умеет каркас страницы.
|
||||
*
|
||||
* @var array<string, string> $actions код => подпись
|
||||
* @var string $confirm вопрос перед отправкой
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$confirm = $confirm ?? 'Выполнить действие над отмеченными записями?';
|
||||
?>
|
||||
<div class="row bulk-bar">
|
||||
<label class="inline">
|
||||
<input type="checkbox" data-check-all>
|
||||
<span class="muted small">отметить все</span>
|
||||
</label>
|
||||
|
||||
<select name="action" required>
|
||||
<option value="">действие с отмеченными</option>
|
||||
<?php foreach ($actions as $code => $label) { ?>
|
||||
<option value="<?= View::e($code) ?>"><?= View::e($label) ?></option>
|
||||
<?php } ?>
|
||||
</select>
|
||||
|
||||
<button type="submit" data-confirm="<?= View::e($confirm) ?>">Выполнить</button>
|
||||
|
||||
<span class="muted small" data-check-count>ничего не отмечено</span>
|
||||
</div>
|
||||
@@ -0,0 +1,75 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* История записи: что с ней делали и кто.
|
||||
*
|
||||
* Берёт журнал действий по паре «раздел + id», поэтому работает для любой
|
||||
* записи, которую пишут через `Audit::created|updated|deleted|action`.
|
||||
*
|
||||
* <?= View::partial('history', ['entity' => 'user', 'id' => $user->id()]) ?>
|
||||
*
|
||||
* @var string $entity раздел журнала: user, role, note
|
||||
* @var int|string $id запись
|
||||
* @var int $limit сколько показывать
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$limit = $limit ?? 10;
|
||||
|
||||
// Право смотреть журнал есть не у всех: кто его не имеет, историю не увидит
|
||||
if (!View::can('audit.view')) {
|
||||
return;
|
||||
}
|
||||
|
||||
$entries = AuditEntry::query()
|
||||
->where('entity', $entity)
|
||||
->where('entity_id', (string) $id)
|
||||
->orderBy('id', 'desc')
|
||||
->limit($limit)
|
||||
->get();
|
||||
?>
|
||||
<div class="card">
|
||||
<h2>История</h2>
|
||||
|
||||
<?php if ($entries === []) { ?>
|
||||
<p class="muted small">Записей в журнале нет.</p>
|
||||
<?php } else { ?>
|
||||
<div class="table-wrap">
|
||||
<table class="list">
|
||||
<?php foreach ($entries as $entry) { ?>
|
||||
<?php $changes = (array) ($entry->changes ?? []); ?>
|
||||
<tr>
|
||||
<td class="muted small nowrap"><?= View::e(View::date((string) $entry->raw('created_at'))) ?></td>
|
||||
<td class="small"><?= View::e((string) $entry->raw('user_login') ?: 'система') ?></td>
|
||||
<td>
|
||||
<span class="badge muted"><?= View::e(AuditEntry::label((string) $entry->raw('action'))) ?></span>
|
||||
<?= View::e((string) $entry->raw('description')) ?>
|
||||
|
||||
<?php if ($changes !== []) { ?>
|
||||
<details>
|
||||
<summary class="small">что изменилось</summary>
|
||||
<table>
|
||||
<?php foreach ($changes as $field => $pair) { ?>
|
||||
<tr>
|
||||
<td class="muted small"><?= View::e((string) $field) ?></td>
|
||||
<td class="small break"><?= View::e((string) ($pair[0] ?? '')) ?> → <?= View::e((string) ($pair[1] ?? '')) ?></td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
</details>
|
||||
<?php } ?>
|
||||
</td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<p class="muted small">
|
||||
<a href="<?= View::e(View::route('admin.audit', ['entity' => $entity])) ?>">весь журнал раздела</a>
|
||||
</p>
|
||||
<?php } ?>
|
||||
</div>
|
||||
@@ -220,6 +220,8 @@ $unread = $viewer->isGuest() ? 0 : UserNotification::unreadFor($viewer->id());
|
||||
.chart .col.empty { background: var(--border); }
|
||||
.chart-legend { display: flex; justify-content: space-between; }
|
||||
|
||||
.bulk-bar { margin-bottom: 10px; padding: 8px 10px; border: 1px solid var(--border); border-radius: 8px; }
|
||||
|
||||
a.sort { color: inherit; text-decoration: none; white-space: nowrap; }
|
||||
a.sort:hover { text-decoration: underline; }
|
||||
a.sort .arrow { margin-left: 4px; color: var(--accent); }
|
||||
@@ -398,6 +400,44 @@ $unread = $viewer->isGuest() ? 0 : UserNotification::unreadFor($viewer->id());
|
||||
Array.prototype.forEach.call(form.querySelectorAll('[data-check-item]'), function (box) {
|
||||
box.checked = master.checked;
|
||||
});
|
||||
|
||||
countChecked(form);
|
||||
});
|
||||
|
||||
// Счётчик отмеченного: без него непонятно, над сколькими записями
|
||||
// сработает массовое действие
|
||||
document.addEventListener('change', function (event) {
|
||||
var box = event.target.closest('[data-check-item]');
|
||||
|
||||
if (box) {
|
||||
countChecked(box.closest('form'));
|
||||
}
|
||||
});
|
||||
|
||||
function countChecked(form) {
|
||||
if (!form) {
|
||||
return;
|
||||
}
|
||||
|
||||
var label = form.querySelector('[data-check-count]');
|
||||
|
||||
if (!label) {
|
||||
return;
|
||||
}
|
||||
|
||||
var count = form.querySelectorAll('[data-check-item]:checked').length;
|
||||
|
||||
label.textContent = count === 0 ? 'ничего не отмечено' : 'отмечено: ' + count;
|
||||
}
|
||||
|
||||
// Опасное действие переспрашивает: массовое удаление промахом мыши
|
||||
// не отменить
|
||||
document.addEventListener('click', function (event) {
|
||||
var button = event.target.closest('[data-confirm]');
|
||||
|
||||
if (button && !window.confirm(button.getAttribute('data-confirm'))) {
|
||||
event.preventDefault();
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener('click', function (event) {
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Migrations;
|
||||
|
||||
use Rsgrinko\Proton\Database\Migration;
|
||||
use Rsgrinko\Proton\Database\Schema\Blueprint;
|
||||
|
||||
/**
|
||||
* Мягкое удаление для пользователей, ролей и вебхуков.
|
||||
*
|
||||
* Раньше запись из панели удалялась насовсем: ошиблись — доставайте копию базы.
|
||||
* Теперь она помечается deleted_at, пропадает из списков и живёт в «Корзине»,
|
||||
* откуда её возвращают или добивают.
|
||||
*
|
||||
* Логин и почта остаются занятыми удалённым пользователем — это сделано
|
||||
* нарочно: пока человека можно вернуть, его имя не должен занять другой.
|
||||
*/
|
||||
final class AddSoftDeletes extends Migration
|
||||
{
|
||||
/** @var array<int, string> */
|
||||
private const TABLES = ['users', 'roles', 'webhooks'];
|
||||
|
||||
public function up(): void
|
||||
{
|
||||
foreach (self::TABLES as $table) {
|
||||
$this->table($table, function (Blueprint $blueprint): void {
|
||||
$blueprint->softDeletes();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public function down(): void
|
||||
{
|
||||
foreach (self::TABLES as $table) {
|
||||
$this->table($table, function (Blueprint $blueprint): void {
|
||||
$blueprint->dropColumn('deleted_at');
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -72,3 +72,7 @@ $granted = $role->permissions();
|
||||
</form>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($role->id() > 0) { ?>
|
||||
<?= View::partial('history', ['entity' => 'role', 'id' => $role->id()]) ?>
|
||||
<?php } ?>
|
||||
@@ -0,0 +1,85 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Корзина: удалённые записи, которые ещё можно вернуть.
|
||||
*
|
||||
* @var array<string, array{model: string, label: string, title: callable, permission: string}> $kinds
|
||||
* @var array<string, int> $counts
|
||||
* @var string $kind выбранный раздел
|
||||
* @var string $label его подпись
|
||||
* @var callable $title как назвать запись
|
||||
* @var array{items: array<int, \Rsgrinko\Proton\Database\Model\Model>, total: int, page: int, pages: int, per_page: int} $page
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
?>
|
||||
<h1>Корзина</h1>
|
||||
|
||||
<div class="card">
|
||||
<div class="row">
|
||||
<?php foreach ($kinds as $key => $item) { ?>
|
||||
<?php if ($key === $kind) { ?>
|
||||
<span class="badge info"><?= View::e($item['label']) ?>: <?= (int) ($counts[$key] ?? 0) ?></span>
|
||||
<?php } else { ?>
|
||||
<a class="btn small" href="<?= View::e(View::route('admin.trash', ['kind' => $key])) ?>">
|
||||
<?= View::e($item['label']) ?> (<?= (int) ($counts[$key] ?? 0) ?>)
|
||||
</a>
|
||||
<?php } ?>
|
||||
<?php } ?>
|
||||
|
||||
<span class="spacer"></span>
|
||||
<span class="muted small">Корзина не архив: слишком старое воркер добивает сам</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="card">
|
||||
<h2><?= View::e($label) ?></h2>
|
||||
|
||||
<?php if ($page['items'] === []) { ?>
|
||||
<p class="muted">Здесь пусто — ничего не удаляли или всё уже вернули.</p>
|
||||
<?php } else { ?>
|
||||
<div class="table-wrap">
|
||||
<table class="list">
|
||||
<tr class="head">
|
||||
<th>Запись</th>
|
||||
<th>Удалена</th>
|
||||
<th></th>
|
||||
</tr>
|
||||
|
||||
<?php foreach ($page['items'] as $record) { ?>
|
||||
<tr>
|
||||
<td><?= View::e(($title)($record)) ?></td>
|
||||
<td class="muted small nowrap"><?= View::e(View::ago((string) $record->raw(Model::DELETED_AT))) ?></td>
|
||||
<td class="right">
|
||||
<div class="row end">
|
||||
<form method="post" action="<?= View::e(View::route('admin.trash.restore')) ?>">
|
||||
<?= View::csrf() ?>
|
||||
<input type="hidden" name="kind" value="<?= View::e($kind) ?>">
|
||||
<input type="hidden" name="id" value="<?= $record->id() ?>">
|
||||
<button type="submit" class="primary">Вернуть</button>
|
||||
</form>
|
||||
|
||||
<form method="post" action="<?= View::e(View::route('admin.trash.destroy')) ?>">
|
||||
<?= View::csrf() ?>
|
||||
<input type="hidden" name="kind" value="<?= View::e($kind) ?>">
|
||||
<input type="hidden" name="id" value="<?= $record->id() ?>">
|
||||
<button type="submit" class="danger">Удалить совсем</button>
|
||||
</form>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<?php } ?>
|
||||
</table>
|
||||
</div>
|
||||
|
||||
<?= View::partial('pagination', [
|
||||
'route' => 'admin.trash',
|
||||
'page' => $page['page'],
|
||||
'pages' => $page['pages'],
|
||||
'params' => ['kind' => $kind],
|
||||
]) ?>
|
||||
<?php } ?>
|
||||
</div>
|
||||
@@ -108,3 +108,7 @@ $hint = $isNew ? 'пусто — придумаем сами' : 'пусто
|
||||
</form>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($user->id() > 0) { ?>
|
||||
<?= View::partial('history', ['entity' => 'user', 'id' => $user->id()]) ?>
|
||||
<?php } ?>
|
||||
@@ -26,9 +26,22 @@ use Rsgrinko\Proton\View\View;
|
||||
<?php if ($page['items'] === []) { ?>
|
||||
<p class="muted">Ничего не нашлось.</p>
|
||||
<?php } else { ?>
|
||||
<form method="post" action="<?= View::e(View::route('admin.users.bulk')) ?>">
|
||||
<?= View::csrf() ?>
|
||||
|
||||
<?= View::partial('bulk', [
|
||||
'actions' => [
|
||||
'enable' => 'включить',
|
||||
'disable' => 'выключить',
|
||||
'delete' => 'удалить (в корзину)',
|
||||
],
|
||||
'confirm' => 'Выполнить действие над отмеченными пользователями?',
|
||||
]) ?>
|
||||
|
||||
<div class="table-wrap">
|
||||
<table class="list">
|
||||
<tr class="head">
|
||||
<th></th>
|
||||
<th><?= View::partial('sort', ['filters' => $filters, 'route' => 'admin.users', 'column' => 'login', 'label' => 'Логин']) ?></th>
|
||||
<th class="hide-sm">Имя</th>
|
||||
<th class="hide-sm">Почта</th>
|
||||
@@ -39,6 +52,7 @@ use Rsgrinko\Proton\View\View;
|
||||
|
||||
<?php foreach ($page['items'] as $user) { ?>
|
||||
<tr>
|
||||
<td><input type="checkbox" name="ids[]" value="<?= $user->id() ?>" data-check-item></td>
|
||||
<td><a href="<?= View::e(View::route('admin.users.show', ['id' => $user->id()])) ?>"><?= View::e((string) $user->login) ?></a></td>
|
||||
<td class="hide-sm"><?= View::e((string) $user->name) ?></td>
|
||||
<td class="hide-sm muted small"><?= View::e((string) $user->email) ?></td>
|
||||
@@ -56,6 +70,8 @@ use Rsgrinko\Proton\View\View;
|
||||
</table>
|
||||
</div>
|
||||
|
||||
</form>
|
||||
|
||||
<?= View::partial('pagination', [
|
||||
'route' => 'admin.users',
|
||||
'page' => $page['page'],
|
||||
|
||||
@@ -197,3 +197,7 @@ $all = in_array(Webhook::ALL_EVENTS, $selected, true);
|
||||
<?php } ?>
|
||||
</div>
|
||||
<?php } ?>
|
||||
|
||||
<?php if ($webhook->id() > 0) { ?>
|
||||
<?= View::partial('history', ['entity' => 'webhook', 'id' => $webhook->id()]) ?>
|
||||
<?php } ?>
|
||||
@@ -75,4 +75,6 @@ use Rsgrinko\Proton\View\View;
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<?= View::partial('history', ['entity' => 'note', 'id' => $note->id()]) ?>
|
||||
|
||||
<p><a href="<?= View::e(View::route('notes.index')) ?>">← ко всем заметкам</a></p>
|
||||
@@ -20,6 +20,7 @@ use App\Controllers\Admin\SecurityController;
|
||||
use App\Controllers\Admin\SettingsController;
|
||||
use App\Controllers\Admin\SystemController;
|
||||
use App\Controllers\Admin\TokensController;
|
||||
use App\Controllers\Admin\TrashController;
|
||||
use App\Controllers\Admin\UsersController;
|
||||
use App\Controllers\Admin\WebhooksController;
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
@@ -39,6 +40,7 @@ return static function (Router $router): void {
|
||||
$router->get('/{id:\d+}', [UsersController::class, 'show'])->name('admin.users.show');
|
||||
$router->post('/{id:\d+}', [UsersController::class, 'update']);
|
||||
$router->post('/{id:\d+}/delete', [UsersController::class, 'delete'])->name('admin.users.delete');
|
||||
$router->post('/bulk', [UsersController::class, 'bulk'])->name('admin.users.bulk');
|
||||
});
|
||||
|
||||
$router->group(['prefix' => '/roles', 'middleware' => 'can:' . Permission::ROLES_MANAGE], function (Router $router): void {
|
||||
@@ -97,6 +99,14 @@ return static function (Router $router): void {
|
||||
$router->post('/unblock', [SecurityController::class, 'unblock'])->name('admin.security.unblock');
|
||||
});
|
||||
|
||||
// Корзина: разделы объявляет реестр, право проверяется внутри — у каждого
|
||||
// раздела оно своё
|
||||
$router->group(['prefix' => '/trash'], function (Router $router): void {
|
||||
$router->get('', [TrashController::class, 'index'])->name('admin.trash');
|
||||
$router->post('/restore', [TrashController::class, 'restore'])->name('admin.trash.restore');
|
||||
$router->post('/destroy', [TrashController::class, 'destroy'])->name('admin.trash.destroy');
|
||||
});
|
||||
|
||||
$router->get('/audit', [AuditController::class, 'index'])
|
||||
->middleware('can:' . Permission::AUDIT_VIEW)
|
||||
->name('admin.audit');
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
/**
|
||||
* Корзина, массовые действия и история записи.
|
||||
*/
|
||||
|
||||
use App\Models\Note;
|
||||
use Rsgrinko\Proton\Database\Model\Factory;
|
||||
use Rsgrinko\Proton\Models\AuditEntry;
|
||||
use Rsgrinko\Proton\Models\Role;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Support\Trash;
|
||||
|
||||
test('корзина: удалённая запись пропадает из списков и возвращается обратно', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $user */
|
||||
$user = Factory::of(User::class)->create();
|
||||
|
||||
$id = $user->id();
|
||||
|
||||
$user->delete();
|
||||
|
||||
assertNull(User::find($id), 'обычный поиск удалённого не видит');
|
||||
assertSame(0, User::query()->count());
|
||||
assertSame(1, User::query()->onlyTrashed()->count(), 'а в корзине он есть');
|
||||
assertSame(1, Trash::query('users')?->count());
|
||||
|
||||
/** @var User $deleted */
|
||||
$deleted = assertNotNull(User::query()->onlyTrashed()->where('id', $id)->first());
|
||||
|
||||
$deleted->restore();
|
||||
|
||||
assertNotNull(User::find($id), 'вернулся');
|
||||
assertSame(0, Trash::query('users')?->count());
|
||||
});
|
||||
});
|
||||
|
||||
test('корзина: считает по разделам и добивает слишком старое', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $owner */
|
||||
$owner = Factory::of(User::class)->create();
|
||||
|
||||
/** @var Note $fresh */
|
||||
$fresh = Factory::of(Note::class)->create(['user_id' => $owner->id()]);
|
||||
/** @var Note $old */
|
||||
$old = Factory::of(Note::class)->create(['user_id' => $owner->id()]);
|
||||
|
||||
$fresh->delete();
|
||||
$old->delete();
|
||||
|
||||
// Одну «удалили» месяц назад
|
||||
$old->forceFill(['deleted_at' => date('Y-m-d H:i:s', time() - 40 * 86400)])->save();
|
||||
|
||||
$counts = Trash::counts();
|
||||
|
||||
assertSame(2, $counts['notes']);
|
||||
assertSame(0, $counts['users']);
|
||||
|
||||
assertSame(1, Trash::purge(30), 'старое добито');
|
||||
assertSame(1, Trash::counts()['notes'], 'свежее осталось');
|
||||
|
||||
// Ноль дней — уборка не трогает ничего
|
||||
assertSame(0, Trash::purge(0));
|
||||
});
|
||||
});
|
||||
|
||||
test('корзина: раздел показывает удалённое и возвращает его кнопкой', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $admin */
|
||||
$admin = Factory::of(User::class)->create(['role_id' => Role::admin()?->id() ?? 0]);
|
||||
/** @var User $victim */
|
||||
$victim = Factory::of(User::class)->create();
|
||||
|
||||
$victim->delete();
|
||||
|
||||
actingAs($admin);
|
||||
|
||||
$response = get('/admin/trash', ['kind' => 'users']);
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertSee((string) $victim->login, $response);
|
||||
|
||||
assertRedirect('/admin/trash', post('/admin/trash/restore', ['kind' => 'users', 'id' => $victim->id()]));
|
||||
assertNotNull(User::find($victim->id()), 'запись вернулась');
|
||||
|
||||
// И добить окончательно
|
||||
$victim->delete();
|
||||
|
||||
post('/admin/trash/destroy', ['kind' => 'users', 'id' => $victim->id()]);
|
||||
|
||||
assertSame(0, User::query()->withTrashed()->where('id', $victim->id())->count(), 'записи больше нет');
|
||||
|
||||
actingAs(null);
|
||||
});
|
||||
});
|
||||
|
||||
test('массовые действия: выключают отмеченных и не трогают того, кто нажал', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $admin */
|
||||
$admin = Factory::of(User::class)->create(['role_id' => Role::admin()?->id() ?? 0]);
|
||||
/** @var array<int, User> $people */
|
||||
$people = Factory::of(User::class)->times(3)->create();
|
||||
|
||||
actingAs($admin);
|
||||
|
||||
$ids = array_map(static fn (User $user): int => $user->id(), $people);
|
||||
|
||||
assertRedirect('/admin/users', post('/admin/users/bulk', [
|
||||
'action' => 'disable',
|
||||
'ids' => [...$ids, $admin->id()],
|
||||
]));
|
||||
|
||||
foreach ($ids as $id) {
|
||||
assertFalse((bool) User::find($id)?->isActive(), 'отмеченный выключен');
|
||||
}
|
||||
|
||||
assertTrue((bool) User::find($admin->id())?->isActive(), 'себя массовое действие не трогает');
|
||||
|
||||
// Удаление уводит в корзину
|
||||
post('/admin/users/bulk', ['action' => 'delete', 'ids' => $ids]);
|
||||
|
||||
assertSame(3, User::query()->onlyTrashed()->count());
|
||||
|
||||
actingAs(null);
|
||||
});
|
||||
});
|
||||
|
||||
test('массовые действия: без отметок ничего не делают', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $admin */
|
||||
$admin = Factory::of(User::class)->create(['role_id' => Role::admin()?->id() ?? 0]);
|
||||
|
||||
actingAs($admin);
|
||||
|
||||
post('/admin/users/bulk', ['action' => 'delete', 'ids' => []]);
|
||||
|
||||
assertSame(1, User::query()->count(), 'никого не удалили');
|
||||
|
||||
actingAs(null);
|
||||
});
|
||||
});
|
||||
|
||||
test('история: карточка показывает записи журнала по этой записи', function (): void {
|
||||
withOwnDatabase(static function (): void {
|
||||
/** @var User $admin */
|
||||
$admin = Factory::of(User::class)->create(['role_id' => Role::admin()?->id() ?? 0]);
|
||||
|
||||
actingAs($admin);
|
||||
|
||||
// Правка пишется в журнал — она и должна появиться в истории
|
||||
post('/admin/users/' . $admin->id(), [
|
||||
'email' => 'novy@example.com',
|
||||
'name' => 'Новое имя',
|
||||
'role_id' => (string) $admin->raw('role_id'),
|
||||
'active' => '1',
|
||||
]);
|
||||
|
||||
assertTrue(AuditEntry::query()->where('entity', 'user')->where('entity_id', (string) $admin->id())->count() > 0);
|
||||
|
||||
$response = get('/admin/users/' . $admin->id());
|
||||
|
||||
assertStatus(200, $response);
|
||||
assertSee('История', $response);
|
||||
assertSee('изменён пользователь', $response);
|
||||
|
||||
actingAs(null);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user