docs(02-05): complete payment system plan — Phase 2 complete
Tasks completed: 2/2 - Task 1: Payment model with FIFO allocation and void - Task 2: Payment APIs, outstanding report, and 29 passing tests Phase 2 (Subscriber and Billing Core) complete — 265/265 tests passing SUMMARY: .planning/phases/02-subscriber-and-billing-core/02-05-SUMMARY.md
This commit is contained in:
@@ -9,30 +9,30 @@ See: .planning/PROJECT.md (updated 2026-03-04)
|
|||||||
|
|
||||||
## Current Position
|
## Current Position
|
||||||
|
|
||||||
Phase: 2 of 5 (Subscriber and Billing Core) — In progress
|
Phase: 2 of 5 (Subscriber and Billing Core) — COMPLETE
|
||||||
Plan: 5 of 5 in phase 2 remaining (10/20 total complete)
|
Plan: 5 of 5 in phase 2 (11/20 total complete)
|
||||||
Status: In progress. 02-01 (COA), 02-02 (JournalEntryService), 02-03 (Subscriber), 02-04 (BillingEngine) complete. Ready for 02-05 (PaymentService).
|
Status: Phase 2 complete. 02-01 (COA), 02-02 (JournalEntryService), 02-03 (Subscriber), 02-04 (BillingEngine), 02-05 (PaymentService) all done.
|
||||||
Last activity: 2026-03-04 — Completed 02-04-PLAN.md (BillingEngine, 38 tests)
|
Last activity: 2026-03-04 — Completed 02-05-PLAN.md (PaymentService, 29 tests, 265 total)
|
||||||
|
|
||||||
Progress: [█████████░] 50% (10/20 plans across all phases)
|
Progress: [███████████░] 55% (11/20 plans across all phases)
|
||||||
|
|
||||||
## Performance Metrics
|
## Performance Metrics
|
||||||
|
|
||||||
**Velocity:**
|
**Velocity:**
|
||||||
- Total plans completed: 8
|
- Total plans completed: 9
|
||||||
- Average duration: 9.5 min
|
- Average duration: 9.4 min
|
||||||
- Total execution time: 76 min
|
- Total execution time: 84 min
|
||||||
|
|
||||||
**By Phase:**
|
**By Phase:**
|
||||||
|
|
||||||
| Phase | Plans | Total | Avg/Plan |
|
| Phase | Plans | Total | Avg/Plan |
|
||||||
|-------|-------|-------|----------|
|
|-------|-------|-------|----------|
|
||||||
| 01-foundation | 5/5 complete | 41 min | 8.2 min |
|
| 01-foundation | 5/5 complete | 41 min | 8.2 min |
|
||||||
| 02-subscriber-and-billing-core | 4/5 complete | 49 min | 12.25 min |
|
| 02-subscriber-and-billing-core | 5/5 complete | 57 min | 11.4 min |
|
||||||
|
|
||||||
**Recent Trend:**
|
**Recent Trend:**
|
||||||
- Last 8 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), 02-04 (12 min)
|
- Last 9 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), 02-04 (12 min), 02-05 (8 min)
|
||||||
- Trend: stable (02-04 was complex — schema + 3 services + 4 API routes + 38 tests)
|
- Trend: stable — 02-05 was complex but tests passed on second run
|
||||||
|
|
||||||
*Updated after each plan completion*
|
*Updated after each plan completion*
|
||||||
|
|
||||||
@@ -90,6 +90,11 @@ Recent decisions affecting current work:
|
|||||||
- [02-04]: generateInvoiceForSubscriber returns null (not error) for duplicates — idempotent by design; generateMonthlyInvoices tracks in skipped array
|
- [02-04]: generateInvoiceForSubscriber returns null (not error) for duplicates — idempotent by design; generateMonthlyInvoices tracks in skipped array
|
||||||
- [02-04]: CreditService is standalone module — applyCredit() callable from BillingService (auto-apply) and PaymentService (02-05 overpayment)
|
- [02-04]: CreditService is standalone module — applyCredit() callable from BillingService (auto-apply) and PaymentService (02-05 overpayment)
|
||||||
- [02-04]: Dynamic route handlers pattern: export function GET/POST(req, { params }) wrapping withPermission()(handler)(req) — required for Next.js 15 Promise params in [id] routes
|
- [02-04]: Dynamic route handlers pattern: export function GET/POST(req, { params }) wrapping withPermission()(handler)(req) — required for Next.js 15 Promise params in [id] routes
|
||||||
|
- [02-05]: PaymentAllocation as separate model — enables per-invoice allocation queries and void recalculation; each allocation row: paymentId + invoiceId + amount
|
||||||
|
- [02-05]: FIFO by dueDate ASC — oldest due date allocated first (matches standard ISP billing practice)
|
||||||
|
- [02-05]: Overpayment to subscriber.creditBalance atomically with JE — same pattern as invoice.amountPaid from 02-04
|
||||||
|
- [02-05]: Outstanding report computed in JS after fetching — Prisma doesn't support computed fields in WHERE/ORDER BY; acceptable for ISP scale
|
||||||
|
- [02-05]: Test invoiceCounter for periodStart uniqueness — monotonic counter generates unique periodStart per invoice, avoids @@unique([tenantId, subscriberId, periodStart]) in test helpers
|
||||||
|
|
||||||
### Pending Todos
|
### Pending Todos
|
||||||
|
|
||||||
@@ -103,9 +108,10 @@ None.
|
|||||||
- [01-05 note]: /admin/tenants/[id] detail page is a stub link ("View") — detail view not implemented yet (out of Phase 1 scope)
|
- [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
|
- [02-02 note]: JournalEntry afterAll cleanup needs explicit order (lines → null reversesEntryId → entries → tenant) — document for any future test that involves journal entries
|
||||||
- [02-04 note]: Invoice cleanup order in tests: invoiceLines → invoices → journalEntryLines → null reversesEntryId → journalEntries → subscribers → servicePlans → tenantSettings → accountingPeriods → accounts → users → tenant
|
- [02-04 note]: Invoice cleanup order in tests: invoiceLines → invoices → journalEntryLines → null reversesEntryId → journalEntries → subscribers → servicePlans → tenantSettings → accountingPeriods → accounts → users → tenant
|
||||||
|
- [02-05 note]: Payment cleanup order in tests: paymentAllocations → payments → invoiceLines → invoices → journalEntryLines → null reversesEntryId → journalEntries → subscribers → servicePlans → tenantSettings → accountingPeriods → accounts → users → tenant
|
||||||
|
|
||||||
## Session Continuity
|
## Session Continuity
|
||||||
|
|
||||||
Last session: 2026-03-04T15:39:35Z
|
Last session: 2026-03-04T15:52:55Z
|
||||||
Stopped at: Completed 02-04-PLAN.md (BillingEngine + 38 tests, Invoice/InvoiceLine models)
|
Stopped at: Completed 02-05-PLAN.md (PaymentService + 29 tests — Phase 2 complete)
|
||||||
Resume file: None
|
Resume file: None
|
||||||
|
|||||||
162
.planning/phases/02-subscriber-and-billing-core/02-05-SUMMARY.md
Normal file
162
.planning/phases/02-subscriber-and-billing-core/02-05-SUMMARY.md
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
---
|
||||||
|
phase: 02-subscriber-and-billing-core
|
||||||
|
plan: "05"
|
||||||
|
subsystem: payments
|
||||||
|
tags: [prisma, postgresql, payment, fifo, journal-entry, double-entry, outstanding-report, idempotency]
|
||||||
|
|
||||||
|
# Dependency graph
|
||||||
|
requires:
|
||||||
|
- phase: 02-04
|
||||||
|
provides: Invoice model with amountPaid convenience field, BillingService, CreditService
|
||||||
|
- phase: 02-02
|
||||||
|
provides: JournalEntryService as sole accounting gateway
|
||||||
|
- phase: 02-01
|
||||||
|
provides: ISP COA — accounts 1010/1020/1100/1150/4010
|
||||||
|
|
||||||
|
provides:
|
||||||
|
- Payment model with idempotency key, FIFO allocation, void fields
|
||||||
|
- PaymentAllocation model linking payments to invoices
|
||||||
|
- PaymentService: recordPayment() FIFO allocation, voidPayment() with reversing JE, getSubscriberPaymentHistory()
|
||||||
|
- OutstandingReportService: getOutstandingReport() with filters/pagination
|
||||||
|
- REST API: POST/GET /api/payments, GET /api/payments/[id], POST /api/payments/[id]/void
|
||||||
|
- REST API: GET /api/subscribers/[id]/payments, GET /api/subscribers/[id]/balance
|
||||||
|
- REST API: GET /api/reports/outstanding
|
||||||
|
- 29 integration tests for full payment lifecycle
|
||||||
|
|
||||||
|
affects:
|
||||||
|
- 03-collections-and-routing (collectors receive/record payments)
|
||||||
|
- 05-online-payment (payment gateway integration scaffolded here)
|
||||||
|
- reporting (outstanding balances, payment history)
|
||||||
|
|
||||||
|
# Tech tracking
|
||||||
|
tech-stack:
|
||||||
|
added: []
|
||||||
|
patterns:
|
||||||
|
- FIFO allocation: oldest unpaid invoice (by dueDate ASC) allocated first
|
||||||
|
- Overpayment creates subscriber.creditBalance (atomically with JE, same pattern as amountPaid)
|
||||||
|
- Idempotency via @@unique([tenantId, idempotencyKey]) — safe to retry
|
||||||
|
- Void via reversing JE (immutability — no deletes, corrections only)
|
||||||
|
- PaymentAllocation model tracks allocation breakdown per payment per invoice
|
||||||
|
|
||||||
|
key-files:
|
||||||
|
created:
|
||||||
|
- prisma/migrations/20260304154606_add_payment_model/migration.sql
|
||||||
|
- src/lib/services/payment-service.ts
|
||||||
|
- src/lib/services/outstanding-report-service.ts
|
||||||
|
- src/app/api/payments/route.ts
|
||||||
|
- src/app/api/payments/[id]/route.ts
|
||||||
|
- src/app/api/payments/[id]/void/route.ts
|
||||||
|
- src/app/api/subscribers/[id]/payments/route.ts
|
||||||
|
- src/app/api/subscribers/[id]/balance/route.ts
|
||||||
|
- src/app/api/reports/outstanding/route.ts
|
||||||
|
- src/lib/__tests__/payment.test.ts
|
||||||
|
modified:
|
||||||
|
- prisma/schema.prisma
|
||||||
|
- src/lib/prisma-tenant.ts
|
||||||
|
|
||||||
|
key-decisions:
|
||||||
|
- "PaymentAllocation is a separate model (not embedded) — enables per-invoice allocation queries and supports void recalculation"
|
||||||
|
- "FIFO by dueDate ASC — earliest due date gets first allocation (matches ISP norms)"
|
||||||
|
- "Overpayment goes to subscriber.creditBalance (same atomically-updated pattern as amountPaid)"
|
||||||
|
- "Void recalculates invoice.amountPaid by subtracting allocation.amount — safe for multiple-payment scenarios"
|
||||||
|
- "Outstanding report computes in-process (not raw SQL) — Prisma computed fields not supported; totalAmount-amountPaid computed in JS"
|
||||||
|
- "Tests use unique invoiceCounter for periodStart — avoids @@unique([tenantId, subscriberId, periodStart]) constraint in test helpers"
|
||||||
|
|
||||||
|
patterns-established:
|
||||||
|
- "Payment cleanup order in tests: paymentAllocations -> payments -> invoiceLines -> invoices -> journalEntryLines -> null reversesEntryId -> journalEntries -> subscribers -> servicePlans -> tenantSettings -> accountingPeriods -> accounts -> users -> tenant"
|
||||||
|
- "withPermission() HOF pattern continued for all payment/report routes"
|
||||||
|
|
||||||
|
# Metrics
|
||||||
|
duration: 8min
|
||||||
|
completed: 2026-03-04
|
||||||
|
---
|
||||||
|
|
||||||
|
# Phase 2 Plan 05: Payment System Summary
|
||||||
|
|
||||||
|
**FIFO cash/bank payment recording with idempotency, partial/full/overpayment tracking, reversing-JE voids, and outstanding balance report — completing the ISP revenue cycle**
|
||||||
|
|
||||||
|
## Performance
|
||||||
|
|
||||||
|
- **Duration:** 8 min
|
||||||
|
- **Started:** 2026-03-04T15:44:52Z
|
||||||
|
- **Completed:** 2026-03-04T15:52:55Z
|
||||||
|
- **Tasks:** 2/2
|
||||||
|
- **Files modified:** 12
|
||||||
|
|
||||||
|
## Accomplishments
|
||||||
|
|
||||||
|
- Payment model with FIFO allocation, idempotency key, void support, and journal entry links
|
||||||
|
- PaymentService: recordPayment() with FIFO, voidPayment() with reversing JE, getSubscriberPaymentHistory()
|
||||||
|
- OutstandingReportService showing who owes what — the core product value
|
||||||
|
- 7 REST API routes for payment recording, history, balance, void, and outstanding report
|
||||||
|
- 29 integration tests covering all payment scenarios (full/partial/overpayment, FIFO, idempotency, void, tenant isolation)
|
||||||
|
- Full regression: 265/265 tests pass
|
||||||
|
|
||||||
|
## Task Commits
|
||||||
|
|
||||||
|
Each task was committed atomically:
|
||||||
|
|
||||||
|
1. **Task 1: Payment model + PaymentService with FIFO allocation** - `6b91e67` (feat)
|
||||||
|
2. **Task 2: Payment APIs + outstanding report + tests** - `bbfc9d6` (feat)
|
||||||
|
|
||||||
|
**Plan metadata:** (created below)
|
||||||
|
|
||||||
|
## Files Created/Modified
|
||||||
|
|
||||||
|
- `prisma/schema.prisma` - Added PaymentMethod/PaymentStatus enums, Payment and PaymentAllocation models, relations
|
||||||
|
- `src/lib/prisma-tenant.ts` - Added "payment" and "paymentAllocation" to TENANT_SCOPED_MODELS and withTenantContext()
|
||||||
|
- `prisma/migrations/20260304154606_add_payment_model/migration.sql` - DB migration for Payment and PaymentAllocation tables
|
||||||
|
- `src/lib/services/payment-service.ts` - recordPayment() FIFO, voidPayment() reversing JE, getSubscriberPaymentHistory()
|
||||||
|
- `src/lib/services/outstanding-report-service.ts` - getOutstandingReport() with amount/date/status filters
|
||||||
|
- `src/app/api/payments/route.ts` - POST record payment, GET list payments
|
||||||
|
- `src/app/api/payments/[id]/route.ts` - GET single payment detail
|
||||||
|
- `src/app/api/payments/[id]/void/route.ts` - POST void payment
|
||||||
|
- `src/app/api/subscribers/[id]/payments/route.ts` - GET subscriber payment history
|
||||||
|
- `src/app/api/subscribers/[id]/balance/route.ts` - GET subscriber outstanding balance
|
||||||
|
- `src/app/api/reports/outstanding/route.ts` - GET outstanding balance report
|
||||||
|
- `src/lib/__tests__/payment.test.ts` - 29 integration tests
|
||||||
|
|
||||||
|
## Decisions Made
|
||||||
|
|
||||||
|
- **PaymentAllocation as separate model:** Enables per-invoice allocation queries and void recalculation. Each allocation is a row: paymentId + invoiceId + amount.
|
||||||
|
- **FIFO by dueDate ASC:** Oldest due date allocated first — matches standard ISP billing practice.
|
||||||
|
- **Overpayment to subscriber.creditBalance:** Same pattern as invoice.amountPaid — always updated atomically in same transaction as journal entry. CreditService from 02-04 is callable for future credit-to-invoice application.
|
||||||
|
- **Void recalculation via subtraction:** voidPayment() subtracts allocation.amount from invoice.amountPaid — safe even when multiple payments partially cover the same invoice.
|
||||||
|
- **Outstanding report computed in JS:** Prisma does not support computed fields in WHERE/ORDER BY. totalAmount-amountPaid computed in process after fetching invoices. Acceptable for ISP scale (hundreds, not millions of records).
|
||||||
|
- **Test invoiceCounter for periodStart uniqueness:** Invoice schema has @@unique([tenantId, subscriberId, periodStart]). Test helper uses a monotonic counter to generate unique periodStart per invoice, avoiding constraint violations when creating multiple invoices per subscriber in tests.
|
||||||
|
|
||||||
|
## Deviations from Plan
|
||||||
|
|
||||||
|
### Auto-fixed Issues
|
||||||
|
|
||||||
|
**1. [Rule 1 - Bug] Fixed unique periodStart constraint in test helper**
|
||||||
|
- **Found during:** Task 2 (first test run — 6 tests failed with PrismaClientKnownRequestError)
|
||||||
|
- **Issue:** Test `createInvoice()` helper used a fixed `periodStart: new Date(Date.UTC(2026, 1, 1))` for all invoices. Multiple invoices for the same subscriber violated `@@unique([tenantId, subscriberId, periodStart])`.
|
||||||
|
- **Fix:** Added `invoiceCounter` variable; each `createInvoice()` call uses `new Date(Date.UTC(2020, 0, invoiceCounter))` as unique periodStart.
|
||||||
|
- **Files modified:** `src/lib/__tests__/payment.test.ts`
|
||||||
|
- **Verification:** All 29 tests pass after fix
|
||||||
|
- **Committed in:** `bbfc9d6` (Task 2 commit)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
**Total deviations:** 1 auto-fixed (Rule 1 - Bug in test helper)
|
||||||
|
**Impact on plan:** Minimal. Test helper bug; no production code affected. Fix is a standard test-isolation technique.
|
||||||
|
|
||||||
|
## Issues Encountered
|
||||||
|
|
||||||
|
None beyond the test helper bug documented above.
|
||||||
|
|
||||||
|
## User Setup Required
|
||||||
|
|
||||||
|
None - no external service configuration required.
|
||||||
|
|
||||||
|
## Next Phase Readiness
|
||||||
|
|
||||||
|
- Phase 2 (Subscriber and Billing Core) is **complete**: COA, JournalEntryService, Subscriber, BillingEngine, PaymentService all done.
|
||||||
|
- 265 total tests passing across all Phase 1 and Phase 2 plans.
|
||||||
|
- Phase 3 (Collections and Routing) can begin: collector routes, payment collection, zone-based assignment.
|
||||||
|
- Key context for Phase 3: collectors will use PaymentService.recordPayment() to record collected payments; subscriber.zone field is already on the schema.
|
||||||
|
|
||||||
|
---
|
||||||
|
*Phase: 02-subscriber-and-billing-core*
|
||||||
|
*Completed: 2026-03-04*
|
||||||
Reference in New Issue
Block a user