feat: add notifications module with bell UI, event listeners, and cleanup job

In-app notification system with topbar bell icon, dropdown panel,
mark-as-read/dismiss actions, and scheduled cleanup of old read
notifications. Includes event listeners for user.created and
user.deleted events, authorization policy, and full test coverage.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-03-19 22:09:44 +01:00
parent 1f0b1caf54
commit fb6e30a062
27 changed files with 1632 additions and 1 deletions

View File

@@ -0,0 +1,43 @@
<?php
namespace MintyPHP\Module\Notifications\Handler;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Service\Scheduler\Handler\ScheduledJobHandlerInterface;
class NotificationCleanupJobHandler implements ScheduledJobHandlerInterface
{
public function __construct(private readonly NotificationService $notificationService)
{
}
public function definition(): array
{
return [
'label' => 'Notification cleanup',
'description' => 'Purges read notifications older than 90 days',
'default_enabled' => 1,
'default_timezone' => defined('APP_TIMEZONE') ? (string) APP_TIMEZONE : 'UTC',
'default_schedule_type' => 'daily',
'default_schedule_interval' => 1,
'default_schedule_time' => '04:00',
'default_schedule_weekdays_csv' => null,
'default_catchup_once' => 1,
'allowed_schedule_types' => ['daily', 'weekly'],
];
}
public function execute(?int $actorUserId): array
{
$deleted = $this->notificationService->purgeOldRead(90);
return [
'status' => 'success',
'error_code' => null,
'error_message' => null,
'result' => [
'deleted_count' => $deleted,
],
];
}
}

View File

@@ -0,0 +1,70 @@
<?php
namespace MintyPHP\Module\Notifications\Listeners;
use MintyPHP\App\Module\Contracts\EventListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
final class UserCreatedNotificationListener implements EventListener
{
public function __construct(
private readonly NotificationService $notificationService,
private readonly UserReadRepositoryInterface $userReadRepository,
private readonly UserTenantRepositoryInterface $userTenantRepository
) {
}
public function handle(string $event, array $payload): void
{
$userId = (int) ($payload['user_id'] ?? 0);
$uuid = (string) ($payload['uuid'] ?? '');
$actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;
if ($userId <= 0 || $uuid === '') {
return;
}
$user = $this->userReadRepository->find($userId);
if ($user === null) {
return;
}
$displayName = trim((string) ($user['display_name'] ?? ''));
if ($displayName === '') {
$displayName = trim(($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? ''));
}
$tenantIds = $this->userTenantRepository->listTenantIdsByUserId($userId);
if ($tenantIds === []) {
return;
}
// Only notify users who have the users.create permission (admins)
$adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
[PermissionService::USERS_CREATE]
);
if ($adminUserIds === []) {
return;
}
$adminSet = array_flip($adminUserIds);
$title = sprintf(t('New user: %s'), $displayName);
$link = 'admin/users/edit/' . $uuid;
foreach ($tenantIds as $tenantId) {
$this->notificationService->createForTenantAdminUsers(
$tenantId,
'user.created',
$title,
null,
$link,
['user_id' => $userId, 'uuid' => $uuid],
$actorUserId,
$adminSet
);
}
}
}

View File

@@ -0,0 +1,65 @@
<?php
namespace MintyPHP\Module\Notifications\Listeners;
use MintyPHP\App\Module\Contracts\EventListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
final class UserDeletedNotificationListener implements EventListener
{
public function __construct(
private readonly NotificationService $notificationService,
private readonly UserReadRepositoryInterface $userReadRepository
) {
}
public function handle(string $event, array $payload): void
{
$userId = (int) ($payload['user_id'] ?? 0);
if ($userId <= 0) {
return;
}
// Belt-and-suspenders cleanup (DB CASCADE handles this too)
$this->notificationService->deleteAllForUser($userId);
// Notify admins about the deletion
$displayName = trim((string) ($payload['display_name'] ?? ''));
$tenantIds = (array) ($payload['tenant_ids'] ?? []);
$actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;
if ($displayName === '' || $tenantIds === []) {
return;
}
$adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
[PermissionService::USERS_DELETE]
);
if ($adminUserIds === []) {
return;
}
$adminSet = array_flip($adminUserIds);
$title = sprintf(t('User deleted: %s'), $displayName);
foreach ($tenantIds as $tenantId) {
$tenantId = (int) $tenantId;
if ($tenantId <= 0) {
continue;
}
$this->notificationService->createForTenantAdminUsers(
$tenantId,
'user.deleted',
$title,
null,
null,
['user_id' => $userId],
$actorUserId,
$adminSet
);
}
}
}

