Phase 5 Xendit: Stages 1-7 (XENDIT_ENABLED=false; Stage 8 pending creds)

Backend
- payment_sessions → payment_requests rename across DB schema + 29 files
- payment.service.js becomes product-agnostic owner: EventEmitter +
  Xendit wrapper + requestPayment / confirmPayment public API; legacy
  aliases retained for existing chat callers
- Webhook handler at POST /api/shared/payment/webhooks/xendit, with
  constant-time token verification (8 vitest cases)
- Server-driven pairing: payment.service emits
  payment_request.confirmed → pairing subscriber starts the blast.
  Legacy POST /chat/request still works during the cutover.
- Reconciliation sweeper extended (re-emits events for confirmed rows
  with no chat session)
- SIGTERM drain + startup reconciliation pass in server.js

Customer app
- waiting_payment_screen opens xendit_invoice_url via
  LaunchMode.inAppBrowserView
- searching / no-bestie / targeted-waiting / pairing-notifier updated
  to consume the new payment_request_id contract
- pending_payments_provider + bestie-unavailable dialog migrated

Dev / testing
- XENDIT_ENABLED=false is the safe default; .env.example documents the
  four new vars
- backend/.dev/xendit-fake-webhook.sh exercises the handler without
  ngrok
- 90/92 backend tests pass (two pre-existing session-timer flakes,
  unrelated); client_app analyzer clean
- requirement/phase5-xendit-plan.md is the canonical reference

Stage 8 (live E2E) blocked on Xendit test-mode keys. The dashboard's
single-webhook-URL constraint will be worked around via a self-poll
script next session.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
2026-05-25 12:52:33 +08:00
parent e6d991373e
commit 3fff4b1c6e
37 changed files with 2805 additions and 515 deletions

View File

