chore: snapshot notifications hardening and css/docs alignment

This commit is contained in:
2026-03-20 00:05:03 +01:00
parent fb6e30a062
commit 60c27e50cb
41 changed files with 1862 additions and 254 deletions

View File

@@ -0,0 +1,13 @@
INSERT INTO `permissions` (`key`, `description`, `active`, `is_system`)
VALUES ('notifications.view', 'Can view and manage own notifications', 1, 1)
ON DUPLICATE KEY UPDATE
`description` = VALUES(`description`),
`active` = VALUES(`active`),
`is_system` = VALUES(`is_system`);
INSERT INTO `role_permissions` (`role_id`, `permission_id`, `created`)
SELECT r.id, p.id, NOW()
FROM roles r
JOIN permissions p ON p.`key` = 'notifications.view'
WHERE r.active = 1
ON DUPLICATE KEY UPDATE role_id = role_id;

View File

@@ -7,6 +7,9 @@ CREATE TABLE IF NOT EXISTS `user_notifications` (
`body` VARCHAR(500) NULL,
`link` VARCHAR(500) NULL,
`data` JSON NULL,
`dedupe_fingerprint` CHAR(64) NULL,
`dedupe_bucket` INT UNSIGNED NULL,
`dedupe_until` DATETIME NULL DEFAULT NULL,
`is_read` TINYINT(1) NOT NULL DEFAULT 0,
`read_at` DATETIME NULL DEFAULT NULL,
`created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP,
@@ -15,6 +18,15 @@ CREATE TABLE IF NOT EXISTS `user_notifications` (
KEY `idx_un_recipient_created` (`recipient_user_id`, `created` DESC),
KEY `idx_un_tenant_created` (`tenant_id`, `created` DESC),
KEY `idx_un_cleanup` (`is_read`, `read_at`),
UNIQUE KEY `uniq_un_dedupe_bucket` (`recipient_user_id`, `dedupe_fingerprint`, `dedupe_bucket`),
CONSTRAINT `fk_un_recipient` FOREIGN KEY (`recipient_user_id`) REFERENCES `users` (`id`) ON DELETE CASCADE,
CONSTRAINT `fk_un_tenant` FOREIGN KEY (`tenant_id`) REFERENCES `tenants` (`id`) ON DELETE SET NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
ALTER TABLE `user_notifications`
ADD COLUMN IF NOT EXISTS `dedupe_fingerprint` CHAR(64) NULL AFTER `data`,
ADD COLUMN IF NOT EXISTS `dedupe_bucket` INT UNSIGNED NULL AFTER `dedupe_fingerprint`,
ADD COLUMN IF NOT EXISTS `dedupe_until` DATETIME NULL DEFAULT NULL AFTER `dedupe_bucket`;
CREATE UNIQUE INDEX IF NOT EXISTS `uniq_un_dedupe_bucket`
ON `user_notifications` (`recipient_user_id`, `dedupe_fingerprint`, `dedupe_bucket`);

View File

@@ -6,5 +6,9 @@
"Dismiss": "Verwerfen",
"Action failed": "Aktion fehlgeschlagen",
"New user: %s": "Neuer Benutzer: %s",
"User deleted: %s": "Benutzer gelöscht: %s"
"User deleted: %s": "Benutzer gelöscht: %s",
"User activated: %s": "Benutzer aktiviert: %s",
"User deactivated: %s": "Benutzer deaktiviert: %s",
"User assignments updated: %s": "Benutzer-Zuweisungen aktualisiert: %s",
"Tenant, role, or department assignments were changed.": "Mandanten-, Rollen- oder Abteilungszuweisungen wurden geändert."
}

View File

@@ -6,5 +6,9 @@
"Dismiss": "Dismiss",
"Action failed": "Action failed",
"New user: %s": "New user: %s",
"User deleted: %s": "User deleted: %s"
"User deleted: %s": "User deleted: %s",
"User activated: %s": "User activated: %s",
"User deactivated: %s": "User deactivated: %s",
"User assignments updated: %s": "User assignments updated: %s",
"Tenant, role, or department assignments were changed.": "Tenant, role, or department assignments were changed."
}

View File

@@ -0,0 +1,90 @@
<?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 UserActivatedNotificationListener 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);
if ($userId <= 0) {
return;
}
$user = $this->userReadRepository->find($userId);
$displayName = trim((string) ($payload['display_name'] ?? ''));
if ($displayName === '' && is_array($user)) {
$displayName = trim((string) ($user['display_name'] ?? ''));
if ($displayName === '') {
$displayName = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
}
}
if ($displayName === '') {
$displayName = '#' . $userId;
}
$uuid = trim((string) ($payload['uuid'] ?? ''));
if ($uuid === '' && is_array($user)) {
$uuid = trim((string) ($user['uuid'] ?? ''));
}
$tenantIds = $this->sanitizeTenantIds($payload['tenant_ids'] ?? []);
if ($tenantIds === []) {
$tenantIds = $this->userTenantRepository->listTenantIdsByUserId($userId);
}
if ($tenantIds === []) {
return;
}
$adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
[PermissionService::USERS_UPDATE]
);
if ($adminUserIds === []) {
return;
}
$adminSet = array_fill_keys(array_map('intval', $adminUserIds), true);
$actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;
$title = sprintf(t('User activated: %s'), $displayName);
$link = $uuid !== '' ? 'admin/users/edit/' . $uuid : null;
foreach ($tenantIds as $tenantId) {
$this->notificationService->createForTenantAdminUsers(
$tenantId,
'user.activated',
$title,
null,
$link,
['user_id' => $userId, 'uuid' => $uuid],
$actorUserId,
$adminSet
);
}
}
/**
* @return list<int>
*/
private function sanitizeTenantIds(mixed $tenantIds): array
{
if (!is_array($tenantIds)) {
return [];
}
$ids = array_values(array_unique(array_map('intval', $tenantIds)));
return array_values(array_filter($ids, static fn (int $tenantId): bool => $tenantId > 0));
}
}

View File

@@ -0,0 +1,104 @@
<?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 UserAssignmentChangedNotificationListener 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;
}
$actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;
$user = $this->userReadRepository->find($userId);
$displayName = trim((string) ($payload['display_name'] ?? ''));
if ($displayName === '' && is_array($user)) {
$displayName = trim((string) ($user['display_name'] ?? ''));
if ($displayName === '') {
$displayName = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
}
}
if ($displayName === '') {
$displayName = '#' . $userId;
}
$uuid = trim((string) ($payload['uuid'] ?? ''));
if ($uuid === '' && is_array($user)) {
$uuid = trim((string) ($user['uuid'] ?? ''));
}
$tenantIds = $this->sanitizeTenantIds($payload['tenant_ids'] ?? []);
$changes = is_array($payload['changes'] ?? null) ? $payload['changes'] : [];
$title = sprintf(t('User assignments updated: %s'), $displayName);
$body = t('Tenant, role, or department assignments were changed.');
$link = $uuid !== '' ? 'admin/users/edit/' . $uuid : null;
$data = [
'user_id' => $userId,
'uuid' => $uuid,
'changes' => $changes,
];
if ($actorUserId === null || $actorUserId !== $userId) {
$this->notificationService->createForUser(
$userId,
null,
'user.assignment_changed',
$title,
$body,
$link,
$data
);
}
if ($tenantIds === []) {
return;
}
$adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
[PermissionService::USERS_UPDATE_ASSIGNMENTS]
);
if ($adminUserIds === []) {
return;
}
$adminSet = array_fill_keys(array_map('intval', $adminUserIds), true);
foreach ($tenantIds as $tenantId) {
$this->notificationService->createForTenantAdminUsers(
$tenantId,
'user.assignment_changed',
$title,
$body,
$link,
$data,
$actorUserId,
$adminSet
);
}
}
/**
* @return list<int>
*/
private function sanitizeTenantIds(mixed $tenantIds): array
{
if (!is_array($tenantIds)) {
return [];
}
$ids = array_values(array_unique(array_map('intval', $tenantIds)));
return array_values(array_filter($ids, static fn (int $tenantId): bool => $tenantId > 0));
}
}

View File

@@ -0,0 +1,90 @@
<?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 UserDeactivatedNotificationListener 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);
if ($userId <= 0) {
return;
}
$user = $this->userReadRepository->find($userId);
$displayName = trim((string) ($payload['display_name'] ?? ''));
if ($displayName === '' && is_array($user)) {
$displayName = trim((string) ($user['display_name'] ?? ''));
if ($displayName === '') {
$displayName = trim((string) (($user['first_name'] ?? '') . ' ' . ($user['last_name'] ?? '')));
}
}
if ($displayName === '') {
$displayName = '#' . $userId;
}
$uuid = trim((string) ($payload['uuid'] ?? ''));
if ($uuid === '' && is_array($user)) {
$uuid = trim((string) ($user['uuid'] ?? ''));
}
$tenantIds = $this->sanitizeTenantIds($payload['tenant_ids'] ?? []);
if ($tenantIds === []) {
$tenantIds = $this->userTenantRepository->listTenantIdsByUserId($userId);
}
if ($tenantIds === []) {
return;
}
$adminUserIds = $this->userReadRepository->listPrivilegedUserIdsByPermissionKeys(
[PermissionService::USERS_UPDATE]
);
if ($adminUserIds === []) {
return;
}
$adminSet = array_fill_keys(array_map('intval', $adminUserIds), true);
$actorUserId = isset($payload['actor_user_id']) ? (int) $payload['actor_user_id'] : null;
$title = sprintf(t('User deactivated: %s'), $displayName);
$link = $uuid !== '' ? 'admin/users/edit/' . $uuid : null;
foreach ($tenantIds as $tenantId) {
$this->notificationService->createForTenantAdminUsers(
$tenantId,
'user.deactivated',
$title,
null,
$link,
['user_id' => $userId, 'uuid' => $uuid],
$actorUserId,
$adminSet
);
}
}
/**
* @return list<int>
*/
private function sanitizeTenantIds(mixed $tenantIds): array
{
if (!is_array($tenantIds)) {
return [];
}
$ids = array_values(array_unique(array_map('intval', $tenantIds)));
return array_values(array_filter($ids, static fn (int $tenantId): bool => $tenantId > 0));
}
}

View File

@@ -4,12 +4,18 @@ namespace MintyPHP\Module\Notifications;
use MintyPHP\Service\Access\AuthorizationDecision;
use MintyPHP\Service\Access\AuthorizationPolicyInterface;
use MintyPHP\Service\Access\PermissionService;
final class NotificationsAuthorizationPolicy implements AuthorizationPolicyInterface
{
public const ABILITY_VIEW = 'notifications.view';
public const PERMISSION_KEY = 'notifications.view';
public function __construct(
private readonly PermissionService $permissionService
) {
}
public function supports(string $ability): bool
{
return $ability === self::ABILITY_VIEW;
@@ -22,6 +28,10 @@ final class NotificationsAuthorizationPolicy implements AuthorizationPolicyInter
return AuthorizationDecision::deny(403, 'forbidden');
}
if (!$this->permissionService->userHas($actorUserId, self::PERMISSION_KEY)) {
return AuthorizationDecision::deny(403, 'forbidden');
}
return AuthorizationDecision::allow();
}
}

View File

@@ -5,13 +5,16 @@ namespace MintyPHP\Module\Notifications;
use MintyPHP\App\AppContainer;
use MintyPHP\App\Container\ContainerRegistrar;
use MintyPHP\Module\Notifications\Handler\NotificationCleanupJobHandler;
use MintyPHP\Module\Notifications\Listeners\UserActivatedNotificationListener;
use MintyPHP\Module\Notifications\Listeners\UserAssignmentChangedNotificationListener;
use MintyPHP\Module\Notifications\Listeners\UserCreatedNotificationListener;
use MintyPHP\Module\Notifications\Listeners\UserDeactivatedNotificationListener;
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;
use MintyPHP\Repository\Tenant\UserTenantRepository;
use MintyPHP\Repository\User\UserReadRepository;
final class NotificationsContainerRegistrar implements ContainerRegistrar
{
@@ -23,7 +26,9 @@ final class NotificationsContainerRegistrar implements ContainerRegistrar
$c->get(NotificationRepositoryFactory::class)
));
$container->set(NotificationService::class, static fn (AppContainer $c): NotificationService => $c->get(NotificationServicesFactory::class)->createNotificationService());
$container->set(NotificationService::class, static fn (AppContainer $c): NotificationService => $c->get(NotificationServicesFactory::class)->createNotificationService(
$c->get(UserTenantRepository::class)
));
$container->set(NotificationCleanupJobHandler::class, static fn (AppContainer $c): NotificationCleanupJobHandler => new NotificationCleanupJobHandler(
$c->get(NotificationService::class)
@@ -31,13 +36,30 @@ final class NotificationsContainerRegistrar implements ContainerRegistrar
$container->set(UserCreatedNotificationListener::class, static fn (AppContainer $c): UserCreatedNotificationListener => new UserCreatedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepositoryInterface::class),
$c->get(UserTenantRepositoryInterface::class)
$c->get(UserReadRepository::class),
$c->get(UserTenantRepository::class)
));
$container->set(UserDeletedNotificationListener::class, static fn (AppContainer $c): UserDeletedNotificationListener => new UserDeletedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepositoryInterface::class)
$c->get(UserReadRepository::class)
));
$container->set(UserActivatedNotificationListener::class, static fn (AppContainer $c): UserActivatedNotificationListener => new UserActivatedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepository::class),
$c->get(UserTenantRepository::class)
));
$container->set(UserDeactivatedNotificationListener::class, static fn (AppContainer $c): UserDeactivatedNotificationListener => new UserDeactivatedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepository::class),
$c->get(UserTenantRepository::class)
));
$container->set(UserAssignmentChangedNotificationListener::class, static fn (AppContainer $c): UserAssignmentChangedNotificationListener => new UserAssignmentChangedNotificationListener(
$c->get(NotificationService::class),
$c->get(UserReadRepository::class)
));
}
}

View File

@@ -25,7 +25,9 @@ final class NotificationsSessionProvider implements SessionProvider
return;
}
$sessionStore->set(self::SESSION_KEY, $service->unreadCount($userId));
$currentTenant = $sessionStore->get('current_tenant', []);
$tenantId = is_array($currentTenant) ? (int) ($currentTenant['id'] ?? 0) : 0;
$sessionStore->set(self::SESSION_KEY, $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null));
}
public function clear(): void

View File

@@ -7,6 +7,8 @@ use MintyPHP\Repository\Support\RepositoryArrayHelper;
class NotificationRepository implements NotificationRepositoryInterface
{
private const DEDUPE_WINDOW_SECONDS = 1800;
private function unwrapList(mixed $rows): array
{
return RepositoryArrayHelper::unwrapList($rows, 'user_notifications');
@@ -14,21 +16,29 @@ class NotificationRepository implements NotificationRepositoryInterface
public function create(array $data): int|false
{
$dedupeFingerprint = trim((string) ($data['dedupe_fingerprint'] ?? ''));
$dedupeBucket = (int) ($data['dedupe_bucket'] ?? 0);
$hasDedupe = $dedupeFingerprint !== '' && $dedupeBucket > 0;
$result = DB::insert(
'insert into user_notifications (recipient_user_id, tenant_id, type, title, body, link, data, created) values (?, ?, ?, ?, ?, ?, ?, NOW())',
($hasDedupe ? 'insert ignore' : 'insert') .
' into user_notifications (recipient_user_id, tenant_id, type, title, body, link, data, dedupe_fingerprint, dedupe_bucket, dedupe_until, 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
isset($data['data']) ? json_encode($data['data'], JSON_THROW_ON_ERROR) : null,
$hasDedupe ? $dedupeFingerprint : null,
$hasDedupe ? (string) $dedupeBucket : null,
$hasDedupe ? gmdate('Y-m-d H:i:s', time() + self::DEDUPE_WINDOW_SECONDS) : null
);
return is_int($result) && $result > 0 ? $result : false;
}
public function listByUser(int $userId, int $limit, int $offset): array
public function listByUser(int $userId, ?int $tenantId, int $limit, int $offset): array
{
if ($userId <= 0) {
return [];
@@ -37,69 +47,83 @@ class NotificationRepository implements NotificationRepositoryInterface
$limit = max(1, min($limit, 100));
$offset = max(0, $offset);
$tenantParams = [];
$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 ?',
'select id, type, title, body, link, is_read, created from user_notifications where recipient_user_id = ?' .
$this->tenantScopeClause($tenantId, true, $tenantParams) .
' order by created desc limit ' . $limit . ' offset ' . $offset,
(string) $userId,
(string) $limit,
(string) $offset
...$tenantParams
);
return $this->unwrapList($rows);
}
public function countUnreadByUser(int $userId): int
public function countUnreadByUser(int $userId, ?int $tenantId): int
{
if ($userId <= 0) {
return 0;
}
$tenantParams = [];
$count = DB::selectValue(
'select count(*) from user_notifications where recipient_user_id = ? and is_read = 0',
(string) $userId
'select count(*) from user_notifications where recipient_user_id = ? and is_read = 0' .
$this->tenantScopeClause($tenantId, true, $tenantParams),
(string) $userId,
...$tenantParams
);
return (int) $count;
}
public function markRead(int $id, int $userId): bool
public function markRead(int $id, int $userId, ?int $tenantId): bool
{
if ($id <= 0 || $userId <= 0) {
return false;
}
$tenantParams = [];
$affected = DB::update(
'update user_notifications set is_read = 1, read_at = NOW() where id = ? and recipient_user_id = ? and is_read = 0',
'update user_notifications set is_read = 1, read_at = NOW() where id = ? and recipient_user_id = ? and is_read = 0' .
$this->tenantScopeClause($tenantId, true, $tenantParams),
(string) $id,
(string) $userId
(string) $userId,
...$tenantParams
);
return is_int($affected) && $affected > 0;
}
public function markAllReadByUser(int $userId): int
public function markAllReadByUser(int $userId, ?int $tenantId): int
{
if ($userId <= 0) {
return 0;
}
$tenantParams = [];
$affected = DB::update(
'update user_notifications set is_read = 1, read_at = NOW() where recipient_user_id = ? and is_read = 0',
(string) $userId
'update user_notifications set is_read = 1, read_at = NOW() where recipient_user_id = ? and is_read = 0' .
$this->tenantScopeClause($tenantId, true, $tenantParams),
(string) $userId,
...$tenantParams
);
return is_int($affected) ? $affected : 0;
}
public function delete(int $id, int $userId): bool
public function delete(int $id, int $userId, ?int $tenantId): bool
{
if ($id <= 0 || $userId <= 0) {
return false;
}
$tenantParams = [];
$affected = DB::delete(
'delete from user_notifications where id = ? and recipient_user_id = ?',
'delete from user_notifications where id = ? and recipient_user_id = ?' .
$this->tenantScopeClause($tenantId, true, $tenantParams),
(string) $id,
(string) $userId
(string) $userId,
...$tenantParams
);
return is_int($affected) && $affected > 0;
@@ -132,4 +156,25 @@ class NotificationRepository implements NotificationRepositoryInterface
return is_int($affected) ? $affected : 0;
}
/**
* Builds a tenant scope SQL condition for a notification recipient query.
* Scope always includes global notifications (`tenant_id is null`).
*
* @param array<int, string> $params
*/
private function tenantScopeClause(?int $tenantId, bool $includeGlobal, array &$params): string
{
$scopedTenantId = (int) ($tenantId ?? 0);
if ($scopedTenantId > 0) {
if ($includeGlobal) {
$params[] = (string) $scopedTenantId;
return ' and (tenant_id is null or tenant_id = ?)';
}
$params[] = (string) $scopedTenantId;
return ' and tenant_id = ?';
}
return $includeGlobal ? ' and tenant_id is null' : '';
}
}

View File

@@ -10,15 +10,15 @@ interface NotificationRepositoryInterface
/**
* @return list<array<string, mixed>>
*/
public function listByUser(int $userId, int $limit, int $offset): array;
public function listByUser(int $userId, ?int $tenantId, int $limit, int $offset): array;
public function countUnreadByUser(int $userId): int;
public function countUnreadByUser(int $userId, ?int $tenantId): int;
public function markRead(int $id, int $userId): bool;
public function markRead(int $id, int $userId, ?int $tenantId): bool;
public function markAllReadByUser(int $userId): int;
public function markAllReadByUser(int $userId, ?int $tenantId): int;
public function delete(int $id, int $userId): bool;
public function delete(int $id, int $userId, ?int $tenantId): bool;
public function deleteAllByUser(int $userId): int;

View File

@@ -3,58 +3,69 @@
namespace MintyPHP\Module\Notifications\Service;
use MintyPHP\Module\Notifications\Repository\NotificationRepositoryInterface;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
class NotificationService
{
private const DEDUPE_WINDOW_MINUTES = 30;
private const DEDUPE_TYPES = [
'user.created' => true,
'user.deleted' => true,
'user.activated' => true,
'user.deactivated' => true,
'user.assignment_changed' => true,
];
public function __construct(
private readonly NotificationRepositoryInterface $notificationRepository
private readonly NotificationRepositoryInterface $notificationRepository,
private readonly UserTenantRepositoryInterface $userTenantRepository
) {
}
/** @return list<array<string, mixed>> */
public function listForUser(int $userId, int $limit = 50): array
public function listForUser(int $userId, ?int $tenantId = null, int $limit = 50): array
{
if ($userId <= 0) {
return [];
}
return $this->notificationRepository->listByUser($userId, $limit, 0);
return $this->notificationRepository->listByUser($userId, $tenantId, $limit, 0);
}
public function unreadCount(int $userId): int
public function unreadCount(int $userId, ?int $tenantId = null): int
{
if ($userId <= 0) {
return 0;
}
return $this->notificationRepository->countUnreadByUser($userId);
return $this->notificationRepository->countUnreadByUser($userId, $tenantId);
}
public function markAsRead(int $userId, int $notificationId): bool
public function markAsRead(int $userId, int $notificationId, ?int $tenantId = null): bool
{
if ($userId <= 0 || $notificationId <= 0) {
return false;
}
return $this->notificationRepository->markRead($notificationId, $userId);
return $this->notificationRepository->markRead($notificationId, $userId, $tenantId);
}
public function markAllAsRead(int $userId): int
public function markAllAsRead(int $userId, ?int $tenantId = null): int
{
if ($userId <= 0) {
return 0;
}
return $this->notificationRepository->markAllReadByUser($userId);
return $this->notificationRepository->markAllReadByUser($userId, $tenantId);
}
public function dismiss(int $userId, int $notificationId): bool
public function dismiss(int $userId, int $notificationId, ?int $tenantId = null): bool
{
if ($userId <= 0 || $notificationId <= 0) {
return false;
}
return $this->notificationRepository->delete($notificationId, $userId);
return $this->notificationRepository->delete($notificationId, $userId, $tenantId);
}
public function createForUser(
@@ -70,6 +81,8 @@ class NotificationService
return false;
}
$dedupeMeta = $this->buildDedupeMeta($recipientUserId, $tenantId, $type, $data);
return $this->notificationRepository->create([
'recipient_user_id' => $recipientUserId,
'tenant_id' => $tenantId,
@@ -78,6 +91,8 @@ class NotificationService
'body' => $body,
'link' => $link,
'data' => $data ?: null,
'dedupe_fingerprint' => $dedupeMeta['fingerprint'] ?? null,
'dedupe_bucket' => $dedupeMeta['bucket'] ?? null,
]);
}
@@ -99,7 +114,7 @@ class NotificationService
return 0;
}
$userIds = $this->listUserIdsForTenant($tenantId);
$userIds = $this->userTenantRepository->listActiveUserIdsByTenantId($tenantId);
$created = 0;
foreach ($userIds as $userId) {
@@ -136,7 +151,7 @@ class NotificationService
return 0;
}
$userIds = $this->listUserIdsForTenant($tenantId);
$userIds = $this->userTenantRepository->listActiveUserIdsByTenantId($tenantId);
$created = 0;
foreach ($userIds as $userId) {
@@ -171,33 +186,55 @@ class NotificationService
}
/**
* Look up active user IDs belonging to a tenant.
*
* @return list<int>
* @param array<string, mixed> $data
* @return array{fingerprint: string, bucket: int}|array{}
*/
private function listUserIdsForTenant(int $tenantId): array
private function buildDedupeMeta(int $recipientUserId, ?int $tenantId, string $type, array $data): array
{
if ($tenantId <= 0) {
if (!isset(self::DEDUPE_TYPES[$type])) {
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)) {
$target = $this->dedupeTargetFromData($data);
if ($target === '') {
return [];
}
$ids = [];
foreach ($rows as $row) {
$data = $row['user_tenants'] ?? $row;
if (is_array($data) && isset($data['user_id'])) {
$ids[] = (int) $data['user_id'];
}
}
$tenantScope = $tenantId !== null && $tenantId > 0 ? $tenantId : 0;
$raw = implode('|', [
'recipient:' . $recipientUserId,
'tenant:' . $tenantScope,
'type:' . $type,
'target:' . $target,
]);
return array_values(array_unique($ids));
return [
'fingerprint' => hash('sha256', $raw),
'bucket' => intdiv(time(), self::DEDUPE_WINDOW_MINUTES * 60),
];
}
/**
* @param array<string, mixed> $data
*/
private function dedupeTargetFromData(array $data): string
{
$explicit = trim((string) ($data['dedupe_target'] ?? ''));
if ($explicit !== '') {
return $explicit;
}
$targetUserId = (int) ($data['user_id'] ?? 0);
if ($targetUserId > 0) {
return 'user:' . $targetUserId;
}
$targetUuid = trim((string) ($data['uuid'] ?? ''));
if ($targetUuid !== '') {
return 'uuid:' . $targetUuid;
}
return '';
}
}

View File

@@ -2,6 +2,8 @@
namespace MintyPHP\Module\Notifications\Service;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
class NotificationServicesFactory
{
private ?NotificationService $notificationService = null;
@@ -11,10 +13,11 @@ class NotificationServicesFactory
) {
}
public function createNotificationService(): NotificationService
public function createNotificationService(UserTenantRepositoryInterface $userTenantRepository): NotificationService
{
return $this->notificationService ??= new NotificationService(
$this->notificationRepositoryFactory->createNotificationRepository()
$this->notificationRepositoryFactory->createNotificationRepository(),
$userTenantRepository
);
}
}

View File

@@ -82,6 +82,15 @@ return [
'user.deleted' => [
['class' => \MintyPHP\Module\Notifications\Listeners\UserDeletedNotificationListener::class, 'method' => 'handle'],
],
'user.activated' => [
['class' => \MintyPHP\Module\Notifications\Listeners\UserActivatedNotificationListener::class, 'method' => 'handle'],
],
'user.deactivated' => [
['class' => \MintyPHP\Module\Notifications\Listeners\UserDeactivatedNotificationListener::class, 'method' => 'handle'],
],
'user.assignment_changed' => [
['class' => \MintyPHP\Module\Notifications\Listeners\UserAssignmentChangedNotificationListener::class, 'method' => 'handle'],
],
],
'scheduler_jobs' => [

View File

@@ -1,12 +1,14 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(NotificationsAuthorizationPolicy::ABILITY_VIEW);
if (requestInput()->method() !== 'POST') {
http_response_code(405);
@@ -22,6 +24,7 @@ if (!Session::checkCsrfToken()) {
$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
if ($userId <= 0) {
http_response_code(401);
Router::json(['ok' => false, 'error' => 'unauthorized']);
@@ -36,9 +39,9 @@ if ($id <= 0) {
}
$service = app(NotificationService::class);
$service->dismiss($userId, $id);
$service->dismiss($userId, $id, $tenantId > 0 ? $tenantId : null);
$unreadCount = $service->unreadCount($userId);
$unreadCount = $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null);
app(SessionStoreInterface::class)->set('module.notifications.unread_count', $unreadCount);
Router::json(['ok' => true, 'unread_count' => $unreadCount]);

View File

@@ -1,11 +1,13 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Router;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(NotificationsAuthorizationPolicy::ABILITY_VIEW);
if (requestInput()->method() !== 'GET') {
http_response_code(405);
@@ -15,6 +17,7 @@ if (requestInput()->method() !== 'GET') {
$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
if ($userId <= 0) {
http_response_code(401);
Router::json(['ok' => false, 'error' => 'unauthorized']);
@@ -22,8 +25,8 @@ if ($userId <= 0) {
}
$service = app(NotificationService::class);
$notifications = $service->listForUser($userId, 50);
$unreadCount = $service->unreadCount($userId);
$notifications = $service->listForUser($userId, $tenantId > 0 ? $tenantId : null, 50);
$unreadCount = $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null);
app(SessionStoreInterface::class)->set('module.notifications.unread_count', $unreadCount);

View File

@@ -1,12 +1,14 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Router;
use MintyPHP\Session;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(NotificationsAuthorizationPolicy::ABILITY_VIEW);
if (requestInput()->method() !== 'POST') {
http_response_code(405);
@@ -22,6 +24,7 @@ if (!Session::checkCsrfToken()) {
$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
if ($userId <= 0) {
http_response_code(401);
Router::json(['ok' => false, 'error' => 'unauthorized']);
@@ -33,16 +36,16 @@ $all = requestInput()->body('all');
$id = (int) requestInput()->body('id');
if ($all) {
$service->markAllAsRead($userId);
$service->markAllAsRead($userId, $tenantId > 0 ? $tenantId : null);
} elseif ($id > 0) {
$service->markAsRead($userId, $id);
$service->markAsRead($userId, $id, $tenantId > 0 ? $tenantId : null);
} else {
http_response_code(400);
Router::json(['ok' => false, 'error' => 'invalid_request']);
return;
}
$unreadCount = $service->unreadCount($userId);
$unreadCount = $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null);
app(SessionStoreInterface::class)->set('module.notifications.unread_count', $unreadCount);
Router::json(['ok' => true, 'unread_count' => $unreadCount]);

View File

@@ -1,11 +1,13 @@
<?php
use MintyPHP\Http\SessionStoreInterface;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Router;
use MintyPHP\Support\Guard;
Guard::requireLogin();
Guard::requireAbilityOrForbidden(NotificationsAuthorizationPolicy::ABILITY_VIEW);
if (requestInput()->method() !== 'GET') {
http_response_code(405);
@@ -15,6 +17,7 @@ if (requestInput()->method() !== 'GET') {
$session = app(SessionStoreInterface::class)->all();
$userId = (int) ($session['user']['id'] ?? 0);
$tenantId = (int) (($session['current_tenant']['id'] ?? 0));
if ($userId <= 0) {
http_response_code(401);
Router::json(['ok' => false, 'error' => 'unauthorized']);
@@ -22,7 +25,7 @@ if ($userId <= 0) {
}
$service = app(NotificationService::class);
$unreadCount = $service->unreadCount($userId);
$unreadCount = $service->unreadCount($userId, $tenantId > 0 ? $tenantId : null);
app(SessionStoreInterface::class)->set('module.notifications.unread_count', $unreadCount);

View File

@@ -5,7 +5,7 @@ $notifNav = is_array($layoutNav['notifications.nav'] ?? null) ? $layoutNav['noti
$unreadCount = (int) ($notifNav['unread_count'] ?? 0);
?>
<li>
<details class="dropdown app-topbar-notification-menu" data-notification-bell>
<details class="dropdown app-topbar-notification-menu" data-notification-bell data-summary-chevron="none">
<summary
aria-label="<?php e(t('Notifications')); ?>"
>
@@ -32,7 +32,7 @@ $unreadCount = (int) ($notifNav['unread_count'] ?? 0);
'size' => 'compact',
'icon' => false,
];
require __DIR__ . '/../../../templates/partials/app-empty-state.phtml';
require templatePath('partials/app-empty-state.phtml');
?>
</li>
</ul>

View File

@@ -0,0 +1,99 @@
<?php
namespace MintyPHP\Tests\Module\Notifications\Listeners;
use MintyPHP\Module\Notifications\Listeners\UserActivatedNotificationListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
final class UserActivatedNotificationListenerTest extends TestCase
{
private NotificationService&MockObject $notificationService;
private UserReadRepositoryInterface&MockObject $userReadRepository;
private UserTenantRepositoryInterface&MockObject $userTenantRepository;
private UserActivatedNotificationListener $listener;
protected function setUp(): void
{
$this->notificationService = $this->createMock(NotificationService::class);
$this->userReadRepository = $this->createMock(UserReadRepositoryInterface::class);
$this->userTenantRepository = $this->createMock(UserTenantRepositoryInterface::class);
$this->listener = new UserActivatedNotificationListener(
$this->notificationService,
$this->userReadRepository,
$this->userTenantRepository
);
}
public function testHandleNotifiesTenantAdmins(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userReadRepository->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->with([PermissionService::USERS_UPDATE])
->willReturn([20, 30]);
$this->notificationService->expects($this->exactly(2))
->method('createForTenantAdminUsers')
->with(
$this->callback(static fn (int $tenantId): bool => in_array($tenantId, [1, 2], true)),
'user.activated',
$this->stringContains('Alice'),
null,
'admin/users/edit/user-uuid',
['user_id' => 10, 'uuid' => 'user-uuid'],
5,
$this->isType('array')
);
$this->listener->handle('user.activated', [
'user_id' => 10,
'tenant_ids' => [1, 2],
'actor_user_id' => 5,
]);
}
public function testHandleFallsBackToUserTenantAssignments(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userTenantRepository->expects($this->once())->method('listTenantIdsByUserId')->with(10)->willReturn([7]);
$this->userReadRepository->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->willReturn([20]);
$this->notificationService->expects($this->once())
->method('createForTenantAdminUsers')
->with(
7,
'user.activated',
$this->anything(),
null,
'admin/users/edit/user-uuid',
$this->anything(),
null,
$this->anything()
);
$this->listener->handle('user.activated', ['user_id' => 10]);
}
public function testHandleSkipsInvalidPayload(): void
{
$this->userReadRepository->expects($this->never())->method('find');
$this->notificationService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.activated', ['user_id' => 0]);
}
}

View File

@@ -0,0 +1,114 @@
<?php
namespace MintyPHP\Tests\Module\Notifications\Listeners;
use MintyPHP\Module\Notifications\Listeners\UserAssignmentChangedNotificationListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
final class UserAssignmentChangedNotificationListenerTest extends TestCase
{
private NotificationService&MockObject $notificationService;
private UserReadRepositoryInterface&MockObject $userReadRepository;
private UserAssignmentChangedNotificationListener $listener;
protected function setUp(): void
{
$this->notificationService = $this->createMock(NotificationService::class);
$this->userReadRepository = $this->createMock(UserReadRepositoryInterface::class);
$this->listener = new UserAssignmentChangedNotificationListener(
$this->notificationService,
$this->userReadRepository
);
}
public function testHandleNotifiesAffectedUserAndTenantAdmins(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userReadRepository->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->with([PermissionService::USERS_UPDATE_ASSIGNMENTS])
->willReturn([20, 30]);
$this->notificationService->expects($this->once())
->method('createForUser')
->with(
10,
null,
'user.assignment_changed',
$this->stringContains('Alice'),
$this->isType('string'),
'admin/users/edit/user-uuid',
$this->isType('array')
)
->willReturn(99);
$this->notificationService->expects($this->once())
->method('createForTenantAdminUsers')
->with(
1,
'user.assignment_changed',
$this->stringContains('Alice'),
$this->isType('string'),
'admin/users/edit/user-uuid',
$this->isType('array'),
7,
$this->isType('array')
)
->willReturn(1);
$this->listener->handle('user.assignment_changed', [
'user_id' => 10,
'tenant_ids' => [1],
'actor_user_id' => 7,
'changes' => ['roles' => ['before' => [1], 'after' => [2]]],
]);
}
public function testHandleExcludesAffectedUserWhenActorEqualsTarget(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userReadRepository->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->willReturn([20]);
$this->notificationService->expects($this->never())->method('createForUser');
$this->notificationService->expects($this->once())
->method('createForTenantAdminUsers')
->with(
1,
'user.assignment_changed',
$this->anything(),
$this->anything(),
'admin/users/edit/user-uuid',
$this->anything(),
10,
$this->anything()
);
$this->listener->handle('user.assignment_changed', [
'user_id' => 10,
'tenant_ids' => [1],
'actor_user_id' => 10,
]);
}
public function testHandleSkipsInvalidPayload(): void
{
$this->notificationService->expects($this->never())->method('createForUser');
$this->notificationService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.assignment_changed', ['user_id' => 0]);
}
}

View File

@@ -27,14 +27,14 @@ class UserCreatedNotificationListenerTest extends TestCase
public function testHandleCreatesNotificationsForTenantAdminUsers(): void
{
$this->userRepo->method('find')->with(10)->willReturn([
$this->userRepo->expects($this->any())->method('find')->with(10)->willReturn([
'id' => 10,
'display_name' => 'Alice Smith',
'first_name' => 'Alice',
'last_name' => 'Smith',
]);
$this->utRepo->method('listTenantIdsByUserId')->with(10)->willReturn([1, 2]);
$this->userRepo->method('listPrivilegedUserIdsByPermissionKeys')
$this->utRepo->expects($this->any())->method('listTenantIdsByUserId')->with(10)->willReturn([1, 2]);
$this->userRepo->expects($this->any())->method('listPrivilegedUserIdsByPermissionKeys')
->with([PermissionService::USERS_CREATE])
->willReturn([20, 30]);
@@ -60,12 +60,12 @@ class UserCreatedNotificationListenerTest extends TestCase
public function testHandleExcludesActorFromRecipients(): void
{
$this->userRepo->method('find')->with(10)->willReturn([
$this->userRepo->expects($this->any())->method('find')->with(10)->willReturn([
'id' => 10,
'display_name' => 'Bob',
]);
$this->utRepo->method('listTenantIdsByUserId')->with(10)->willReturn([1]);
$this->userRepo->method('listPrivilegedUserIdsByPermissionKeys')->willReturn([20]);
$this->utRepo->expects($this->any())->method('listTenantIdsByUserId')->with(10)->willReturn([1]);
$this->userRepo->expects($this->any())->method('listPrivilegedUserIdsByPermissionKeys')->willReturn([20]);
$this->notifService->expects($this->once())
->method('createForTenantAdminUsers')
@@ -99,7 +99,7 @@ class UserCreatedNotificationListenerTest extends TestCase
public function testHandleSkipsWhenUserNotFound(): void
{
$this->userRepo->method('find')->with(99)->willReturn(null);
$this->userRepo->expects($this->any())->method('find')->with(99)->willReturn(null);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.created', [
@@ -111,11 +111,11 @@ class UserCreatedNotificationListenerTest extends TestCase
public function testHandleSkipsWhenNoTenants(): void
{
$this->userRepo->method('find')->with(10)->willReturn([
$this->userRepo->expects($this->any())->method('find')->with(10)->willReturn([
'id' => 10,
'display_name' => 'Alice',
]);
$this->utRepo->method('listTenantIdsByUserId')->with(10)->willReturn([]);
$this->utRepo->expects($this->any())->method('listTenantIdsByUserId')->with(10)->willReturn([]);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.created', [
@@ -127,12 +127,12 @@ class UserCreatedNotificationListenerTest extends TestCase
public function testHandleSkipsWhenNoAdminUsers(): void
{
$this->userRepo->method('find')->with(10)->willReturn([
$this->userRepo->expects($this->any())->method('find')->with(10)->willReturn([
'id' => 10,
'display_name' => 'Alice',
]);
$this->utRepo->method('listTenantIdsByUserId')->with(10)->willReturn([1]);
$this->userRepo->method('listPrivilegedUserIdsByPermissionKeys')->willReturn([]);
$this->utRepo->expects($this->any())->method('listTenantIdsByUserId')->with(10)->willReturn([1]);
$this->userRepo->expects($this->any())->method('listPrivilegedUserIdsByPermissionKeys')->willReturn([]);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');

View File

@@ -0,0 +1,76 @@
<?php
namespace MintyPHP\Tests\Module\Notifications\Listeners;
use MintyPHP\Module\Notifications\Listeners\UserDeactivatedNotificationListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
final class UserDeactivatedNotificationListenerTest extends TestCase
{
private NotificationService&MockObject $notificationService;
private UserReadRepositoryInterface&MockObject $userReadRepository;
private UserTenantRepositoryInterface&MockObject $userTenantRepository;
private UserDeactivatedNotificationListener $listener;
protected function setUp(): void
{
$this->notificationService = $this->createMock(NotificationService::class);
$this->userReadRepository = $this->createMock(UserReadRepositoryInterface::class);
$this->userTenantRepository = $this->createMock(UserTenantRepositoryInterface::class);
$this->listener = new UserDeactivatedNotificationListener(
$this->notificationService,
$this->userReadRepository,
$this->userTenantRepository
);
}
public function testHandleNotifiesTenantAdmins(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userReadRepository->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->with([PermissionService::USERS_UPDATE])
->willReturn([20, 30]);
$this->notificationService->expects($this->exactly(2))
->method('createForTenantAdminUsers')
->with(
$this->callback(static fn (int $tenantId): bool => in_array($tenantId, [1, 2], true)),
'user.deactivated',
$this->stringContains('Alice'),
null,
'admin/users/edit/user-uuid',
['user_id' => 10, 'uuid' => 'user-uuid'],
5,
$this->isType('array')
);
$this->listener->handle('user.deactivated', [
'user_id' => 10,
'tenant_ids' => [1, 2],
'actor_user_id' => 5,
]);
}
public function testHandleSkipsWhenNoTenantIsResolved(): void
{
$this->userReadRepository->expects($this->once())->method('find')->with(10)->willReturn([
'id' => 10,
'uuid' => 'user-uuid',
'display_name' => 'Alice',
]);
$this->userTenantRepository->expects($this->once())->method('listTenantIdsByUserId')->with(10)->willReturn([]);
$this->notificationService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.deactivated', ['user_id' => 10]);
}
}

View File

@@ -0,0 +1,142 @@
<?php
namespace MintyPHP\Tests\Module\Notifications\Listeners;
use MintyPHP\Module\Notifications\Listeners\UserDeletedNotificationListener;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\User\UserReadRepositoryInterface;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class UserDeletedNotificationListenerTest extends TestCase
{
private NotificationService&MockObject $notifService;
private UserReadRepositoryInterface&MockObject $userRepo;
private UserDeletedNotificationListener $listener;
protected function setUp(): void
{
$this->notifService = $this->createMock(NotificationService::class);
$this->userRepo = $this->createMock(UserReadRepositoryInterface::class);
$this->listener = new UserDeletedNotificationListener($this->notifService, $this->userRepo);
}
public function testHandleCleansUpAndNotifiesAdmins(): void
{
$this->notifService->expects($this->once())
->method('deleteAllForUser')
->with(10);
$this->userRepo->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->with([PermissionService::USERS_DELETE])
->willReturn([20, 30]);
$this->notifService->expects($this->exactly(2))
->method('createForTenantAdminUsers')
->willReturnCallback(function (int $tenantId, string $type, string $title, ?string $body, ?string $link, array $data, ?int $excludeUserId, array $adminSet): int {
$this->assertContains($tenantId, [1, 2]);
$this->assertSame('user.deleted', $type);
$this->assertStringContainsString('Alice', $title);
$this->assertNull($link);
$this->assertSame(5, $excludeUserId);
$this->assertArrayHasKey(20, $adminSet);
$this->assertArrayHasKey(30, $adminSet);
return 1;
});
$this->listener->handle('user.deleted', [
'user_id' => 10,
'display_name' => 'Alice',
'tenant_ids' => [1, 2],
'actor_user_id' => 5,
]);
}
public function testHandleSkipsOnInvalidUserId(): void
{
$this->notifService->expects($this->never())->method('deleteAllForUser');
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.deleted', ['user_id' => 0]);
$this->listener->handle('user.deleted', []);
}
public function testHandleStillCleansUpWhenDisplayNameEmpty(): void
{
$this->notifService->expects($this->once())
->method('deleteAllForUser')
->with(10);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.deleted', [
'user_id' => 10,
'display_name' => '',
'tenant_ids' => [1],
]);
}
public function testHandleStillCleansUpWhenTenantIdsEmpty(): void
{
$this->notifService->expects($this->once())
->method('deleteAllForUser')
->with(10);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.deleted', [
'user_id' => 10,
'display_name' => 'Alice',
'tenant_ids' => [],
]);
}
public function testHandleExcludesActorFromRecipients(): void
{
$this->notifService->expects($this->once())->method('deleteAllForUser')->with(10);
$this->userRepo->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->willReturn([20]);
$this->notifService->expects($this->once())
->method('createForTenantAdminUsers')
->with(
1,
'user.deleted',
$this->anything(),
null,
null,
$this->anything(),
7, // actor excluded
$this->anything()
)
->willReturn(1);
$this->listener->handle('user.deleted', [
'user_id' => 10,
'display_name' => 'Alice',
'tenant_ids' => [1],
'actor_user_id' => 7,
]);
}
public function testHandleSkipsNotificationWhenNoAdminUsers(): void
{
$this->notifService->expects($this->once())->method('deleteAllForUser')->with(10);
$this->userRepo->expects($this->once())
->method('listPrivilegedUserIdsByPermissionKeys')
->willReturn([]);
$this->notifService->expects($this->never())->method('createForTenantAdminUsers');
$this->listener->handle('user.deleted', [
'user_id' => 10,
'display_name' => 'Alice',
'tenant_ids' => [1],
]);
}
}

View File

@@ -0,0 +1,55 @@
<?php
namespace MintyPHP\Tests\Module\Notifications;
use MintyPHP\Module\Notifications\NotificationsAuthorizationPolicy;
use MintyPHP\Service\Access\PermissionService;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
final class NotificationsAuthorizationPolicyTest extends TestCase
{
private PermissionService&MockObject $permissionService;
private NotificationsAuthorizationPolicy $policy;
protected function setUp(): void
{
$this->permissionService = $this->createMock(PermissionService::class);
$this->policy = new NotificationsAuthorizationPolicy($this->permissionService);
}
public function testSupportsNotificationsAbilityOnly(): void
{
self::assertTrue($this->policy->supports(NotificationsAuthorizationPolicy::ABILITY_VIEW));
self::assertFalse($this->policy->supports('users.view'));
}
public function testAuthorizeAllowsUserWithPermission(): void
{
$this->permissionService->expects($this->once())
->method('userHas')
->with(11, NotificationsAuthorizationPolicy::PERMISSION_KEY)
->willReturn(true);
$decision = $this->policy->authorize(NotificationsAuthorizationPolicy::ABILITY_VIEW, [
'actor_user_id' => 11,
]);
self::assertTrue($decision->isAllowed());
}
public function testAuthorizeDeniesWithoutPermission(): void
{
$this->permissionService->expects($this->once())
->method('userHas')
->with(11, NotificationsAuthorizationPolicy::PERMISSION_KEY)
->willReturn(false);
$decision = $this->policy->authorize(NotificationsAuthorizationPolicy::ABILITY_VIEW, [
'actor_user_id' => 11,
]);
self::assertFalse($decision->isAllowed());
self::assertSame(403, $decision->status());
}
}

View File

@@ -4,18 +4,21 @@ namespace MintyPHP\Tests\Module\Notifications\Service;
use MintyPHP\Module\Notifications\Repository\NotificationRepositoryInterface;
use MintyPHP\Module\Notifications\Service\NotificationService;
use MintyPHP\Repository\Tenant\UserTenantRepositoryInterface;
use PHPUnit\Framework\MockObject\MockObject;
use PHPUnit\Framework\TestCase;
class NotificationServiceTest extends TestCase
{
private NotificationRepositoryInterface&MockObject $notifRepo;
private UserTenantRepositoryInterface&MockObject $utRepo;
private NotificationService $service;
protected function setUp(): void
{
$this->notifRepo = $this->createMock(NotificationRepositoryInterface::class);
$this->service = new NotificationService($this->notifRepo);
$this->utRepo = $this->createMock(UserTenantRepositoryInterface::class);
$this->service = new NotificationService($this->notifRepo, $this->utRepo);
}
public function testCreateForUserInsertsNotification(): void
@@ -46,7 +49,7 @@ class NotificationServiceTest extends TestCase
public function testUnreadCountReturnsCorrectCount(): void
{
$this->notifRepo->method('countUnreadByUser')->with(3)->willReturn(7);
$this->notifRepo->expects($this->any())->method('countUnreadByUser')->with(3, null)->willReturn(7);
$this->assertSame(7, $this->service->unreadCount(3));
}
@@ -62,7 +65,7 @@ class NotificationServiceTest extends TestCase
{
$this->notifRepo->expects($this->once())
->method('markRead')
->with(10, 3)
->with(10, 3, null)
->willReturn(true);
$this->assertTrue($this->service->markAsRead(3, 10));
@@ -80,7 +83,7 @@ class NotificationServiceTest extends TestCase
{
$this->notifRepo->expects($this->once())
->method('markAllReadByUser')
->with(3)
->with(3, null)
->willReturn(5);
$this->assertSame(5, $this->service->markAllAsRead(3));
@@ -90,7 +93,7 @@ class NotificationServiceTest extends TestCase
{
$this->notifRepo->expects($this->once())
->method('delete')
->with(10, 3)
->with(10, 3, null)
->willReturn(true);
$this->assertTrue($this->service->dismiss(3, 10));
@@ -122,8 +125,161 @@ class NotificationServiceTest extends TestCase
['id' => 1, 'title' => 'Test', 'is_read' => 0],
['id' => 2, 'title' => 'Test 2', 'is_read' => 1],
];
$this->notifRepo->method('listByUser')->with(3, 50, 0)->willReturn($expected);
$this->notifRepo->expects($this->any())->method('listByUser')->with(3, null, 50, 0)->willReturn($expected);
$this->assertSame($expected, $this->service->listForUser(3));
}
public function testListForUserPassesTenantScope(): void
{
$this->notifRepo->expects($this->once())
->method('listByUser')
->with(3, 9, 25, 0)
->willReturn([]);
$this->assertSame([], $this->service->listForUser(3, 9, 25));
}
// --- createForTenantUsers ---
public function testCreateForTenantUsersCreatesForAllUsersExcludingActor(): void
{
$this->utRepo->expects($this->once())
->method('listActiveUserIdsByTenantId')
->with(1)
->willReturn([10, 20, 30]);
$this->notifRepo->expects($this->exactly(2))
->method('create')
->willReturn(1);
$result = $this->service->createForTenantUsers(1, 'system', 'Hello', null, null, [], 20);
$this->assertSame(2, $result);
}
public function testCreateForTenantUsersSkipsSuppressedDuplicates(): void
{
$this->utRepo->expects($this->once())
->method('listActiveUserIdsByTenantId')
->with(1)
->willReturn([10, 20, 30]);
$this->notifRepo->expects($this->exactly(3))
->method('create')
->willReturnOnConsecutiveCalls(11, false, 13);
$result = $this->service->createForTenantUsers(1, 'user.activated', 'Activated', null, null, ['user_id' => 99], null);
$this->assertSame(2, $result);
}
public function testCreateForTenantUsersCreatesForAllWhenNoExclude(): void
{
$this->utRepo->expects($this->once())
->method('listActiveUserIdsByTenantId')
->with(1)
->willReturn([10, 20]);
$this->notifRepo->expects($this->exactly(2))
->method('create')
->willReturn(1);
$result = $this->service->createForTenantUsers(1, 'system', 'Hello', null, null, [], null);
$this->assertSame(2, $result);
}
public function testCreateForTenantUsersRejectsInvalidInputs(): void
{
$this->utRepo->expects($this->never())->method('listActiveUserIdsByTenantId');
$this->notifRepo->expects($this->never())->method('create');
$this->assertSame(0, $this->service->createForTenantUsers(0, 'system', 'Hello', null, null, [], null));
$this->assertSame(0, $this->service->createForTenantUsers(1, '', 'Hello', null, null, [], null));
$this->assertSame(0, $this->service->createForTenantUsers(1, 'system', '', null, null, [], null));
}
// --- createForTenantAdminUsers ---
public function testCreateForTenantAdminUsersFiltersToAllowedUsers(): void
{
$this->utRepo->expects($this->once())
->method('listActiveUserIdsByTenantId')
->with(1)
->willReturn([10, 20, 30, 40]);
$this->notifRepo->expects($this->exactly(2))
->method('create')
->willReturn(1);
$allowedUserIds = array_flip([20, 30]);
$result = $this->service->createForTenantAdminUsers(1, 'system', 'Hello', null, null, [], null, $allowedUserIds);
$this->assertSame(2, $result);
}
public function testCreateForTenantAdminUsersExcludesActor(): void
{
$this->utRepo->expects($this->once())
->method('listActiveUserIdsByTenantId')
->with(1)
->willReturn([10, 20, 30]);
$this->notifRepo->expects($this->once())
->method('create')
->willReturn(1);
$allowedUserIds = array_flip([20, 30]);
$result = $this->service->createForTenantAdminUsers(1, 'system', 'Hello', null, null, [], 20, $allowedUserIds);
$this->assertSame(1, $result);
}
public function testCreateForTenantAdminUsersRejectsEmptyAllowedUsers(): void
{
$this->utRepo->expects($this->never())->method('listActiveUserIdsByTenantId');
$this->notifRepo->expects($this->never())->method('create');
$this->assertSame(0, $this->service->createForTenantAdminUsers(1, 'system', 'Hello', null, null, [], null, []));
}
public function testCreateForTenantAdminUsersRejectsInvalidInputs(): void
{
$this->utRepo->expects($this->never())->method('listActiveUserIdsByTenantId');
$this->notifRepo->expects($this->never())->method('create');
$allowed = array_flip([10]);
$this->assertSame(0, $this->service->createForTenantAdminUsers(0, 'system', 'Hello', null, null, [], null, $allowed));
$this->assertSame(0, $this->service->createForTenantAdminUsers(1, '', 'Hello', null, null, [], null, $allowed));
$this->assertSame(0, $this->service->createForTenantAdminUsers(1, 'system', '', null, null, [], null, $allowed));
}
public function testCreateForUserAddsDedupeMetadataForCoreTypes(): void
{
$this->notifRepo->expects($this->once())
->method('create')
->with($this->callback(function (array $data): bool {
return $data['type'] === 'user.deleted'
&& !empty($data['dedupe_fingerprint'])
&& !empty($data['dedupe_bucket']);
}))
->willReturn(55);
$result = $this->service->createForUser(5, 1, 'user.deleted', 'User deleted: Bob', null, null, ['user_id' => 33]);
$this->assertSame(55, $result);
}
public function testCreateForUserSkipsDedupeMetadataForNonCoreTypes(): void
{
$this->notifRepo->expects($this->once())
->method('create')
->with($this->callback(function (array $data): bool {
return !isset($data['dedupe_fingerprint']) || $data['dedupe_fingerprint'] === null;
}))
->willReturn(56);
$result = $this->service->createForUser(5, 1, 'system', 'System', null, null, ['user_id' => 33]);
$this->assertSame(56, $result);
}
}

View File

@@ -1,125 +1,159 @@
@layer components {
ul.app-notification-dropdown {
width: 360px;
padding: 0;
}
ul.app-notification-dropdown {
width: 360px;
padding: 0;
--app-notification-text: var(--app-dropdown-color);
--app-notification-muted: var(--app-muted-color);
--app-notification-hover: var(--app-dropdown-hover-background-color);
--app-notification-border: var(--app-dropdown-border-color);
--app-notification-focus: var(--app-primary-focus);
}
.app-notification-dropdown__header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 12px 16px;
border-bottom: 1px solid var(--app-border, #dee2e6);
}
.app-notification-dropdown__header {
padding: 12px 16px;
border-bottom: 1px solid var(--app-notification-border);
}
.app-notification-dropdown__title {
font-size: 14px;
font-weight: 600;
}
.app-notification-dropdown__title {
font-size: 14px;
font-weight: 600;
color: var(--app-notification-text);
}
.app-notification-dropdown__mark-all {
background: none;
border: none;
color: var(--app-primary, #105433);
font-size: 12px;
cursor: pointer;
padding: 2px 4px;
}
.app-notification-dropdown__mark-all {
background: none;
border: none;
color: var(--app-primary);
font-size: 11px;
cursor: pointer;
padding: 0;
}
.app-notification-dropdown__mark-all:hover {
text-decoration: underline;
}
.app-notification-dropdown__mark-all:hover {
text-decoration: underline;
}
.app-notification-dropdown__body {
overflow-y: auto;
max-height: 400px;
padding: 0;
}
.app-notification-dropdown__body {
overflow-y: auto;
max-height: 400px;
padding: 0;
}
.app-notification-item {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 16px;
border-bottom: 1px solid var(--app-border-light, #f0f0f0);
cursor: pointer;
transition: background 0.15s;
}
.app-notification-item {
display: flex;
align-items: flex-start;
gap: 10px;
padding: 10px 16px;
border-bottom: 1px solid var(--app-notification-border);
cursor: pointer;
transition: background 0.15s;
color: var(--app-notification-text);
}
.app-notification-item:hover {
background: var(--app-hover, #f8f9fa);
}
/* Keep row-link notifications visually stable despite global role-based styles. */
.app-notification-item--link {
margin: 0;
border: 0;
border-radius: 0;
border-bottom: 1px solid var(--app-notification-border);
outline: 0;
background: transparent;
box-shadow: none;
color: var(--app-notification-text);
font: inherit;
font-weight: inherit;
line-height: inherit;
text-align: left;
text-decoration: none;
}
.app-notification-item--unread {
border-left: 3px solid var(--app-primary, #105433);
}
.app-notification-item--link:is(:hover, :active, :focus) {
background: var(--app-notification-hover);
box-shadow: none;
color: var(--app-notification-text);
}
.app-notification-item__icon {
flex-shrink: 0;
font-size: 16px;
margin-top: 2px;
color: var(--app-muted, #6c757d);
}
.app-notification-item--link:focus-visible {
outline: 2px solid var(--app-notification-focus);
outline-offset: -2px;
}
.app-notification-item--unread .app-notification-item__icon {
color: var(--app-primary, #105433);
}
.app-notification-item:hover {
background: var(--app-notification-hover);
}
.app-notification-item__content {
flex: 1;
min-width: 0;
}
.app-notification-item--unread {
border-left: 3px solid var(--app-primary);
}
.app-notification-item__title {
font-size: 13px;
font-weight: 500;
line-height: 1.3;
margin: 0 0 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-notification-item__icon {
flex-shrink: 0;
font-size: 16px;
margin-top: 2px;
color: var(--app-notification-muted);
}
.app-notification-item__body {
font-size: 12px;
color: var(--app-muted, #6c757d);
line-height: 1.3;
margin: 0 0 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-notification-item--unread .app-notification-item__icon {
color: var(--app-primary);
}
.app-notification-item__time {
font-size: 11px;
color: var(--app-muted, #6c757d);
}
.app-notification-item__content {
flex: 1;
min-width: 0;
}
.app-notification-item__actions {
flex-shrink: 0;
display: flex;
gap: 4px;
opacity: 0;
transition: opacity 0.15s;
}
.app-notification-item__title {
font-size: 13px;
font-weight: 500;
color: var(--app-notification-text);
line-height: 1.3;
margin: 0 0 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-notification-item:hover .app-notification-item__actions {
opacity: 1;
}
.app-notification-item__body {
font-size: 12px;
color: var(--app-notification-muted);
line-height: 1.3;
margin: 0 0 2px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.app-notification-item__action-btn {
background: none;
border: none;
color: var(--app-muted, #6c757d);
font-size: 14px;
cursor: pointer;
padding: 2px;
line-height: 1;
border-radius: 4px;
}
.app-notification-item__time {
font-size: 11px;
color: var(--app-notification-muted);
}
.app-notification-item__action-btn:hover {
color: var(--app-text, #212529);
background: var(--app-border-light, #f0f0f0);
}
.app-notification-item__actions {
flex-shrink: 0;
display: flex;
gap: 4px;
opacity: 0;
transition: opacity 0.15s;
}
.app-notification-item:hover .app-notification-item__actions,
.app-notification-item:focus-within .app-notification-item__actions {
opacity: 1;
}
.app-notification-item__action-btn {
background: none;
border: none;
color: var(--app-notification-muted);
font-size: 14px;
cursor: pointer;
padding: 2px;
line-height: 1;
border-radius: 4px;
}
.app-notification-item__action-btn:hover {
color: var(--app-notification-text);
background: var(--app-notification-border);
}
}

View File

@@ -1,22 +1,40 @@
@layer layout {
.app-topbar-notification-menu > summary {
position: relative;
}
.app-topbar-notification-menu {
--app-notification-badge-bg: var(--app-action-danger-background);
--app-notification-badge-color: var(--app-action-danger-color);
}
.app-notification-badge {
position: absolute;
top: 2px;
right: 2px;
min-width: 18px;
height: 18px;
padding: 0 4px;
border-radius: 9px;
background: var(--app-danger, #dc3545);
color: #fff;
font-size: 11px;
font-weight: 600;
line-height: 18px;
text-align: center;
pointer-events: none;
}
.app-topbar-notification-menu > summary {
position: relative;
}
.app-topbar-notification-menu > summary::after {
display: none;
content: none;
}
.app-topbar-notification-menu > summary::-webkit-details-marker {
display: none;
}
.app-topbar-notification-menu > summary::marker {
content: "";
}
.app-notification-badge {
position: absolute;
top: 5px;
right: 0px;
min-width: 13px;
height: 13px;
padding: 0 3px;
border-radius: 999px;
background: var(--app-notification-badge-bg);
color: var(--app-notification-badge-color);
font-size: 7px;
font-weight: 600;
line-height: 13px;
text-align: center;
pointer-events: none;
}
}

View File

@@ -5,10 +5,16 @@
* notification list rendering, mark-read and dismiss actions.
*/
import { telemetry } from '../../../../js/core/app-telemetry.js';
import { getAppBase } from '../../../../js/pages/app-list-utils.js';
const POLL_INTERVAL_MS = 60_000;
const TYPE_ICONS = {
'user.created': 'bi-person-plus',
'user.deleted': 'bi-person-dash',
'user.activated': 'bi-person-check',
'user.deactivated': 'bi-person-x',
'user.assignment_changed': 'bi-diagram-3',
'system': 'bi-gear',
};
@@ -47,6 +53,8 @@ export function initNotificationBell(root = document, config = {}) {
const details = root.querySelector('[data-notification-bell]');
const dropdown = root.querySelector('[data-notification-dropdown]');
if (!details || !dropdown) return { destroy() {} };
const appBase = getAppBase();
const endpoint = (path) => new URL(path, appBase).toString();
const badge = details.querySelector('[data-notification-badge]');
const list = dropdown.querySelector('[data-notification-list]');
@@ -109,15 +117,34 @@ export function initNotificationBell(root = document, config = {}) {
`<button type="button" class="app-notification-item__action-btn" data-action="dismiss" title="${escapeHtml(dropdown.dataset.labelDismiss || '')}"><i class="bi bi-x"></i></button>` +
`</div>`;
// Click on item navigates if link exists
item.addEventListener('click', (e) => {
if (e.target.closest('[data-action]')) return;
if (n.link) {
// Keyboard + click navigation for items with a link
if (n.link) {
item.classList.add('app-notification-item--link');
item.setAttribute('role', 'link');
item.setAttribute('tabindex', '0');
const navigate = () => {
if (n.is_read === 0) markRead(n.id);
const base = document.querySelector('base')?.getAttribute('href') || '/';
window.location.href = base + n.link;
}
}, { signal });
window.location.href = endpoint(String(n.link));
};
item.addEventListener('click', (e) => {
if (e.target.closest('[data-action]')) return;
navigate();
}, { signal });
item.addEventListener('keydown', (e) => {
if (e.target.closest('[data-action]')) return;
if (e.key === 'Enter') {
e.preventDefault();
navigate();
}
}, { signal });
} else {
item.addEventListener('click', (e) => {
if (e.target.closest('[data-action]')) return;
}, { signal });
}
// Action buttons
item.addEventListener('click', (e) => {
@@ -135,21 +162,33 @@ export function initNotificationBell(root = document, config = {}) {
// --- API ---
async function loadNotifications() {
try {
const data = await fetchJson('notifications/list-data', { signal });
const data = await fetchJson(endpoint('notifications/list-data'), { signal });
if (data.ok) {
renderNotifications(data.notifications || []);
updateBadge(data.unread_count ?? 0);
}
} catch { /* swallow */ }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
telemetry.capture('warn_once', {
message: 'Notification bell: load failed',
meta: { module: 'notifications', component: 'notification-bell', action: 'load' },
});
}
}
async function pollUnreadCount() {
try {
const data = await fetchJson('notifications/unread-count-data', { signal });
const data = await fetchJson(endpoint('notifications/unread-count-data'), { signal });
if (data.ok) {
updateBadge(data.unread_count ?? 0);
}
} catch { /* swallow */ }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
telemetry.capture('warn_once', {
message: 'Notification bell: poll failed',
meta: { module: 'notifications', component: 'notification-bell', action: 'poll' },
});
}
}
async function markRead(id) {
@@ -159,7 +198,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('id', String(id));
if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson('notifications/mark-read-data', {
const data = await fetchJson(endpoint('notifications/mark-read-data'), {
method: 'POST',
body,
signal,
@@ -168,7 +207,13 @@ export function initNotificationBell(root = document, config = {}) {
updateBadge(data.unread_count ?? 0);
if (details.open) loadNotifications();
}
} catch { /* swallow */ }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
telemetry.capture('warn_once', {
message: 'Notification bell: mark-read failed',
meta: { module: 'notifications', component: 'notification-bell', action: 'mark-read' },
});
}
}
async function markAllRead() {
@@ -178,7 +223,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('all', '1');
if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson('notifications/mark-read-data', {
const data = await fetchJson(endpoint('notifications/mark-read-data'), {
method: 'POST',
body,
signal,
@@ -187,7 +232,13 @@ export function initNotificationBell(root = document, config = {}) {
updateBadge(data.unread_count ?? 0);
if (details.open) loadNotifications();
}
} catch { /* swallow */ }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
telemetry.capture('warn_once', {
message: 'Notification bell: mark-all-read failed',
meta: { module: 'notifications', component: 'notification-bell', action: 'mark-all-read' },
});
}
}
async function dismiss(id) {
@@ -197,7 +248,7 @@ export function initNotificationBell(root = document, config = {}) {
body.set('id', String(id));
if (csrf.key) body.set(csrf.key, csrf.token);
const data = await fetchJson('notifications/delete-data', {
const data = await fetchJson(endpoint('notifications/delete-data'), {
method: 'POST',
body,
signal,
@@ -212,7 +263,13 @@ export function initNotificationBell(root = document, config = {}) {
}
}
}
} catch { /* swallow */ }
} catch (err) {
if (err instanceof DOMException && err.name === 'AbortError') return;
telemetry.capture('warn_once', {
message: 'Notification bell: dismiss failed',
meta: { module: 'notifications', component: 'notification-bell', action: 'dismiss' },
});
}
}
// --- Events ---