View File

@@ -0,0 +1,27 @@
<?php
namespace MintyPHP\Module\Notifications;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Service\Access\AuthorizationPolicyInterface;
final class NotificationsAuthorizationPolicy implements AuthorizationPolicyInterface
{
public const ABILITY_VIEW = 'notifications.view';
public const PERMISSION_KEY = 'notifications.view';
public function supports(string $ability): bool
{
return $ability === self::ABILITY_VIEW;
}
public function authorize(string $ability, array $context = []): AuthorizationDecision
{
$actorUserId = (int) ($context['actor_user_id'] ?? 0);
if ($actorUserId <= 0) {
return AuthorizationDecision::deny(403, 'forbidden');
}
return AuthorizationDecision::allow();
}
}

View File

@@ -0,0 +1,43 @@
<?php
namespace MintyPHP\Module\Notifications;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Container\ContainerRegistrar;
use MintyPHP\Module\Notifications\Handler\NotificationCleanupJobHandler;
use MintyPHP\Module\Notifications\Listeners\UserCreatedNotificationListener;
use MintyPHP\Module\Notifications\Listeners\UserDeletedNotificationListener;
use MintyPHP\Module\Notifications\Service\NotificationRepositoryFactory;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Module\Notifications\Service\NotificationServicesFactory;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
final class NotificationsContainerRegistrar implements ContainerRegistrar
{
public function register(AppContainer $container): void
{
$container->set(NotificationRepositoryFactory::class, static fn (): NotificationRepositoryFactory => new NotificationRepositoryFactory());
$container->set(NotificationServicesFactory::class, static fn (AppContainer $c): NotificationServicesFactory => new NotificationServicesFactory(
$c->get(NotificationRepositoryFactory::class)
));
$container->set(NotificationService::class, static fn (AppContainer $c): NotificationService => $c->get(NotificationServicesFactory::class)->createNotificationService());
$container->set(NotificationCleanupJobHandler::class, static fn (AppContainer $c): NotificationCleanupJobHandler => new NotificationCleanupJobHandler(
$c->get(NotificationService::class)
));
$container->set(UserCreatedNotificationListener::class, static fn (AppContainer $c): UserCreatedNotificationListener => new UserCreatedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepositoryInterface::class),
$c->get(UserTenantRepositoryInterface::class)
));
$container->set(UserDeletedNotificationListener::class, static fn (AppContainer $c): UserDeletedNotificationListener => new UserDeletedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepositoryInterface::class)
));
}
}

View File

@@ -0,0 +1,18 @@
<?php
namespace MintyPHP\Module\Notifications\Providers;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\LayoutContextProvider;
final class NotificationsLayoutProvider implements LayoutContextProvider
{
public function provide(array $session, AppContainer $container): array
{
return [
'notifications.nav' => [
'unread_count' => (int) ($session['module.notifications.unread_count'] ?? 0),
],
];
}
}

View File

@@ -0,0 +1,35 @@
<?php
namespace MintyPHP\Module\Notifications\Providers;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Module\Contracts\SessionProvider;
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\Service\NotificationService;
final class NotificationsSessionProvider implements SessionProvider
{
private const SESSION_KEY = 'module.notifications.unread_count';
public function populate(array $user, AppContainer $container): void
{
$userId = (int) ($user['id'] ?? 0);
if ($userId <= 0) {
unset($_SESSION[self::SESSION_KEY]);
return;
}
$sessionStore = $container->get(SessionStoreInterface::class);
$service = $container->get(NotificationService::class);
if (!$sessionStore instanceof SessionStoreInterface || !$service instanceof NotificationService) {
return;
}
$sessionStore->set(self::SESSION_KEY, $service->unreadCount($userId));
}
public function clear(): void
{
unset($_SESSION[self::SESSION_KEY]);
}
}

View File

