Phase 3.7: paid pairing flow + returning chat + extension flip

- Backend: payment_sessions + pairing_failures tables; payment.service.js
  and pairing-failure.service.js (new); rewritten pairing.service.js
  (payment-gated blast + targeted "Curhat lagi" + cancel + fallback);
  rewritten extension.service.js (data-driven auto-approve with offline
  safeguard, charge-at-approval); pricing.service.js (extension tiers
  without free trial); mitra-status.service.js (countAvailableMitras
  cached path); 60s sweeper for stale payment sessions
- Backend routes: client.payment.routes, client.mitra-availability.routes,
  internal/failed-pairings.routes; client.chat.routes rewritten for
  payment-gated start + /returning + /cancel + /fallback-to-blast;
  internal/config.routes adds 4 new keys with Valkey invalidate publish
- client_app: mitra-availability poll, payment screen + notifier, pairing
  notifier rewrite (PairingTargetedWaiting + PairingFailed states),
  targeted-waiting overlay + bestie-unavailable dialog, "Curhat lagi"
  CTA, failed-pairing terminal, extension via payment-session
- mitra_app: PairingRequestType enum, returning-chat 20s countdown
  auto-dismiss, extension card "otomatis disetujui" copy
- control_center: 4 new config rows in Settings, Failed Pairings page
  (filter + paginate + action menu), sidebar + route registered
- Test infrastructure: Vitest backend (7/7 pass), Playwright CC (4/4
  pass), Maestro mobile scaffold (CLI install pending)
- Bugs found via Playwright + fixed: LoginPage labels not associated
  with inputs (a11y); backend internal CORS missing PATCH/PUT/DELETE
  in allow-methods (silent settings breakage in browsers since Stage 4)
