# Project State ## Project Reference See: .planning/PROJECT.md (updated 2026-03-04) **Core value:** ISP owners can see exactly where their money is — who owes what, what's been collected, what's been spent, and what the business actually looks like financially — in real time. **Current focus:** Phase 2 - Subscriber and Billing Core ## Current Position Phase: 2 of 5 (Subscriber and Billing Core) — In progress Plan: 1 of 5 in phase 2 complete (6/20 total) Status: In progress. 02-01 (COA + Accounting Periods) complete. Last activity: 2026-03-04 — Completed 02-01-PLAN.md (ISP Chart of Accounts, accounting period management, 121 tests) Progress: [██████░░░░] 30% (6/20 plans across all phases) ## Performance Metrics **Velocity:** - Total plans completed: 6 - Average duration: 8.0 min - Total execution time: 48 min **By Phase:** | Phase | Plans | Total | Avg/Plan | |-------|-------|-------|----------| | 01-foundation | 5/5 complete | 41 min | 8.2 min | | 02-subscriber-and-billing-core | 1/5 complete | 7 min | 7 min | **Recent Trend:** - Last 6 plans: 01-01 (11 min), 01-02 (8 min), 01-03 (9 min), 01-04 (7 min), 01-05 (6 min), 02-01 (7 min) - Trend: stable around 7-8 min *Updated after each plan completion* ## Accumulated Context ### Decisions Decisions are logged in PROJECT.md Key Decisions table. Recent decisions affecting current work: - [Roadmap]: Accounting COA and JournalEntryService built in Phase 2 before first invoice — cannot be retrofitted - [Roadmap]: Inventory modeled as event-ledger (immutable movements) from Phase 4 — mutable quantity columns explicitly rejected - [Roadmap]: Collector balances derived from transaction log, never stored as mutable fields - [Roadmap]: PORT-05 (online payment) scaffolded in Phase 5 but payment gateway integration deferred to v2 per project out-of-scope decision - [01-01]: DATABASE_URL uses Docker service name `db` (for app container); DATABASE_URL_LOCAL uses `localhost:5432` (for host Prisma CLI) - [01-01]: tenantId is nullable on User — super-admins have no tenant scope, avoiding a separate SuperAdmin model - [01-01]: Email uniqueness is @@unique([email, tenantId]) — same email can exist across different tenants (realistic for ISP domain) - [01-01]: Grace period fields (suspendedAt, gracePeriodEndsAt) included on Tenant at schema creation — cannot be retrofit later - [01-02]: NextAuth v4 chosen over v5/Auth.js beta — credentials provider stability priority - [01-02]: JWT carries tenantId + roles directly — no DB lookup on each request, stateless multi-tenancy - [01-02]: Super-admin authorize uses OR [isSuperAdmin, tenant.status=ACTIVE] — one Prisma query handles both user types - [01-02]: Seed uses findFirst+create for super-admin (null tenantId) — PostgreSQL NULL != NULL in unique constraints, upsert would create duplicates - [01-02]: SessionProvider wrapped at root layout via Providers component — enables useSession() in all client components - [01-03]: withTenantContext() creates new $extends per call — correct pattern, $extends is lightweight and request-scoped context is right - [01-03]: findUnique cross-tenant protection routes through findFirst internally — Prisma unique key cannot have tenantId injected without changing where shape - [01-03]: RLS USING allows null app.current_tenant_id — super-admin mode (no tenant context) sees all rows - [01-03]: Initial migration baselined with migrate resolve --applied (schema was created via db push in 01-01) - [01-04]: createMongoAbility used throughout (not PureAbility) — string subjects require conditionsMatcher which createMongoAbility provides built-in - [01-04]: cannot() rules excluded when merging multi-role abilities — additive union means more roles = more (never less) access - [01-04]: Condition objects cast via any for string subjects — CASL infers MongoQuery for strings; tighten when Prisma models defined in Phase 2+ - [01-04]: Technician can("read", "Subscriber") coarse-grained — data layer enforces actual scope to assigned job contacts only - [01-04]: withPermission() HOF wraps Next.js route handlers; authorize() as convenience alias - [01-05]: withSuperAdmin() implemented as standalone HOF (not via CASL) — super-admin access is binary, not permission-based - [01-05]: Next.js 15 route params wrapped in Promise

— HOF awaits params before passing to handler - [01-05]: subscriberCount hardcoded to 0 in admin API — Subscriber model added in Phase 2; API shape is forward-compatible - [01-05]: Dual guard strategy for /admin: middleware.ts (JWT edge), layout.tsx (server), API handlers (endpoint) — three defense-in-depth layers - [02-01]: ISP COA has 28 accounts (5 category headers 1000/2000/3000/4000/5000 + 23 leaf accounts) — hierarchical for reporting - [02-01]: Subscriber Credits (1150) is contra-asset with CREDIT normal balance — correctly reduces AR for overpayments - [02-01]: seedChartOfAccounts receives Prisma tx client — works inside createTenant $transaction for atomic provisioning - [02-01]: Accounting periods created on-demand via getOpenPeriod() — not pre-seeded on signup (no wasted periods for unused months) - [02-01]: close route uses closure pattern over withPermission HOF — withPermission doesn't support dynamic params directly; POST fn closes over Next.js params ### Pending Todos None. ### Blockers/Concerns - [Phase 1 research flag]: MikroTik RouterOS Node.js client library maintenance status is LOW confidence — verify `node-routeros` vs `mikronode` before implementing router integration (MikroTik integration is v2, but adapter interface should be planned) - [Phase 3 research flag]: Semaphore SMS API pricing/stability for 2026 is MEDIUM confidence — verify before any SMS work (SMS is v2, but abstraction layer design is relevant) - [01-04 note]: CASL condition types for string subjects use any cast — upgrade to class-based subjects when Phase 2 Prisma models (Subscriber, Invoice, etc.) are defined - [01-05 note]: /admin/tenants/[id] detail page is a stub link ("View") — detail view not implemented yet (out of Phase 1 scope) ## Session Continuity Last session: 2026-03-04T14:51:56Z Stopped at: Completed 02-01-PLAN.md (COA + accounting period management + 28 new tests, 121 total) Resume file: None