Корзина, массовые действия в списках и история записи в карточке
This commit is contained in:
1 parent
20f3d79552
commit
00bba5abfa
23 files changed
+936
No files matched your search
@@ -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) {
|
||||
|
||||
Reference in new issue
Block a user