- Docs: phase3.7.md PRD, phase3.7-plan.md, phase3.7-questions.md (Q&A),
  phase3.7-testing.md (E2E checklist), phase3.7-test-run-2026-05-03.md
  (today's run results)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-03 23:02:49 +08:00
parent f3766813f3
commit d09e50af55
92 changed files with 9579 additions and 437 deletions

118
backend/test/README.md Normal file
View File

@@ -0,0 +1,118 @@
# Backend tests (Vitest)
Vitest scaffolding for the Halo Bestie Fastify backend. Three sample tests exist
to demonstrate the patterns; broader coverage will be filled in incrementally.
## Strategy: schema-isolated remote DB (default)
The remote dev role on `omv.sjamsani.id` does **not** have `CREATE DATABASE`
privilege, so the chosen isolation mechanism is a separate **schema** inside the
existing `halobestie_clone` database. The migration runs into a `halobestie_test`
schema (driven by `?options=-c search_path=...` on the test DB URL), leaving the
dev `public` schema untouched.
Valkey isolation uses a separate logical db number (`/1`) on the same instance.
### Why not Docker?
Docker availability could not be verified inside the agent sandbox at scaffold
time. A `docker-compose.test.yml` exists for users who prefer ephemeral local
containers — see "Switching to local Docker" below.
### Why not a separate Postgres database?
The dev role is non-superuser and lacks `CREATE DATABASE`. Schema isolation gives
us the same isolation guarantee (test tables live in their own namespace) without
requiring a privilege bump.
## Setup
1. Copy `.env.test.example``.env.test`:
```
cp .env.test.example .env.test
```
Adjust `TEST_DATABASE_URL` / `TEST_VALKEY_URL` if your dev DB is elsewhere.
2. (Optional) Verify connectivity:
```
node -e "import('postgres').then(({default:p})=>{const s=p(process.env.TEST_DATABASE_URL);s\`SELECT 1\`.then(console.log).finally(()=>s.end())})"
```
3. The `halobestie_test` schema and all test tables are created automatically the
first time `npm test` runs (idempotent — re-running `npm test` is safe).
## Running
```
npm test # one-shot run
npm run test:watch # re-run on file change
npm run test:coverage # plus coverage report under coverage/
```
## Required environment variables
| Var | Default | Purpose |
|-----|---------|---------|
| `TEST_DATABASE_URL` | `postgresql://halobestie_clone:halobestie_clone@omv.sjamsani.id:5432/halobestie_clone` | Same as dev — schema isolates |
| `TEST_DB_SCHEMA` | `halobestie_test` | Schema name for test tables. Hard-rejected if set to `public` |
| `TEST_VALKEY_URL` | `redis://omv.sjamsani.id:6379/1` | Note the `/1` — separate logical db from dev |
| `AUTH_JWT_SECRET` | (must be ≥ 32 chars) | Signs JWTs the prod `authenticate` plugin verifies. Test value can differ from dev |
| `ACCESS_TOKEN_TTL_SECONDS` | `3600` | Optional |
| `REFRESH_TOKEN_TTL_DAYS` | `30` | Optional |
| `CC_ORIGIN` | `http://localhost:5173` | Required by the internal app's CORS config |
## Adding a new test
Templates by type:
| Test type | Template | Sample |
|-----------|----------|--------|
| Pure service | uses `db()` + fixtures | `test/services/payment.service.test.js` |
| Service with mocked WS/FCM | `vi.mock('../../src/plugins/websocket.js')` at top | `test/services/pairing.service.test.js` |
| Route (HTTP-free via inject) | `app.inject({ method, url, headers, payload })` | `test/routes/client.payment.routes.test.js` |
Helpers (under `test/helpers/`):
- `db.js` — `db()` returns the shared sql client; `resetDb()` truncates Phase 3.7 + dependent tables; `resetAppConfig()` restores config defaults.
- `valkey.js` — `getTestValkey()` for direct keyspace assertions; `flushTestDb()` to wipe between tests.
- `server.js` — `buildPublic()` / `buildInternal()` for route tests.
- `jwt.js` — `customerJwt(id)`, `mitraJwt(id)`, `ccJwt(id)` mint tokens the prod `authenticate` plugin accepts. `authHeader(token)` builds the header.
- `fixtures.js` — `createCustomer()`, `createMitra({ isOnline })`.
Patterns to follow (from the sample tests):
- Always import status / cause values from `../../src/constants.js` — never hard-code `'pending'`, `'all_mitras_rejected'`, etc. (See project memory: "Use Enums for Fixed Values".)
- Mock `../../src/plugins/websocket.js` and `../../src/services/notification.service.js` for any test that touches pairing / extension / closure — they fan out via WS + FCM and you don't want either to fire on a real socket / Firebase project.
- Call `resetDb()` in `beforeEach`, `resetAppConfig()` once in `beforeAll` (or in `afterEach` if your test mutates config).
## Isolation notes
Tests run **sequentially** (`fileParallelism: false`, `sequence.concurrent: false`)
because they share one DB schema and one Valkey db. If you ever need
parallelism: switch to per-test transactions (`BEGIN` in `beforeEach`, `ROLLBACK`
in `afterEach`) or per-test schemas (`CREATE SCHEMA test_${random}`) and update
`vitest.config.js`.
## Switching to local Docker
If you'd rather run an isolated, throwaway Postgres + Valkey on your machine:
```
docker compose -f docker-compose.test.yml up -d
# In .env.test:
TEST_DATABASE_URL=postgresql://test:test@localhost:55432/halobestie_test
TEST_DB_SCHEMA=public
TEST_VALKEY_URL=redis://localhost:56379/0
npm test
docker compose -f docker-compose.test.yml down -v
```
The non-default ports (55432, 56379) avoid clashing with any local Postgres /
Redis you have running. Note `TEST_DB_SCHEMA=public` is OK in the Docker case
because the whole database is throwaway — schema isolation is only required
when sharing with the dev DB.
## Safety guards
- `setup.js` hard-fails if `TEST_DB_SCHEMA === 'public'` AND `TEST_DATABASE_URL` looks like the dev DB. (Schema reuse on the dev DB would clobber dev tables.)
- `setup.js` hard-fails if any required env var is missing — silent fallback to dev URLs would be catastrophic.
- The migration runs as a **child process** (not in-process) so its `sql.end()` at the bottom doesn't tear down the singleton this test process shares with services.

View File

@@ -0,0 +1,81 @@
import { getDb } from '../../src/db/client.js'
/**
* Single shared sql client used by tests. Same singleton the services use, since
* setup.js has already rewritten DATABASE_URL to point at the test schema.
*/
export const db = () => getDb()
/**
* Truncate Phase 3.7-relevant tables between tests.
*
* Order matters: pairing_failures FK → payment_sessions; chat_request_notifications
* FK → chat_sessions; customer_transactions FK → chat_sessions; etc. Use CASCADE so
* we don't have to maintain the topological order when tables get added.
*
* We deliberately do NOT truncate roles / control_center_users / mitras / customers
* — those are seeded once per test file by fixtures and re-truncating them would
* force every test to re-create users (slow + noisy).
*/
const TRUNCATE_TABLES = [
'pairing_failures',
'payment_sessions',
'chat_request_notifications',
'session_extensions',
'session_closures',
'session_sensitivity_log',
'chat_messages',
'customer_transactions',
'chat_sessions',
'auth_sessions',
'otp_requests',
'mitra_online_logs',
'mitra_online_status',
]
export const resetDb = async () => {
const sql = db()
// RESTART IDENTITY is a no-op for UUID PKs but cheap; CASCADE handles any future FK additions.
await sql.unsafe(`TRUNCATE TABLE ${TRUNCATE_TABLES.join(', ')} RESTART IDENTITY CASCADE`)
}
/**
* Wipe the slow-changing tables too — call sparingly (a single test that needs to
* verify "no users" semantics, or in afterAll teardown).
*/
export const resetDbHard = async () => {
const sql = db()
await sql.unsafe(
`TRUNCATE TABLE ${TRUNCATE_TABLES.join(', ')}, mitras, customers, control_center_users, roles RESTART IDENTITY CASCADE`
)
}
/**
* Drop and re-seed the configurable app_config rows back to their canonical defaults.
* Tests that mutate config (e.g. flipping free_trial_enabled) call this in afterEach.
*/
export const resetAppConfig = async () => {
const sql = db()
// Restore the same defaults the migration sets. Using ON CONFLICT … DO UPDATE so a
// test-mutated row gets clobbered back, not just left alone.
const defaults = [
['anonymity', { enabled: false }],
['max_customers_per_mitra', { value: 3 }],
['free_trial_enabled', { value: true }],
['free_trial_duration_minutes', { value: 5 }],
['extension_timeout_seconds', { value: 60 }],
['early_end_mitra_enabled', { value: false }],
['early_end_customer_enabled', { value: false }],
['payment_session_timeout_minutes', { value: 20 }],
['returning_chat_confirmation_timeout_seconds', { value: 20 }],
['extension_default_action_on_timeout', { value: 'auto_approve' }],
['pairing_blast_timeout_seconds', { value: 60 }],
]
for (const [key, value] of defaults) {
await sql`
INSERT INTO app_config (key, value, updated_at)
VALUES (${key}, ${sql.json(value)}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
}
}

View File

@@ -0,0 +1,64 @@
import { randomUUID } from 'node:crypto'
import { db, resetAppConfig } from './db.js'
/**
* Insert a customer row. Defaults to the schema after the Phase 3.4 auth rewrite
* (display_name nullable, is_anonymous defaults true).
*/
export const createCustomer = async ({
id = randomUUID(),
callName = `TestCust-${id.slice(0, 6)}`,
phone = null,
isAnonymous = false,
} = {}) => {
const sql = db()
const [row] = await sql`
INSERT INTO customers (id, display_name, phone, is_anonymous)
VALUES (${id}, ${callName}, ${phone}, ${isAnonymous})
RETURNING id, display_name, phone, is_anonymous, created_at
`
return row
}
/**
* Insert a mitra row. If `isOnline` is true, also creates the mitra_online_status row
* so pairing.findAvailableMitras includes it.
*/
export const createMitra = async ({
id = randomUUID(),
callName = `TestMitra-${id.slice(0, 6)}`,
phone = null,
isActive = true,
isOnline = false,
} = {}) => {
const sql = db()
// mitras.phone is NOT NULL UNIQUE — synthesize a unique phone if not given.
const finalPhone = phone || `+62800${Math.floor(Math.random() * 1e10).toString().padStart(10, '0')}`
const [row] = await sql`
INSERT INTO mitras (id, display_name, phone, is_active)
VALUES (${id}, ${callName}, ${finalPhone}, ${isActive})
RETURNING id, display_name, phone, is_active, created_at
`
if (isOnline) {
const now = new Date()
await sql`
INSERT INTO mitra_online_status (mitra_id, is_online, last_online_at, last_heartbeat_at, updated_at)
VALUES (${id}, true, ${now}, ${now}, ${now})
ON CONFLICT (mitra_id) DO UPDATE
SET is_online = true, last_online_at = ${now}, last_heartbeat_at = ${now}, updated_at = ${now}
`
}
return row
}
/**
* Reset app_config rows to their canonical defaults. Tests that mutate config call
* this in afterEach (or rely on the global beforeEach in resetAll).
*/
export const seedDefaultConfig = () => resetAppConfig()
/**
* Convenience: full reset between tests. Truncates Phase 3.7 tables, restores
* default config rows.
*/
export { resetDb, resetDbHard, resetAppConfig } from './db.js'

View File

@@ -0,0 +1,42 @@
import jwt from 'jsonwebtoken'
import { randomUUID } from 'node:crypto'
import { UserType } from '../../src/constants.js'
/**
* Mint a JWT that the production `authenticate` plugin will accept. Mirrors the
* payload shape from src/services/token.service.js#signAccessToken.
*
* We deliberately do NOT call issueTokens (which writes an auth_sessions row) so
* tests stay independent of that table. The access-token verification path in
* production never reads the DB — it only validates the JWT signature + claims.
*
* sessionId defaults to a random UUID; pass an explicit one if a test asserts on
* the session_id value.
*/
const sign = ({ userType, userId, sessionId = randomUUID() }) => {
const secret = process.env.AUTH_JWT_SECRET
if (!secret || secret.length < 32) {
throw new Error('AUTH_JWT_SECRET missing or too short for test JWT minting')
}
return jwt.sign(
{ user_type: userType, session_id: sessionId },
secret,
{
algorithm: 'HS256',
expiresIn: 3600,
subject: userId,
},
)
}
export const customerJwt = (userId, opts = {}) =>
sign({ userType: UserType.CUSTOMER, userId, ...opts })
export const mitraJwt = (userId, opts = {}) =>
sign({ userType: UserType.MITRA, userId, ...opts })
export const ccJwt = (userId, opts = {}) =>
sign({ userType: UserType.CC_USER, userId, ...opts })
/** `Authorization: Bearer …` header builder for app.inject calls. */
export const authHeader = (token) => ({ authorization: `Bearer ${token}` })

View File

@@ -0,0 +1,25 @@
/**
* Build the public or internal Fastify app for in-process testing.
*
* Tests use `app.inject({ method, url, headers, payload })` to issue requests —
* this skips the HTTP layer entirely (no port binding, no socket overhead) and
* returns a typed response object.
*
* Each test file should call `buildPublic()` / `buildInternal()` in beforeAll and
* `await app.close()` in afterAll. Re-using the same app across tests in a file
* is fine — the DB state is what's reset between tests.
*/
export const buildPublic = async () => {
const { buildPublicApp } = await import('../../src/app.public.js')
const app = await buildPublicApp()
await app.ready()
return app
}
export const buildInternal = async () => {
const { buildInternalApp } = await import('../../src/app.internal.js')
const app = await buildInternalApp()
await app.ready()
return app
}

View File

@@ -0,0 +1,27 @@
import Redis from 'ioredis'
let testClient
/**
* Test-scoped Valkey client (separate db number from dev — see .env.test).
* Tests can use this directly for keyspace assertions, or just rely on the services
* which read VALKEY_URL via the production plugin (now pointing at the test db).
*/
export const getTestValkey = () => {
if (!testClient) {
testClient = new Redis(process.env.TEST_VALKEY_URL || process.env.VALKEY_URL)
}
return testClient
}
export const flushTestDb = async () => {
const c = getTestValkey()
await c.flushdb()
}
export const closeTestValkey = async () => {
if (testClient) {
testClient.disconnect()
testClient = null
}
}

View File

@@ -0,0 +1,115 @@
import { describe, it, expect, beforeAll, beforeEach, afterAll, vi } from 'vitest'
// The public app pulls in the websocket plugin which opens real WS upgrades on
// requests — out of scope for HTTP route tests. Mock it to a no-op.
vi.mock('../../src/plugins/websocket.js', () => ({
sendToUser: vi.fn(() => false),
sendToSessionParticipant: vi.fn(() => false),
registerWebSocketPlugin: vi.fn(async () => {}),
registerWebSocketRoute: vi.fn(),
isUserOnlineWs: vi.fn(() => false),
getSessionConnections: vi.fn(() => ({})),
}))
vi.mock('../../src/services/notification.service.js', () => ({
sendPushNotification: vi.fn(async () => true),
registerDeviceToken: vi.fn(async () => {}),
}))
const { buildPublic } = await import('../helpers/server.js')
const { resetDb, resetAppConfig, db } = await import('../helpers/db.js')
const { createCustomer } = await import('../helpers/fixtures.js')
const { customerJwt, authHeader } = await import('../helpers/jwt.js')
const { PaymentSessionStatus } = await import('../../src/constants.js')
describe('POST /api/client/payment-sessions', () => {
let app
let customer
let token
beforeAll(async () => {
await resetAppConfig()
app = await buildPublic()
})
beforeEach(async () => {
await resetDb()
customer = await createCustomer({ callName: 'PaymentTester' })
token = customerJwt(customer.id)
})
afterAll(async () => {
await app?.close()
})
it('happy path returns 201 + a pending payment-session row', async () => {
const res = await app.inject({
method: 'POST',
url: '/api/client/payment-sessions',
headers: authHeader(token),
payload: { duration_minutes: 15 },
})
expect(res.statusCode).toBe(201)
const body = res.json()
expect(body.success).toBe(true)
expect(body.data.status).toBe(PaymentSessionStatus.PENDING)
expect(body.data.duration_minutes).toBe(15)
// Default tier for 15min from migrate.js is 30000 — but the eligibility logic
// also needs `free_trial_enabled` to be true (default) AND no prior tx. Customer is
// brand-new so they get the trial → amount=0, is_free_trial=true. Verify accordingly.
expect(body.data.is_free_trial).toBe(true)
expect(body.data.amount).toBe(0)
expect(body.data.is_extension).toBe(false)
// Verify persistence
const sql = db()
const [row] = await sql`SELECT * FROM payment_sessions WHERE id = ${body.data.id}`
expect(row).toBeDefined()
expect(row.customer_id).toBe(customer.id)
})
it('POST /:id/confirm transitions the row and returns 200', async () => {
// Create a paid (non-trial) tier so the row has a non-zero amount and we exercise the
// confirm path with a "real" payment. Insert a transaction first so the customer is
// ineligible for the free trial.
const sql = db()
// Bootstrap: create a fake prior chat session + transaction so the customer is no
// longer eligible for the free trial. (The simpler alternative — flipping
// free_trial_enabled in app_config — would impact other tests.)
const [prior] = await sql`
INSERT INTO chat_sessions (customer_id, status, duration_minutes, price)
VALUES (${customer.id}, 'completed', 15, 30000)
RETURNING id
`
await sql`
INSERT INTO customer_transactions (customer_id, session_id, type, amount)
VALUES (${customer.id}, ${prior.id}, 'paid', 30000)
`
const createRes = await app.inject({
method: 'POST',
url: '/api/client/payment-sessions',
headers: authHeader(token),
payload: { duration_minutes: 15 },
})
expect(createRes.statusCode).toBe(201)
const created = createRes.json().data
expect(created.status).toBe(PaymentSessionStatus.PENDING)
expect(created.is_free_trial).toBe(false)
expect(created.amount).toBe(30000)
const confirmRes = await app.inject({
method: 'POST',
url: `/api/client/payment-sessions/${created.id}/confirm`,
headers: authHeader(token),
payload: {},
})
expect(confirmRes.statusCode).toBe(200)
const confirmed = confirmRes.json().data
expect(confirmed.id).toBe(created.id)
expect(confirmed.status).toBe(PaymentSessionStatus.CONFIRMED)
expect(confirmed.confirmed_at).toBeTruthy()
})
})

View File

@@ -0,0 +1,135 @@
import { describe, it, expect, beforeAll, beforeEach, afterEach, afterAll, vi } from 'vitest'
/**
* The pairing service fans out via the websocket plugin (`sendToUser`) and FCM
* (`sendPushNotification`). We mock both so tests assert on intent (which event
* was sent to which user) without needing a real WS client or FCM credentials.
*
* Mocks must be declared at the top level so vi.mock hoists them above the
* service imports.
*/
vi.mock('../../src/plugins/websocket.js', () => ({
// Default: pretend the user is not connected so the service falls back to FCM —
// matches the "customer is in the app but socket isn't open" path.
sendToUser: vi.fn(() => false),
sendToSessionParticipant: vi.fn(() => false),
registerWebSocketPlugin: vi.fn(),
registerWebSocketRoute: vi.fn(),
isUserOnlineWs: vi.fn(() => false),
getSessionConnections: vi.fn(() => ({})),
}))
vi.mock('../../src/services/notification.service.js', () => ({
sendPushNotification: vi.fn(async () => true),
registerDeviceToken: vi.fn(async () => {}),
}))
// Imports BELOW the mocks (vi.mock is hoisted, but keeping the order explicit aids
// readability and matches Vitest docs).
const { sendToUser } = await import('../../src/plugins/websocket.js')
const {
createPairingRequest,
declinePairingRequest,
cancelPairingRequest,
} = await import('../../src/services/pairing.service.js')
const { createPaymentSession, confirmPaymentSession } = await import('../../src/services/payment.service.js')
const {
WsMessage,
PairingFailureCause,
PaymentSessionStatus,
SessionStatus,
} = await import('../../src/constants.js')
const { db, resetDb, resetAppConfig } = await import('../helpers/db.js')
const { createCustomer, createMitra } = await import('../helpers/fixtures.js')
describe('pairing.service', () => {
let customer
let mitra
beforeAll(async () => {
await resetAppConfig()
})
beforeEach(async () => {
await resetDb()
sendToUser.mockClear()
customer = await createCustomer({ callName: 'Alice' })
mitra = await createMitra({ callName: 'MitraOne', isOnline: true })
})
afterEach(() => {
vi.clearAllMocks()
})
it('single-recipient general blast → mitra declines → terminates with ALL_MITRAS_REJECTED', async () => {
// Arrange: confirmed, non-targeted payment session.
const pay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 30000,
})
await confirmPaymentSession(pay.id, customer.id)
// Act: customer fires the general blast — only one mitra is online.
const session = await createPairingRequest(customer.id, {
paymentSessionId: pay.id,
})
expect(session.status).toBe(SessionStatus.PENDING_ACCEPTANCE)
// The single recipient declines. With the /simplify fix this is correctly
// classified as a general-blast all-rejected, NOT a targeted reject.
await declinePairingRequest(session.id, mitra.id)
// Assert: pairing_failures row carries ALL_MITRAS_REJECTED, not TARGETED_*.
const sql = db()
const failures = await sql`
SELECT cause_tag FROM pairing_failures WHERE payment_session_id = ${pay.id}
`
expect(failures).toHaveLength(1)
expect(failures[0].cause_tag).toBe(PairingFailureCause.ALL_MITRAS_REJECTED)
// Payment session is terminal (failed_pairing) — terminal failures consume the payment.
const [paySession] = await sql`SELECT status FROM payment_sessions WHERE id = ${pay.id}`
expect(paySession.status).toBe(PaymentSessionStatus.FAILED_PAIRING)
// Customer was notified with PAIRING_FAILED carrying the same cause tag.
const pairingFailedCalls = sendToUser.mock.calls.filter(
([, , data]) => data?.type === WsMessage.PAIRING_FAILED,
)
expect(pairingFailedCalls).toHaveLength(1)
expect(pairingFailedCalls[0][2].cause_tag).toBe(PairingFailureCause.ALL_MITRAS_REJECTED)
})
it('cancelPairingRequest does NOT push PAIRING_FAILED to the customer', async () => {
// Arrange: a confirmed payment + an in-flight pairing request the customer is about to cancel.
const pay = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 30000,
})
await confirmPaymentSession(pay.id, customer.id)
const session = await createPairingRequest(customer.id, {
paymentSessionId: pay.id,
})
// Act: customer cancels.
await cancelPairingRequest(session.id, customer.id)
// Assert: the customer must NOT receive a PAIRING_FAILED event for their own cancel.
// Mitras still get CHAT_REQUEST_CLOSED (that's the dismiss event) — we only assert on
// the customer-targeted events.
const customerEvents = sendToUser.mock.calls.filter(
// sendToUser signature: (userType, userId, data)
([userType, userId]) => userId === customer.id,
)
const customerEventTypes = customerEvents.map(([, , data]) => data?.type)
expect(customerEventTypes).not.toContain(WsMessage.PAIRING_FAILED)
// Payment session is still terminated (CUSTOMER_CANCELLED) — the failure row exists
// for ops accounting, just no real-time push to the customer who initiated the cancel.
const sql = db()
const failures = await sql`SELECT cause_tag FROM pairing_failures WHERE payment_session_id = ${pay.id}`
expect(failures).toHaveLength(1)
expect(failures[0].cause_tag).toBe(PairingFailureCause.CUSTOMER_CANCELLED)
})
})

View File

@@ -0,0 +1,85 @@
import { describe, it, expect, beforeAll, beforeEach, afterAll } from 'vitest'
import {
createPaymentSession,
confirmPaymentSession,
getPaymentSession,
} from '../../src/services/payment.service.js'
import { PaymentSessionStatus } from '../../src/constants.js'
import { resetDb, resetAppConfig } from '../helpers/db.js'
import { createCustomer } from '../helpers/fixtures.js'
describe('payment.service', () => {
let customer
let otherCustomer
beforeAll(async () => {
await resetAppConfig()
})
beforeEach(async () => {
await resetDb()
customer = await createCustomer({ callName: 'Alice' })
otherCustomer = await createCustomer({ callName: 'Bob' })
})
afterAll(async () => {
// Leave the seeded users alone for the next test file's speed.
})
it('createPaymentSession writes a row with status pending and expires_at in the future', async () => {
const before = Date.now()
const session = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 30000,
})
expect(session.status).toBe(PaymentSessionStatus.PENDING)
expect(session.customer_id).toBe(customer.id)
expect(session.duration_minutes).toBe(15)
expect(session.amount).toBe(30000)
expect(session.is_free_trial).toBe(false)
expect(session.is_extension).toBe(false)
expect(new Date(session.expires_at).getTime()).toBeGreaterThan(before)
// Verify it's actually persisted (not just returned from the INSERT)
const reloaded = await getPaymentSession(session.id)
expect(reloaded.id).toBe(session.id)
expect(reloaded.status).toBe(PaymentSessionStatus.PENDING)
})
it('confirmPaymentSession transitions pending → confirmed', async () => {
const session = await createPaymentSession({
customerId: customer.id,
durationMinutes: 30,
amount: 60000,
})
expect(session.status).toBe(PaymentSessionStatus.PENDING)
const confirmed = await confirmPaymentSession(session.id, customer.id)
expect(confirmed.status).toBe(PaymentSessionStatus.CONFIRMED)
expect(confirmed.confirmed_at).toBeTruthy()
expect(new Date(confirmed.confirmed_at).getTime()).toBeGreaterThan(0)
})
it('confirmPaymentSession throws when the session belongs to a different customer', async () => {
const session = await createPaymentSession({
customerId: customer.id,
durationMinutes: 15,
amount: 30000,
})
await expect(
confirmPaymentSession(session.id, otherCustomer.id),
).rejects.toMatchObject({
code: 'FORBIDDEN',
statusCode: 403,
})
// Row should still be pending — the failed confirm must not have side effects.
const reloaded = await getPaymentSession(session.id)
expect(reloaded.status).toBe(PaymentSessionStatus.PENDING)
expect(reloaded.confirmed_at).toBeNull()
})
})

110
backend/test/setup.js Normal file
View File

@@ -0,0 +1,110 @@
/**
* Vitest global setup. Runs once per test file before any test bodies.
*
* Responsibilities:
* 1. Load .env.test (falls back to env vars already in process.env if missing).
* 2. Override DATABASE_URL / VALKEY_URL with the *test* equivalents BEFORE any
* backend service modules are imported — services capture `getDb()` at module
* load, so this rewrite must happen first.
* 3. Run the migration against the test schema (idempotent — single migrate.js).
* 4. Provide a `beforeEach` truncate hook for any test that imports the helper.
*
* Why this file is small: helpers live under test/helpers/* and are imported lazily
* by individual test files. This file is intentionally just env setup + migrate.
*/
import { existsSync } from 'node:fs'
import { resolve, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { config as loadDotenv } from 'dotenv'
import { spawnSync } from 'node:child_process'
import { afterAll, beforeAll } from 'vitest'
const __dirname = dirname(fileURLToPath(import.meta.url))
const backendRoot = resolve(__dirname, '..')
// 1. Load .env.test if it exists
const envTestPath = resolve(backendRoot, '.env.test')
if (existsSync(envTestPath)) {
loadDotenv({ path: envTestPath })
}
// 2. Validate required env (fail fast — silent fallback to dev DB would be catastrophic)
const required = ['TEST_DATABASE_URL', 'TEST_VALKEY_URL', 'AUTH_JWT_SECRET']
for (const key of required) {
if (!process.env[key]) {
throw new Error(
`Missing required test env var: ${key}. Copy .env.test.example → .env.test or set it in your shell.`
)
}
}
if (process.env.AUTH_JWT_SECRET.length < 32) {
throw new Error('AUTH_JWT_SECRET must be at least 32 chars')
}
const TEST_SCHEMA = process.env.TEST_DB_SCHEMA || 'halobestie_test'
if (TEST_SCHEMA === 'public') {
// Hard guard: schema isolation only works if we don't reuse the dev `public` schema.
throw new Error(
`TEST_DB_SCHEMA must not be "public" (would clobber dev tables). ` +
`Set TEST_DB_SCHEMA to something like "halobestie_test".`
)
}
// 3. Build the schema-scoped URL used by getDb() in services.
// The `?options=-c search_path=...` query param tells Postgres to set search_path
// on every new connection. All CREATE TABLE / INSERT / SELECT then default to the
// test schema, leaving the dev `public` schema untouched.
const baseTestUrl = process.env.TEST_DATABASE_URL
const sep = baseTestUrl.includes('?') ? '&' : '?'
const scopedTestUrl = `${baseTestUrl}${sep}options=${encodeURIComponent(`-c search_path=${TEST_SCHEMA},public`)}`
// CRITICAL: rewrite the env vars services read at module load time. Must happen before
// any `import { ... } from '../src/services/...'` in a test or helper.
process.env.DATABASE_URL = scopedTestUrl
process.env.VALKEY_URL = process.env.TEST_VALKEY_URL
beforeAll(async () => {
// Ensure the schema exists. Use a one-shot connection that's NOT the singleton.
const { default: postgres } = await import('postgres')
const bootstrap = postgres(process.env.TEST_DATABASE_URL)
try {
await bootstrap`CREATE SCHEMA IF NOT EXISTS ${bootstrap(TEST_SCHEMA)}`
} finally {
await bootstrap.end()
}
// Run the migration via a child process so we don't conflict with the singleton
// sql client this test process will use. migrate.js calls sql.end() at the bottom,
// which would tear down the shared client if invoked in-process.
const result = spawnSync(
process.execPath,
[resolve(backendRoot, 'src/db/migrate.js')],
{
env: {
...process.env,
DATABASE_URL: scopedTestUrl,
},
cwd: backendRoot,
encoding: 'utf8',
}
)
if (result.status !== 0) {
throw new Error(
`Test migration failed (exit ${result.status}):\n` +
`stdout: ${result.stdout}\nstderr: ${result.stderr}`
)
}
}, 60_000)
afterAll(async () => {
// Best-effort cleanup of any singletons opened by the test process. Each helper that
// opens a connection registers its own teardown; this is a safety net.
try {
const { getDb } = await import('../src/db/client.js')
const sql = getDb()
await sql.end({ timeout: 5 })
} catch {
// Singleton was never created — fine.
}
})