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

26
backend/.env.test.example Normal file
View File

@@ -0,0 +1,26 @@
# Test environment configuration. Copy to .env.test and adjust if needed.
#
# DEFAULT STRATEGY (Option C): same remote Postgres, isolated `halobestie_test` SCHEMA.
# The dev role on the remote DB cannot CREATE DATABASE, so we use schema isolation
# instead of a separate database. Tests set search_path so the migration creates all
# tables inside `halobestie_test`, leaving the dev `public` schema untouched.
# Test Postgres (same instance + same database as dev — schema isolates).
TEST_DATABASE_URL=postgresql://halobestie_clone:halobestie_clone@omv.sjamsani.id:5432/halobestie_clone
# Schema used to isolate test tables from dev tables. MUST NOT be `public`.
TEST_DB_SCHEMA=halobestie_test
# Test Valkey (same instance, separate db number 1 to avoid clashing with dev db 0).
TEST_VALKEY_URL=redis://omv.sjamsani.id:6379/1
# JWT secret for test-minted tokens. Any 32+ char string is fine (does not need to
# match the dev secret; tests mint and verify in the same process).
AUTH_JWT_SECRET=test-secret-must-be-at-least-32-characters-long
# Token TTLs (kept short for tests).
ACCESS_TOKEN_TTL_SECONDS=3600
REFRESH_TOKEN_TTL_DAYS=30
# CC origin needed by app.internal CORS — anything resolvable.
CC_ORIGIN=http://localhost:5173

4
backend/.gitignore vendored
View File

@@ -1,5 +1,9 @@
node_modules/
.env
.env.test
*.log
firebase-service-account.json
*-firebase-adminsdk-*.json
coverage/
_phase37_smoke.mjs
_check_db.mjs

View File

@@ -0,0 +1,34 @@
# Alternative test infrastructure: ephemeral Postgres + Valkey containers.
#
# CURRENT DEFAULT is Option C (schema-isolated remote DB) because the dev role on
# the remote DB cannot CREATE DATABASE. Use this docker-compose if you'd rather
# run an isolated, throwaway test DB on your local machine.
#
# To switch to docker-compose:
# 1. docker compose -f docker-compose.test.yml up -d
# 2. In .env.test set:
# TEST_DATABASE_URL=postgresql://test:test@localhost:55432/halobestie_test
# TEST_DB_SCHEMA=public
# TEST_VALKEY_URL=redis://localhost:56379/0
# 3. npm test
# 4. docker compose -f docker-compose.test.yml down -v
#
# The non-default ports (55432, 56379) avoid clashing with any local Postgres/Redis.
services:
postgres-test:
image: postgres:15-alpine
environment:
POSTGRES_USER: test
POSTGRES_PASSWORD: test
POSTGRES_DB: halobestie_test
ports:
- "55432:5432"
tmpfs:
- /var/lib/postgresql/data # ephemeral — wiped on container stop
valkey-test:
image: valkey/valkey:7-alpine
ports:
- "56379:6379"
tmpfs:
- /data

1441
backend/package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -8,7 +8,10 @@
"dev": "node --watch src/server.js",
"start": "node src/server.js",
"db:migrate": "node src/db/migrate.js",
"db:seed": "node src/db/seed.js"
"db:seed": "node src/db/seed.js",
"test": "vitest run",
"test:watch": "vitest",
"test:coverage": "vitest run --coverage"
},
"dependencies": {
"@fastify/cookie": "^11.0.2",
@@ -28,6 +31,8 @@
"zod": "^3.23.8"
},
"devDependencies": {
"@types/pg": "^8.11.6"
"@types/pg": "^8.11.6",
"@vitest/coverage-v8": "^4.1.5",
"vitest": "^4.1.5"
}
}

View File