@@ -48,14 +48,14 @@ class SessionClosure extends _$SessionClosure {
SessionClosureData build() => const ClosureInitialData();
/// Extension request is a 3-step flow with the extension cost held in its
/// own `payment_session` (never combined with a free trial). Server-side,
/// own `payment_request` (never combined with a free trial). Server-side,
/// the extension service refuses requests without an
/// `extension_payment_session_id` on a confirmed, is_extension payment session.
/// `extension_payment_request_id` on a confirmed, is_extension payment session.
///
/// 1. POST `/api/client/payment-sessions` with `is_extension: true`
/// 2. POST `/api/client/payment-sessions/:id/confirm`
/// 1. POST `/api/client/payment-requests` with `is_extension: true`
/// 2. POST `/api/client/payment-requests/:id/confirm`
/// 3. POST `/api/client/chat/session/:sessionId/extend` with the
/// extension_payment_session_id from step 2.
/// extension_payment_request_id from step 2.
///
/// Charge timing is server-side: only on actual approve / auto-approve.
/// If the mitra explicitly rejects within 10s the payment is failed back, no charge.
@@ -64,15 +64,15 @@ class SessionClosure extends _$SessionClosure {
try {
final api = ref.read(apiClientProvider);
final createResp = await api.post('/api/client/payment-sessions/', data: {
final createResp = await api.post('/api/client/payment-requests/', data: {
'duration_minutes': durationMinutes,
'is_extension': true,
});
final paymentSessionId = (createResp['data'] as Map<String, dynamic>)['id'] as String;
final paymentRequestId = (createResp['data'] as Map<String, dynamic>)['id'] as String;
// Backend rejects truly empty bodies on confirm, so always send `{}`.
await api.post(
'/api/client/payment-sessions/$paymentSessionId/confirm',
'/api/client/payment-requests/$paymentRequestId/confirm',
data: const <String, dynamic>{},
);
@@ -81,7 +81,7 @@ class SessionClosure extends _$SessionClosure {
await api.post('/api/client/chat/session/$sessionId/extend', data: {
'duration_minutes': durationMinutes,
'price': price,
'extension_payment_session_id': paymentSessionId,
'extension_payment_request_id': paymentRequestId,
});
} catch (e) {
state = const ClosureErrorData('Gagal meminta perpanjangan.');

View File

@@ -64,7 +64,7 @@ class ExtensionStatus {
ExtensionStatus._();
}
/// Session mode — chat or voice call. Mirrors backend `payment_sessions.mode`
/// Session mode — chat or voice call. Mirrors backend `payment_requests.mode`
/// (added in Phase 4 stage 1). A `call` session is functionally a chat with a
/// "voice call" badge and (eventually) a Meet link the mitra pastes manually;
/// no real audio transport is built yet.
@@ -153,7 +153,7 @@ enum PairingFailureCause {
targetedMitraOffline('targeted_mitra_offline'),
targetedMitraRejected('targeted_mitra_rejected'),
targetedMitraTimeout('targeted_mitra_timeout'),
paymentSessionExpired('payment_session_expired'),
paymentSessionExpired('payment_request_expired'),
customerCancelled('customer_cancelled'),
unknown('unknown');
@@ -165,13 +165,13 @@ enum PairingFailureCause {
}
/// Payment session lifecycle. Mirror of backend
/// `PaymentSessionStatus`.
class PaymentSessionStatus {
/// `PaymentRequestStatus`.
class PaymentRequestStatus {
static const pending = 'pending';
static const confirmed = 'confirmed';
static const consumed = 'consumed';
static const failedPairing = 'failed_pairing';
static const failedPairing = 'failed_delivery';
static const abandoned = 'abandoned';
static const expired = 'expired';
PaymentSessionStatus._();
PaymentRequestStatus._();
}

View File

@@ -23,12 +23,12 @@ class PairingInitialData extends PairingData {
/// General-blast in flight. The chat_session row exists; backend has already
/// notified all available mitras and is waiting for the first to accept.
class PairingSearchingData extends PairingData {
/// chat_session id (NOT payment_session id).
/// chat_session id (NOT payment_request id).
final String sessionId;
/// payment_session id — we keep it on the state so cancelSearch can call
/// payment_request id — we keep it on the state so cancelSearch can call
/// the payment-session-scoped cancel endpoint without re-prompting.
final String paymentSessionId;
final String paymentRequestId;
/// Carried so a retryable PAIRING_FAILED can preserve the customer's original
/// topic choice when looping back into Blast via retryBlast().
@@ -36,7 +36,7 @@ class PairingSearchingData extends PairingData {
const PairingSearchingData({
required this.sessionId,
required this.paymentSessionId,
required this.paymentRequestId,
required this.topicSensitivity,
});
}
@@ -49,7 +49,7 @@ class PairingSearchingData extends PairingData {
/// server is the source of truth for the actual auto-reject; the local timer
/// is purely cosmetic.
class PairingTargetedWaitingData extends PairingData {
final String paymentSessionId;
final String paymentRequestId;
final String mitraId;
final String mitraName;
final int secondsRemaining;
@@ -58,7 +58,7 @@ class PairingTargetedWaitingData extends PairingData {
final TopicSensitivity topicSensitivity;
const PairingTargetedWaitingData({
required this.paymentSessionId,
required this.paymentRequestId,
required this.mitraId,
required this.mitraName,
required this.secondsRemaining,
@@ -67,7 +67,7 @@ class PairingTargetedWaitingData extends PairingData {
PairingTargetedWaitingData copyWith({int? secondsRemaining}) {
return PairingTargetedWaitingData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraId: mitraId,
mitraName: mitraName,
secondsRemaining: secondsRemaining ?? this.secondsRemaining,
@@ -96,14 +96,14 @@ class PairingActiveData extends PairingData {
///
/// The UI surfaces this via the bestie-unavailable dialog.
class PairingTargetedUnavailableData extends PairingData {
final String paymentSessionId;
final String paymentRequestId;
final String mitraName;
final PairingFailureCause cause;
// Carried so the fallback-to-blast call preserves the customer's original choice.
final TopicSensitivity topicSensitivity;
const PairingTargetedUnavailableData({
required this.paymentSessionId,
required this.paymentRequestId,
required this.mitraName,
required this.cause,
required this.topicSensitivity,
@@ -114,11 +114,11 @@ class PairingTargetedUnavailableData extends PairingData {
///
/// `isRetryable=true` means the backend kept the payment session `confirmed`
/// (audit-only failure) so the customer can re-blast on the same payment via
/// `retryBlast()`. `isRetryable=false` means the payment is in `failed_pairing`
/// `retryBlast()`. `isRetryable=false` means the payment is in `failed_delivery`
/// and any retry must start from a fresh payment session.
class PairingFailedData extends PairingData {
final PairingFailureCause cause;
final String? paymentSessionId;
final String? paymentRequestId;
final bool isRetryable;
// Carried so retryBlast() can re-issue the blast with the customer's original
// topic choice. Null when the failure originated before any topic was known.
@@ -126,7 +126,7 @@ class PairingFailedData extends PairingData {
const PairingFailedData({
required this.cause,
this.paymentSessionId,
this.paymentRequestId,
this.isRetryable = false,
this.topicSensitivity,
});
@@ -156,7 +156,7 @@ class Pairing extends _$Pairing {
/// Returns once the chat_session row is created server-side; subsequent
/// transitions (paired / pairing_failed) arrive via WS.
Future<void> startSearch({
required String paymentSessionId,
required String paymentRequestId,
required TopicSensitivity topicSensitivity,
}) async {
state = const PairingInitialData();
@@ -165,7 +165,7 @@ class Pairing extends _$Pairing {
final response = await _apiClient.post(
'/api/client/chat/request',
data: {
'payment_session_id': paymentSessionId,
'payment_request_id': paymentRequestId,
'topic_sensitivity': topicSensitivity.value,
},
);
@@ -173,7 +173,7 @@ class Pairing extends _$Pairing {
final sessionId = data['id'] as String;
state = PairingSearchingData(
sessionId: sessionId,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
);
} on DioException catch (e) {
@@ -183,7 +183,7 @@ class Pairing extends _$Pairing {
// Backend already failed the payment in this case — terminal.
state = PairingFailedData(
cause: PairingFailureCause.noMitraAvailable,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
);
} else if (code == 'ALREADY_ACTIVE') {
state = const PairingErrorData('Kamu sudah memiliki sesi aktif.');
@@ -201,7 +201,7 @@ class Pairing extends _$Pairing {
/// row (payment stays confirmed) — we transition to TargetedUnavailable so
/// the UI can offer the fallback dialog.
Future<void> startTargetedSearch({
required String paymentSessionId,
required String paymentRequestId,
required String mitraId,
required String mitraName,
required TopicSensitivity topicSensitivity,
@@ -212,7 +212,7 @@ class Pairing extends _$Pairing {
final response = await _apiClient.post(
'/api/client/chat/chat-requests/returning',
data: {
'payment_session_id': paymentSessionId,
'payment_request_id': paymentRequestId,
'mitra_id': mitraId,
'topic_sensitivity': topicSensitivity.value,
},
@@ -222,7 +222,7 @@ class Pairing extends _$Pairing {
final sessionData = response['data'] as Map<String, dynamic>?;
final seconds = (sessionData?['confirmation_timeout_seconds'] as num?)?.toInt() ?? 20;
state = PairingTargetedWaitingData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraId: mitraId,
mitraName: mitraName,
secondsRemaining: seconds,
@@ -237,7 +237,7 @@ class Pairing extends _$Pairing {
// Intermediate — payment session is still confirmed; show the
// bestie-unavailable popup with a "Chat dengan bestie lain" option.
state = PairingTargetedUnavailableData(
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
mitraName: mitraName,
cause: PairingFailureCause.targetedMitraOffline,
topicSensitivity: topicSensitivity,
@@ -251,17 +251,17 @@ class Pairing extends _$Pairing {
}
/// Customer-initiated cancel during a search/wait. Terminal — payment
/// session moves to `failed_pairing` server-side. We route the UI to home
/// session moves to `failed_delivery` server-side. We route the UI to home
/// (NOT to the failed-pairing screen) since the customer chose this.
Future<void> cancelSearch() async {
String? paymentSessionId;
String? paymentRequestId;
final current = state;
if (current is PairingSearchingData) {
paymentSessionId = current.paymentSessionId;
paymentRequestId = current.paymentRequestId;
} else if (current is PairingTargetedWaitingData) {
paymentSessionId = current.paymentSessionId;
paymentRequestId = current.paymentRequestId;
}
if (paymentSessionId == null) {
if (paymentRequestId == null) {
_cleanup();
state = const PairingCancelledData();
return;
@@ -269,7 +269,7 @@ class Pairing extends _$Pairing {
try {
await _apiClient.post(
'/api/client/chat/chat-requests/cancel',
data: {'payment_session_id': paymentSessionId},
data: {'payment_request_id': paymentRequestId},
);
} catch (_) {
// Best-effort. Backend will still fail the payment if/when it
@@ -283,21 +283,21 @@ class Pairing extends _$Pairing {
/// Reuses the same payment session — backend transitions back into the
/// general-blast path.
Future<void> fallbackToBlast({
required String paymentSessionId,
required String paymentRequestId,
required TopicSensitivity topicSensitivity,
}) async {
state = const PairingInitialData();
try {
await _connectWebSocket();
final response = await _apiClient.post(
'/api/client/chat/chat-requests/$paymentSessionId/fallback-to-blast',
'/api/client/chat/chat-requests/$paymentRequestId/fallback-to-blast',
data: {'topic_sensitivity': topicSensitivity.value},
);
final data = response['data'] as Map<String, dynamic>;
final sessionId = data['id'] as String;
state = PairingSearchingData(
sessionId: sessionId,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
);
} on DioException catch (e) {
@@ -306,7 +306,7 @@ class Pairing extends _$Pairing {
if (code == 'NO_MITRA_AVAILABLE') {
state = PairingFailedData(
cause: PairingFailureCause.noMitraAvailable,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
);
} else {
state = const PairingErrorData('Gagal memulai. Coba lagi.');
@@ -326,17 +326,17 @@ class Pairing extends _$Pairing {
/// `confirmed` (retryable failure). Re-blasts on the same payment session.
///
/// Caller should only invoke this when `state is PairingFailedData &&
/// state.isRetryable && paymentSessionId != null && topicSensitivity != null`.
/// state.isRetryable && paymentRequestId != null && topicSensitivity != null`.
Future<void> retryBlast() async {
final current = state;
if (current is! PairingFailedData
|| !current.isRetryable
|| current.paymentSessionId == null
|| current.paymentRequestId == null
|| current.topicSensitivity == null) {
return;
}
await startSearch(
paymentSessionId: current.paymentSessionId!,
paymentRequestId: current.paymentRequestId!,
topicSensitivity: current.topicSensitivity!,
);
}
@@ -388,7 +388,7 @@ class Pairing extends _$Pairing {
if (type == WsMessage.pairingFailed) {
final causeTag = data['cause_tag'] as String?;
final paymentSessionId = data['payment_session_id'] as String?;
final paymentRequestId = data['payment_request_id'] as String?;
// Missing flag = terminal (backward-compat with older emit sites). When
// false, the backend kept the payment confirmed and we can re-blast.
final isRetryable = data['is_terminal'] == false;
@@ -398,7 +398,7 @@ class Pairing extends _$Pairing {
_cleanup();
state = PairingFailedData(
cause: PairingFailureCause.fromString(causeTag),
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
isRetryable: isRetryable,
topicSensitivity: carriedTopic,
);
@@ -409,7 +409,7 @@ class Pairing extends _$Pairing {
// Intermediate — payment still confirmed. Show the bestie-unavailable
// dialog (UI surfaces via state listener).
_stopLocalCountdown();
final paymentSessionId = data['payment_session_id'] as String?;
final paymentRequestId = data['payment_request_id'] as String?;
// Pull mitra name + topic from the prior targeted-waiting state (we know it from
// the request payload). If we somehow lost it, fall back to safe defaults.
String mitraName = 'Bestie';
@@ -419,7 +419,7 @@ class Pairing extends _$Pairing {
carriedTopic = current.topicSensitivity;
}
state = PairingTargetedUnavailableData(
paymentSessionId: paymentSessionId ?? (current is PairingTargetedWaitingData ? current.paymentSessionId : ''),
paymentRequestId: paymentRequestId ?? (current is PairingTargetedWaitingData ? current.paymentRequestId : ''),
mitraName: mitraName,
topicSensitivity: carriedTopic,
cause: type == WsMessage.returningChatTimeout