Files
halobestie-clone/backend/test/routes/client.payment.routes.test.js
ramadhan sjamsani d09e50af55 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>
2026-05-03 23:02:49 +08:00

116 lines
4.2 KiB
JavaScript

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()
})
})