fixed notification system and added a new tenant notifications receipt table to track read status and filter messages by scope.

This commit is contained in:
Codex Agent
2025-12-17 10:57:19 +01:00
parent 0aae494945
commit d64839ba2f
31 changed files with 1089 additions and 127 deletions

View File

@@ -2,9 +2,12 @@
namespace App\Jobs\Concerns;
use App\Models\TenantNotificationLog;
use App\Models\TenantNotificationReceipt;
use App\Models\Tenant;
use App\Services\Packages\TenantNotificationLogger;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Carbon;
trait LogsTenantNotifications
{
@@ -18,6 +21,21 @@ trait LogsTenantNotifications
$this->notificationLogger()->log($tenant, $attributes);
}
protected function createNotificationReceipt(
Tenant $tenant,
TenantNotificationLog $log,
?int $userId,
?string $recipient
): TenantNotificationReceipt {
return TenantNotificationReceipt::query()->create([
'tenant_id' => $tenant->id,
'notification_log_id' => $log->id,
'user_id' => $userId,
'recipient' => $recipient,
'status' => 'delivered',
]);
}
protected function dispatchToRecipients(
Tenant $tenant,
iterable $recipients,
@@ -29,7 +47,7 @@ trait LogsTenantNotifications
try {
$callback($recipient);
$this->logNotification($tenant, [
$log = $this->notificationLogger()->log($tenant, [
'type' => $type,
'channel' => 'mail',
'recipient' => $recipient,
@@ -37,6 +55,13 @@ trait LogsTenantNotifications
'context' => $context,
'sent_at' => now(),
]);
$this->createNotificationReceipt(
$tenant,
$log,
$tenant->user?->id,
$recipient
);
} catch (\Throwable $e) {
Log::error('Tenant notification failed', [
'tenant_id' => $tenant->id,
@@ -57,4 +82,51 @@ trait LogsTenantNotifications
}
}
}
/**
* Simple idempotency guard to avoid duplicate notifications within a cooldown window.
*
* @param string[] $dedupeKeys
*/
protected function isDuplicateNotification(
Tenant $tenant,
string $type,
array $context,
array $dedupeKeys,
int $cooldownMinutes = 1440
): bool {
$window = Carbon::now()->subMinutes($cooldownMinutes);
$logs = TenantNotificationLog::query()
->where('tenant_id', $tenant->id)
->where('type', $type)
->whereIn('status', ['sent', 'queued'])
->where(function ($query) use ($window) {
$query->whereNull('created_at')
->orWhere('created_at', '>=', $window)
->orWhere('sent_at', '>=', $window);
})
->get();
foreach ($logs as $log) {
$existing = is_array($log->context) ? $log->context : [];
$matches = true;
foreach ($dedupeKeys as $key) {
$currentValue = $context[$key] ?? null;
$existingValue = $existing[$key] ?? null;
if ($currentValue != $existingValue) {
$matches = false;
break;
}
}
if ($matches) {
return true;
}
}
return false;
}
}