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>
This commit is contained in:
hamid
2026-07-02 01:18:00 +03:30
parent aae1ce971f
commit 2f2aec61a2
99 changed files with 6172 additions and 52 deletions
@@ -0,0 +1,78 @@
# Backend Phase 1 — Config, reference & platform signals — Report (2026-07-02)
## What was built
- **First marketplace migration baseline** `20260701193257_InitialMarketplaceBaseline` (on top of b0's
`InitialBaseline`) creating a new **`ops` schema** with six tables:
- `PlatformConfigs` (unique `Key`, audit fields, `IAuditable`), `AuditLogs` (append-only; indexes on
`(EntityType,EntityId)` + `OccurredAt`; nullable FK → `usr.Users`), `SystemEvents` (append-only;
indexes on `Name`/`OccurredAt`/`UserId`), `IranianHolidays` (unique `HolidayDate`), `Notifications`
(index `(UserId,IsRead,CreatedAt)`; FK → Users), `SupportAlerts` (indexes on `Status`/`Type`;
nullable `BookingId`/`ReviewId` columns **without FK yet**; FK → Users on `OwnerUserId`).
- Seeded via `HasData`: 12 `platform_configs` keys and 7 sample holidays (Nowruz block + Revolution
Day + Nature Day + a religious day).
- **Domain:** entities under `Configuration/Audit/Analytics/Holidays/Notifications/SupportAlerts`; the
`IAuditable` marker + `[AuditRedacted]` attribute (`Domain/Common`); string-code constant holders
(`ConfigDataType`, `AuditAction`, `HolidayType`, `SupportAlertType/Severity/Status`).
- **Application:** facade contracts `IPlatformConfig`/`IHolidayCalendar`/`IAnalyticsSink`/`IAuditLogger`/
`INotificationService`/`ISupportAlertService`; DTOs + `PagedResult<T>`; evolved the
`INotificationDispatcher.Notification` record to carry `Type` + `DataJson`; a `Pagination.Normalize`
helper; **14 CQRS commands/queries** (+ validators) wiring the endpoints to the facades.
- **Persistence (`Services/`):** DB-backed implementations of every facade; the real
`InAppNotificationDispatcher` (supersedes and **removes** the b0 `LogNotificationDispatcher`);
`NotificationRetentionHostedService` (interval `BackgroundService`). The `AuditFieldInterceptor` was
**extended** (not duplicated) to append an `audit_logs` row with an old/new diff for every `IAuditable`
change, in the same transaction, redacting `[AuditRedacted]` properties. Registered all facades +
hosted service in `AddPersistenceServices`; removed the `INotificationDispatcher` registration from
`AddCrossCuttingSeams`.
- **API:** 5 sealed `BaseController` controllers — admin `PlatformConfigController`/`HolidaysController`/
`AuditController`/`SupportAlertsController` (`[Authorize(DynamicPermission)]`) and current-user
`NotificationsController` (`[Authorize]`).
## What is now testable (and exactly how)
`dotnet test Baya.sln`**22 pass** (4 identity + 18 new foundation), build clean (0 new code warnings;
only pre-existing NU1903/NU1510 package advisories remain). Foundation tests run against a real
`ApplicationDbContext` over in-memory SQLite (`OpsTestHost`, seed applied via `EnsureCreated`):
1. **Typed config**`GetConfig<decimal>("vat_rate")==0.10`, `<int>("dispute_window_hours")==72`,
`<int>("booking_payment_deadline_minutes")==30`; cache hit on re-read.
2. **Config change is audited**`SetConfig("platform_fee_rate","0.18")` → new value read back (cache
evicted) + one `audit_logs` row (`updated`, actor, old `0.15`/new `0.18`); missing key → `false`.
3. **Holidays**`IsBankClosed(2026-03-21)==true`, `IsHoliday(non-holiday)==false`,
`NextBusinessDay(2026-03-21)` → a later open, non-Friday day; upsert/delete round-trip.
4. **Notifications** — dispatch → list unread-first → unread count 1 → mark read → 0; tenancy (another
user sees nothing and cannot mark your row); **retention** deletes only read >90d (unread >90d and
read <90d survive).
5. **Support alerts** — raise (`low_rating`,`review`,`42`) → list open → assign → resolve; resolved is
terminal.
6. **Analytics**`EmitAsync` inserts a `system_events` row.
**Live:** the migration was applied to the dev DB (`Server=87.107.152.16`); the API boots with all 16
Swagger paths present, and the notification-retention hosted service runs its purge query on startup.
Swagger snapshot refreshed at `dev/contracts/openapi/swagger.v1.json` (fetched over HTTP/2 — the gRPC
plugin makes the REST port HTTP/2-only, so a browser or HTTP/2 client is needed to hit Swagger by hand).
## What is mocked / waiting on a real service
See `reports/mocks-registry.md`. New/changed 🟡: `IHolidayCalendar` (seeded table → real feed/sync),
`IAnalyticsSink` (system_events row → warehouse), retention `IJobScheduler`
(`NotificationRetentionHostedService` interval runner → Hangfire/Quartz), `INotificationDispatcher`
(now **real in-app write**; SMS/push channels deferred). Selection is by registration, never `if(mock)`.
## Contracts produced
`dev/contracts/domains/config-reference.md` (live as of b1; consumers f14/f15) + refreshed
`openapi/swagger.v1.json`.
## Decisions recorded (were not pinned by product docs)
Seeded config defaults marked _provisional_ in `product/data-model/12-audit-config-and-reference.md`:
`platform_fee_rate` 0.15, `nurse_response_deadline_hours` 24, `evv_location_tolerance_meters` 200,
`min_rating_for_support_alert` 2, `bnpl_provider_commission_rate` 0.07, `bnpl_settlement_timing`
immediate, and a 3-tier `cancellation_tiers` default. Confirm before launch — all are config-driven.
## Follow-ups for later phases
- **b9 / b14:** add the FK constraints `SupportAlerts.BookingId → Bookings` and
`SupportAlerts.ReviewId → Reviews` when those tables land (columns already exist).
- List orderings use the monotonic `Id` (newest-first, deterministic, cross-provider) rather than the
`DateTimeOffset` column — SQLite can't `ORDER BY`/compare `DateTimeOffset`; equivalent on SQL Server.
- Notification retention filters the age cutoff in memory (after a server-side `IsRead` filter) so the
bulk delete translates on every provider; fine for a bounded, off-peak job.
- **Integration tests** (`WebApplicationFactory<Program>`, CONVENTIONS §10) still not scaffolded — the
HTTP pipeline (auth 401/403, envelope) is covered by the live Swagger boot but not automated; add the
project when convenient.