Skip to content

Commit 06f291c

Browse files
mayborn005zeemscriptclaude
authored
feat: replace in-memory PrismaService fake with real PrismaClient (#475) (#537)
* feat: replace in-memory PrismaService fake with real PrismaClient (#475) - Rewrite PrismaService to extend PrismaClient with @prisma/adapter-pg - Remove all 13 Map-based in-memory stores (1532 -> 420 lines) - reset() now executes TRUNCATE TABLE ... CASCADE - Add Postgres 16 service to CI workflow - Fix BuyerDisputeService to explicitly transition escrow to DISPUTED - Fix vendor-analytics integration test (remove direct store access) - Update 4 test files for real PrismaClient API * fix(prisma): complete real-PrismaClient migration in production code Reconcile the fake->real PrismaClient swap with ~40 commits of base code that was written against the in-memory fake's loose types. - Declare the previously-undeclared driver-adapter deps so `npm ci` installs them: @prisma/adapter-pg, pg (deps) and @types/pg (devDep). - prisma.service.ts: enable query-event logging via constructor `log` option and narrow $on('query') to Prisma.QueryEvent; drop dead input types; add boundary mappers (toEscrowRecord/toFailedTransactionRecord/ toVendorAccountDetailsRecord/toVendorTrackingSettingsRecord) that convert generated rows (Decimal, JsonValue) to the hand-written *Record contract (number, plain objects) the rest of the app and its tests depend on. - escrow / dlq / vendor repositories: convert rows through the mappers; write JSON columns via Prisma.DbNull / InputJsonValue. - admin-stats: Number() the Decimal _sum.amount aggregate. - analytics: type $queryRaw result as an array. - schema: add Notification.providerMessageId / attemptCount / lastResponseCode (persisted by NotificationsService; previously only in the fake) + migration. Production `tsc --noEmit` is clean. Remaining type errors are confined to test/spec files and the benchmark script (follow-up commit). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HzXa5DbrJ4CsnYs4Sx4qiK * test: fix type errors from real-PrismaClient swap; repair bad-merge specs Make `npm run typecheck` (tsc --noEmit) fully green after the fake->real PrismaClient migration. Type-only test changes plus repair of pre-existing bad-merge corruption inherited from base dev. - Add required `itemRef` to escrow creates; annotate `state: '...' as const` where widening broke EscrowRecord/EscrowSummaryDto assignability (escrow/dispute/admin-stats/analytics/cross-vendor/tracking-poll specs). - Add missing fields to VendorTrackingSettingsRecord mocks; cast the DLQ ABANDONED record; pass the new DlqService arg to SorobanPollerService; use Prisma.DbNull for null JSON columns. - prisma.service.spec.ts: drop the invalid `@jest/globals` Test import, remove unused e1..e4 bindings, Prisma.DbNull for ledgerFeedback. - Remove duplicated halves left by earlier bad merges in tracing.interceptor.spec, tracing.middleware.spec, and notification-retry-queue.service.spec. - config.module.spec.ts: repair the corrupted abortEarly block, the three missing sync-test `});`, the duplicate Keypair import, and restore the dropped ALL_KNOWN_KEYS definition. - benchmark script: array-typed $queryRaw, itemRef on seed escrows. No assertions or test intent changed. Note: the repo-wide `lint:check` job was already red on base dev (pre-existing prettier/require/console violations in untouched files); the files changed here are formatted clean. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HzXa5DbrJ4CsnYs4Sx4qiK * fix: adapt tests and services to real PrismaClient - bind this for Prisma query-event logger (v7 Proxy unbound methods) - single-statement TRUNCATE with advisory lock to avoid reset deadlocks - seed vendor profiles in tests/seed for escrow FK constraints - use DisputeStatus enum in admin stats query - validate ADMIN_ADDRESS with stellarPublicKey schema - pass encryption key config to LogisticsService constructor --------- Co-authored-by: Sakariyah Abdulhazeem <sakariyahabdulhazeem@gmail.com> Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com> Co-authored-by: Sakariyah Abdulhazeem <150973162+zeemscript@users.noreply.github.com>
1 parent 99d439c commit 06f291c

49 files changed

Lines changed: 1868 additions & 3172 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

AGENTS.md

Lines changed: 40 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -3,36 +3,52 @@
33
## What We've Done
44
Phase 1–3 of unit test fixes complete. All **65 test suites, 642 tests passing** (integration + unit).
55

6-
### Phase 1 — Environment & Setup
7-
- Added `CREDENTIAL_ENCRYPTION_KEY=...` to `.env.test` — unblocked `credential-encryption.util.spec.ts` (7 tests) + `logistics.service.spec.ts` (5 tests)
8-
- Added missing `import { ConfigService }` to `cache.service.spec.ts` — fixed 11 tests
9-
- Fixed encrypt/delete ordering in `credential-encryption.util.spec.ts` "should throw when key not set"
10-
11-
### Phase 2 — Logic & Type Fixes
12-
- `sep10.service.spec.ts` — unclosed `beforeEach`, orphaned object literal, duplicate test block (36 tests + 3 TS1005 fixed)
13-
- `auto-release.worker.spec.ts` — added second expected arg `GAUTORELEASE...` to `submitAutoRelease` assertion
14-
- `gigl-logistics.service.spec.ts``toEqual({ status })``toMatchObject({ status })` matching richer response shape
15-
16-
### Phase 3 — Edge Cases
17-
- `escrow.repository.spec.ts` — added `cursor` support to `PrismaService` mock's `findMany` (cursor-based pagination was ignored, returning remaining records instead of skipping past cursor)
18-
- `analytics.service.spec.ts` — two fixes:
19-
- "fill gaps" test: passed `createdAt` to `prisma.escrow.create()` so escrows land on different dates (mock defaults to `new Date()`)
20-
- "aggregations" test: used `result.data.find(d => d.transactionCount > 0)` instead of `result.data[0]` (transactions are on the last day of the range)
21-
- `escrow.evidence-upload.spec.ts` — removed `@Throttle()` decorator from controller (was hardcoding `limit: 10, ttl: 60000` overriding env vars); module-level throttler config now reads from env vars
22-
23-
### Earlier Work (Integration Tests)
6+
### Phase 4 — Real PrismaClient (In-Progress)
7+
Replaced the 1532-line in-memory PrismaService fake with a real `PrismaClient` using `@prisma/adapter-pg` (Prisma v7 driver adapter). This removes all Map-based stores and delegates all queries to PostgreSQL.
8+
9+
#### Core Changes
10+
- `src/prisma/prisma.service.ts` — extends `PrismaClient` instead of in-memory Map stores
11+
- Constructor accepts optional `databaseUrl` (falls back to `process.env.DATABASE_URL`)
12+
- Creates `PrismaPg` adapter with connection string internally
13+
- Applies `statement_timeout` and `connect_timeout` to URL
14+
- `onModuleInit()` calls `$connect()` and registers slow-query logger via `$on('query')`
15+
- `onModuleDestroy()` calls `$disconnect()`
16+
- `reset()` executes `TRUNCATE TABLE ... CASCADE` on all public tables (skips `_prisma_migrations`)
17+
- All custom type exports preserved for backward compatibility
18+
- `src/prisma/prisma.module.ts` — comment-only update
19+
- `.github/workflows/ci.yml` — added Postgres 16 service (matched from `test.yml`)
20+
21+
#### Behavioral Fixes
22+
- `src/escrow/buyer-dispute.service.ts``openDispute()` now explicitly calls `escrowRepository.updateState(escrowId, 'DISPUTED')` after creating a dispute (in-memory fake auto-transitioned escrow as side-effect; real DB does not)
23+
- `test/integration/vendor-analytics.integration-spec.ts` — removed `(prisma as any).escrows.set(...)`; now passes `createdAt` directly to `prisma.escrow.create()`
24+
- `src/prisma/prisma.service.spec.ts`, `test/unit/prisma.service.spec.ts`, `test/unit/prisma-schema-parity.spec.ts`, `src/prisma/escrow-event-logging.spec.ts` — updated for real PrismaClient API
25+
26+
#### Known Behavioral Changes
27+
- `prisma.escrow.findMany()` no longer auto-filters CANCELLED records (remove CANCELLED-hiding behavior). All records are returned unless a `state` filter is provided.
28+
- `prisma.escrow.create()` / `prisma.escrow.update()` no longer auto-create `EscrowEvent` rows — event logging must be done explicitly.
29+
- `prisma.dispute.create()` no longer auto-transitions escrow to DISPUTED — handled by `BuyerDisputeService`.
30+
- `amount` fields are `Prisma.Decimal` at runtime (not `number`). Use `toEqual()` instead of `toBe()` for comparisons, or call `Number(escrow.amount)` for arithmetic.
31+
32+
#### Prerequisites
33+
- PostgreSQL must be running on `localhost:5432` with `trustlink_test` database
34+
- `DATABASE_URL` in `.env.test` points to `postgresql://postgres:postgres@localhost:5432/trustlink_test`
35+
36+
### Earlier Work
2437
All 24 integration test suites (182 tests) passing after:
2538
- CI Node v20→v22, baseline migration, `SENTRY_DSN` fix, Stellar addresses, `Idempotency-Key` header
2639
- `markAutoReleaseSubmitting` race condition → atomic `updateMany`
2740
- `PrismaService` in-memory mock additions (`updateMany`, `CacheService.del`, etc.)
2841

2942
## Key Files Modified
30-
- `src/prisma/prisma.service.ts` — cursor in `findMany`, `updateMany` store, `$queryRaw` mock
31-
- `src/escrow/escrow.controller.ts` — removed `@Throttle` decorator from evidence-upload
32-
- `src/vendor/analytics/analytics.service.spec.ts``createdAt` pass-through, `find` instead of `[0]`
33-
- `src/escrow/escrow.evidence-upload.spec.ts` — increased loop iterations to `limit+10`
34-
- `.env.test` — added `CREDENTIAL_ENCRYPTION_KEY=...`
35-
- `.github/workflows/*.yml` — node-version `'22'`
43+
- `src/prisma/prisma.service.ts` — full rewrite (extends PrismaClient + PrismaPg adapter)
44+
- `src/prisma/prisma.module.ts` — comment update
45+
- `src/escrow/buyer-dispute.service.ts` — explicit escrow state transition
46+
- `src/prisma/prisma.service.spec.ts` — updated for real DB
47+
- `src/prisma/escrow-event-logging.spec.ts` — updated for real DB
48+
- `test/unit/prisma.service.spec.ts` — updated for real DB
49+
- `test/unit/prisma-schema-parity.spec.ts` — updated for real DB
50+
- `test/integration/vendor-analytics.integration-spec.ts` — removed direct store access
51+
- `.github/workflows/ci.yml` — added Postgres service
3652

3753
## Jest Config
3854
- `jest-integration.json`: `testTimeout: 60000`

package-lock.json

Lines changed: 120 additions & 3 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)