Уведомления: лента в приложении и письма по каналам
Notify рассылает по каналам database и mail, адресовать можно по праву. Роутер теперь поднимается и вне запроса, появился Router::absolute для писем.
This commit is contained in:
1 parent
7b6ac42f1e
commit
2f162a846f
24 files changed
+1234
-17
No files matched your search
@@ -7,6 +7,7 @@ namespace Rsgrinko\Proton\Http;
|
||||
use ReflectionFunctionAbstract;
|
||||
use ReflectionMethod;
|
||||
use ReflectionNamedType;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Container;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
|
||||
@@ -37,6 +38,9 @@ final class Router
|
||||
/** @var array<string, Route> Именованные маршруты — общие для всех роутеров */
|
||||
private static array $named = [];
|
||||
|
||||
/** Защита от повторного входа: файл маршрутов сам может спросить адрес */
|
||||
private static bool $booting = false;
|
||||
|
||||
/**
|
||||
* Подключает файл маршрутов. Файл возвращает функцию, принимающую роутер.
|
||||
*/
|
||||
@@ -200,6 +204,8 @@ final class Router
|
||||
*/
|
||||
public static function url(string $name, array $params = []): string
|
||||
{
|
||||
self::boot();
|
||||
|
||||
if (!isset(self::$named[$name])) {
|
||||
throw new ProtonException('Неизвестный маршрут: ' . $name);
|
||||
}
|
||||
@@ -207,14 +213,51 @@ final class Router
|
||||
return self::$named[$name]->url($params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Полный адрес с доменом — для писем и чужих систем: относительный путь
|
||||
* в письме не кликается.
|
||||
*
|
||||
* @param array<string, mixed> $params
|
||||
*/
|
||||
public static function absolute(string $name, array $params = []): string
|
||||
{
|
||||
$base = rtrim((string) Config::get('app.url', ''), '/');
|
||||
|
||||
return $base . self::url($name, $params);
|
||||
}
|
||||
|
||||
/**
|
||||
* Есть ли такой маршрут — вьюхе иногда нужно спросить, не падая.
|
||||
*/
|
||||
public static function has(string $name): bool
|
||||
{
|
||||
self::boot();
|
||||
|
||||
return isset(self::$named[$name]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Поднимает маршруты, если их ещё никто не поднимал.
|
||||
*
|
||||
* Веб поднимает их сам — первым же запросом. А вот воркер и консоль ядро
|
||||
* не поднимают вовсе, и адрес для письма там собрать не из чего: без этого
|
||||
* уведомление из задачи падало бы на «Неизвестный маршрут».
|
||||
*/
|
||||
public static function boot(): void
|
||||
{
|
||||
if (self::$named !== [] || self::$booting) {
|
||||
return;
|
||||
}
|
||||
|
||||
self::$booting = true;
|
||||
|
||||
try {
|
||||
(new Kernel())->router();
|
||||
} finally {
|
||||
self::$booting = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Запоминает именованный маршрут — зовётся из Route::name().
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Models;
|
||||
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Database\Model\Model;
|
||||
use Rsgrinko\Proton\Database\Model\Relations\BelongsTo;
|
||||
|
||||
/**
|
||||
* Запись в ленте уведомлений: что человеку показать и прочитал ли он это.
|
||||
*
|
||||
* Модель называется UserNotification, а не Notification, чтобы не путаться с
|
||||
* самим уведомлением (`Notifications\Notification` — описание «что случилось»,
|
||||
* эта запись — его след в ленте одного пользователя).
|
||||
*/
|
||||
final class UserNotification extends Model
|
||||
{
|
||||
protected static string $table = 'notifications';
|
||||
|
||||
protected bool $timestamps = false;
|
||||
|
||||
protected array $casts = ['user_id' => 'int'];
|
||||
|
||||
public function user(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'user_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Кладёт уведомление в ленту.
|
||||
*/
|
||||
public static function add(int $userId, string $type, string $title, string $body = '', string $url = ''): self
|
||||
{
|
||||
$notification = new self();
|
||||
|
||||
$notification->forceFill([
|
||||
'user_id' => $userId,
|
||||
'type' => mb_substr($type, 0, 64),
|
||||
'title' => mb_substr($title, 0, 191),
|
||||
'body' => $body,
|
||||
'url' => mb_substr($url, 0, 500),
|
||||
'created_at' => Connection::now(),
|
||||
])->save();
|
||||
|
||||
return $notification;
|
||||
}
|
||||
|
||||
/**
|
||||
* Сколько непрочитанных — число у ссылки в шапке.
|
||||
*/
|
||||
public static function unreadFor(int $userId): int
|
||||
{
|
||||
if ($userId <= 0 || !Connection::instance()->hasTable('notifications')) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return self::query()->where('user_id', $userId)->whereNull('read_at')->count();
|
||||
}
|
||||
|
||||
public function read(): bool
|
||||
{
|
||||
return (string) $this->raw('read_at') !== '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Отмечает прочитанным. Повторно время не переписываем: в ленте видно,
|
||||
* когда человек это увидел.
|
||||
*/
|
||||
public function markRead(): void
|
||||
{
|
||||
if ($this->read()) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->forceFill(['read_at' => Connection::now()])->save();
|
||||
}
|
||||
|
||||
/**
|
||||
* Отмечает прочитанным всё у пользователя. Возвращает число строк.
|
||||
*/
|
||||
public static function markAllRead(int $userId): int
|
||||
{
|
||||
return self::query()
|
||||
->where('user_id', $userId)
|
||||
->whereNull('read_at')
|
||||
->update(['read_at' => Connection::now()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Чистка по сроку — зовётся воркером. Непрочитанные не трогаем: человек
|
||||
* их ещё не видел, и молча убирать их нечестно.
|
||||
*/
|
||||
public static function purge(int $days): int
|
||||
{
|
||||
if ($days <= 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return self::query()
|
||||
->whereNotNull('read_at')
|
||||
->where('created_at', '<', date('Y-m-d H:i:s', time() - $days * 86400))
|
||||
->delete();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Notifications;
|
||||
|
||||
use Rsgrinko\Proton\Mail\Message;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
|
||||
/**
|
||||
* Уведомление: что случилось и как об этом сказать человеку.
|
||||
*
|
||||
* final class OrderPaid extends Notification
|
||||
* {
|
||||
* public function __construct(private Order $order)
|
||||
* {
|
||||
* }
|
||||
*
|
||||
* public function type(): string { return 'order.paid'; }
|
||||
* public function title(): string { return 'Заказ №' . $this->order->id() . ' оплачен'; }
|
||||
* public function body(): string { return 'Сумма: ' . $this->order->total . ' ₽'; }
|
||||
* public function url(): string { return Router::url('orders.show', ['id' => $this->order->id()]); }
|
||||
* }
|
||||
*
|
||||
* Notify::send($user, new OrderPaid($order));
|
||||
*
|
||||
* Каналы перечисляет само уведомление: что-то стоит и в ленте, и письмом,
|
||||
* а что-то — только в ленте. Письмо собирается из заголовка и текста общим
|
||||
* шаблоном; нужно своё — переопределите mail().
|
||||
*/
|
||||
abstract class Notification
|
||||
{
|
||||
/**
|
||||
* Короткий код события: `webhook.disabled`, `order.paid`. По нему
|
||||
* уведомления отличают друг от друга, не разбирая текст.
|
||||
*/
|
||||
public function type(): string
|
||||
{
|
||||
return 'notification';
|
||||
}
|
||||
|
||||
/**
|
||||
* Заголовок — он же тема письма.
|
||||
*/
|
||||
abstract public function title(): string;
|
||||
|
||||
/**
|
||||
* Текст. Может быть пустым: иногда заголовка достаточно.
|
||||
*/
|
||||
public function body(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Куда вести по нажатию. Пусто — уведомление без перехода.
|
||||
*/
|
||||
public function url(): string
|
||||
{
|
||||
return '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Каналы доставки.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function channels(): array
|
||||
{
|
||||
return [Notify::DATABASE];
|
||||
}
|
||||
|
||||
/**
|
||||
* Письмо. По умолчанию — общий шаблон с заголовком, текстом и кнопкой.
|
||||
*/
|
||||
public function mail(User $user): Message
|
||||
{
|
||||
return Message::to((string) $user->email)
|
||||
->subject($this->title())
|
||||
->view('mail/notification', [
|
||||
'user' => $user,
|
||||
'title' => $this->title(),
|
||||
'body' => $this->body(),
|
||||
'url' => $this->url(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Notifications;
|
||||
|
||||
use Rsgrinko\Proton\Database\Connection;
|
||||
use Rsgrinko\Proton\Events\Events;
|
||||
use Rsgrinko\Proton\Models\Role;
|
||||
use Rsgrinko\Proton\Models\User;
|
||||
use Rsgrinko\Proton\Models\UserNotification;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
use Rsgrinko\Proton\Support\ProtonException;
|
||||
use Rsgrinko\Proton\Support\Validator;
|
||||
use Throwable;
|
||||
|
||||
/**
|
||||
* Доставка уведомлений по каналам.
|
||||
*
|
||||
* Notify::send($user, new OrderPaid($order));
|
||||
* Notify::toPermission(Permission::SYSTEM_MANAGE, new WebhookDisabledNotification($webhook));
|
||||
*
|
||||
* Два канала: `database` — запись в ленте пользователя, `mail` — письмо через
|
||||
* очередь (страница не ждёт чужой SMTP). Какие нужны, решает само уведомление.
|
||||
*
|
||||
* Уведомление никогда не роняет то, что его вызвало: это сообщение о событии,
|
||||
* а не часть действия. Сорвалось — строка в логе.
|
||||
*/
|
||||
final class Notify
|
||||
{
|
||||
public const DATABASE = 'database';
|
||||
public const MAIL = 'mail';
|
||||
|
||||
/**
|
||||
* Отправляет уведомление одному человеку. Возвращает каналы, которые
|
||||
* действительно отработали.
|
||||
*
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public static function send(User $user, Notification $notification): array
|
||||
{
|
||||
$done = [];
|
||||
|
||||
foreach ($notification->channels() as $channel) {
|
||||
try {
|
||||
if (self::deliver($channel, $user, $notification)) {
|
||||
$done[] = $channel;
|
||||
}
|
||||
} catch (Throwable $e) {
|
||||
(new Logger('notifications'))->error('Уведомление не доставлено', [
|
||||
'channel' => $channel,
|
||||
'type' => $notification->type(),
|
||||
'user' => $user->id(),
|
||||
'error' => $e->getMessage(),
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
if ($done !== []) {
|
||||
Events::fire('notification.sent', [
|
||||
'user' => $user,
|
||||
'notification' => $notification,
|
||||
'channels' => $done,
|
||||
]);
|
||||
}
|
||||
|
||||
return $done;
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет нескольким.
|
||||
*
|
||||
* @param array<int, User> $users
|
||||
*/
|
||||
public static function sendMany(array $users, Notification $notification): int
|
||||
{
|
||||
$count = 0;
|
||||
|
||||
foreach ($users as $user) {
|
||||
if (self::send($user, $notification) !== []) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
|
||||
return $count;
|
||||
}
|
||||
|
||||
/**
|
||||
* Отправляет всем, у кого есть право: так уведомляют «тех, кто отвечает
|
||||
* за сервис», не заводя отдельного списка адресатов.
|
||||
*/
|
||||
public static function toPermission(string $permission, Notification $notification): int
|
||||
{
|
||||
return self::sendMany(self::whoCan($permission), $notification);
|
||||
}
|
||||
|
||||
/**
|
||||
* Действующие пользователи с нужным правом.
|
||||
*
|
||||
* @return array<int, User>
|
||||
*/
|
||||
public static function whoCan(string $permission): array
|
||||
{
|
||||
if (!Connection::instance()->hasTable('users')) {
|
||||
return [];
|
||||
}
|
||||
|
||||
$roles = [];
|
||||
|
||||
foreach (Role::all() as $role) {
|
||||
if (in_array($permission, $role->permissions(), true)) {
|
||||
$roles[] = $role->id();
|
||||
}
|
||||
}
|
||||
|
||||
if ($roles === []) {
|
||||
return [];
|
||||
}
|
||||
|
||||
/** @var array<int, User> $users */
|
||||
$users = User::query()->where('active', 1)->whereIn('role_id', $roles)->orderBy('id')->get();
|
||||
|
||||
return $users;
|
||||
}
|
||||
|
||||
/**
|
||||
* Уборка прочитанных уведомлений по сроку — зовётся воркером.
|
||||
*/
|
||||
public static function purge(): int
|
||||
{
|
||||
return UserNotification::purge((int) Config::get('notifications.keep_days', 90));
|
||||
}
|
||||
|
||||
/**
|
||||
* Один канал. true — доставлено.
|
||||
*/
|
||||
private static function deliver(string $channel, User $user, Notification $notification): bool
|
||||
{
|
||||
return match ($channel) {
|
||||
self::DATABASE => self::toDatabase($user, $notification),
|
||||
self::MAIL => self::toMail($user, $notification),
|
||||
// Чужой канал — не молчим: опечатка в channels() иначе теряется
|
||||
default => throw new ProtonException('Неизвестный канал уведомлений: ' . $channel),
|
||||
};
|
||||
}
|
||||
|
||||
private static function toDatabase(User $user, Notification $notification): bool
|
||||
{
|
||||
if (!Connection::instance()->hasTable('notifications')) {
|
||||
return false;
|
||||
}
|
||||
|
||||
UserNotification::add(
|
||||
$user->id(),
|
||||
$notification->type(),
|
||||
$notification->title(),
|
||||
$notification->body(),
|
||||
$notification->url()
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function toMail(User $user, Notification $notification): bool
|
||||
{
|
||||
$email = trim((string) $user->email);
|
||||
|
||||
// Адреса нет или он негодный — письмо не уйдёт, но лента уже сработала
|
||||
if (!Validator::isEmail($email)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
$notification->mail($user)->queue();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Notifications;
|
||||
|
||||
use Rsgrinko\Proton\Http\Router;
|
||||
use Rsgrinko\Proton\Models\Webhook;
|
||||
|
||||
/**
|
||||
* Подписка на события отключилась сама: подписчик не отвечал слишком долго.
|
||||
*
|
||||
* Уходит тем, кто отвечает за вебхуки (право webhooks.manage), и письмом тоже:
|
||||
* молча отключённая подписка — это тихо потерянные события, о таком нужно
|
||||
* узнавать сразу, а не из журнала через неделю.
|
||||
*/
|
||||
final class WebhookDisabledNotification extends Notification
|
||||
{
|
||||
public function __construct(private Webhook $webhook, private string $error = '')
|
||||
{
|
||||
}
|
||||
|
||||
public function type(): string
|
||||
{
|
||||
return 'webhook.disabled';
|
||||
}
|
||||
|
||||
public function title(): string
|
||||
{
|
||||
return 'Подписка «' . (string) $this->webhook->name . '» отключена';
|
||||
}
|
||||
|
||||
public function body(): string
|
||||
{
|
||||
$text = 'Подписчик ' . (string) $this->webhook->url . ' не отвечает, неудач подряд — '
|
||||
. (int) $this->webhook->raw('failures') . '. Подписка отключена, события ему '
|
||||
. 'больше не уходят.';
|
||||
|
||||
if ($this->error !== '') {
|
||||
$text .= ' Последняя ошибка: ' . $this->error . '.';
|
||||
}
|
||||
|
||||
return $text . ' Починив подписчика, включите подписку обратно в разделе «Вебхуки».';
|
||||
}
|
||||
|
||||
public function url(): string
|
||||
{
|
||||
// Адрес с доменом: уведомление уходит и письмом, а там путь не кликается
|
||||
return Router::absolute('admin.webhooks.show', ['id' => $this->webhook->id()]);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<int, string>
|
||||
*/
|
||||
public function channels(): array
|
||||
{
|
||||
return [Notify::DATABASE, Notify::MAIL];
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use Rsgrinko\Proton\Models\RememberToken;
|
||||
use Rsgrinko\Proton\Models\Setting;
|
||||
use Rsgrinko\Proton\Models\UserSession;
|
||||
use Rsgrinko\Proton\Models\WebhookDelivery;
|
||||
use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\RateLimit\RateLimiter;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\Logger;
|
||||
@@ -232,6 +233,7 @@ final class Worker
|
||||
UserSession::purge((int) Config::get('auth.sessions_keep_days', 60));
|
||||
AuditEntry::purge((int) Config::get('audit.keep_days', 180));
|
||||
WebhookDelivery::purge((int) Config::get('webhooks.keep_days', 14));
|
||||
Notify::purge();
|
||||
|
||||
(new Logger('app'))->purge();
|
||||
|
||||
|
||||
@@ -16,12 +16,16 @@ declare(strict_types=1);
|
||||
* @var bool $bare страница входа — без шапки и меню
|
||||
*/
|
||||
|
||||
use Rsgrinko\Proton\Models\UserNotification;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\View\View;
|
||||
|
||||
$bare = $bare ?? false;
|
||||
$menu = (array) Config::get('menu', []);
|
||||
$name = (string) Config::get('app.name', 'Proton');
|
||||
|
||||
// Число у ссылки «Уведомления»: один COUNT на страницу, и только вошедшему
|
||||
$unread = $viewer->isGuest() ? 0 : UserNotification::unreadFor($viewer->id());
|
||||
?>
|
||||
<!doctype html>
|
||||
<html lang="ru">
|
||||
@@ -320,6 +324,9 @@ $name = (string) Config::get('app.name', 'Proton');
|
||||
|
||||
<?php if (!$viewer->isGuest()) { ?>
|
||||
<span class="who">
|
||||
<a class="muted small" href="<?= View::e(View::route('notifications')) ?>" title="Уведомления">
|
||||
Уведомления<?= $unread > 0 ? ' <span class="badge warn">' . $unread . '</span>' : '' ?>
|
||||
</a>
|
||||
<a class="muted small" href="<?= View::e(View::route('profile')) ?>"><?= View::e($viewer->name()) ?></a>
|
||||
<form method="post" action="<?= View::e(View::route('logout')) ?>">
|
||||
<?= View::csrf() ?>
|
||||
|
||||
@@ -4,8 +4,11 @@ declare(strict_types=1);
|
||||
|
||||
namespace Rsgrinko\Proton\Webhooks;
|
||||
|
||||
use Rsgrinko\Proton\Access\Permission;
|
||||
use Rsgrinko\Proton\Models\Webhook;
|
||||
use Rsgrinko\Proton\Models\WebhookDelivery;
|
||||
use Rsgrinko\Proton\Notifications\Notify;
|
||||
use Rsgrinko\Proton\Notifications\WebhookDisabledNotification;
|
||||
use Rsgrinko\Proton\Queue\Job;
|
||||
use Rsgrinko\Proton\Support\Config;
|
||||
use Rsgrinko\Proton\Support\HttpClient;
|
||||
@@ -145,6 +148,15 @@ final class DeliverWebhookJob extends Job
|
||||
'error' => $error,
|
||||
'disabled' => $disabled,
|
||||
]);
|
||||
|
||||
// Отключённая подписка — это тихо потерянные события: пусть те, кто
|
||||
// отвечает за вебхуки, узнают об этом сразу
|
||||
if ($disabled) {
|
||||
Notify::toPermission(
|
||||
Permission::WEBHOOKS_MANAGE,
|
||||
new WebhookDisabledNotification($webhook, $error)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
private function client(): HttpClient
|
||||
|
||||
Reference in new issue
Block a user