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

@@ -6,7 +6,7 @@ import '../../../core/pairing/pairing_notifier.dart';
/// Terminal failed-pairing screen.
///
/// Reached when the pairing notifier transitions to [PairingFailedData]
/// (terminal — payment session is `failed_pairing` server-side, audit row
/// (terminal — payment session is `failed_delivery` server-side, audit row
/// recorded). Copy is intentionally identical regardless of `cause_tag` for
/// now (the design pass will revise this later).
///

View File

@@ -70,7 +70,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
if (draft.targetedMitraId != null) {
// ignore: discarded_futures
ref.read(pairingProvider.notifier).startTargetedSearch(
paymentSessionId: draft.paymentId!,
paymentRequestId: draft.paymentId!,
mitraId: draft.targetedMitraId!,
mitraName: draft.targetedMitraName ?? 'Bestie',
topicSensitivity: draft.topicSensitivity,
@@ -80,7 +80,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
}
// ignore: discarded_futures
ref.read(pairingProvider.notifier).startSearch(
paymentSessionId: draft.paymentId!,
paymentRequestId: draft.paymentId!,
topicSensitivity: draft.topicSensitivity,
);
}
@@ -117,7 +117,7 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
context,
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
paymentRequestId: next.paymentRequestId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _unavailableDialogShown = false;

View File