@@ -0,0 +1,135 @@
<?php
namespace MintyPHP\Module\Notifications\Repository;
use MintyPHP\DB;
use MintyPHP\Repository\Support\RepositoryArrayHelper;
class NotificationRepository implements NotificationRepositoryInterface
{
private function unwrapList(mixed $rows): array
{
return RepositoryArrayHelper::unwrapList($rows, 'user_notifications');
}
public function create(array $data): int|false
{
$result = DB::insert(
'insert into user_notifications (recipient_user_id, tenant_id, type, title, body, link, data, created) values (?, ?, ?, ?, ?, ?, ?, NOW())',
(string) ($data['recipient_user_id'] ?? 0),
$data['tenant_id'] !== null ? (string) $data['tenant_id'] : null,
(string) ($data['type'] ?? ''),
(string) ($data['title'] ?? ''),
$data['body'] ?? null,
$data['link'] ?? null,
isset($data['data']) ? json_encode($data['data'], JSON_THROW_ON_ERROR) : null
);
return is_int($result) && $result > 0 ? $result : false;
}
public function listByUser(int $userId, int $limit, int $offset): array
{
if ($userId <= 0) {
return [];
}
$limit = max(1, min($limit, 100));
$offset = max(0, $offset);
$rows = DB::select(
'select id, type, title, body, link, is_read, created from user_notifications where recipient_user_id = ? order by created desc limit ? offset ?',
(string) $userId,
(string) $limit,
(string) $offset
);
return $this->unwrapList($rows);
}
public function countUnreadByUser(int $userId): int
{
if ($userId <= 0) {
return 0;
}
$count = DB::selectValue(
'select count(*) from user_notifications where recipient_user_id = ? and is_read = 0',
(string) $userId
);
return (int) $count;
}
public function markRead(int $id, int $userId): bool
{
if ($id <= 0 || $userId <= 0) {
return false;
}
$affected = DB::update(
'update user_notifications set is_read = 1, read_at = NOW() where id = ? and recipient_user_id = ? and is_read = 0',
(string) $id,
(string) $userId
);
return is_int($affected) && $affected > 0;
}
public function markAllReadByUser(int $userId): int
{
if ($userId <= 0) {
return 0;
}
$affected = DB::update(
'update user_notifications set is_read = 1, read_at = NOW() where recipient_user_id = ? and is_read = 0',
(string) $userId
);
return is_int($affected) ? $affected : 0;
}
public function delete(int $id, int $userId): bool
{
if ($id <= 0 || $userId <= 0) {
return false;
}
$affected = DB::delete(
'delete from user_notifications where id = ? and recipient_user_id = ?',
(string) $id,
(string) $userId
);
return is_int($affected) && $affected > 0;
}
public function deleteAllByUser(int $userId): int
{
if ($userId <= 0) {
return 0;
}
$affected = DB::delete(
'delete from user_notifications where recipient_user_id = ?',
(string) $userId
);
return is_int($affected) ? $affected : 0;
}
public function purgeReadOlderThanDays(int $days): int
{
if ($days <= 0) {
return 0;
}
$affected = DB::delete(
'delete from user_notifications where is_read = 1 and read_at < DATE_SUB(NOW(), INTERVAL ? DAY)',
(string) $days
);
return is_int($affected) ? $affected : 0;
}
}

View File

@@ -0,0 +1,26 @@
<?php
namespace MintyPHP\Module\Notifications\Repository;
interface NotificationRepositoryInterface
{
/** @return int|false Insert ID on success, false on failure */
public function create(array $data): int|false;
/**
* @return list<array<string, mixed>>
*/
public function listByUser(int $userId, int $limit, int $offset): array;
public function countUnreadByUser(int $userId): int;
public function markRead(int $id, int $userId): bool;
public function markAllReadByUser(int $userId): int;
public function delete(int $id, int $userId): bool;
public function deleteAllByUser(int $userId): int;
public function purgeReadOlderThanDays(int $days): int;
}

View File

@@ -0,0 +1,16 @@
<?php
namespace MintyPHP\Module\Notifications\Service;
use MintyPHP\Module\Notifications\Repository\NotificationRepository;
use MintyPHP\Module\Notifications\Repository\NotificationRepositoryInterface;
class NotificationRepositoryFactory
{
private ?NotificationRepository $notificationRepository = null;
public function createNotificationRepository(): NotificationRepositoryInterface
{
return $this->notificationRepository ??= new NotificationRepository();
}
}

View File