@@ -9,16 +9,21 @@ import { internalAuthRoutes } from './routes/internal/auth.routes.js'
import { internalConfigRoutes } from './routes/internal/config.routes.js'
import { sessionManagementRoutes } from './routes/internal/session.routes.js'
import { mitraActivityRoutes } from './routes/internal/mitra-activity.routes.js'
import { failedPairingsRoutes } from './routes/internal/failed-pairings.routes.js'
import { errorHandler } from './plugins/error-handler.js'
export const buildInternalApp = async () => {
const app = Fastify({ logger: true })
// CORS: control center origin must be allowed with credentials for httpOnly refresh cookie
// CORS: control center origin must be allowed with credentials for httpOnly refresh cookie.
// Methods must include PATCH/PUT/DELETE — settings mutations and other admin actions
// use those, and @fastify/cors's default allow-methods (GET,HEAD,POST) silently breaks
// them with a CORS preflight rejection in the browser (curl bypasses preflight).
const ccOrigin = process.env.CC_ORIGIN
await app.register(cors, {
origin: ccOrigin ? ccOrigin.split(',').map((s) => s.trim()) : true,
credentials: true,
methods: ['GET', 'HEAD', 'POST', 'PATCH', 'PUT', 'DELETE'],
})
await app.register(cookie)
await app.register(sensible)
@@ -31,6 +36,7 @@ export const buildInternalApp = async () => {
app.register(internalConfigRoutes, { prefix: '/internal/config' })
app.register(sessionManagementRoutes, { prefix: '/internal/sessions' })
app.register(mitraActivityRoutes, { prefix: '/internal/mitra-activity' })
app.register(failedPairingsRoutes, { prefix: '/internal/failed-pairings' })
return app
}

View File

@@ -8,6 +8,8 @@ import { sharedConfigRoutes } from './routes/public/shared.config.routes.js'
import { mitraStatusRoutes } from './routes/public/mitra.status.routes.js'
import { mitraChatRoutes } from './routes/public/mitra.chat.routes.js'
import { clientChatRoutes } from './routes/public/client.chat.routes.js'
import { clientPaymentRoutes } from './routes/public/client.payment.routes.js'
import { clientMitraAvailabilityRoutes } from './routes/public/client.mitra-availability.routes.js'
import { sharedChatRoutes } from './routes/public/shared.chat.routes.js'
import { errorHandler } from './plugins/error-handler.js'
import { registerWebSocketPlugin, registerWebSocketRoute } from './plugins/websocket.js'
@@ -28,6 +30,8 @@ export const buildPublicApp = async () => {
app.register(mitraStatusRoutes, { prefix: '/api/mitra/status' })
app.register(mitraChatRoutes, { prefix: '/api/mitra/chat-requests' })
app.register(clientChatRoutes, { prefix: '/api/client/chat' })
app.register(clientPaymentRoutes, { prefix: '/api/client/payment-sessions' })
app.register(clientMitraAvailabilityRoutes, { prefix: '/api/client/mitra-availability' })
// WebSocket route (registered at app level, not prefixed)
registerWebSocketRoute(app)

View File

@@ -53,6 +53,48 @@ export const TransactionType = Object.freeze({
EXTENSION: 'extension',
})
// Payment session lifecycle
export const PaymentSessionStatus = Object.freeze({
PENDING: 'pending',
CONFIRMED: 'confirmed',
CONSUMED: 'consumed',
FAILED_PAIRING: 'failed_pairing',
ABANDONED: 'abandoned',
EXPIRED: 'expired',
})
// Pairing failure cause tags
export const PairingFailureCause = Object.freeze({
NO_MITRA_AVAILABLE: 'no_mitra_available',
ALL_MITRAS_REJECTED: 'all_mitras_rejected',
TARGETED_MITRA_OFFLINE: 'targeted_mitra_offline',
TARGETED_MITRA_REJECTED: 'targeted_mitra_rejected',
TARGETED_MITRA_TIMEOUT: 'targeted_mitra_timeout',
PAYMENT_SESSION_EXPIRED: 'payment_session_expired',
CUSTOMER_CANCELLED: 'customer_cancelled',
EXTENSION_REJECTED: 'extension_rejected',
EXTENSION_SAFEGUARD_TRIPPED: 'extension_safeguard_tripped',
})
// Operator actions on failed-pairing rows
export const PairingFailureOperatorAction = Object.freeze({
REFUNDED: 'refunded',
CREDITED: 'credited',
NO_ACTION: 'no_action',
})
// Default action when extension request times out (configurable)
export const ExtensionTimeoutAction = Object.freeze({
AUTO_APPROVE: 'auto_approve',
AUTO_REJECT: 'auto_reject',
})
// Pairing request type — distinguishes general blast from targeted "Curhat lagi"
export const PairingRequestType = Object.freeze({
GENERAL: 'general',
RETURNING: 'returning',
})
// Who ended a session
export const EndedBy = Object.freeze({
SYSTEM: 'system',
@@ -116,6 +158,16 @@ export const WsMessage = Object.freeze({
EXTENSION_REQUEST: 'extension_request',
EXTENSION_RESPONSE: 'extension_response',
// Returning-chat
RETURNING_CHAT_TIMEOUT: 'returning_chat_timeout',
RETURNING_CHAT_REJECTED: 'returning_chat_rejected',
// Sent when the customer is sitting in a searching/waiting state and the server terminates
// the payment session out from under them (general blast exhausts, payment expires mid-search,
// etc). NOT used for intermediate failures like targeted reject/timeout — those use
// RETURNING_CHAT_* events instead.
PAIRING_FAILED: 'pairing_failed',
// Topic sensitivity
SESSION_TOPIC_UPDATED: 'session_topic_updated',

View File

@@ -120,6 +120,13 @@ const migrate = async () => {
ON chat_sessions (status)
`
// Composite index for the per-mitra active-session count subquery used by the
// 5s availability poll and the per-blast capacity filter.
await sql`
CREATE INDEX IF NOT EXISTS idx_chat_sessions_mitra_status
ON chat_sessions (mitra_id, status)
`
await sql`
CREATE TABLE IF NOT EXISTS chat_request_notifications (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
@@ -413,6 +420,135 @@ const migrate = async () => {
ON CONFLICT (key) DO NOTHING
`
// --- Phase 3.7: Paid Pairing Flow + Returning-Chat + Extension Flip ---
// payment_sessions: customer-initiated payment intents (mocked) that gate pairing
await sql`
CREATE TABLE IF NOT EXISTS payment_sessions (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
customer_id UUID NOT NULL REFERENCES customers(id),
amount INTEGER NOT NULL DEFAULT 0,
duration_minutes INTEGER NOT NULL,
is_free_trial BOOLEAN NOT NULL DEFAULT false,
is_extension BOOLEAN NOT NULL DEFAULT false,
status TEXT NOT NULL DEFAULT 'pending'
CHECK (status IN ('pending','confirmed','consumed','failed_pairing','abandoned','expired')),
targeted_mitra_id UUID REFERENCES mitras(id),
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
confirmed_at TIMESTAMPTZ,
consumed_at TIMESTAMPTZ,
expires_at TIMESTAMPTZ NOT NULL
)
`
await sql`
CREATE INDEX IF NOT EXISTS idx_payment_sessions_customer
ON payment_sessions (customer_id)
`
await sql`
CREATE INDEX IF NOT EXISTS idx_payment_sessions_status_expires
ON payment_sessions (status, expires_at)
`
// pairing_failures: cause-tagged audit rows for confirmed payments that did not yield a chat
await sql`
CREATE TABLE IF NOT EXISTS pairing_failures (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
payment_session_id UUID NOT NULL REFERENCES payment_sessions(id) ON DELETE CASCADE,
customer_id UUID NOT NULL REFERENCES customers(id),
targeted_mitra_id UUID REFERENCES mitras(id),
cause_tag TEXT NOT NULL
CHECK (cause_tag IN (
'no_mitra_available',
'all_mitras_rejected',
'targeted_mitra_offline',
'targeted_mitra_rejected',
'targeted_mitra_timeout',
'payment_session_expired',
'customer_cancelled'
)),
amount INTEGER NOT NULL,
operator_action TEXT
CHECK (operator_action IS NULL OR operator_action IN ('refunded','credited','no_action')),
actioned_by UUID REFERENCES control_center_users(id),
actioned_at TIMESTAMPTZ,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
)
`
// Phase 3.7 follow-up: extend the pairing_failures.cause_tag CHECK to include the two
// extension-specific tags. Idempotent: drop the existing check (whatever its exact name) and
// re-add the expanded list. Postgres auto-names CHECK constraints `<table>_<column>_check`
// unless we name them explicitly; the original DDL above relies on that default.
await sql`
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'pairing_failures'::regclass
AND conname = 'pairing_failures_cause_tag_check'
) THEN
ALTER TABLE pairing_failures DROP CONSTRAINT pairing_failures_cause_tag_check;
END IF;
ALTER TABLE pairing_failures ADD CONSTRAINT pairing_failures_cause_tag_check
CHECK (cause_tag IN (
'no_mitra_available',
'all_mitras_rejected',
'targeted_mitra_offline',
'targeted_mitra_rejected',
'targeted_mitra_timeout',
'payment_session_expired',
'customer_cancelled',
'extension_rejected',
'extension_safeguard_tripped'
));
END
$$
`
await sql`
CREATE INDEX IF NOT EXISTS idx_pairing_failures_created_at
ON pairing_failures (created_at DESC)
`
await sql`
CREATE INDEX IF NOT EXISTS idx_pairing_failures_cause
ON pairing_failures (cause_tag)
`
await sql`
CREATE INDEX IF NOT EXISTS idx_pairing_failures_unactioned
ON pairing_failures (created_at DESC) WHERE operator_action IS NULL
`
// chat_sessions FK to payment_sessions (nullable for backward compat with pre-3.7 rows)
await sql`
ALTER TABLE chat_sessions
ADD COLUMN IF NOT EXISTS payment_session_id UUID REFERENCES payment_sessions(id)
`
await sql`
CREATE INDEX IF NOT EXISTS idx_chat_sessions_payment
ON chat_sessions (payment_session_id)
`
// session_extensions FK to payment_sessions (extensions also have their own payment session)
await sql`
ALTER TABLE session_extensions
ADD COLUMN IF NOT EXISTS payment_session_id UUID REFERENCES payment_sessions(id)
`
// Phase 3.7 config keys (idempotent — existing dev DBs need a manual update for extension_timeout_seconds → 10)
await sql`
INSERT INTO app_config (key, value) VALUES
('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}')
ON CONFLICT (key) DO NOTHING
`
console.log('Migration complete.')
await sql.end()
}

View File

@@ -1,6 +1,7 @@
import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { UserType } from '../../constants.js'
import { UserType, ExtensionTimeoutAction } from '../../constants.js'
import { publish } from '../../plugins/valkey.js'
import {
getAnonymityConfig, setAnonymityConfig,
getMaxCustomersPerMitra, setMaxCustomersPerMitra,
@@ -9,6 +10,10 @@ import {
getEarlyEndConfig, setEarlyEndConfig,
getMitraPingConfig, setMitraPingConfig,
getSensitivityConfig, setSensitivityConfig,
getPaymentSessionTimeoutMinutes, setPaymentSessionTimeoutMinutes,
getReturningChatConfirmationTimeoutSeconds, setReturningChatConfirmationTimeoutSeconds,
getExtensionDefaultActionOnTimeout, setExtensionDefaultActionOnTimeout,
getPairingBlastTimeoutSeconds, setPairingBlastTimeoutSeconds,
} from '../../services/config.service.js'
const attachCcUser = async (request, reply) => {
@@ -21,6 +26,17 @@ const attachCcUser = async (request, reply) => {
}
export const internalConfigRoutes = async (app) => {
// Cross-instance config invalidate. Local mutators (e.g. setMaxCustomersPerMitra) bust
// their own in-process caches directly; this publish fans out to other instances.
const publishConfigInvalidate = async (key) => {
try {
await publish('config:invalidate', { key, ts: Date.now() })
} catch (err) {
// Valkey may be down in dev. Local invalidate already happened.
app.log.warn({ err, key }, 'config invalidate publish failed')
}
}
app.get('/anonymity', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (request, reply) => {
@@ -54,6 +70,7 @@ export const internalConfigRoutes = async (app) => {
return reply.code(422).send({ success: false, error: { code: 'VALIDATION_ERROR', message: 'max_customers_per_mitra must be a positive number' } })
}
const config = await setMaxCustomersPerMitra(max_customers_per_mitra)
await publishConfigInvalidate('max_customers_per_mitra')
return reply.send({ success: true, data: config })
})
@@ -178,4 +195,93 @@ export const internalConfigRoutes = async (app) => {
await sql`UPDATE app_config SET value = ${sql.json({ tiers })}, updated_at = NOW() WHERE key = 'price_tiers'`
return reply.send({ success: true, data: tiers })
})
// --- Paid pairing flow + extension flip ---
app.get('/payment-session-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (_req, reply) => {
return reply.send({ success: true, data: await getPaymentSessionTimeoutMinutes() })
})
app.patch('/payment-session-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
}, async (request, reply) => {
const { payment_session_timeout_minutes } = request.body ?? {}
if (typeof payment_session_timeout_minutes !== 'number' || payment_session_timeout_minutes < 1) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: 'payment_session_timeout_minutes must be a number >= 1' },
})
}
const config = await setPaymentSessionTimeoutMinutes(payment_session_timeout_minutes)
await publishConfigInvalidate('payment_session_timeout_minutes')
return reply.send({ success: true, data: config })
})
app.get('/returning-chat-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (_req, reply) => {
return reply.send({ success: true, data: await getReturningChatConfirmationTimeoutSeconds() })
})
app.patch('/returning-chat-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
}, async (request, reply) => {
const { returning_chat_confirmation_timeout_seconds } = request.body ?? {}
if (typeof returning_chat_confirmation_timeout_seconds !== 'number' || returning_chat_confirmation_timeout_seconds < 5) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: 'returning_chat_confirmation_timeout_seconds must be a number >= 5' },
})
}
const config = await setReturningChatConfirmationTimeoutSeconds(returning_chat_confirmation_timeout_seconds)
await publishConfigInvalidate('returning_chat_confirmation_timeout_seconds')
return reply.send({ success: true, data: config })
})
app.get('/extension-default-action', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (_req, reply) => {
return reply.send({ success: true, data: await getExtensionDefaultActionOnTimeout() })
})
app.patch('/extension-default-action', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
}, async (request, reply) => {
const { extension_default_action_on_timeout } = request.body ?? {}
if (!Object.values(ExtensionTimeoutAction).includes(extension_default_action_on_timeout)) {
return reply.code(422).send({
success: false,
error: {
code: 'VALIDATION_ERROR',
message: `extension_default_action_on_timeout must be one of: ${Object.values(ExtensionTimeoutAction).join(', ')}`,
},
})
}
const config = await setExtensionDefaultActionOnTimeout(extension_default_action_on_timeout)
await publishConfigInvalidate('extension_default_action_on_timeout')
return reply.send({ success: true, data: config })
})
app.get('/pairing-blast-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (_req, reply) => {
return reply.send({ success: true, data: await getPairingBlastTimeoutSeconds() })
})
app.patch('/pairing-blast-timeout', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
}, async (request, reply) => {
const { pairing_blast_timeout_seconds } = request.body ?? {}
if (typeof pairing_blast_timeout_seconds !== 'number' || pairing_blast_timeout_seconds < 5) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: 'pairing_blast_timeout_seconds must be a number >= 5' },
})
}
const config = await setPairingBlastTimeoutSeconds(pairing_blast_timeout_seconds)
await publishConfigInvalidate('pairing_blast_timeout_seconds')
return reply.send({ success: true, data: config })
})
}

View File

@@ -0,0 +1,69 @@
import { authenticate, requirePermission } from '../../plugins/auth.js'
import { getCcUserById } from '../../services/cc-user.service.js'
import { listFailures, setOperatorAction } from '../../services/pairing-failure.service.js'
import { UserType, PairingFailureCause, PairingFailureOperatorAction } from '../../constants.js'
const attachCcUser = async (request, reply) => {
if (request.auth?.userType !== UserType.CC_USER) {
return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
}
const user = await getCcUserById(request.auth.userId)
if (!user) return reply.code(403).send({ success: false, error: { code: 'FORBIDDEN', message: 'Not a control center user' } })
request.ccUser = user
}
const VALID_CAUSE_TAGS = new Set(Object.values(PairingFailureCause))
const VALID_ACTIONS = new Set(Object.values(PairingFailureOperatorAction))
/**
* Control-center "Failed Pairings" review screen backend.
*
* GET /internal/failed-pairings
* POST /internal/failed-pairings/:id/action
*/
export const failedPairingsRoutes = async (app) => {
app.get('/', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'read')],
}, async (request, reply) => {
const { cause_tags, date_from, date_to, limit = 50, offset = 0 } = request.query ?? {}
// cause_tags can arrive as a single string (?cause_tags=foo) or an array
// (?cause_tags=foo&cause_tags=bar). Normalize and validate.
let causeTagsArr = null
if (cause_tags !== undefined) {
causeTagsArr = Array.isArray(cause_tags) ? cause_tags : [cause_tags]
for (const tag of causeTagsArr) {
if (!VALID_CAUSE_TAGS.has(tag)) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: `Unknown cause_tag: ${tag}` },
})
}
}
}
const result = await listFailures({
causeTags: causeTagsArr,
dateFrom: date_from || null,
dateTo: date_to || null,
limit: Number(limit) || 50,
offset: Number(offset) || 0,
})
return reply.send({ success: true, data: result })
})
app.post('/:id/action', {
preHandler: [authenticate, attachCcUser, requirePermission('config', 'update')],
}, async (request, reply) => {
const { action } = request.body ?? {}
if (!VALID_ACTIONS.has(action)) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: `action must be one of: ${[...VALID_ACTIONS].join(', ')}` },
})
}
const updated = await setOperatorAction(request.params.id, request.ccUser.id, action)
return reply.send({ success: true, data: updated })
})
}

View File

@@ -1,8 +1,19 @@
import { authenticate } from '../../plugins/auth.js'
import { getCustomerById } from '../../services/customer.service.js'
import { createPairingRequest, cancelPairingRequest } from '../../services/pairing.service.js'
import { getActiveSessionByCustomer, getActiveSessionByCustomerWithUnread, endSession, getCustomerHistory } from '../../services/session.service.js'
import { getPricingForCustomer, isValidTier, isCustomerEligibleForFreeTrial, getFreeTrial } from '../../services/pricing.service.js'
import {
createPairingRequest,
createTargetedPairingRequest,
cancelPairingRequest,
cancelPaymentSearch,
fallbackToGeneralBlast,
} from '../../services/pairing.service.js'
import {
getActiveSessionByCustomer,
getActiveSessionByCustomerWithUnread,
endSession,
getCustomerHistory,
} from '../../services/session.service.js'
import { getPricingForCustomer } from '../../services/pricing.service.js'
import { requestExtension } from '../../services/extension.service.js'
import { EndedBy, TopicSensitivity, UserType } from '../../constants.js'
@@ -30,8 +41,21 @@ export const clientChatRoutes = async (app) => {
return reply.send({ success: true, data: pricing })
})
/**
* Start a general-blast pairing search.
*
* Body MUST include `payment_session_id` (a confirmed payment_session owned by the caller).
* Pricing/duration/free-trial values are sourced from the payment session, NOT from the client.
*/
app.post('/request', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const { duration_minutes, price, is_free_trial, topic_sensitivity } = request.body || {}
const { payment_session_id, topic_sensitivity } = request.body ?? {}
if (!payment_session_id) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
})
}
if (topic_sensitivity !== TopicSensitivity.REGULAR && topic_sensitivity !== TopicSensitivity.SENSITIVE) {
return reply.code(400).send({
@@ -40,43 +64,91 @@ export const clientChatRoutes = async (app) => {
})
}
// Validate selection
if (is_free_trial) {
const eligible = await isCustomerEligibleForFreeTrial(request.customer.id)
if (!eligible) {
return reply.code(403).send({
success: false,
error: { code: 'FREE_TRIAL_INELIGIBLE', message: 'Not eligible for free trial' },
})
}
const freeTrial = await getFreeTrial()
const session = await createPairingRequest(request.customer.id, {
duration_minutes: freeTrial.duration_minutes,
price: 0,
is_free_trial: true,
topic_sensitivity,
})
return reply.code(201).send({ success: true, data: session })
}
if (!duration_minutes || price === undefined) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'duration_minutes and price are required' },
})
}
if (!(await isValidTier(duration_minutes, price))) {
return reply.code(400).send({
success: false,
error: { code: 'INVALID_TIER', message: 'Invalid price tier selection' },
})
}
const session = await createPairingRequest(request.customer.id, { duration_minutes, price, is_free_trial: false, topic_sensitivity })
const session = await createPairingRequest(request.customer.id, {
paymentSessionId: payment_session_id,
topic_sensitivity,
})
return reply.code(201).send({ success: true, data: session })
})
/**
* Start a targeted "Curhat lagi" pairing request.
*
* Body: { payment_session_id, mitra_id, topic_sensitivity? }
* Returns 409 with reason: 'targeted_mitra_offline' if the targeted mitra is unreachable
* or at capacity. The payment session stays `confirmed` in that case so the customer
* can fall back to general blast on the same payment.
*/
app.post('/chat-requests/returning', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const { payment_session_id, mitra_id, topic_sensitivity } = request.body ?? {}
if (!payment_session_id) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
})
}
if (!mitra_id) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'mitra_id is required' },
})
}
const resolvedTopic = (topic_sensitivity === TopicSensitivity.SENSITIVE)
? TopicSensitivity.SENSITIVE
: TopicSensitivity.REGULAR
const session = await createTargetedPairingRequest(request.customer.id, {
paymentSessionId: payment_session_id,
targetedMitraId: mitra_id,
topic_sensitivity: resolvedTopic,
})
return reply.code(201).send({ success: true, data: session })
})
/**
* Customer-initiated cancel during searching/waiting.
*
* Body: { payment_session_id }
* Terminal — payment session moves to failed_pairing with cause = customer_cancelled.
*/
app.post('/chat-requests/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const { payment_session_id } = request.body ?? {}
if (!payment_session_id) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'payment_session_id is required' },
})
}
const result = await cancelPaymentSearch(payment_session_id, request.customer.id)
return reply.send({ success: true, data: result })
})
/**
* After a returning-chat fail, customer taps "Chat dengan bestie lain".
* Reuses the same payment_session_id (no double-charge), runs general blast.
*/
app.post('/chat-requests/:paymentSessionId/fallback-to-blast', {
preHandler: [authenticate, resolveCustomer],
}, async (request, reply) => {
const { topic_sensitivity } = request.body ?? {}
const resolvedTopic = (topic_sensitivity === TopicSensitivity.SENSITIVE)
? TopicSensitivity.SENSITIVE
: TopicSensitivity.REGULAR
const session = await fallbackToGeneralBlast(
request.params.paymentSessionId,
request.customer.id,
{ topic_sensitivity: resolvedTopic },
)
return reply.code(201).send({ success: true, data: session })
})
/**
* Cancel-by-session-id retained for in-flight chat_session cancels (e.g. cancel
* during the 20s targeted wait after a chat_session has been created). Customer cancel
* via payment_session_id should prefer POST /chat-requests/cancel above.
*/
app.post('/request/:sessionId/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const session = await cancelPairingRequest(request.params.sessionId, request.customer.id)
return reply.send({ success: true, data: session })
@@ -97,16 +169,32 @@ export const clientChatRoutes = async (app) => {
return reply.send({ success: true, data: session })
})
// Request session extension
/**
* Extension request REQUIRES `extension_payment_session_id`.
* The payment session must be is_extension=true and is_free_trial=false.
* Pricing/duration come from the payment session via the extension service.
*/
app.post('/session/:sessionId/extend', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const { duration_minutes, price } = request.body || {}
const { duration_minutes, price, extension_payment_session_id } = request.body ?? {}
if (!extension_payment_session_id) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'extension_payment_session_id is required' },
})
}
if (!duration_minutes || price === undefined) {
return reply.code(400).send({
success: false,
error: { code: 'BAD_REQUEST', message: 'duration_minutes and price are required' },
})
}
const extension = await requestExtension(request.params.sessionId, request.customer.id, { duration_minutes, price })
const extension = await requestExtension(request.params.sessionId, request.customer.id, {
duration_minutes,
price,
extension_payment_session_id,
})
return reply.send({ success: true, data: extension })
})

View File

@@ -0,0 +1,27 @@
import { authenticate } from '../../plugins/auth.js'
import { countAvailableMitrasFromCache } from '../../services/mitra-status.service.js'
import { UserType } from '../../constants.js'
/**
* Customer-home availability poll.
*
* GET /api/client/mitra-availability → 200 { available: bool, count?: number }
*
* Hot endpoint by design — polled every 5s per active customer while their home is
* foregrounded. Backed by a 10s in-memory cache (see mitra-status.service.js) so DB load
* stays bounded regardless of poller count. No rate limit by intent.
*
* `count` is included for CC/debug; the customer UI must read only `available`.
*/
export const clientMitraAvailabilityRoutes = async (app) => {
app.get('/', { preHandler: [authenticate] }, async (request, reply) => {
if (request.auth?.userType !== UserType.CUSTOMER) {
return reply.code(403).send({
success: false,
error: { code: 'FORBIDDEN', message: 'Customer account required' },
})
}
const result = await countAvailableMitrasFromCache()
return reply.send({ success: true, data: result })
})
}

View File

@@ -0,0 +1,155 @@
import { authenticate } from '../../plugins/auth.js'
import { getCustomerById } from '../../services/customer.service.js'
import {
createPaymentSession,
confirmPaymentSession,
abandonPaymentSession,
getPaymentSession,
} from '../../services/payment.service.js'
import {
isCustomerEligibleForFreeTrial,
isValidTier,
getPriceTiers,
} from '../../services/pricing.service.js'
import { UserType } from '../../constants.js'
const resolveCustomer = async (request, reply) => {
if (request.auth?.userType !== UserType.CUSTOMER) {
return reply.code(403).send({
success: false,
error: { code: 'FORBIDDEN', message: 'Customer account required' },
})
}
const customer = await getCustomerById(request.auth.userId)
if (!customer) {
return reply.code(404).send({
success: false,
error: { code: 'ACCOUNT_NOT_FOUND', message: 'Customer account not found' },
})
}
request.customer = customer
}
/**
* Payment session lifecycle (mocked — no Xendit yet).
*
* POST /api/client/payment-sessions
* POST /api/client/payment-sessions/:id/confirm
* POST /api/client/payment-sessions/:id/cancel
* GET /api/client/payment-sessions/:id
*/
export const clientPaymentRoutes = async (app) => {
// Create a payment session (status = pending). Free-trial logic is server-side: if the
// customer is eligible AND this is NOT an extension, amount is forced to 0 and
// is_free_trial = true regardless of what the client passes.
app.post('/', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const {
duration_minutes,
targeted_mitra_id = null,
is_extension = false,
} = request.body ?? {}
if (typeof duration_minutes !== 'number' || duration_minutes <= 0) {
return reply.code(422).send({
success: false,
error: { code: 'VALIDATION_ERROR', message: 'duration_minutes must be a positive number' },
})
}
// Free trial: never for extensions.
let isFreeTrial = false
let amount
if (!is_extension) {
const eligible = await isCustomerEligibleForFreeTrial(request.customer.id)
if (eligible) {
isFreeTrial = true
amount = 0
}
}
if (!isFreeTrial) {
// Resolve amount from the price tiers (duration-keyed). The client passes
// duration_minutes; we look up the matching tier to get the canonical price.
const tiers = await getPriceTiers()
const tier = tiers.find((t) => t.duration_minutes === duration_minutes)
if (!tier) {
return reply.code(400).send({
success: false,
error: { code: 'INVALID_TIER', message: 'No price tier matches the requested duration' },
})
}
amount = tier.price
// Sanity check (defense-in-depth) — duration+price should match a known tier.
if (!(await isValidTier(duration_minutes, amount))) {
return reply.code(400).send({
success: false,
error: { code: 'INVALID_TIER', message: 'Invalid price tier selection' },
})
}
}
const session = await createPaymentSession({
customerId: request.customer.id,
durationMinutes: duration_minutes,
amount,
isFreeTrial,
isExtension: Boolean(is_extension),
targetedMitraId: targeted_mitra_id || null,
})
return reply.code(201).send({
success: true,
data: {
id: session.id,
amount: session.amount,
duration_minutes: session.duration_minutes,
is_free_trial: session.is_free_trial,
is_extension: session.is_extension,
targeted_mitra_id: session.targeted_mitra_id,
expires_at: session.expires_at,
status: session.status,
},
})
})
app.post('/:id/confirm', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const session = await confirmPaymentSession(request.params.id, request.customer.id)
return reply.send({
success: true,
data: {
id: session.id,
status: session.status,
confirmed_at: session.confirmed_at,
},
})
})
app.post('/:id/cancel', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const session = await abandonPaymentSession(request.params.id, request.customer.id)
return reply.send({
success: true,
data: {
id: session.id,
status: session.status,
},
})
})
app.get('/:id', { preHandler: [authenticate, resolveCustomer] }, async (request, reply) => {
const session = await getPaymentSession(request.params.id)
if (!session) {
return reply.code(404).send({
success: false,
error: { code: 'NOT_FOUND', message: 'Payment session not found' },
})
}
if (session.customer_id !== request.customer.id) {
return reply.code(403).send({
success: false,
error: { code: 'FORBIDDEN', message: 'Payment session does not belong to this customer' },
})
}
return reply.send({ success: true, data: session })
})
}

View File

@@ -4,6 +4,7 @@ import { buildInternalApp } from './app.internal.js'
import { autoOfflineStaleMitras } from './services/mitra-status.service.js'
import { initFirebase } from './plugins/firebase.js'
import { restoreActiveTimers } from './services/session-timer.service.js'
import { expireStalePaymentSessions } from './services/payment.service.js'
const PUBLIC_PORT = process.env.PUBLIC_PORT || 3000
const INTERNAL_PORT = process.env.INTERNAL_PORT || 3001
@@ -32,6 +33,21 @@ const start = async () => {
console.error('Auto-offline check failed:', err)
}
}, 30_000)
// Expire stale payment_sessions (every 60s).
// Pending past expires_at → expired (no failure row). Confirmed-but-stale → failed_pairing
// with cause = payment_session_expired (writes a pairing_failures row).
// Single-instance for now; Valkey keyspace notifications when we go multi-instance.
setInterval(async () => {
try {
const result = await expireStalePaymentSessions()
if (result.expired > 0 || result.failed > 0) {
console.log(`Payment sweeper: ${result.expired} expired, ${result.failed} failed_pairing`)
}
} catch (err) {
console.error('Payment session sweeper failed:', err)
}
}, 60_000)
}
start().catch((err) => {

View File

@@ -1,4 +1,5 @@
import { getDb } from '../db/client.js'
import { ExtensionTimeoutAction } from '../constants.js'
const sql = getDb()
@@ -27,6 +28,10 @@ export const setMaxCustomersPerMitra = async (value) => {
VALUES ('max_customers_per_mitra', ${sql.json({ value })}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
// Capacity changed → drop cached availability snapshot.
// Imported lazily to avoid a circular import (mitra-status.service uses config).
const { invalidateAvailabilityCache } = await import('./mitra-status.service.js')
invalidateAvailabilityCache()
return { max_customers_per_mitra: value }
}
@@ -61,7 +66,8 @@ export const setFreeTrialConfig = async ({ enabled, duration_minutes }) => {
export const getExtensionTimeoutConfig = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'extension_timeout_seconds'`
return { extension_timeout_seconds: row?.value?.value ?? 60 }
// Default 10s pairs with the auto-approve-on-timeout flow; raise this if you change the policy to auto-reject.
return { extension_timeout_seconds: row?.value?.value ?? 10 }
}
export const setExtensionTimeoutConfig = async (seconds) => {
@@ -222,3 +228,61 @@ export const setCcLoginLockoutConfig = async ({ max_attempts, lockout_minutes })
}
return getCcLoginLockoutConfig()
}
// --- Paid Pairing Flow + Returning-Chat + Extension Flip ---
export const getPaymentSessionTimeoutMinutes = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'payment_session_timeout_minutes'`
return { payment_session_timeout_minutes: row?.value?.value ?? 20 }
}
export const setPaymentSessionTimeoutMinutes = async (value) => {
await sql`
INSERT INTO app_config (key, value, updated_at)
VALUES ('payment_session_timeout_minutes', ${sql.json({ value })}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
return { payment_session_timeout_minutes: value }
}
export const getReturningChatConfirmationTimeoutSeconds = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'returning_chat_confirmation_timeout_seconds'`
return { returning_chat_confirmation_timeout_seconds: row?.value?.value ?? 20 }
}
export const setReturningChatConfirmationTimeoutSeconds = async (value) => {
await sql`
INSERT INTO app_config (key, value, updated_at)
VALUES ('returning_chat_confirmation_timeout_seconds', ${sql.json({ value })}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
return { returning_chat_confirmation_timeout_seconds: value }
}
export const getExtensionDefaultActionOnTimeout = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'extension_default_action_on_timeout'`
return { extension_default_action_on_timeout: row?.value?.value ?? ExtensionTimeoutAction.AUTO_APPROVE }
}
export const setExtensionDefaultActionOnTimeout = async (value) => {
await sql`
INSERT INTO app_config (key, value, updated_at)
VALUES ('extension_default_action_on_timeout', ${sql.json({ value })}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
return { extension_default_action_on_timeout: value }
}
export const getPairingBlastTimeoutSeconds = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'pairing_blast_timeout_seconds'`
return { pairing_blast_timeout_seconds: row?.value?.value ?? 60 }
}
export const setPairingBlastTimeoutSeconds = async (value) => {
await sql`
INSERT INTO app_config (key, value, updated_at)
VALUES ('pairing_blast_timeout_seconds', ${sql.json({ value })}, NOW())
ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = NOW()
`
return { pairing_blast_timeout_seconds: value }
}

View File

@@ -1,20 +1,53 @@
import { getDb } from '../db/client.js'
import { publish } from '../plugins/valkey.js'
import { sendToSessionParticipant } from '../plugins/websocket.js'
import { sendToSessionParticipant, isUserOnlineWs } from '../plugins/websocket.js'
import { extendSessionTimer, clearClosureGraceTimer, startClosureGraceTimer } from './session-timer.service.js'
import { UserType, SessionStatus, ExtensionStatus, TransactionType, WsMessage } from '../constants.js'
import { isMitraReachable } from './mitra-status.service.js'
import { consumePaymentSession, failPaymentSession, getPaymentSession } from './payment.service.js'
import {
getExtensionTimeoutConfig,
getExtensionDefaultActionOnTimeout,
} from './config.service.js'
import {
UserType,
SessionStatus,
ExtensionStatus,
TransactionType,
WsMessage,
PaymentSessionStatus,
ExtensionTimeoutAction,
PairingFailureCause,
} from '../constants.js'
const sql = getDb()
// Extension timeout map: extensionId → timeoutId
const extensionTimeouts = new Map()
const getExtensionTimeout = async () => {
const [row] = await sql`SELECT value FROM app_config WHERE key = 'extension_timeout_seconds'`
return (row?.value?.value ?? 60) * 1000 // Convert to ms
const getExtensionTimeoutMs = async () => {
const { extension_timeout_seconds } = await getExtensionTimeoutConfig()
return extension_timeout_seconds * 1000
}
export const requestExtension = async (sessionId, customerId, { duration_minutes, price }) => {
const getExtensionTimeoutAction = async () => {
const { extension_default_action_on_timeout } = await getExtensionDefaultActionOnTimeout()
return Object.values(ExtensionTimeoutAction).includes(extension_default_action_on_timeout)
? extension_default_action_on_timeout
: ExtensionTimeoutAction.AUTO_APPROVE
}
/**
* Customer requests an extension.
*
* `extension_payment_session_id` is REQUIRED. The payment session must:
* - belong to this customer
* - be in `confirmed` status (not yet consumed)
* - have `is_extension = true`
* - have `is_free_trial = false` (extensions never use free trial)
*
* The payment session is NOT consumed at request time. It is consumed at approval moment
* (mitra explicit accept OR auto-approve fires).
*/
export const requestExtension = async (sessionId, customerId, { duration_minutes, price, extension_payment_session_id }) => {
// Verify session belongs to customer and is in an extendable state
const [session] = await sql`
SELECT id, customer_id, mitra_id, status, topic_sensitivity FROM chat_sessions
@@ -25,16 +58,51 @@ export const requestExtension = async (sessionId, customerId, { duration_minutes
throw Object.assign(new Error('Session not found or already ended'), { code: 'SESSION_NOT_ACTIVE', statusCode: 409 })
}
// Create extension record
// Validate extension payment session
if (!extension_payment_session_id) {
throw Object.assign(new Error('extension_payment_session_id is required'), {
code: 'VALIDATION_ERROR', statusCode: 422,
})
}
const paySession = await getPaymentSession(extension_payment_session_id)
if (!paySession) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (paySession.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), {
code: 'FORBIDDEN', statusCode: 403,
})
}
if (paySession.status !== PaymentSessionStatus.CONFIRMED) {
throw Object.assign(new Error(`Payment session is ${paySession.status}, must be confirmed`), {
code: 'INVALID_STATE', statusCode: 409,
})
}
if (!paySession.is_extension) {
throw Object.assign(new Error('Payment session is not flagged as an extension payment'), {
code: 'INVALID_STATE', statusCode: 409,
})
}
if (paySession.is_free_trial) {
throw Object.assign(new Error('Free trial is not available for extensions'), {
code: 'FREE_TRIAL_NOT_ALLOWED', statusCode: 400,
})
}
// Create extension record (linked to its payment session)
const [extension] = await sql`
INSERT INTO session_extensions (session_id, requested_duration_minutes, requested_price, status)
VALUES (${sessionId}, ${duration_minutes}, ${price}, ${ExtensionStatus.PENDING})
RETURNING id, session_id, requested_duration_minutes, requested_price, status, requested_at
INSERT INTO session_extensions (session_id, requested_duration_minutes, requested_price, status, payment_session_id)
VALUES (${sessionId}, ${duration_minutes}, ${price}, ${ExtensionStatus.PENDING}, ${extension_payment_session_id})
RETURNING id, session_id, requested_duration_minutes, requested_price, status, requested_at, payment_session_id
`
// Pause the session
await sql`UPDATE chat_sessions SET status = ${SessionStatus.EXTENDING} WHERE id = ${sessionId}`
// Resolve timeout once so we can both surface it in the WS payload and start the server-side timer.
const timeoutMs = await getExtensionTimeoutMs()
const timeoutSeconds = Math.round(timeoutMs / 1000)
// Notify mitra — include current topic sensitivity so UI can highlight
sendToSessionParticipant(sessionId, UserType.MITRA, {
type: WsMessage.EXTENSION_REQUEST,
@@ -43,6 +111,7 @@ export const requestExtension = async (sessionId, customerId, { duration_minutes
duration_minutes,
price,
topic_sensitivity: session.topic_sensitivity,
timeout_seconds: timeoutSeconds,
})
// Notify customer that chat is paused
@@ -51,13 +120,12 @@ export const requestExtension = async (sessionId, customerId, { duration_minutes
session_id: sessionId,
reason: 'extension_pending',
})
// Start timeout
const timeoutMs = await getExtensionTimeout()
const timeoutId = setTimeout(async () => {
try {
await timeoutExtension(extension.id, sessionId)
} catch (_) {}
await timeoutExtension(extension.id, sessionId, session.mitra_id)
} catch (err) {
console.error('timeoutExtension failed', { extensionId: extension.id, sessionId, err })
}
}, timeoutMs)
extensionTimeouts.set(extension.id, timeoutId)
@@ -73,16 +141,25 @@ export const respondToExtension = async (extensionId, sessionId, mitraId, accept
throw Object.assign(new Error('Session not found'), { code: 'FORBIDDEN', statusCode: 403 })
}
return finalizeExtension(extensionId, sessionId, accepted, /* viaTimeout */ false)
}
/**
* Internal: applies the accepted/rejected outcome. Used by both explicit response
* and the data-driven timeout path.
*/
const finalizeExtension = async (extensionId, sessionId, accepted, viaTimeout) => {
const status = accepted ? ExtensionStatus.ACCEPTED : ExtensionStatus.REJECTED
const [extension] = await sql`
UPDATE session_extensions
SET status = ${status}, responded_at = NOW()
WHERE id = ${extensionId} AND session_id = ${sessionId} AND status = ${ExtensionStatus.PENDING}
RETURNING id, session_id, requested_duration_minutes, requested_price, status
RETURNING id, session_id, requested_duration_minutes, requested_price, status, payment_session_id
`
if (!extension) {
if (viaTimeout) return null // race: already resolved before timer fired
throw Object.assign(new Error('Extension not found or already resolved'), {
code: 'EXTENSION_RESOLVED', statusCode: 409,
})
@@ -96,6 +173,11 @@ export const respondToExtension = async (extensionId, sessionId, mitraId, accept
}
if (accepted) {
// Charge fires AT approval moment (explicit OR auto-approve).
if (extension.payment_session_id) {
await consumePaymentSession(extension.payment_session_id)
}
// Clear any pending grace timer from the previous expiry
clearClosureGraceTimer(sessionId)
@@ -117,6 +199,7 @@ export const respondToExtension = async (extensionId, sessionId, mitraId, accept
type: WsMessage.EXTENSION_RESPONSE,
accepted: true,
duration_minutes: extension.requested_duration_minutes,
via_timeout: viaTimeout,
})
sendToSessionParticipant(sessionId, UserType.CUSTOMER, {
type: WsMessage.SESSION_RESUMED,
@@ -127,12 +210,19 @@ export const respondToExtension = async (extensionId, sessionId, mitraId, accept
session_id: sessionId,
})
} else {
// Rejected — proceed to closure
// Rejected — no charge. Fail the extension payment session if present.
// viaTimeout=false here means an explicit mitra reject (the timer path goes through
// timeoutExtension which never enters this branch with viaTimeout=true for reject).
if (extension.payment_session_id) {
await failPaymentSession(extension.payment_session_id, PairingFailureCause.EXTENSION_REJECTED)
}
await sql`UPDATE chat_sessions SET status = ${SessionStatus.CLOSING} WHERE id = ${extension.session_id}`
sendToSessionParticipant(sessionId, UserType.CUSTOMER, {
type: WsMessage.EXTENSION_RESPONSE,
accepted: false,
via_timeout: viaTimeout,
})
sendToSessionParticipant(sessionId, UserType.MITRA, {
type: WsMessage.SESSION_CLOSING,
@@ -148,24 +238,72 @@ export const respondToExtension = async (extensionId, sessionId, mitraId, accept
return extension
}
const timeoutExtension = async (extensionId, sessionId) => {
/**
* Data-driven timeout handler.
*
* - read `extension_default_action_on_timeout` config:
* - 'auto_approve': check mitra reachability (WS + Valkey online). If both OK → approve.
* If either is offline/disconnected → fall back to reject (no charge).
* - 'auto_reject' (back-compat flag): reject regardless.
*/
const timeoutExtension = async (extensionId, sessionId, mitraId) => {
extensionTimeouts.delete(extensionId)
const [extension] = await sql`
// Confirm extension is still pending (race with explicit response)
const [pending] = await sql`
SELECT id FROM session_extensions
WHERE id = ${extensionId} AND status = ${ExtensionStatus.PENDING}
`
if (!pending) return
const action = await getExtensionTimeoutAction()
// Track WHY we ended up rejecting so the failed-pairings audit row gets the right tag.
// Default: configured policy is auto_reject → use EXTENSION_REJECTED.
let causeTag = PairingFailureCause.EXTENSION_REJECTED
let reasonForClient = 'timeout'
if (action === ExtensionTimeoutAction.AUTO_APPROVE) {
// Safeguard: mitra must be reachable (online in Valkey AND connected via WS).
// Never use "in-session" as a proxy for "online".
const wsConnected = isUserOnlineWs(UserType.MITRA, mitraId)
const onlineFlag = await isMitraReachable(mitraId)
if (wsConnected && onlineFlag) {
// Approve via the same path as explicit accept.
await finalizeExtension(extensionId, sessionId, /* accepted */ true, /* viaTimeout */ true)
return
}
// Safeguard tripped — treat as auto-reject (no charge), but tag the audit row distinctly
// so CC operators can see this was a system-safety decision, not a mitra reject or a
// configured auto-reject policy decision.
causeTag = PairingFailureCause.EXTENSION_SAFEGUARD_TRIPPED
reasonForClient = 'safeguard'
}
// auto_reject (configured) OR auto_approve-with-safeguard-tripped — both end with
// the extension marked TIMEOUT, no charge, session moves to CLOSING. The cause_tag
// distinguishes them in the failed-pairings audit log. RETURNING guards against a race
// with explicit accept/decline that landed between the pending check above and here —
// if no row was matched, the extension is no longer ours to time out.
const [timedOut] = await sql`
UPDATE session_extensions
SET status = ${ExtensionStatus.TIMEOUT}, responded_at = NOW()
WHERE id = ${extensionId} AND status = ${ExtensionStatus.PENDING}
RETURNING id, session_id
RETURNING id, payment_session_id
`
if (!extension) return
if (!timedOut) return
// Timeout = proceed to closure
await sql`UPDATE chat_sessions SET status = ${SessionStatus.CLOSING} WHERE id = ${extension.session_id}`
if (timedOut.payment_session_id) {
await failPaymentSession(timedOut.payment_session_id, causeTag)
}
// Move session to closing & notify both parties (matches the explicit-reject UX).
await sql`UPDATE chat_sessions SET status = ${SessionStatus.CLOSING} WHERE id = ${sessionId}`
sendToSessionParticipant(sessionId, UserType.CUSTOMER, {
type: WsMessage.EXTENSION_RESPONSE,
accepted: false,
reason: 'timeout',
reason: reasonForClient,
})
sendToSessionParticipant(sessionId, UserType.MITRA, {
type: WsMessage.SESSION_CLOSING,

View File

@@ -1,9 +1,40 @@
import { getDb } from '../db/client.js'
import { SessionStatus } from '../constants.js'
import { getMitraPingConfig } from './config.service.js'
import { getMitraPingConfig, getMaxCustomersPerMitra } from './config.service.js'
import { subscribe } from '../plugins/valkey.js'
const sql = getDb()
// --- Short-TTL availability cache for the 5s-poll endpoint ---
// In-memory snapshot { available, count, expiresAt }. The cache:
// - is recomputed at most once per AVAILABILITY_TTL_MS (10s backstop)
// - is invalidated explicitly when CC changes max_customers_per_mitra (call invalidateAvailabilityCache())
// This keeps customer polls off the DB hot path while staying close to real time.
const AVAILABILITY_TTL_MS = 10_000
let availabilityCache = null // { available, count, expiresAt }
export const invalidateAvailabilityCache = () => {
availabilityCache = null
}
// Subscribe once at module load so other-instance config updates also bust this cache.
// Single-instance: the local mutator already invalidates, so this is a no-op extra.
let _subscribed = false
const ensureSubscribed = () => {
if (_subscribed) return
_subscribed = true
try {
subscribe('config:invalidate', (msg) => {
if (msg?.key === 'max_customers_per_mitra') {
invalidateAvailabilityCache()
}
})
} catch (_) {
// Valkey may not be reachable in some test contexts; non-fatal.
}
}
ensureSubscribed()
export const ensureStatusRow = async (mitraId) => {
await sql`
INSERT INTO mitra_online_status (mitra_id)
@@ -23,6 +54,7 @@ export const setOnline = async (mitraId) => {
await sql`
INSERT INTO mitra_online_logs (mitra_id, status) VALUES (${mitraId}, 'online')
`
invalidateAvailabilityCache()
}
export const setOffline = async (mitraId) => {
@@ -41,6 +73,7 @@ export const setOffline = async (mitraId) => {
await sql`
INSERT INTO mitra_online_logs (mitra_id, status) VALUES (${mitraId}, 'offline')
`
invalidateAvailabilityCache()
}
export const heartbeat = async (mitraId) => {
@@ -116,5 +149,93 @@ export const autoOfflineStaleMitras = async () => {
`
}
// Capacity may have changed (mitra went offline) — invalidate the customer-facing
// availability cache so the next poll reflects reality.
if (stale.length > 0) invalidateAvailabilityCache()
return stale.length
}
/**
* Customer-home availability check, cached in-memory for AVAILABILITY_TTL_MS.
*
* Returns { available, count } where:
* - available = true iff at least one mitra is online AND below max_customers_per_mitra
* - count is the number of qualifying mitras (CC/debug only — never expose to customer UI)
*
* The 5s-poll endpoint backed by this function MUST NOT issue per-poll DB queries.
* The 10s TTL caps DB load to ~6 queries/min total regardless of poller count.
*
* Note: today the source of truth for online status + active session counts is Postgres
* (mitra_online_status + chat_sessions). A future refactor can mirror these into Valkey
* sets/hashes (matching the existing memory item "Session Timer Scaling"); the contract
* of this function — Valkey/cache reads only on the hot path — stays the same.
*/
export const countAvailableMitrasFromCache = async () => {
const now = Date.now()
if (availabilityCache && availabilityCache.expiresAt > now) {
return { available: availabilityCache.available, count: availabilityCache.count }
}
const { max_customers_per_mitra } = await getMaxCustomersPerMitra()
const [{ count }] = await sql`
SELECT COUNT(*)::int AS count
FROM mitras m
INNER JOIN mitra_online_status s ON s.mitra_id = m.id
WHERE m.is_active = true
AND s.is_online = true
AND (
SELECT COUNT(*) FROM chat_sessions cs
WHERE cs.mitra_id = m.id
AND cs.status IN (${SessionStatus.ACTIVE}, ${SessionStatus.PENDING_PAYMENT})
) < ${max_customers_per_mitra}
`
const available = count > 0
availabilityCache = {
available,
count,
expiresAt: now + AVAILABILITY_TTL_MS,
}
return { available, count }
}
/**
* Mitra-online check for use during pairing/extension safeguards.
* Combines the Valkey-mirrored online flag (Postgres mitra_online_status today) with
* the WebSocket-connected check. Never use "in-session" as a proxy for "online".
*/
export const isMitraReachable = async (mitraId) => {
const [row] = await sql`
SELECT is_online FROM mitra_online_status WHERE mitra_id = ${mitraId}
`
return Boolean(row?.is_online)
}
/**
* Returns active session count for a mitra (sessions that count toward max_customers_per_mitra).
*/
export const getMitraActiveSessionCount = async (mitraId) => {
const [{ count }] = await sql`
SELECT COUNT(*)::int AS count FROM chat_sessions
WHERE mitra_id = ${mitraId}
AND status IN (${SessionStatus.ACTIVE}, ${SessionStatus.PENDING_PAYMENT})
`
return count
}
/**
* True iff this mitra is currently in an ACTIVE chat with this specific customer.
* Used by targeted "Curhat lagi" pre-check: a mitra at-capacity but mid-session
* with the requesting customer is still allowed to receive a returning-chat card.
*/
export const isMitraInActiveSessionWithCustomer = async (mitraId, customerId) => {
const [row] = await sql`
SELECT id FROM chat_sessions
WHERE mitra_id = ${mitraId}
AND customer_id = ${customerId}
AND status IN (${SessionStatus.ACTIVE}, ${SessionStatus.EXTENDING}, ${SessionStatus.CLOSING})
LIMIT 1
`
return Boolean(row)
}

View File

@@ -0,0 +1,85 @@
import { getDb } from '../db/client.js'
import { PairingFailureCause, PairingFailureOperatorAction } from '../constants.js'
const sql = getDb()
/**
* Insert a pairing_failures row. Called from payment.service.failPaymentSession (and the
* background sweeper for `payment_session_expired`).
*/
export const recordFailure = async ({ paymentSessionId, customerId, targetedMitraId = null, causeTag, amount }) => {
if (!Object.values(PairingFailureCause).includes(causeTag)) {
throw Object.assign(new Error(`Unknown cause_tag: ${causeTag}`), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
const [row] = await sql`
INSERT INTO pairing_failures (
payment_session_id, customer_id, targeted_mitra_id, cause_tag, amount
)
VALUES (
${paymentSessionId}, ${customerId}, ${targetedMitraId}, ${causeTag}, ${amount}
)
RETURNING id, payment_session_id, customer_id, targeted_mitra_id, cause_tag, amount,
operator_action, actioned_by, actioned_at, created_at
`
return row
}
/**
* Control-center listing with optional filters. Returns rows + total count.
*/
export const listFailures = async ({ causeTags = null, dateFrom = null, dateTo = null, limit = 50, offset = 0 } = {}) => {
const safeLimit = Math.min(Math.max(Number(limit) || 50, 1), 200)
const safeOffset = Math.max(Number(offset) || 0, 0)
const items = await sql`
SELECT
pf.id, pf.payment_session_id, pf.customer_id, pf.targeted_mitra_id,
pf.cause_tag, pf.amount, pf.operator_action, pf.actioned_by, pf.actioned_at, pf.created_at,
c.display_name AS customer_call_name,
m.display_name AS targeted_mitra_call_name,
cc.display_name AS actioned_by_name
FROM pairing_failures pf
JOIN customers c ON c.id = pf.customer_id
LEFT JOIN mitras m ON m.id = pf.targeted_mitra_id
LEFT JOIN control_center_users cc ON cc.id = pf.actioned_by
WHERE
${causeTags && causeTags.length > 0 ? sql`pf.cause_tag IN ${sql(causeTags)}` : sql`TRUE`}
AND ${dateFrom ? sql`pf.created_at >= ${dateFrom}` : sql`TRUE`}
AND ${dateTo ? sql`pf.created_at <= ${dateTo}` : sql`TRUE`}
ORDER BY pf.created_at DESC
LIMIT ${safeLimit} OFFSET ${safeOffset}
`
const [{ count }] = await sql`
SELECT COUNT(*) FROM pairing_failures pf
WHERE
${causeTags && causeTags.length > 0 ? sql`pf.cause_tag IN ${sql(causeTags)}` : sql`TRUE`}
AND ${dateFrom ? sql`pf.created_at >= ${dateFrom}` : sql`TRUE`}
AND ${dateTo ? sql`pf.created_at <= ${dateTo}` : sql`TRUE`}
`
return { rows: items, total: Number(count), limit: safeLimit, offset: safeOffset }
}
/**
* Operator action menu — record the chosen action against a failure row.
* Each call overwrites the previous decision (operator can change their mind).
*/
export const setOperatorAction = async (failureId, ccUserId, action) => {
if (!Object.values(PairingFailureOperatorAction).includes(action)) {
throw Object.assign(new Error(`Unknown operator action: ${action}`), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
const [updated] = await sql`
UPDATE pairing_failures
SET operator_action = ${action},
actioned_by = ${ccUserId},
actioned_at = NOW()
WHERE id = ${failureId}
RETURNING id, payment_session_id, customer_id, targeted_mitra_id, cause_tag, amount,
operator_action, actioned_by, actioned_at, created_at
`
if (!updated) {
throw Object.assign(new Error('Failure row not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
return updated
}

View File

@@ -1,10 +1,22 @@
import { getDb } from '../db/client.js'
import { getMaxCustomersPerMitra } from './config.service.js'
import { getMaxCustomersPerMitra, getPairingBlastTimeoutSeconds, getReturningChatConfirmationTimeoutSeconds } from './config.service.js'
import { sendToUser } from '../plugins/websocket.js'
import { sendPushNotification } from './notification.service.js'
import { startSessionTimer } from './session-timer.service.js'
import { startSessionListener } from './chat-handler.service.js'
import { UserType, SessionStatus, NotificationResponse, TransactionType, WsMessage, TopicSensitivity } from '../constants.js'
import { consumePaymentSession, failPaymentSession, getPaymentSession, recordIntermediateFailure } from './payment.service.js'
import { isMitraReachable, isMitraInActiveSessionWithCustomer, getMitraActiveSessionCount } from './mitra-status.service.js'
import {
UserType,
SessionStatus,
NotificationResponse,
TransactionType,
WsMessage,
TopicSensitivity,
PaymentSessionStatus,
PairingFailureCause,
PairingRequestType,
} from '../constants.js'
const sql = getDb()
@@ -20,7 +32,12 @@ const notifyMitra = async (mitraId, data) => {
await sendPushNotification(UserType.MITRA, mitraId, {
title: 'Permintaan Chat Baru',
body: 'Ada pelanggan yang ingin curhat! Ketuk untuk menerima.',
data: { type: WsMessage.CHAT_REQUEST, session_id: data.session_id, action: 'open_accept' },
data: {
type: WsMessage.CHAT_REQUEST,
session_id: data.session_id,
request_type: data.request_type || PairingRequestType.GENERAL,
action: 'open_accept',
},
})
}
}
@@ -43,27 +60,101 @@ const notifyCustomer = async (customerId, data) => {
body: 'Maaf, tidak ada bestie yang tersedia saat ini.',
data: { type: WsMessage.SESSION_EXPIRED, session_id: data.session_id },
})
} else if (data.type === WsMessage.PAIRING_FAILED) {
// Terminal pairing failure on a confirmed payment. Push so the customer
// can come back to the app and see the failed-pairing screen / contact support.
await sendPushNotification(UserType.CUSTOMER, customerId, {
title: 'Sesi gagal',
body: 'Maaf, kami tidak bisa menemukan bestie untuk sesimu. Tim kami akan menghubungimu segera.',
data: {
type: WsMessage.PAIRING_FAILED,
payment_session_id: data.payment_session_id || '',
cause_tag: data.cause_tag || '',
},
})
}
}
}
export const findAvailableMitras = async () => {
const { max_customers_per_mitra } = await getMaxCustomersPerMitra()
// Project active_session_count alongside the mitra row so the blast loop doesn't
// need a per-mitra COUNT roundtrip later.
const mitras = await sql`
SELECT m.id, m.display_name
SELECT m.id, m.display_name, sub.active_session_count
FROM mitras m
INNER JOIN mitra_online_status s ON s.mitra_id = m.id
INNER JOIN LATERAL (
SELECT COUNT(*)::int AS active_session_count
FROM chat_sessions cs
WHERE cs.mitra_id = m.id AND cs.status IN (${SessionStatus.ACTIVE}, ${SessionStatus.PENDING_PAYMENT})
) sub ON true
WHERE m.is_active = true
AND s.is_online = true
AND (
SELECT COUNT(*) FROM chat_sessions cs
WHERE cs.mitra_id = m.id AND cs.status IN (${SessionStatus.ACTIVE}, ${SessionStatus.PENDING_PAYMENT})
) < ${max_customers_per_mitra}
AND sub.active_session_count < ${max_customers_per_mitra}
`
return mitras
}
export const createPairingRequest = async (customerId, { duration_minutes, price, is_free_trial, topic_sensitivity } = {}) => {
/**
* Validate that a payment session is owned by the customer, confirmed, and not yet consumed.
* Throws on mismatch. Returns the loaded payment session row.
*/
const requireConfirmedPaymentSession = async (paymentSessionId, customerId, { allowExtension = false } = {}) => {
if (!paymentSessionId) {
throw Object.assign(new Error('payment_session_id is required'), {
code: 'VALIDATION_ERROR', statusCode: 422,
})
}
const paySession = await getPaymentSession(paymentSessionId)
if (!paySession) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (paySession.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), {
code: 'FORBIDDEN', statusCode: 403,
})
}
if (paySession.status !== PaymentSessionStatus.CONFIRMED) {
throw Object.assign(new Error(`Payment session is ${paySession.status}, must be confirmed`), {
code: 'INVALID_STATE', statusCode: 409,
})
}
if (paySession.is_extension && !allowExtension) {
throw Object.assign(new Error('Extension payment session cannot be used to start a new chat'), {
code: 'INVALID_STATE', statusCode: 409,
})
}
if (new Date(paySession.expires_at) <= new Date()) {
// Check expiry inline at every state transition (defense in depth vs. the background sweeper).
await failPaymentSession(paymentSessionId, PairingFailureCause.PAYMENT_SESSION_EXPIRED)
throw Object.assign(new Error('Payment session has expired'), { code: 'EXPIRED', statusCode: 409 })
}
return paySession
}
/**
* General-blast pairing request. Requires a confirmed payment_session_id.
*
* The duration_minutes / price / is_free_trial values for the chat_session row are
* sourced from the payment session — the client does not dictate pricing here.
*
* `allowTargetedPayment` is set true by the fallback-to-blast path: the original payment
* was created with a `targeted_mitra_id` for "Curhat lagi" but the customer chose to
* fall back to general blast on the same payment. The flag bypasses the
* "use returning-chat endpoint" guard in that exact case.
*/
export const createPairingRequest = async (customerId, { paymentSessionId, topic_sensitivity, allowTargetedPayment = false } = {}) => {
const paySession = await requireConfirmedPaymentSession(paymentSessionId, customerId)
// Targeted payment session must use createTargetedPairingRequest unless we're
// explicitly invoked by the fallback-to-blast path.
if (paySession.targeted_mitra_id && !allowTargetedPayment) {
throw Object.assign(new Error('Payment session is targeted to a specific mitra; use returning-chat endpoint'), {
code: 'INVALID_STATE', statusCode: 409,
})
}
// Check for existing active session or request
const [existing] = await sql`
SELECT id, status FROM chat_sessions
@@ -78,6 +169,8 @@ export const createPairingRequest = async (customerId, { duration_minutes, price
const availableMitras = await findAvailableMitras()
if (availableMitras.length === 0) {
// No mitras to blast to — fail the payment immediately.
await failPaymentSession(paymentSessionId, PairingFailureCause.NO_MITRA_AVAILABLE)
throw Object.assign(new Error('No bestie available'), {
code: 'NO_MITRA_AVAILABLE', statusCode: 404,
})
@@ -87,53 +180,182 @@ export const createPairingRequest = async (customerId, { duration_minutes, price
? TopicSensitivity.SENSITIVE
: TopicSensitivity.REGULAR
// Create session with duration/price/topic
// Create session sourced from the payment session.
const [session] = await sql`
INSERT INTO chat_sessions (customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity)
VALUES (${customerId}, ${SessionStatus.PENDING_ACCEPTANCE}, ${duration_minutes || null}, ${price || 0}, ${is_free_trial || false}, ${resolvedTopic})
RETURNING id, customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity, created_at
INSERT INTO chat_sessions (
customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity, payment_session_id
)
VALUES (
${customerId}, ${SessionStatus.PENDING_ACCEPTANCE},
${paySession.duration_minutes}, ${paySession.amount}, ${paySession.is_free_trial},
${resolvedTopic}, ${paymentSessionId}
)
RETURNING id, customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity, payment_session_id, created_at
`
// Create notifications for all available mitras
for (const mitra of availableMitras) {
const [{ count: activeCount }] = await sql`
SELECT COUNT(*)::int AS count FROM chat_sessions
WHERE mitra_id = ${mitra.id}
AND status IN (${SessionStatus.ACTIVE}, ${SessionStatus.PENDING_PAYMENT})
`
// Fan out to all available mitras in parallel — DB inserts and notifications are
// independent per mitra. active_session_count was already projected by findAvailableMitras.
await Promise.all(availableMitras.map(async (mitra) => {
await sql`
INSERT INTO chat_request_notifications (session_id, mitra_id, active_session_count)
VALUES (${session.id}, ${mitra.id}, ${activeCount})
VALUES (${session.id}, ${mitra.id}, ${mitra.active_session_count})
`
// Notify mitra via WebSocket (FCM fallback if offline)
await notifyMitra(mitra.id, {
type: WsMessage.CHAT_REQUEST,
session_id: session.id,
request_type: PairingRequestType.GENERAL,
created_at: session.created_at,
duration_minutes: session.duration_minutes,
is_free_trial: session.is_free_trial,
topic_sensitivity: session.topic_sensitivity,
})
}
}))
// Start 60s timeout
// Start blast timeout (configurable via app_config)
const { pairing_blast_timeout_seconds } = await getPairingBlastTimeoutSeconds()
const timeoutId = setTimeout(async () => {
try {
await expirePairingRequest(session.id)
} catch (_) {}
}, 60_000)
await expirePairingRequest(session.id, PairingFailureCause.NO_MITRA_AVAILABLE)
} catch (err) {
console.error('expirePairingRequest failed', { sessionId: session.id, err })
}
}, pairing_blast_timeout_seconds * 1000)
pairingTimeouts.set(session.id, timeoutId)
return session
}
/**
* Targeted pairing request for "Curhat lagi" (returning chat).
*
* - Pre-check targeted mitra reachability + capacity. If unreachable or at-capacity-and-not-mid-session
* with this customer → fail payment immediately and return 409 with `reason: 'targeted_mitra_offline'`.
* - Fire ONE notification to the targeted mitra.
* - Start a server-side timer of `returning_chat_confirmation_timeout_seconds`. On expiry,
* mark request auto-rejected, fail payment with `targeted_mitra_timeout`, push WS event.
* - On explicit decline by mitra: fail payment with `targeted_mitra_rejected`, push WS event.
* - On accept: existing accept path runs (consumes payment session as for general blast).
*/
export const createTargetedPairingRequest = async (customerId, { paymentSessionId, targetedMitraId, topic_sensitivity } = {}) => {
const paySession = await requireConfirmedPaymentSession(paymentSessionId, customerId)
if (!targetedMitraId) {
throw Object.assign(new Error('targetedMitraId is required'), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
// Cross-check: payment_session.targeted_mitra_id should match (if set).
if (paySession.targeted_mitra_id && paySession.targeted_mitra_id !== targetedMitraId) {
throw Object.assign(new Error('targetedMitraId does not match payment session'), {
code: 'INVALID_STATE', statusCode: 409,
})
}
// Check for existing active session or request
const [existing] = await sql`
SELECT id, status FROM chat_sessions
WHERE customer_id = ${customerId}
AND status IN (${SessionStatus.SEARCHING}, ${SessionStatus.PENDING_ACCEPTANCE}, ${SessionStatus.PENDING_PAYMENT}, ${SessionStatus.ACTIVE})
`
if (existing) {
throw Object.assign(new Error('Customer already has an active session or request'), {
code: 'ALREADY_ACTIVE', statusCode: 409,
})
}
// Pre-check: mitra reachable?
const reachable = await isMitraReachable(targetedMitraId)
if (!reachable) {
// Intermediate failure: audit row written, payment stays `confirmed` so the customer
// can choose to fall back to general blast (or cancel, which terminates).
await recordIntermediateFailure({
paymentSessionId,
customerId,
targetedMitraId,
causeTag: PairingFailureCause.TARGETED_MITRA_OFFLINE,
amount: paySession.amount,
})
throw Object.assign(new Error('Targeted mitra is offline'), {
code: 'TARGETED_MITRA_OFFLINE', statusCode: 409, reason: 'targeted_mitra_offline',
})
}
// Pre-check: mitra at capacity AND not mid-session with this customer?
const { max_customers_per_mitra } = await getMaxCustomersPerMitra()
const activeCount = await getMitraActiveSessionCount(targetedMitraId)
if (activeCount >= max_customers_per_mitra) {
const midSessionWithCustomer = await isMitraInActiveSessionWithCustomer(targetedMitraId, customerId)
if (!midSessionWithCustomer) {
await recordIntermediateFailure({
paymentSessionId,
customerId,
targetedMitraId,
causeTag: PairingFailureCause.TARGETED_MITRA_OFFLINE,
amount: paySession.amount,
})
throw Object.assign(new Error('Targeted mitra is at capacity'), {
code: 'TARGETED_MITRA_OFFLINE', statusCode: 409, reason: 'targeted_mitra_offline',
})
}
// Else: at-capacity but mid-session with the requesting customer — request allowed through.
}
const resolvedTopic = topic_sensitivity === TopicSensitivity.SENSITIVE
? TopicSensitivity.SENSITIVE
: TopicSensitivity.REGULAR
// Create session sourced from the payment session, status = pending_acceptance.
const [session] = await sql`
INSERT INTO chat_sessions (
customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity, payment_session_id
)
VALUES (
${customerId}, ${SessionStatus.PENDING_ACCEPTANCE},
${paySession.duration_minutes}, ${paySession.amount}, ${paySession.is_free_trial},
${resolvedTopic}, ${paymentSessionId}
)
RETURNING id, customer_id, status, duration_minutes, price, is_free_trial, topic_sensitivity, payment_session_id, created_at
`
// Single notification to the targeted mitra
await sql`
INSERT INTO chat_request_notifications (session_id, mitra_id, active_session_count)
VALUES (${session.id}, ${targetedMitraId}, ${activeCount})
`
// Server-side timer (configurable, default 20s) — also surfaced in the WS payload so the mitra
// app countdown UI matches what the server is enforcing.
const { returning_chat_confirmation_timeout_seconds } = await getReturningChatConfirmationTimeoutSeconds()
await notifyMitra(targetedMitraId, {
type: WsMessage.CHAT_REQUEST,
session_id: session.id,
request_type: PairingRequestType.RETURNING,
created_at: session.created_at,
duration_minutes: session.duration_minutes,
is_free_trial: session.is_free_trial,
topic_sensitivity: session.topic_sensitivity,
confirmation_timeout_seconds: returning_chat_confirmation_timeout_seconds,
})
const timeoutId = setTimeout(async () => {
try {
await expireTargetedPairingRequest(session.id)
} catch (err) {
console.error('expireTargetedPairingRequest failed', { sessionId: session.id, err })
}
}, returning_chat_confirmation_timeout_seconds * 1000)
pairingTimeouts.set(session.id, timeoutId)
// Surface the timeout to the customer so the targeted-waiting overlay countdown
// matches the server-side timer exactly (CC-configurable; never stale).
return { ...session, confirmation_timeout_seconds: returning_chat_confirmation_timeout_seconds }
}
export const acceptPairingRequest = async (sessionId, mitraId) => {
// Use a transaction-like approach: update only if status is still pending_acceptance
const [session] = await sql`
UPDATE chat_sessions
SET mitra_id = ${mitraId}, status = ${SessionStatus.PENDING_PAYMENT}, paired_at = NOW()
WHERE id = ${sessionId} AND status = ${SessionStatus.PENDING_ACCEPTANCE} AND mitra_id IS NULL
RETURNING id, customer_id, mitra_id, status, paired_at
RETURNING id, customer_id, mitra_id, status, paired_at, payment_session_id
`
if (!session) {
@@ -163,7 +385,12 @@ export const acceptPairingRequest = async (sessionId, mitraId) => {
pairingTimeouts.delete(sessionId)
}
// Auto-skip payment for now: move to active and set expires_at
// Consume the payment session at the moment of acceptance.
if (session.payment_session_id) {
await consumePaymentSession(session.payment_session_id)
}
// Activate the session and set expires_at.
const [activeSession] = await sql`
UPDATE chat_sessions
SET status = ${SessionStatus.ACTIVE},
@@ -172,7 +399,7 @@ export const acceptPairingRequest = async (sessionId, mitraId) => {
ELSE NULL
END
WHERE id = ${sessionId}
RETURNING id, customer_id, mitra_id, status, paired_at, duration_minutes, price, is_free_trial, expires_at
RETURNING id, customer_id, mitra_id, status, paired_at, duration_minutes, price, is_free_trial, expires_at, payment_session_id
`
// Record transaction
@@ -205,18 +432,16 @@ export const acceptPairingRequest = async (sessionId, mitraId) => {
status: SessionStatus.ACTIVE,
})
// Notify other mitras to dismiss the request
// Notify other mitras to dismiss the request — independent fan-out, run in parallel.
const notifications = await sql`
SELECT mitra_id FROM chat_request_notifications
WHERE session_id = ${sessionId} AND mitra_id != ${mitraId}
`
for (const n of notifications) {
await notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'accepted_by_other',
})
}
await Promise.all(notifications.map((n) => notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'accepted_by_other',
})))
return activeSession
}
@@ -227,6 +452,94 @@ export const declinePairingRequest = async (sessionId, mitraId) => {
SET response = ${NotificationResponse.DECLINED}, responded_at = NOW()
WHERE session_id = ${sessionId} AND mitra_id = ${mitraId} AND response IS NULL
`
// Targeted-vs-general is determined by the payment_session.targeted_mitra_id, not by
// notification count — a general blast with only one online mitra also has length=1.
const [targetCheck] = await sql`
SELECT ps.targeted_mitra_id
FROM chat_sessions cs
LEFT JOIN payment_sessions ps ON ps.id = cs.payment_session_id
WHERE cs.id = ${sessionId}
`
const isTargeted = !!targetCheck?.targeted_mitra_id
if (isTargeted) {
// Mark the chat_session as expired (the targeted attempt is over) — but keep the
// payment_session in `confirmed` so the customer can fall back to general blast on
// the same payment, or cancel (which then terminates).
const [session] = await sql`
UPDATE chat_sessions
SET status = ${SessionStatus.EXPIRED}
WHERE id = ${sessionId} AND status = ${SessionStatus.PENDING_ACCEPTANCE}
RETURNING id, customer_id, payment_session_id
`
if (session) {
// Clear the 20s timer if still pending.
const timeoutId = pairingTimeouts.get(sessionId)
if (timeoutId) {
clearTimeout(timeoutId)
pairingTimeouts.delete(sessionId)
}
// Audit row only; payment session stays `confirmed`.
if (session.payment_session_id) {
const paySession = await getPaymentSession(session.payment_session_id)
if (paySession) {
await recordIntermediateFailure({
paymentSessionId: session.payment_session_id,
customerId: session.customer_id,
targetedMitraId: mitraId,
causeTag: PairingFailureCause.TARGETED_MITRA_REJECTED,
amount: paySession.amount,
})
}
}
// Push a returning-chat-rejected WS event to the customer (fall-through to fallback flow).
await notifyCustomer(session.customer_id, {
type: WsMessage.RETURNING_CHAT_REJECTED,
session_id: sessionId,
payment_session_id: session.payment_session_id,
})
}
return
}
// General-blast: if all notifications now have a non-null DECLINED response → treat as
// every-mitra-rejected (terminal, distinct from blast-window-timeout). Empty-array guard
// prevents a misfire when the SELECT happens to return zero rows.
const notifications = await sql`
SELECT response FROM chat_request_notifications WHERE session_id = ${sessionId}
`
const allDeclined = notifications.length > 0
&& notifications.every((n) => n.response === NotificationResponse.DECLINED)
if (allDeclined) {
const [session] = await sql`
UPDATE chat_sessions
SET status = ${SessionStatus.EXPIRED}
WHERE id = ${sessionId} AND status = ${SessionStatus.PENDING_ACCEPTANCE}
RETURNING id, customer_id, payment_session_id
`
if (session) {
const timeoutId = pairingTimeouts.get(sessionId)
if (timeoutId) {
clearTimeout(timeoutId)
pairingTimeouts.delete(sessionId)
}
if (session.payment_session_id) {
await failPaymentSession(session.payment_session_id, PairingFailureCause.ALL_MITRAS_REJECTED)
}
// Terminal: customer is in a searching state and the search just ended with no chat.
await notifyCustomer(session.customer_id, {
type: WsMessage.PAIRING_FAILED,
session_id: sessionId,
payment_session_id: session.payment_session_id,
cause_tag: PairingFailureCause.ALL_MITRAS_REJECTED,
})
}
}
}
export const cancelPairingRequest = async (sessionId, customerId) => {
@@ -235,7 +548,7 @@ export const cancelPairingRequest = async (sessionId, customerId) => {
SET status = ${SessionStatus.CANCELLED}
WHERE id = ${sessionId} AND customer_id = ${customerId}
AND status IN (${SessionStatus.SEARCHING}, ${SessionStatus.PENDING_ACCEPTANCE})
RETURNING id, status
RETURNING id, customer_id, status, payment_session_id
`
if (!session) {
@@ -258,27 +571,109 @@ export const cancelPairingRequest = async (sessionId, customerId) => {
WHERE session_id = ${sessionId} AND response IS NULL
`
// Notify mitras to dismiss (customer cancelled)
// Notify mitras to dismiss (customer cancelled) — independent fan-out, run in parallel.
const notifications = await sql`
SELECT mitra_id FROM chat_request_notifications WHERE session_id = ${sessionId}
`
for (const n of notifications) {
await notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'cancelled_by_customer',
})
await Promise.all(notifications.map((n) => notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'cancelled_by_customer',
})))
// Customer initiated this cancel; the calling client already navigates home. Do not
// push PAIRING_FAILED for customer-initiated cancels — surfacing it as a "failure"
// event (especially via FCM if backgrounded) misframes the user's own action.
if (session.payment_session_id) {
await failPaymentSession(session.payment_session_id, PairingFailureCause.CUSTOMER_CANCELLED)
}
return session
}
export const expirePairingRequest = async (sessionId) => {
/**
* Customer-initiated cancel during a payment-search.
*
* Use this when the customer is sitting on the searching/waiting screen with a confirmed
* payment but no chat-session row yet exists, OR when they're in a returning-chat 20s wait.
* If a chat_session was already created (general blast in flight, or targeted request out),
* we cancel that too.
*/
export const cancelPaymentSearch = async (paymentSessionId, customerId) => {
const paySession = await getPaymentSession(paymentSessionId)
if (!paySession) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (paySession.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), {
code: 'FORBIDDEN', statusCode: 403,
})
}
// If a chat_session exists for this payment in pending_acceptance/searching, cancel it.
const [linkedSession] = await sql`
SELECT id FROM chat_sessions
WHERE payment_session_id = ${paymentSessionId}
AND status IN (${SessionStatus.SEARCHING}, ${SessionStatus.PENDING_ACCEPTANCE})
`
if (linkedSession) {
// cancelPairingRequest also fails the payment session — short-circuit to avoid double work.
return cancelPairingRequest(linkedSession.id, customerId)
}
// Otherwise fail the payment directly. Covers the case where the customer cancels after
// the targeted attempt already expired/rejected (chat_session no longer pending_acceptance)
// but the payment is still `confirmed`. No customer-side WS push — see cancelPairingRequest.
if (paySession.status === PaymentSessionStatus.CONFIRMED) {
await failPaymentSession(paymentSessionId, PairingFailureCause.CUSTOMER_CANCELLED)
}
return { id: paymentSessionId, payment_session_id: paymentSessionId }
}
/**
* After a returning-chat fail, customer taps "Chat dengan bestie lain".
*
* The original payment_session stays in `confirmed` for the entire returning-chat flow —
* targeted reject/timeout writes an audit-only `pairing_failures` row but does NOT terminate.
* So when the customer falls back to general blast, we reuse the same `payment_session_id`
* directly. Multiple `pairing_failures` rows may FK from one payment_session — that's the
* desired CC UX (one row per failed attempt). Termination happens only at the actual end
* of the flow (chat starts → consumed; cancel/blast-exhaust → failed_pairing).
*
* The targeted_mitra_id flag on the original row is left as-is (it records the customer's
* original intent); the general blast happens regardless.
*/
export const fallbackToGeneralBlast = async (paymentSessionId, customerId, { topic_sensitivity } = {}) => {
const paySession = await getPaymentSession(paymentSessionId)
if (!paySession) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (paySession.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), {
code: 'FORBIDDEN', statusCode: 403,
})
}
if (paySession.status !== PaymentSessionStatus.CONFIRMED) {
throw Object.assign(new Error(`Cannot fallback from payment in status ${paySession.status}`), {
code: 'INVALID_STATE', statusCode: 409,
})
}
// Run the general blast against the SAME payment session. Pass `allowTargetedPayment`
// so the targeted_mitra_id on the payment session doesn't trip the general-blast guard.
return createPairingRequest(customerId, {
paymentSessionId,
topic_sensitivity,
allowTargetedPayment: true,
})
}
export const expirePairingRequest = async (sessionId, causeTag = PairingFailureCause.NO_MITRA_AVAILABLE) => {
const [session] = await sql`
UPDATE chat_sessions
SET status = ${SessionStatus.EXPIRED}
WHERE id = ${sessionId} AND status = ${SessionStatus.PENDING_ACCEPTANCE}
RETURNING id, customer_id, status
RETURNING id, customer_id, status, payment_session_id
`
if (!session) return null
@@ -291,38 +686,134 @@ export const expirePairingRequest = async (sessionId) => {
WHERE session_id = ${sessionId} AND response IS NULL
`
// Notify customer via WebSocket (FCM fallback)
// Fail the payment session (if any) — terminal.
if (session.payment_session_id) {
await failPaymentSession(session.payment_session_id, causeTag)
}
// Notify customer via WebSocket (FCM fallback). Terminal pairing failure → PAIRING_FAILED
// so the client can route to the failed-pairing screen consistently with the other
// terminal paths (cancel / all-rejected / payment-expired-mid-search).
await notifyCustomer(session.customer_id, {
type: WsMessage.SESSION_EXPIRED,
type: WsMessage.PAIRING_FAILED,
session_id: sessionId,
payment_session_id: session.payment_session_id,
cause_tag: causeTag,
})
// Notify mitras to dismiss (request expired)
// Notify mitras to dismiss (request expired) — independent fan-out, run in parallel.
const notifications = await sql`
SELECT mitra_id FROM chat_request_notifications WHERE session_id = ${sessionId}
`
for (const n of notifications) {
await notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'expired',
})
await Promise.all(notifications.map((n) => notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'expired',
})))
return session
}
/**
* Targeted-request timer fired with no mitra response.
*
* INTERMEDIATE failure: the chat_session is marked expired (the targeted attempt is over)
* but the payment_session stays `confirmed` so the customer can fall back to general blast
* on the same payment, or cancel (which then terminates).
*
* - cause_tag is targeted_mitra_timeout (audit row only)
* - WS event sent to customer is RETURNING_CHAT_TIMEOUT (not PAIRING_FAILED)
*/
const expireTargetedPairingRequest = async (sessionId) => {
const [session] = await sql`
UPDATE chat_sessions
SET status = ${SessionStatus.EXPIRED}
WHERE id = ${sessionId} AND status = ${SessionStatus.PENDING_ACCEPTANCE}
RETURNING id, customer_id, status, payment_session_id
`
if (!session) return null
pairingTimeouts.delete(sessionId)
// Capture which mitra was targeted (for the audit row).
const [notif] = await sql`
SELECT mitra_id FROM chat_request_notifications WHERE session_id = ${sessionId} LIMIT 1
`
await sql`
UPDATE chat_request_notifications
SET response = ${NotificationResponse.IGNORED}, responded_at = NOW()
WHERE session_id = ${sessionId} AND response IS NULL
`
if (session.payment_session_id) {
const paySession = await getPaymentSession(session.payment_session_id)
if (paySession) {
await recordIntermediateFailure({
paymentSessionId: session.payment_session_id,
customerId: session.customer_id,
targetedMitraId: notif?.mitra_id ?? null,
causeTag: PairingFailureCause.TARGETED_MITRA_TIMEOUT,
amount: paySession.amount,
})
}
}
await notifyCustomer(session.customer_id, {
type: WsMessage.RETURNING_CHAT_TIMEOUT,
session_id: sessionId,
payment_session_id: session.payment_session_id,
})
// Notify the targeted mitra that the card is no longer actionable — fan-out in parallel
// (single recipient today, but cheap to future-proof).
const notifications = await sql`
SELECT mitra_id FROM chat_request_notifications WHERE session_id = ${sessionId}
`
await Promise.all(notifications.map((n) => notifyMitra(n.mitra_id, {
type: WsMessage.CHAT_REQUEST_CLOSED,
session_id: sessionId,
reason: 'timeout',
})))
return session
}
export const getPendingRequestsForMitra = async (mitraId) => {
// Distinguish general blast from "Curhat lagi" returning requests via payment_session.targeted_mitra_id.
// For returning requests, surface the configured timeout so the cold-start (FCM-tap) path can render
// the countdown overlay — same field the WS payload provides for the live path.
const rows = await sql`
SELECT cs.id AS session_id, cs.duration_minutes, cs.is_free_trial, cs.topic_sensitivity, cs.created_at
SELECT
cs.id AS session_id,
cs.duration_minutes,
cs.is_free_trial,
cs.topic_sensitivity,
cs.created_at,
CASE
WHEN ps.targeted_mitra_id IS NOT NULL THEN ${PairingRequestType.RETURNING}
ELSE ${PairingRequestType.GENERAL}
END AS request_type
FROM chat_request_notifications crn
JOIN chat_sessions cs ON cs.id = crn.session_id
LEFT JOIN payment_sessions ps ON ps.id = cs.payment_session_id
WHERE crn.mitra_id = ${mitraId}
AND crn.response IS NULL
AND cs.status = ${SessionStatus.PENDING_ACCEPTANCE}
ORDER BY cs.created_at ASC
`
return rows
if (!rows.some((r) => r.request_type === PairingRequestType.RETURNING)) {
return rows
}
// At least one returning row — fetch the timeout config once and attach.
const { returning_chat_confirmation_timeout_seconds } = await getReturningChatConfirmationTimeoutSeconds()
return rows.map((r) =>
r.request_type === PairingRequestType.RETURNING
? { ...r, confirmation_timeout_seconds: returning_chat_confirmation_timeout_seconds }
: r
)
}
export const getSessionStatus = async (sessionId) => {

View File

@@ -0,0 +1,298 @@
import { getDb } from '../db/client.js'
import { PaymentSessionStatus, PairingFailureCause, UserType, WsMessage } from '../constants.js'
import { recordFailure } from './pairing-failure.service.js'
import { sendToUser } from '../plugins/websocket.js'
import { sendPushNotification } from './notification.service.js'
import { getPaymentSessionTimeoutMinutes as readPaymentSessionTimeoutMinutes } from './config.service.js'
const sql = getDb()
const getPaymentSessionTimeoutMinutes = async () => {
const { payment_session_timeout_minutes } = await readPaymentSessionTimeoutMinutes()
return payment_session_timeout_minutes
}
/**
* Create a new payment session in `pending` status.
* Reads `payment_session_timeout_minutes` from config to compute expires_at.
*/
export const createPaymentSession = async ({
customerId,
durationMinutes,
amount,
isFreeTrial = false,
isExtension = false,
targetedMitraId = null,
}) => {
if (!customerId) {
throw Object.assign(new Error('customerId is required'), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
if (typeof durationMinutes !== 'number' || durationMinutes <= 0) {
throw Object.assign(new Error('durationMinutes must be a positive number'), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
if (typeof amount !== 'number' || amount < 0) {
throw Object.assign(new Error('amount must be a non-negative number'), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
const ttlMinutes = await getPaymentSessionTimeoutMinutes()
const [row] = await sql`
INSERT INTO payment_sessions (
customer_id, amount, duration_minutes, is_free_trial, is_extension,
status, targeted_mitra_id, expires_at
)
VALUES (
${customerId}, ${amount}, ${durationMinutes}, ${isFreeTrial}, ${isExtension},
${PaymentSessionStatus.PENDING}, ${targetedMitraId},
NOW() + (${ttlMinutes} || ' minutes')::interval
)
RETURNING id, customer_id, amount, duration_minutes, is_free_trial, is_extension,
status, targeted_mitra_id, created_at, confirmed_at, consumed_at, expires_at
`
return row
}
/**
* Transition pending → confirmed. Throws on ownership/status/expiry mismatch.
*/
export const confirmPaymentSession = async (paymentSessionId, customerId) => {
const [existing] = await sql`
SELECT id, customer_id, status, expires_at
FROM payment_sessions
WHERE id = ${paymentSessionId}
`
if (!existing) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (existing.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), { code: 'FORBIDDEN', statusCode: 403 })
}
if (existing.status !== PaymentSessionStatus.PENDING) {
throw Object.assign(new Error(`Payment session is ${existing.status}, cannot confirm`), {
code: 'INVALID_STATE', statusCode: 409,
})
}
if (new Date(existing.expires_at) <= new Date()) {
// Inline expiry check in addition to the background sweeper, since the customer can
// attempt to confirm a row that's already past expires_at before the sweep runs.
await sql`
UPDATE payment_sessions SET status = ${PaymentSessionStatus.EXPIRED}
WHERE id = ${paymentSessionId} AND status = ${PaymentSessionStatus.PENDING}
`
throw Object.assign(new Error('Payment session has expired'), { code: 'EXPIRED', statusCode: 409 })
}
const [updated] = await sql`
UPDATE payment_sessions
SET status = ${PaymentSessionStatus.CONFIRMED}, confirmed_at = NOW()
WHERE id = ${paymentSessionId} AND status = ${PaymentSessionStatus.PENDING}
RETURNING id, customer_id, amount, duration_minutes, is_free_trial, is_extension,
status, targeted_mitra_id, created_at, confirmed_at, consumed_at, expires_at
`
if (!updated) {
throw Object.assign(new Error('Payment session state changed during confirm'), { code: 'CONFLICT', statusCode: 409 })
}
return updated
}
/**
* Transition confirmed → consumed. Called from pairing service when a chat starts.
* Idempotent at higher level (caller should check status first if it matters).
*/
export const consumePaymentSession = async (paymentSessionId) => {
const [updated] = await sql`
UPDATE payment_sessions
SET status = ${PaymentSessionStatus.CONSUMED}, consumed_at = NOW()
WHERE id = ${paymentSessionId} AND status = ${PaymentSessionStatus.CONFIRMED}
RETURNING id, status, consumed_at
`
return updated || null
}
/**
* TERMINAL: mark a confirmed payment session as failed_pairing AND write a pairing_failures row.
* Idempotent: no-op if already terminal (consumed/failed_pairing/expired/abandoned).
*
* Use only for true terminal failures (no fallback path possible):
* - general blast exhausted, no acceptance
* - all blasted mitras explicitly rejected
* - customer cancels mid-search
* - payment session expires before consumption
*
* For intermediate failures that have a fallback CTA available (targeted-mitra reject/timeout
* during a returning-chat flow), use `recordIntermediateFailure` instead — that writes the
* audit row WITHOUT terminating the payment session. Termination is the caller's decision
* (cancel CTA = terminal, fallback-to-blast CTA = stays confirmed).
*/
export const failPaymentSession = async (paymentSessionId, causeTag) => {
if (!Object.values(PairingFailureCause).includes(causeTag)) {
throw Object.assign(new Error(`Unknown cause_tag: ${causeTag}`), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
const [existing] = await sql`
SELECT id, customer_id, targeted_mitra_id, amount, status
FROM payment_sessions
WHERE id = ${paymentSessionId}
`
if (!existing) {
return null
}
// Idempotent: only confirmed sessions transition to failed_pairing here.
// Pending sessions become expired/abandoned via their own paths.
if (existing.status !== PaymentSessionStatus.CONFIRMED) {
return existing
}
const [updated] = await sql`
UPDATE payment_sessions
SET status = ${PaymentSessionStatus.FAILED_PAIRING}
WHERE id = ${paymentSessionId} AND status = ${PaymentSessionStatus.CONFIRMED}
RETURNING id, customer_id, targeted_mitra_id, amount, status
`
if (!updated) {
return existing
}
await recordFailure({
paymentSessionId,
customerId: existing.customer_id,
targetedMitraId: existing.targeted_mitra_id,
causeTag,
amount: existing.amount,
})
return updated
}
/**
* INTERMEDIATE: write a pairing_failures audit row WITHOUT terminating the payment session.
*
* Used for failures inside a flow that still has a fallback path: targeted "Curhat lagi"
* reject/timeout (customer can fall back to general blast on the same payment), or any
* other intermediate attempt where the payment_session must remain `confirmed` so it can be
* reused.
*
* One payment_session may FK from multiple pairing_failures rows — that's the desired CC
* UX (each attempt lists as its own row in the Failed Pairings table).
*
* Returns the inserted pairing_failures row, or null if the payment session was missing.
*/
export const recordIntermediateFailure = async ({ paymentSessionId, customerId, targetedMitraId = null, causeTag, amount }) => {
if (!Object.values(PairingFailureCause).includes(causeTag)) {
throw Object.assign(new Error(`Unknown cause_tag: ${causeTag}`), { code: 'VALIDATION_ERROR', statusCode: 422 })
}
// Loose sanity: the row should exist. If not, fall through with null — caller likely
// already moved on; we'd rather skip the audit than throw mid-callback.
const [existing] = await sql`SELECT id FROM payment_sessions WHERE id = ${paymentSessionId}`
if (!existing) return null
return recordFailure({
paymentSessionId,
customerId,
targetedMitraId,
causeTag,
amount,
})
}
/**
* Customer-initiated abandonment of a `pending` payment session (e.g. closed payment screen).
* No pairing_failures row is written — only confirmed-but-no-chat counts as a pairing failure.
*/
export const abandonPaymentSession = async (paymentSessionId, customerId) => {
const [existing] = await sql`
SELECT id, customer_id, status FROM payment_sessions WHERE id = ${paymentSessionId}
`
if (!existing) {
throw Object.assign(new Error('Payment session not found'), { code: 'NOT_FOUND', statusCode: 404 })
}
if (existing.customer_id !== customerId) {
throw Object.assign(new Error('Payment session does not belong to this customer'), { code: 'FORBIDDEN', statusCode: 403 })
}
if (existing.status !== PaymentSessionStatus.PENDING) {
// Idempotent — already terminal.
return existing
}
const [updated] = await sql`
UPDATE payment_sessions SET status = ${PaymentSessionStatus.ABANDONED}
WHERE id = ${paymentSessionId} AND status = ${PaymentSessionStatus.PENDING}
RETURNING id, customer_id, status
`
return updated || existing
}
/**
* Background sweeper:
* - pending rows past expires_at → expired (no failure row; never confirmed)
* - confirmed rows past expires_at AND not consumed → failed_pairing with cause = payment_session_expired
*/
export const expireStalePaymentSessions = async () => {
// 1) pending → expired
const expired = await sql`
UPDATE payment_sessions
SET status = ${PaymentSessionStatus.EXPIRED}
WHERE status = ${PaymentSessionStatus.PENDING}
AND expires_at <= NOW()
RETURNING id
`
// 2) confirmed-but-stale → failed_pairing. Single atomic UPDATE returns the rows we
// actually flipped (vs. the old SELECT + per-row UPDATE which leaked a TOCTOU window
// with concurrent confirmPaymentSession/consumePaymentSession). Audit-row writes and
// customer notifications then fan out in parallel.
const flipped = await sql`
UPDATE payment_sessions
SET status = ${PaymentSessionStatus.FAILED_PAIRING}
WHERE status = ${PaymentSessionStatus.CONFIRMED}
AND expires_at <= NOW()
RETURNING id, customer_id, targeted_mitra_id, amount
`
await Promise.all(flipped.map(async (row) => {
await recordFailure({
paymentSessionId: row.id,
customerId: row.customer_id,
targetedMitraId: row.targeted_mitra_id,
causeTag: PairingFailureCause.PAYMENT_SESSION_EXPIRED,
amount: row.amount,
})
// Customer may be on searching/waiting; push terminal PAIRING_FAILED in real time.
// FCM fallback when not WS-connected so they're notified at the OS level.
try {
const wsSent = sendToUser(UserType.CUSTOMER, row.customer_id, {
type: WsMessage.PAIRING_FAILED,
payment_session_id: row.id,
cause_tag: PairingFailureCause.PAYMENT_SESSION_EXPIRED,
})
if (!wsSent) {
await sendPushNotification(UserType.CUSTOMER, row.customer_id, {
title: 'Sesi gagal',
body: 'Sesi pembayaranmu telah berakhir. Silakan mulai ulang.',
data: {
type: WsMessage.PAIRING_FAILED,
payment_session_id: row.id,
cause_tag: PairingFailureCause.PAYMENT_SESSION_EXPIRED,
},
})
}
} catch (err) {
console.error('expireStalePaymentSessions: failed to notify customer', {
paymentSessionId: row.id, customerId: row.customer_id, err,
})
}
}))
return { expired: expired.length, failed: flipped.length }
}
export const getPaymentSession = async (id) => {
const [row] = await sql`
SELECT id, customer_id, amount, duration_minutes, is_free_trial, is_extension,
status, targeted_mitra_id, created_at, confirmed_at, consumed_at, expires_at
FROM payment_sessions
WHERE id = ${id}
`
return row || null
}

View File

@@ -57,3 +57,19 @@ export const getPricingForCustomer = async (customerId) => {
: { eligible: false },
}
}
/**
* Extension pricing tiers.
*
* Same shape as `getPricingForCustomer`, but free trial is NEVER eligible for extensions.
* The customerId is accepted for API symmetry/future tier personalization.
*/
// eslint-disable-next-line no-unused-vars
export const getExtensionPriceTiers = async (customerId) => {
const tiers = await getPriceTiers()
return {
tiers,
free_trial: { eligible: false },
is_free_trial: false,
}
}

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

24
backend/vitest.config.js Normal file
View File

@@ -0,0 +1,24 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
environment: 'node',
setupFiles: ['./test/setup.js'],
// Sequential execution: tests share a single test schema and Valkey db, so we
// serialize to keep state predictable. Switch to per-test transactions or per-test
// schema if you need parallelism later.
fileParallelism: false,
sequence: { concurrent: false },
// Some tests wait on backend timers (pairing blast, payment expiry sweep, etc).
testTimeout: 30_000,
hookTimeout: 30_000,
include: ['test/**/*.test.js'],
coverage: {
provider: 'v8',
reporter: ['text', 'html'],
include: ['src/**/*.js'],
exclude: ['src/server.js', 'src/db/migrate.js', 'src/db/seed.js'],
},
},
})