@@ -64,7 +64,7 @@ class _TargetedWaitingScreenState extends ConsumerState<TargetedWaitingScreen> {
context,
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
paymentRequestId: next.paymentRequestId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _popupShown = false;

View File

@@ -23,7 +23,7 @@ import '../../support/widgets/tanya_admin_sheet.dart';
/// payment session exists yet, so the "cari bestie lain" CTA resets the
/// payment draft and pushes `/payment/entry` for a fresh blast-payment
/// flow. This branch never calls [Pairing.fallbackToBlast] because there's
/// no `paymentSessionId` to attach to.
/// no `paymentRequestId` to attach to.
/// - [BestieOfflineVariant.new_] — the customer triggered a general blast
/// that bottomed out (no online besties). No fallback button; just a
/// ghost `tanya admin` and a `kembali ke home` exit.
@@ -35,14 +35,14 @@ enum BestieOfflineVariant { returning, prePayReturning, new_ }
class BestieOfflinePopup extends ConsumerWidget {
final BestieOfflineVariant variant;
final String mitraName;
final String? paymentSessionId;
final String? paymentRequestId;
final TopicSensitivity? topicSensitivity;
const BestieOfflinePopup({
super.key,
required this.variant,
required this.mitraName,
this.paymentSessionId,
this.paymentRequestId,
this.topicSensitivity,
});
@@ -50,7 +50,7 @@ class BestieOfflinePopup extends ConsumerWidget {
BuildContext context, {
required BestieOfflineVariant variant,
required String mitraName,
String? paymentSessionId,
String? paymentRequestId,
TopicSensitivity? topicSensitivity,
}) {
return showDialog<void>(
@@ -60,7 +60,7 @@ class BestieOfflinePopup extends ConsumerWidget {
builder: (_) => BestieOfflinePopup(
variant: variant,
mitraName: mitraName,
paymentSessionId: paymentSessionId,
paymentRequestId: paymentRequestId,
topicSensitivity: topicSensitivity,
),
);
@@ -83,7 +83,7 @@ class BestieOfflinePopup extends ConsumerWidget {
final canFallbackToBlast = isReturning &&
hasOtherAvailable &&
paymentSessionId != null &&
paymentRequestId != null &&
topicSensitivity != null;
return Dialog(
@@ -145,7 +145,7 @@ class BestieOfflinePopup extends ConsumerWidget {
Navigator.of(context).pop();
// ignore: discarded_futures
ref.read(pairingProvider.notifier).fallbackToBlast(
paymentSessionId: paymentSessionId!,
paymentRequestId: paymentRequestId!,
topicSensitivity: topicSensitivity!,
);
},

View File

@@ -4,7 +4,7 @@ import '../../../core/auth/auth_notifier.dart';
/// One row in the Chat Tab > Pembayaran sub-tab.
///
/// Mirrors the response of `GET /api/client/payment-sessions/pending`. A row
/// Mirrors the response of `GET /api/client/payment-requests/pending`. A row
/// is either an initial-session payment (`isExtension == false`) — for which
/// mitra info is only present in the targeted "Curhat lagi" flow — or an
/// extension payment (`isExtension == true`) — mitra info resolved by the
@@ -80,7 +80,7 @@ final pendingPaymentsProvider =
if (customerId == null) return PendingPaymentsData.empty;
final api = ref.read(apiClientProvider);
final response =
await api.get('/api/client/payment-sessions/pending');
await api.get('/api/client/payment-requests/pending');
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()

View File

@@ -9,7 +9,7 @@ import '../../../core/theme/widgets/halo_button.dart';
import '../state/payment_draft_provider.dart';
/// "Cara bayar" — QRIS-first list of payment methods. On tap of `bayar`:
/// 1. POST `/api/client/payment-sessions` with the draft + chosen method.
/// 1. POST `/api/client/payment-requests` with the draft + chosen method.
/// 2. Push `/payment/waiting/:paymentId`.
class PaymentMethodScreen extends ConsumerStatefulWidget {
const PaymentMethodScreen({super.key});
@@ -72,7 +72,7 @@ class _PaymentMethodScreenState extends ConsumerState<PaymentMethodScreen> {
};
// Trailing slash matches the existing payment_notifier path — Fastify
// is not configured with `ignoreTrailingSlash`.
final response = await api.post('/api/client/payment-sessions/', data: body);
final response = await api.post('/api/client/payment-requests/', data: body);
final data = response['data'] as Map<String, dynamic>;
final paymentId = data['id'] as String;
ref.read(paymentDraftNotifierProvider.notifier).setPaymentId(paymentId);

View File

@@ -4,6 +4,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:url_launcher/url_launcher.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
@@ -36,6 +37,7 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
bool _initialLoading = true;
bool _terminal = false;
String? _error;
bool _invoiceUrlLaunched = false; // Phase 5: only auto-launch the Custom Tab once
Duration get _remaining {
final exp = _expiresAt;
@@ -80,11 +82,34 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
_qrPayload = (session['qr_string'] as String?) ?? widget.paymentId;
_initialLoading = false;
});
// Phase 5: when Xendit is on, the backend returns an `xendit_invoice_url`
// (Xendit's hosted checkout). Open it in a Custom Tab (Android) /
// SFSafariViewController (iOS) so the customer stays inside the app's
// browser context. Fire-and-forget — polling continues regardless.
// When Xendit is off (dev/Maestro), invoice_url is null and the QR fallback below is used.
await _maybeLaunchInvoiceUrl(session);
_maybeHandleStatus(session);
_startTicker();
_resumePolling();
}
Future<void> _maybeLaunchInvoiceUrl(Map<String, dynamic> session) async {
if (_invoiceUrlLaunched) return;
final url = (session['xendit_invoice_url'] as String?) ?? (session['invoice_url'] as String?);
if (url == null || url.isEmpty) return;
_invoiceUrlLaunched = true;
try {
await launchUrl(
Uri.parse(url),
mode: LaunchMode.inAppBrowserView, // Custom Tab on Android, SFVC on iOS
);
} catch (e) {
// Silent — polling will eventually resolve to expired if the customer can't pay.
// Don't surface an error toast; the user might have a non-Custom-Tab-capable env
// and url_launcher falls back to the system browser automatically.
}
}
void _startTicker() {
_ticker?.cancel();
_ticker = Timer.periodic(_tickInterval, (_) {
@@ -111,7 +136,7 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
Future<Map<String, dynamic>?> _fetchSession() async {
try {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/payment-sessions/${widget.paymentId}');
final response = await api.get('/api/client/payment-requests/${widget.paymentId}');
return response['data'] as Map<String, dynamic>?;
} catch (e) {
if (!mounted) return null;
@@ -122,12 +147,12 @@ class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
void _maybeHandleStatus(Map<String, dynamic> session) {
final status = session['status'] as String?;
if (status == PaymentSessionStatus.confirmed ||
status == PaymentSessionStatus.consumed) {
if (status == PaymentRequestStatus.confirmed ||
status == PaymentRequestStatus.consumed) {
_markTerminal();
_navigateTerminal('/onboarding/notif-gate');
} else if (status == PaymentSessionStatus.expired ||
status == PaymentSessionStatus.abandoned) {
} else if (status == PaymentRequestStatus.expired ||
status == PaymentRequestStatus.abandoned) {
_markTerminal();
_navigateTerminal('/payment/expired/${widget.paymentId}');
}