From c60c22b0804bbedc7b9bb5abe55979256117bc78 Mon Sep 17 00:00:00 2001 From: kevin-asprec Date: Wed, 4 Mar 2026 23:25:42 +0800 Subject: [PATCH] docs(02-02): complete JournalEntryService plan Tasks completed: 2/2 - Task 1: JournalEntry models + JournalEntryService - Task 2: Journal entry API routes + comprehensive tests SUMMARY: .planning/phases/02-subscriber-and-billing-core/02-02-SUMMARY.md --- .planning/STATE.md | 32 ++-- .../02-02-SUMMARY.md | 169 ++++++++++++++++++ 2 files changed, 189 insertions(+), 12 deletions(-) create mode 100644 .planning/phases/02-subscriber-and-billing-core/02-02-SUMMARY.md diff --git a/.planning/STATE.md b/.planning/STATE.md index 5428a41..d64297d 100644 --- a/.planning/STATE.md +++ b/.planning/STATE.md @@ -10,29 +10,29 @@ See: .planning/PROJECT.md (updated 2026-03-04) ## Current Position Phase: 2 of 5 (Subscriber and Billing Core) — In progress -Plan: 3 of 5 in phase 2 complete (8/20 total) -Status: In progress. 02-01 (COA + Accounting Periods) and 02-03 (Subscriber + ServicePlan) complete. -Last activity: 2026-03-04 — Completed 02-03-PLAN.md (Subscriber management, service plans, 41 new tests, 162 total) +Plan: 4 of 5 in phase 2 complete (9/20 total) +Status: In progress. 02-01 (COA), 02-02 (JournalEntryService), 02-03 (Subscriber) complete. Now ready for 02-04 (BillingEngine). +Last activity: 2026-03-04 — Completed 02-02-PLAN.md (JournalEntryService, 36 new tests, 198 total) -Progress: [████████░░] 40% (8/20 plans across all phases) +Progress: [████████░░] 45% (9/20 plans across all phases) ## Performance Metrics **Velocity:** -- Total plans completed: 6 -- Average duration: 8.0 min -- Total execution time: 48 min +- Total plans completed: 7 +- Average duration: 8.7 min +- Total execution time: 64 min **By Phase:** | Phase | Plans | Total | Avg/Plan | |-------|-------|-------|----------| | 01-foundation | 5/5 complete | 41 min | 8.2 min | -| 02-subscriber-and-billing-core | 3/5 complete | 21 min | 7 min | +| 02-subscriber-and-billing-core | 4/5 complete | 37 min | 9.25 min | **Recent Trend:** -- Last 7 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), 02-03 (7 min) -- Trend: stable around 7-8 min +- Last 7 plans: 01-02 (8 min), 01-03 (9 min), 01-04 (7 min), 01-05 (6 min), 02-01 (7 min), 02-03 (7 min), 02-02 (16 min) +- Trend: slightly elevated (02-02 was complex — schema + service + API + 36 tests) *Updated after each plan completion* @@ -74,6 +74,13 @@ Recent decisions affecting current work: - [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 +- [02-02]: JournalEntry self-referential reversal uses reversesEntryId @unique — one-to-one Prisma relation requires unique; semantically correct (one entry reverses at most one other) +- [02-02]: tenantId passed explicitly in $transaction callbacks — raw tx client lacks the withTenantContext() extension; must inject tenantId manually in create data +- [02-02]: startDate added to getAccountBalance — enables date-range balance queries; needed for period-scoped reporting and test isolation +- [02-02]: Integer cents for debit=credit validation — Math.round(n*100) avoids floating point drift on decimal amounts +- [02-02]: SYSTEM source auto-posts (POSTED status), MANUAL entries start DRAFT for maker-checker workflow +- [02-02]: Self-approval allowed — single-person ISP operations are common; blocking self-approval breaks common use case +- [02-02]: JournalEntryService is sole gateway — NO other code may write to JournalEntry/JournalEntryLine directly - [02-03]: creditBalance on Subscriber is operational convenience (FIFO credit allocation for 02-05), NOT a ledger balance — always updated atomically with journal entries - [02-03]: billingDay capped at 28 — subscribers signing up on days 29-31 get billingDay=28 to avoid month-length invoice generation issues - [02-03]: CANCELLED -> ACTIVE transition is reversible by design — ISPs frequently reinstate cancelled accounts per CONTEXT.md @@ -89,9 +96,10 @@ None. - [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) +- [02-02 note]: JournalEntry afterAll cleanup needs explicit order (lines → null reversesEntryId → entries → tenant) — document for any future test that involves journal entries ## Session Continuity -Last session: 2026-03-04T15:02:45Z -Stopped at: Completed 02-03-PLAN.md (Subscriber + ServicePlan management + 41 new tests, 162 total) +Last session: 2026-03-04T15:23:19Z +Stopped at: Completed 02-02-PLAN.md (JournalEntryService + 36 new tests, 198 total) Resume file: None diff --git a/.planning/phases/02-subscriber-and-billing-core/02-02-SUMMARY.md b/.planning/phases/02-subscriber-and-billing-core/02-02-SUMMARY.md new file mode 100644 index 0000000..7043dc5 --- /dev/null +++ b/.planning/phases/02-subscriber-and-billing-core/02-02-SUMMARY.md @@ -0,0 +1,169 @@ +--- +phase: 02-subscriber-and-billing-core +plan: "02" +subsystem: database +tags: [prisma, postgresql, double-entry-accounting, journal-entries, ledger, maker-checker] + +# Dependency graph +requires: + - phase: 02-01 + provides: Chart of Accounts (Account model, AccountingPeriod model, isDateInClosedPeriod) + - phase: 01-03 + provides: withTenantContext() multi-tenancy middleware, TENANT_SCOPED_MODELS pattern + - phase: 01-04 + provides: withPermission() HOF for RBAC enforcement on API routes + +provides: + - JournalEntry and JournalEntryLine Prisma models with migration + - JournalEntryService — sole gateway to the accounting ledger + - Journal entry REST API (list, create, approve, reverse) + - Account balance derivation API (GET /accounts/[id]/balance) + - 36 integration tests covering all ledger invariants + +affects: + - 02-04 (billing engine — uses JournalEntryService.createEntry to post invoice JEs) + - 02-05 (payment tracker — uses JournalEntryService.createEntry to post payment JEs) + - future phases that need trial balance or account balance queries + +# Tech tracking +tech-stack: + added: [] + patterns: + - "Sole gateway pattern: JournalEntryService is the ONLY code that writes to JournalEntry/JournalEntryLine" + - "Closure params pattern: dynamic route handlers use closure over withPermission HOF (same as periods/close)" + - "Integer cents validation: debit/credit balance checked in integer cents (Math.round(n*100)) to avoid float errors" + - "Isolated balance testing: use startDate+asOfDate to scope balance queries to test-year to avoid cross-test contamination" + - "Tenant scoping in transactions: tenantId passed explicitly in $transaction callbacks (raw client, no extension)" + +key-files: + created: + - prisma/migrations/20260304150817_add_journal_entry_models/migration.sql + - src/lib/accounting/journal-entry-service.ts + - src/app/api/accounting/journal-entries/route.ts + - src/app/api/accounting/journal-entries/[id]/route.ts + - src/app/api/accounting/journal-entries/[id]/approve/route.ts + - src/app/api/accounting/journal-entries/[id]/reverse/route.ts + - src/app/api/accounting/accounts/[id]/balance/route.ts + - src/lib/__tests__/journal-entry-service.test.ts + modified: + - prisma/schema.prisma + - src/lib/prisma-tenant.ts + +key-decisions: + - "JournalEntry self-referential reversal relation uses reversesEntryId @unique — one entry can only reverse one other" + - "tenantId injected explicitly inside $transaction callbacks — raw tx client doesn't have the extension active" + - "startDate parameter added to getAccountBalance — enables date-range scoped queries (not just all-time or asOfDate)" + - "Integer cents comparison for debit=credit validation — Math.round(n*100) avoids floating point drift with decimal amounts" + - "SYSTEM source entries auto-post (status=POSTED), MANUAL entries start as DRAFT for maker-checker workflow" + - "Self-approval allowed per CONTEXT.md — single-person ISP operations are the common case" + - "Balance derivation uses journalEntryLine.aggregate with nested journalEntry status filter — no stored balance fields" + +patterns-established: + - "Sole gateway: all financial events flow through JournalEntryService.createEntry, never direct DB writes" + - "Immutability: service has no updateEntry or deleteEntry methods — only reverseEntry for corrections" + - "Trial balance self-verification: sum(debitBalance) must equal sum(creditBalance) across all accounts" + +# Metrics +duration: 16min +completed: 2026-03-04 +--- + +# Phase 2 Plan 02: JournalEntryService Summary + +**Double-entry accounting engine with debit=credit enforcement, immutable entries, reversals, maker-checker workflow, and balance derivation — the sole gateway to the ISP financial ledger** + +## Performance + +- **Duration:** 16 min +- **Started:** 2026-03-04T15:06:43Z +- **Completed:** 2026-03-04T15:23:19Z +- **Tasks:** 2/2 +- **Files modified:** 10 + +## Accomplishments + +- JournalEntry and JournalEntryLine models in PostgreSQL with migration. Self-referential reversal relation, maker-checker fields (createdById, approvedById, approvedAt), full audit trail. +- JournalEntryService enforces: debit=credit on every entry (integer cents comparison), minimum 2 lines, exclusive debit/credit per line, no entries in closed accounting periods, immutability (no update/delete methods), SYSTEM entries auto-post, MANUAL entries use DRAFT+approve workflow. +- Reversing entries atomically swap debits/credits, mark original REVERSED, and create new POSTED entry in single transaction. +- Account balance derived via SUM(debit/credit) on journalEntryLine grouped by accountId and filtered by POSTED status — never stored. +- Trial balance self-verifies: total debit balances always equal total credit balances. +- 36 integration tests + 198 total test suite (all passing). + +## Task Commits + +1. **Task 1: JournalEntry models + JournalEntryService** - `837b7f1` (feat) +2. **Task 2: Journal entry API routes + comprehensive tests** - `30ec936` (feat) + +## Files Created/Modified + +- `prisma/schema.prisma` - Added JournalEntryStatus/JournalEntrySource enums, JournalEntry model, JournalEntryLine model; Account and User back-relations +- `prisma/migrations/20260304150817_add_journal_entry_models/migration.sql` - DB migration +- `src/lib/prisma-tenant.ts` - Added journalEntry and journalEntryLine to TENANT_SCOPED_MODELS with full query extension blocks +- `src/lib/accounting/journal-entry-service.ts` - JournalEntryService: createEntry, approveEntry, reverseEntry, getAccountBalance (startDate+asOfDate), getTrialBalance +- `src/app/api/accounting/journal-entries/route.ts` - GET (list with filters) + POST (create manual) +- `src/app/api/accounting/journal-entries/[id]/route.ts` - GET single entry +- `src/app/api/accounting/journal-entries/[id]/approve/route.ts` - POST approve +- `src/app/api/accounting/journal-entries/[id]/reverse/route.ts` - POST reverse +- `src/app/api/accounting/accounts/[id]/balance/route.ts` - GET derived balance +- `src/lib/__tests__/journal-entry-service.test.ts` - 36 integration tests + +## Decisions Made + +- **JournalEntry self-referential relation uses `reversesEntryId @unique`** — Prisma requires `@unique` for one-to-one self-relations. This correctly models that one entry can only reverse one other entry. +- **`tenantId` passed explicitly inside `$transaction` callbacks** — The raw tx client from `prisma.$transaction()` doesn't carry the `withTenantContext()` extension. Must pass `tenantId` explicitly in `create` data within transactions. +- **`startDate` added to `getAccountBalance`** — Plan specified only `asOfDate` (all entries up to date). Added `startDate` to enable date-range queries, which is needed for proper test isolation and will be useful for period-scoped reporting. +- **Integer cents for balance validation** — `Math.round(n * 100)` avoids floating point drift. `100.1 * 100 = 10009.9999...` in JS; cents comparison is exact. +- **Self-approval allowed** — CONTEXT.md notes most ISPs are single-person operations. Maker-checker exists for multi-person orgs; blocking self-approval would break single-admin ISPs. + +## Deviations from Plan + +### Auto-fixed Issues + +**1. [Rule 1 - Bug] Prisma one-to-one self-relation requires `@unique` on FK field** +- **Found during:** Task 1 (JournalEntry models) +- **Issue:** Prisma rejected schema with error: "A one-to-one relation must use unique fields on the defining side" for `reversesEntryId` +- **Fix:** Added `@unique` to `reversesEntryId` field. This is semantically correct: one entry can reverse at most one other entry. +- **Files modified:** prisma/schema.prisma +- **Verification:** `npx prisma generate` succeeded after fix +- **Committed in:** 837b7f1 (Task 1 commit) + +**2. [Rule 2 - Missing Critical] Added `startDate` parameter to `getAccountBalance`** +- **Found during:** Task 2 (balance test design) +- **Issue:** Tests using `asOfDate` alone couldn't isolate to a specific year because prior test entries (using same accounts but different dates) were included in the aggregate. Without `startDate`, balance tests would be non-deterministic. +- **Fix:** Added optional `startDate: Date` to `GetAccountBalanceInput` and `dateConditions` object in aggregate query. The API balance endpoint also exposes `?startDate=` query param. +- **Files modified:** src/lib/accounting/journal-entry-service.ts, src/app/api/accounting/accounts/[id]/balance/route.ts +- **Verification:** Balance tests using `startDate + asOfDate` produce exact expected values (700, 800, 1500, 0) +- **Committed in:** 30ec936 (Task 2 commit) + +**3. [Rule 1 - Bug] `afterAll` test cleanup needed explicit ordering due to FK constraints** +- **Found during:** Task 2 (test run, cleanup failure) +- **Issue:** `prisma.tenant.delete()` failed with FK constraint on `JournalEntry_createdById_fkey`. Cascade from tenant didn't handle journal entry self-reference cleanly. +- **Fix:** afterAll deletes in order: (1) journalEntryLine.deleteMany, (2) journalEntry.updateMany (null out reversesEntryId), (3) journalEntry.deleteMany, (4) tenant.delete. +- **Files modified:** src/lib/__tests__/journal-entry-service.test.ts +- **Verification:** afterAll completes without errors, DB cleaned up +- **Committed in:** 30ec936 (Task 2 commit) + +--- + +**Total deviations:** 3 auto-fixed (1 Prisma schema bug, 1 missing critical feature for correctness, 1 test cleanup bug) +**Impact on plan:** All fixes necessary for correctness. The `startDate` addition enhances the API (not scope creep — it's needed for period-scoped balance reporting in future phases). + +## Issues Encountered + +- Prisma `$transaction` callback receives raw PrismaClient (not extended). This is a known Prisma architectural constraint. Solution: pass `tenantId` explicitly in `data` objects inside transactions. This is already the pattern used in `tenant.ts` for COA seeding. +- Decimal `toString()` omits trailing zeros (e.g., `"100.5"` not `"100.50"`). Tests updated to use `toNumber()` for numeric comparison instead. + +## User Setup Required + +None - no external service configuration required. + +## Next Phase Readiness + +- JournalEntryService is complete and ready for 02-04 (BillingEngine) and 02-05 (PaymentTracker) to call +- Both billing and payment services must call `JournalEntryService.createEntry({ source: SYSTEM, ... })` — never write to JournalEntry directly +- Account IDs needed: billing will use AR (1100), Revenue (4010); payments will use Cash (1010/1020), AR (1100), Subscriber Credits (1150) +- Closed period protection is active — any attempt to post to a closed period will throw + +--- +*Phase: 02-subscriber-and-billing-core* +*Completed: 2026-03-04*