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

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,
}
}