Files
baya-monorepo/server/src/Infrastructure/Baya.Infrastructure.Persistence/Services/Notifications/NotificationService.cs
T
hamid 2f2aec61a2 backend phase 1: config, reference & platform signals
Lay the cross-cutting platform backbone every later phase reads from. Adds
the first marketplace EF migration baseline (new `ops` schema) and the
mechanisms b2..b15 reuse: typed runtime config, an append-only audit trail,
an analytics event log, the holiday/bank-closure calendar, in-app
notifications, and the internal support-alert worklist.

Schema & migration
- New `ops` schema + migration InitialMarketplaceBaseline with 6 tables:
  PlatformConfigs (IAuditable), AuditLogs (append-only), SystemEvents,
  IranianHolidays, Notifications, SupportAlerts — with indexes/uniques and
  FKs to usr.Users. Seeded 12 config keys + 7 sample holidays via HasData.

Domain / Application
- IAuditable marker + [AuditRedacted] attribute; entities + string-code
  constant holders (config data_type, holiday type, alert type/severity/status).
- Facade contracts: IPlatformConfig, IHolidayCalendar, IAnalyticsSink,
  IAuditLogger, INotificationService, ISupportAlertService; DTOs +
  PagedResult<T>; evolved the INotificationDispatcher.Notification record to
  carry Type + DataJson; Pagination helper.
- 14 CQRS commands/queries (+ validators) wiring the endpoints to the facades.

Infrastructure
- DB-backed facade implementations in Persistence/Services/; real in-app
  INotificationDispatcher (removes the b0 log stub); notification-retention
  hosted service (purge is_read=1 AND age>90d).
- Extended AuditFieldInterceptor to also append an old/new-diff audit_logs row
  for every IAuditable change in the same transaction (PII redacted).
- Registered all facades + hosted service in AddPersistenceServices; removed
  the dispatcher registration from AddCrossCuttingSeams.

API
- 5 controllers: admin PlatformConfig/Holidays/Audit/SupportAlerts
  ([Authorize(DynamicPermission)]) + current-user Notifications ([Authorize]),
  all tenant-scoped and paginated. 16 Swagger paths total.

Money-correctness & safety rules honoured
- Config read at compute time (cached, parsed by data_type), never hardcoded;
  every config change is audited in the same transaction; audit_logs is
  append-only (no update/delete path); support alerts are admin-only;
  notifications are tenant-scoped; analytics is fire-and-forget.

Tests & docs
- 18 new foundation tests over in-memory SQLite (config typing + audit,
  holidays, notifications + tenancy + retention, support alerts, analytics);
  build clean (0 new code warnings), 22 tests green; migration applied to the
  dev DB and swagger.v1.json refreshed.
- Updated server Project map + CONVENTIONS, product data-model doc 12 (seeded
  config defaults), config-reference contract, mock registry, backend handoff/
  STATUS/report.

Follow-ups: add FK constraints for SupportAlerts.BookingId (b9) and ReviewId
(b14) when those tables land.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 01:18:00 +03:30

89 lines
3.8 KiB
C#

#nullable enable
using Baya.Application.Contracts.Common;
using Baya.Application.Contracts.Notifications;
using Baya.Application.Models.Common;
using Baya.Application.Models.Notifications;
using Microsoft.EntityFrameworkCore;
using NotificationEntity = Baya.Domain.Entities.Notifications.Notification;
namespace Baya.Infrastructure.Persistence.Services.Notifications;
/// <summary>
/// Reads and per-user commands over <c>notifications</c>. Every method is scoped to the passed
/// <c>userId</c> (the authenticated caller). Retention hard-deletes read notifications past the window
/// and never touches unread ones.
/// </summary>
internal sealed class NotificationService(ApplicationDbContext db, IDateTimeProvider dateTimeProvider) : INotificationService
{
public async ValueTask<PagedResult<NotificationDto>> ListMineAsync(int userId, int page, int pageSize, CancellationToken cancellationToken = default)
{
var query = db.Set<NotificationEntity>()
.AsNoTracking()
.Where(n => n.UserId == userId)
// Unread first, then newest-first via the monotonic identity (deterministic, no timestamp ties).
.OrderBy(n => n.IsRead)
.ThenByDescending(n => n.Id);
var total = await query.CountAsync(cancellationToken);
var items = await query
.Skip((page - 1) * pageSize)
.Take(pageSize)
.Select(n => new NotificationDto(n.Id, n.Type, n.Title, n.Body, n.DataJson, n.IsRead, n.ReadAt, n.CreatedAt))
.ToListAsync(cancellationToken);
return new PagedResult<NotificationDto>(items, total, page, pageSize);
}
public ValueTask<int> GetUnreadCountAsync(int userId, CancellationToken cancellationToken = default) =>
new(db.Set<NotificationEntity>().AsNoTracking().CountAsync(n => n.UserId == userId && !n.IsRead, cancellationToken));
public async ValueTask<bool> MarkReadAsync(int userId, long notificationId, CancellationToken cancellationToken = default)
{
var notification = await db.Set<NotificationEntity>()
.FirstOrDefaultAsync(n => n.Id == notificationId && n.UserId == userId, cancellationToken);
if (notification is null)
return false;
if (!notification.IsRead)
{
notification.IsRead = true;
notification.ReadAt = dateTimeProvider.UtcNow;
await db.SaveChangesAsync(cancellationToken);
}
return true;
}
public async ValueTask<int> MarkAllReadAsync(int userId, CancellationToken cancellationToken = default)
{
var now = dateTimeProvider.UtcNow;
return await db.Set<NotificationEntity>()
.Where(n => n.UserId == userId && !n.IsRead)
.ExecuteUpdateAsync(
s => s.SetProperty(n => n.IsRead, true).SetProperty(n => n.ReadAt, now),
cancellationToken);
}
public async ValueTask<int> PurgeOldReadAsync(int retentionDays, CancellationToken cancellationToken = default)
{
var cutoff = dateTimeProvider.UtcNow.AddDays(-retentionDays);
// Read-only rows are the only purge candidates (unread is never deleted). The age cutoff is
// applied in memory so the delete is a single id-keyed statement that translates on every
// provider; the candidate set is bounded (only read notifications).
var readRows = await db.Set<NotificationEntity>()
.Where(n => n.IsRead)
.Select(n => new { n.Id, n.CreatedAt })
.ToListAsync(cancellationToken);
var expiredIds = readRows.Where(n => n.CreatedAt < cutoff).Select(n => n.Id).ToList();
if (expiredIds.Count == 0)
return 0;
return await db.Set<NotificationEntity>()
.Where(n => expiredIds.Contains(n.Id))
.ExecuteDeleteAsync(cancellationToken);
}
}