@@ -0,0 +1,203 @@
<?php
namespace MintyPHP\Module\Notifications\Service;
use MintyPHP\Module\Notifications\Repository\NotificationRepositoryInterface;
class NotificationService
{
public function __construct(
private readonly NotificationRepositoryInterface $notificationRepository
) {
}
/** @return list<array<string, mixed>> */
public function listForUser(int $userId, int $limit = 50): array
{
if ($userId <= 0) {
return [];
}
return $this->notificationRepository->listByUser($userId, $limit, 0);
}
public function unreadCount(int $userId): int
{
if ($userId <= 0) {
return 0;
}
return $this->notificationRepository->countUnreadByUser($userId);
}
public function markAsRead(int $userId, int $notificationId): bool
{
if ($userId <= 0 || $notificationId <= 0) {
return false;
}
return $this->notificationRepository->markRead($notificationId, $userId);
}
public function markAllAsRead(int $userId): int
{
if ($userId <= 0) {
return 0;
}
return $this->notificationRepository->markAllReadByUser($userId);
}
public function dismiss(int $userId, int $notificationId): bool
{
if ($userId <= 0 || $notificationId <= 0) {
return false;
}
return $this->notificationRepository->delete($notificationId, $userId);
}
public function createForUser(
int $recipientUserId,
?int $tenantId,
string $type,
string $title,
?string $body,
?string $link,
array $data
): int|false {
if ($recipientUserId <= 0 || $type === '' || $title === '') {
return false;
}
return $this->notificationRepository->create([
'recipient_user_id' => $recipientUserId,
'tenant_id' => $tenantId,
'type' => $type,
'title' => $title,
'body' => $body,
'link' => $link,
'data' => $data ?: null,
]);
}
/**
* Fan-out: create notification for all active users in a tenant, optionally excluding actor.
*
* @return int Number of notifications created
*/
public function createForTenantUsers(
int $tenantId,
string $type,
string $title,
?string $body,
?string $link,
array $data,
?int $excludeUserId
): int {
if ($tenantId <= 0 || $type === '' || $title === '') {
return 0;
}
$userIds = $this->listUserIdsForTenant($tenantId);
$created = 0;
foreach ($userIds as $userId) {
if ($excludeUserId !== null && $userId === $excludeUserId) {
continue;
}
$result = $this->createForUser($userId, $tenantId, $type, $title, $body, $link, $data);
if ($result !== false) {
$created++;
}
}
return $created;
}
/**
* Fan-out: create notification only for tenant users whose ID is in $allowedUserIds.
*
* @param array<int, mixed> $allowedUserIds Flipped array (user ID as key) for fast lookup
* @return int Number of notifications created
*/
public function createForTenantAdminUsers(
int $tenantId,
string $type,
string $title,
?string $body,
?string $link,
array $data,
?int $excludeUserId,
array $allowedUserIds
): int {
if ($tenantId <= 0 || $type === '' || $title === '' || $allowedUserIds === []) {
return 0;
}
$userIds = $this->listUserIdsForTenant($tenantId);
$created = 0;
foreach ($userIds as $userId) {
if (!isset($allowedUserIds[$userId])) {
continue;
}
if ($excludeUserId !== null && $userId === $excludeUserId) {
continue;
}
$result = $this->createForUser($userId, $tenantId, $type, $title, $body, $link, $data);
if ($result !== false) {
$created++;
}
}
return $created;
}
public function purgeOldRead(int $retentionDays = 90): int
{
return $this->notificationRepository->purgeReadOlderThanDays($retentionDays);
}
public function deleteAllForUser(int $userId): int
{
if ($userId <= 0) {
return 0;
}
return $this->notificationRepository->deleteAllByUser($userId);
}
/**
* Look up active user IDs belonging to a tenant.
*
* @return list<int>
*/
private function listUserIdsForTenant(int $tenantId): array
{
if ($tenantId <= 0) {
return [];
}
$rows = \MintyPHP\DB::select(
'select ut.user_id from user_tenants ut join users u on u.id = ut.user_id and u.active = 1 where ut.tenant_id = ?',
(string) $tenantId
);
if (!is_array($rows)) {
return [];
}
$ids = [];
foreach ($rows as $row) {
$data = $row['user_tenants'] ?? $row;
if (is_array($data) && isset($data['user_id'])) {
$ids[] = (int) $data['user_id'];
}
}
return array_values(array_unique($ids));
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace MintyPHP\Module\Notifications\Service;
class NotificationServicesFactory
{
private ?NotificationService $notificationService = null;
public function __construct(
private readonly NotificationRepositoryFactory $notificationRepositoryFactory
) {
}
public function createNotificationService(): NotificationService
{
return $this->notificationService ??= new NotificationService(
$this->notificationRepositoryFactory->createNotificationRepository()
);
}
}