Phase 4 Stage 3: payment shell (multi-screen flow)

Six new screens under /payment/* + a paymentDraftProvider holding
mode/durationId/durationMinutes/priceIDR/paymentId/isFirstSessionDiscount
across the flow. PaymentEntryScreen handles the routing decision
(eligible+enabled -> /payment/discount-paywall, else /payment/method-pick)
and clears the draft on fresh entry.

Screens:
- discount_paywall_screen: S6 first-session discount with struck-through
  gimmick price + actual price + 'mulai · Rp{actual}' CTA -> /payment/method
- method_pick_screen: chat vs call cards
- duration_pick_screen: tier list with chat|call mode toggle that resets
  the selection on swap
- payment_method_screen: QRIS-first list, posts to existing
  /api/client/payment-sessions with mode/duration/price/discount/method
- waiting_payment_screen: qr_flutter QR (encodes paymentId in mock mode),
  20-min countdown header, 3s polling for status, pauses on background
  via WidgetsBindingObserver
- payment_expired_screen: retry CTA -> /payment/method with draft retained

Status mapping: real payment_sessions.status uses 'confirmed'/'consumed'
for paid (not 'paid' as in plan) and 'expired'/'abandoned' as terminal.

home_screen 'Mulai Curhat' CTA now pushes /payment/entry.

Dev-only /internal/_test/force-expire-payment endpoint to drive Maestro
flow 04_payment_expired.yaml without waiting 20 minutes. Gated behind
NODE_ENV !== 'production'.

chat_opening_provider PricingData extended to carry Phase 4 chat/call
groups + firstSessionDiscount, back-compat with the Phase 3 shape.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-10 16:28:59 +08:00
parent 2645bcd0e5
commit 706149c75e
19 changed files with 2209 additions and 15 deletions

View File

@@ -0,0 +1,325 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/chat_opening_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/halo_button.dart';
import '../state/payment_draft_provider.dart';
/// S6 first-session discount paywall.
///
/// Renders only when `chat-pricing.first_session_discount.eligible == true`.
/// Layout: struck-through gimmick price next to a prominent actual price,
/// "untuk N menit ngobrol" subtitle, and a primary CTA that seeds the payment
/// draft and routes to `/payment/method`.
class DiscountPaywallScreen extends ConsumerWidget {
const DiscountPaywallScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final pricingAsync = ref.watch(chatPricingProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.chevron_left, color: HaloTokens.brandDark),
onPressed: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/home');
}
},
),
),
body: pricingAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) => const Center(
child: Padding(
padding: EdgeInsets.all(HaloSpacing.s24),
child: Text(
'Gagal memuat harga. Coba lagi.',
textAlign: TextAlign.center,
),
),
),
data: (pricing) {
final discount = pricing.firstSessionDiscount;
if (discount == null || !discount.eligible) {
// Defensive: route guard normally prevents this. If we got here
// anyway (stale state), kick over to method-pick.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!context.mounted) return;
context.go('/payment/method-pick');
});
return const SizedBox.shrink();
}
return _Body(discount: discount);
},
),
);
}
}
class _Body extends ConsumerWidget {
final FirstSessionDiscount discount;
const _Body({required this.discount});
void _onMulai(BuildContext context, WidgetRef ref) {
ref.read(paymentDraftNotifierProvider.notifier).setDiscountPlan(
durationMinutes: discount.durationMinutes,
priceIDR: discount.actualPriceIDR,
);
context.push('/payment/method');
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final showModeToggle = discount.modes.length > 1;
final actual = formatRupiah(discount.actualPriceIDR);
final gimmick = formatRupiah(discount.gimmickPriceIDR);
return Column(
children: [
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s8,
HaloSpacing.s24,
HaloSpacing.s16,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (showModeToggle) const _ModeToggleHidden(),
const Text(
'🌷',
style: TextStyle(fontSize: 38),
),
const SizedBox(height: HaloSpacing.s12),
Text(
'biar yakin yang mau cerita,\nbestie cuma minta $actual',
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 26,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
height: 1.2,
letterSpacing: -0.5,
),
),
const SizedBox(height: HaloSpacing.s16),
const Text(
'bukan biaya — anggap aja seperti senyum hangat di awal pertemuan, biar bestie tau kamu beneran mau ngobrol.',
style: TextStyle(
fontSize: 14,
color: HaloTokens.inkSoft,
height: 1.55,
),
),
const SizedBox(height: HaloSpacing.s20),
_PriceCard(
actual: actual,
gimmick: gimmick,
durationMinutes: discount.durationMinutes,
),
const SizedBox(height: HaloSpacing.s12),
const Center(
child: Text(
'sesi-sesi berikutnya pakai harga normal, sesuai durasi yang kamu pilih.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 12,
color: HaloTokens.inkMuted,
height: 1.5,
),
),
),
],
),
),
),
Container(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s12,
HaloSpacing.s24,
HaloSpacing.s32,
),
decoration: const BoxDecoration(
color: HaloTokens.bg,
border: Border(top: BorderSide(color: HaloTokens.border)),
),
child: Column(
children: [
HaloButton(
label: 'mulai · $actual',
size: HaloButtonSize.lg,
fullWidth: true,
onPressed: () => _onMulai(context, ref),
),
const SizedBox(height: HaloSpacing.s8),
const Text(
'QRIS · GoPay · OVO · DANA · ShopeePay',
style: TextStyle(fontSize: 11, color: HaloTokens.inkMuted),
),
],
),
),
],
);
}
}
class _PriceCard extends StatelessWidget {
final String actual;
final String gimmick;
final int durationMinutes;
const _PriceCard({
required this.actual,
required this.gimmick,
required this.durationMinutes,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(HaloSpacing.s20),
decoration: BoxDecoration(
gradient: const LinearGradient(
begin: Alignment.topLeft,
end: Alignment.bottomRight,
colors: [HaloTokens.brandSofter, HaloTokens.surface],
),
borderRadius: HaloRadius.xl,
border: Border.all(color: HaloTokens.brandSoft),
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'SESI PERTAMA',
style: TextStyle(
fontSize: 11,
color: HaloTokens.inkSoft,
fontWeight: FontWeight.w500,
letterSpacing: 0.6,
),
),
const SizedBox(height: HaloSpacing.s4),
Row(
crossAxisAlignment: CrossAxisAlignment.end,
children: [
Text(
actual,
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 36,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
height: 1,
letterSpacing: -1,
),
),
const SizedBox(width: HaloSpacing.s8),
Padding(
padding: const EdgeInsets.only(bottom: 4),
child: Text(
gimmick,
style: const TextStyle(
fontSize: 14,
color: HaloTokens.inkMuted,
decoration: TextDecoration.lineThrough,
),
),
),
],
),
const SizedBox(height: HaloSpacing.s4),
Text(
'untuk $durationMinutes menit ngobrol',
style: const TextStyle(
fontSize: 13,
color: HaloTokens.inkSoft,
),
),
],
),
),
Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s12,
vertical: 6,
),
decoration: const BoxDecoration(
color: HaloTokens.mint,
borderRadius: HaloRadius.pill,
),
child: const Text(
'HANYA SEKALI',
style: TextStyle(
fontSize: 10,
fontWeight: FontWeight.w700,
color: Color(0xFF1F4D34),
letterSpacing: 0.6,
),
),
),
],
),
const Padding(
padding: EdgeInsets.symmetric(vertical: HaloSpacing.s16),
child: Divider(height: 1, color: HaloTokens.border),
),
..._features.map((row) => Padding(
padding: const EdgeInsets.only(bottom: HaloSpacing.s8),
child: Row(
children: [
Text(row.$1, style: const TextStyle(fontSize: 14)),
const SizedBox(width: HaloSpacing.s8),
Expanded(
child: Text(
row.$2,
style: const TextStyle(
fontSize: 13,
color: HaloTokens.ink,
),
),
),
],
),
)),
],
),
);
}
static const List<(String, String)> _features = [
('🤍', 'menit private sama bestie kamu'),
('👤', 'manusia nyata, bukan AI'),
('🛡️', 'gak cocok? sesi gratis tanpa tanya'),
];
}
/// Placeholder for the chat|call mode toggle on the discount screen. Default
/// config is chat-only (`modes = ['chat']`) so we never render anything yet —
/// kept as a marker so the spot is reserved when ops eventually flips
/// `first_session_discount_modes` to `['chat', 'call']`.
class _ModeToggleHidden extends StatelessWidget {
const _ModeToggleHidden();
@override
Widget build(BuildContext context) => const SizedBox.shrink();
}

View File

@@ -0,0 +1,346 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/chat_opening_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/halo_button.dart';
import '../state/payment_draft_provider.dart';
/// "Pemilihan harga" — tier list scoped to the currently-selected mode.
/// A chat|call mode toggle at the top rebuilds the list and resets the
/// selection. Bottom CTA carries the picked tier into `/payment/method`.
class DurationPickScreen extends ConsumerWidget {
const DurationPickScreen({super.key});
List<PriceTier> _tiersForMode(PricingData pricing, PaymentMode mode) {
return mode == PaymentMode.call ? pricing.callTiers : pricing.chatTiers;
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final pricingAsync = ref.watch(chatPricingProvider);
final draft = ref.watch(paymentDraftNotifierProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.chevron_left, color: HaloTokens.brandDark),
onPressed: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/payment/method-pick');
}
},
),
title: const Text(
'pilih durasi',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 18,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
),
),
centerTitle: false,
),
body: pricingAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) => const Center(
child: Padding(
padding: EdgeInsets.all(HaloSpacing.s24),
child: Text(
'Gagal memuat harga. Coba lagi.',
textAlign: TextAlign.center,
),
),
),
data: (pricing) => _Body(
pricing: pricing,
mode: draft.mode,
selectedDurationId: draft.durationId,
tiers: _tiersForMode(pricing, draft.mode),
),
),
);
}
}
class _Body extends ConsumerWidget {
final PricingData pricing;
final PaymentMode mode;
final String? selectedDurationId;
final List<PriceTier> tiers;
const _Body({
required this.pricing,
required this.mode,
required this.selectedDurationId,
required this.tiers,
});
void _onModeToggle(WidgetRef ref, PaymentMode next) {
if (next == mode) return;
ref.read(paymentDraftNotifierProvider.notifier).setMode(next);
}
void _onTierTap(WidgetRef ref, PriceTier tier) {
ref.read(paymentDraftNotifierProvider.notifier).setTier(
durationId: tier.id ?? tier.durationMinutes.toString(),
durationMinutes: tier.durationMinutes,
priceIDR: tier.price,
);
}
void _onPay(BuildContext context) {
context.push('/payment/method');
}
@override
Widget build(BuildContext context, WidgetRef ref) {
final selectedTier = tiers.firstWhere(
(t) => (t.id ?? t.durationMinutes.toString()) == selectedDurationId,
orElse: () => const PriceTier(durationMinutes: 0, price: 0, label: ''),
);
final hasSelection = selectedTier.durationMinutes > 0;
final ctaLabel = hasSelection
? '${mode == PaymentMode.call ? '📞' : '💬'} bayar ${formatRupiah(selectedTier.price)}'
: 'pilih durasi dulu';
return Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s8,
HaloSpacing.s24,
HaloSpacing.s8,
),
child: _ModeToggle(mode: mode, onChanged: (m) => _onModeToggle(ref, m)),
),
Expanded(
child: tiers.isEmpty
? const _EmptyState()
: ListView.separated(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s12,
HaloSpacing.s24,
HaloSpacing.s24,
),
itemCount: tiers.length,
separatorBuilder: (_, __) => const SizedBox(height: HaloSpacing.s8),
itemBuilder: (context, i) {
final tier = tiers[i];
final id = tier.id ?? tier.durationMinutes.toString();
final selected = id == selectedDurationId;
return _TierCard(
tier: tier,
selected: selected,
onTap: () => _onTierTap(ref, tier),
);
},
),
),
Container(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s12,
HaloSpacing.s24,
HaloSpacing.s32,
),
decoration: const BoxDecoration(
color: HaloTokens.bg,
border: Border(top: BorderSide(color: HaloTokens.border)),
),
child: HaloButton(
label: ctaLabel,
size: HaloButtonSize.lg,
fullWidth: true,
onPressed: hasSelection ? () => _onPay(context) : null,
),
),
],
);
}
}
class _ModeToggle extends StatelessWidget {
final PaymentMode mode;
final ValueChanged<PaymentMode> onChanged;
const _ModeToggle({required this.mode, required this.onChanged});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.all(4),
decoration: const BoxDecoration(
color: HaloTokens.brandSofter,
borderRadius: HaloRadius.pill,
),
child: Row(
children: [
Expanded(child: _Pill(label: 'chat', selected: mode == PaymentMode.chat, onTap: () => onChanged(PaymentMode.chat))),
Expanded(child: _Pill(label: 'call', selected: mode == PaymentMode.call, onTap: () => onChanged(PaymentMode.call))),
],
),
);
}
}
class _Pill extends StatelessWidget {
final String label;
final bool selected;
final VoidCallback onTap;
const _Pill({required this.label, required this.selected, required this.onTap});
@override
Widget build(BuildContext context) {
return Material(
color: selected ? HaloTokens.surface : Colors.transparent,
borderRadius: HaloRadius.pill,
child: InkWell(
borderRadius: HaloRadius.pill,
onTap: onTap,
child: Container(
padding: const EdgeInsets.symmetric(vertical: HaloSpacing.s8),
alignment: Alignment.center,
child: Text(
label,
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13.5,
fontWeight: FontWeight.w600,
color: selected ? HaloTokens.brandDark : HaloTokens.inkSoft,
),
),
),
),
);
}
}
class _TierCard extends StatelessWidget {
final PriceTier tier;
final bool selected;
final VoidCallback onTap;
const _TierCard({required this.tier, required this.selected, required this.onTap});
@override
Widget build(BuildContext context) {
return Material(
color: selected ? HaloTokens.brandSofter : HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
borderRadius: HaloRadius.lg,
onTap: onTap,
child: AnimatedContainer(
duration: HaloMotion.fast,
padding: const EdgeInsets.all(HaloSpacing.s16),
decoration: BoxDecoration(
border: Border.all(
color: selected ? HaloTokens.brand : HaloTokens.border,
width: selected ? 2 : 1,
),
borderRadius: HaloRadius.lg,
),
child: Row(
children: [
Container(
width: 44,
height: 44,
decoration: const BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.md,
),
alignment: Alignment.center,
child: Text(
'${tier.durationMinutes}',
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
),
),
),
const SizedBox(width: HaloSpacing.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
'${tier.durationMinutes} menit',
style: const TextStyle(
fontSize: 15,
fontWeight: FontWeight.w600,
color: HaloTokens.ink,
),
),
if (tier.tag != null) ...[
const SizedBox(width: HaloSpacing.s8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s8,
vertical: 2,
),
decoration: const BoxDecoration(
color: HaloTokens.mint,
borderRadius: HaloRadius.pill,
),
child: Text(
tier.tag!,
style: const TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: Color(0xFF1F4D34),
letterSpacing: 0.4,
),
),
),
],
],
),
],
),
),
Text(
formatRupiah(tier.price),
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
),
),
],
),
),
),
);
}
}
class _EmptyState extends StatelessWidget {
const _EmptyState();
@override
Widget build(BuildContext context) {
return const Center(
child: Padding(
padding: EdgeInsets.all(HaloSpacing.s24),
child: Text(
'Belum ada paket untuk mode ini.',
style: TextStyle(color: HaloTokens.inkSoft),
),
),
);
}
}

View File

@@ -0,0 +1,191 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../state/payment_draft_provider.dart';
/// "Pilih cara curhat" — two cards (chat / call). The "premium" call indicator
/// is visual only, no hard-coded multiplier. Tapping a card stores the mode
/// in the draft and pushes `/payment/duration-pick`.
class MethodPickScreen extends ConsumerWidget {
const MethodPickScreen({super.key});
void _onPick(BuildContext context, WidgetRef ref, PaymentMode mode) {
ref.read(paymentDraftNotifierProvider.notifier).setMode(mode);
context.push('/payment/duration-pick');
}
@override
Widget build(BuildContext context, WidgetRef ref) {
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.chevron_left, color: HaloTokens.brandDark),
onPressed: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/home');
}
},
),
),
body: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s8,
HaloSpacing.s24,
HaloSpacing.s24,
),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'pilih cara curhat',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 26,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.5,
),
),
const SizedBox(height: HaloSpacing.s8),
const Text(
'mau ngobrol pakai chat atau dengar suaranya langsung?',
style: TextStyle(
fontSize: 14,
color: HaloTokens.inkSoft,
height: 1.5,
),
),
const SizedBox(height: HaloSpacing.s24),
_ModeCard(
emoji: '💬',
title: 'chat',
subtitle: 'tulis dan baca dengan tenang',
onTap: () => _onPick(context, ref, PaymentMode.chat),
),
const SizedBox(height: HaloSpacing.s12),
_ModeCard(
emoji: '📞',
title: 'call',
subtitle: 'dengar suara bestie langsung',
isPremium: true,
onTap: () => _onPick(context, ref, PaymentMode.call),
),
],
),
),
),
);
}
}
class _ModeCard extends StatelessWidget {
final String emoji;
final String title;
final String subtitle;
final VoidCallback onTap;
final bool isPremium;
const _ModeCard({
required this.emoji,
required this.title,
required this.subtitle,
required this.onTap,
this.isPremium = false,
});
@override
Widget build(BuildContext context) {
return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
borderRadius: HaloRadius.lg,
onTap: onTap,
child: Container(
padding: const EdgeInsets.all(HaloSpacing.s20),
decoration: BoxDecoration(
border: Border.all(color: HaloTokens.border),
borderRadius: HaloRadius.lg,
),
child: Row(
children: [
Container(
width: 56,
height: 56,
decoration: const BoxDecoration(
color: HaloTokens.brandSofter,
borderRadius: HaloRadius.md,
),
alignment: Alignment.center,
child: Text(emoji, style: const TextStyle(fontSize: 28)),
),
const SizedBox(width: HaloSpacing.s16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
title,
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 18,
fontWeight: FontWeight.w700,
color: HaloTokens.ink,
),
),
if (isPremium) ...[
const SizedBox(width: HaloSpacing.s8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s8,
vertical: 2,
),
decoration: const BoxDecoration(
color: HaloTokens.accentSoft,
borderRadius: HaloRadius.pill,
),
child: const Text(
'PREMIUM',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: Color(0xFF8C5418),
letterSpacing: 0.6,
),
),
),
],
],
),
const SizedBox(height: 2),
Text(
subtitle,
style: const TextStyle(
fontSize: 12.5,
color: HaloTokens.inkSoft,
),
),
],
),
),
const Icon(
Icons.chevron_right,
color: HaloTokens.inkMuted,
),
],
),
),
),
);
}
}

View File

@@ -0,0 +1,67 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/chat_opening_provider.dart';
import '../../../core/theme/halo_tokens.dart';
import '../state/payment_draft_provider.dart';
/// Single point of truth for the discount-vs-method-pick branch.
///
/// Reads `chat-pricing.first_session_discount.eligible`. When the customer
/// is eligible (and the discount is enabled), routes to the S6 paywall;
/// otherwise routes to the regular method-pick screen. The draft is reset
/// here so a fresh entry into the flow always starts clean.
class PaymentEntryScreen extends ConsumerStatefulWidget {
const PaymentEntryScreen({super.key});
@override
ConsumerState<PaymentEntryScreen> createState() => _PaymentEntryScreenState();
}
class _PaymentEntryScreenState extends ConsumerState<PaymentEntryScreen> {
bool _routed = false;
@override
void initState() {
super.initState();
Future.microtask(() {
if (!mounted) return;
ref.read(paymentDraftNotifierProvider.notifier).reset();
});
}
void _routeOnce(String location) {
if (_routed || !mounted) return;
_routed = true;
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.go(location);
});
}
@override
Widget build(BuildContext context) {
final pricingAsync = ref.watch(chatPricingProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
body: pricingAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) {
// Pricing fetch failed — fall through to method-pick (which fetches
// pricing again and surfaces the error there).
_routeOnce('/payment/method-pick');
return const SizedBox.shrink();
},
data: (pricing) {
if (pricing.firstSessionDiscount?.eligible ?? false) {
_routeOnce('/payment/discount-paywall');
} else {
_routeOnce('/payment/method-pick');
}
return const SizedBox.shrink();
},
),
);
}
}

View File

@@ -0,0 +1,94 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/halo_button.dart';
/// "Pembayaran expired" — terminal screen for the timeout path. The retry CTA
/// pushes back to `/payment/method`; the draft is intentionally retained so
/// the user re-pays the same plan/mode/discount without re-picking.
class PaymentExpiredScreen extends ConsumerWidget {
final String paymentId;
const PaymentExpiredScreen({super.key, required this.paymentId});
@override
Widget build(BuildContext context, WidgetRef ref) {
return PopScope(
canPop: true,
child: Scaffold(
backgroundColor: HaloTokens.bg,
body: SafeArea(
child: Padding(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s32,
HaloSpacing.s24,
HaloSpacing.s32,
),
child: Column(
children: [
Expanded(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Container(
width: 90,
height: 90,
decoration: const BoxDecoration(
color: Color(0xFFFFE5E5),
borderRadius: HaloRadius.xl,
),
alignment: Alignment.center,
child: const Text('', style: TextStyle(fontSize: 42)),
),
const SizedBox(height: HaloSpacing.s20),
const Text(
'pembayaran kedaluwarsa',
textAlign: TextAlign.center,
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 22,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
height: 1.25,
letterSpacing: -0.5,
),
),
const SizedBox(height: HaloSpacing.s12),
const SizedBox(
width: 280,
child: Text(
'sesi pembayaran udah lewat 20 menit. coba lagi yuk, gak ada potongan apapun.',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 13.5,
color: HaloTokens.inkSoft,
height: 1.55,
),
),
),
],
),
),
HaloButton(
label: 'coba lagi',
size: HaloButtonSize.lg,
fullWidth: true,
onPressed: () => context.go('/payment/method'),
),
const SizedBox(height: HaloSpacing.s8),
HaloButton(
label: 'kembali ke home',
variant: HaloButtonVariant.ghost,
size: HaloButtonSize.md,
fullWidth: true,
onPressed: () => context.go('/home'),
),
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,411 @@
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
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.
/// 2. Push `/payment/waiting/:paymentId`.
class PaymentMethodScreen extends ConsumerStatefulWidget {
const PaymentMethodScreen({super.key});
@override
ConsumerState<PaymentMethodScreen> createState() => _PaymentMethodScreenState();
}
enum _PayMethod {
qris('qris', 'QRIS', 'semua e-wallet & m-banking', '🔲', recommended: true),
ovo('ovo', 'OVO', 'saldo OVO', '🟣'),
gopay('gopay', 'GoPay', 'saldo GoPay', '🟢'),
dana('dana', 'DANA', 'saldo DANA', '🔵'),
shopee('shopee', 'ShopeePay', 'saldo ShopeePay', '🟠');
final String id;
final String label;
final String sub;
final String icon;
final bool recommended;
const _PayMethod(
this.id,
this.label,
this.sub,
this.icon, {
this.recommended = false,
});
}
class _PaymentMethodScreenState extends ConsumerState<PaymentMethodScreen> {
_PayMethod _selected = _PayMethod.qris;
bool _submitting = false;
String? _error;
Future<void> _onPay() async {
if (_submitting) return;
final draft = ref.read(paymentDraftNotifierProvider);
if (draft.durationMinutes == null || draft.priceIDR == null) {
setState(() => _error = 'Pilih durasi dulu sebelum bayar.');
return;
}
setState(() {
_submitting = true;
_error = null;
});
final api = ref.read(apiClientProvider);
try {
final body = <String, dynamic>{
'mode': draft.mode.value,
'duration_minutes': draft.durationMinutes,
'price_idr': draft.priceIDR,
'is_first_session_discount': draft.isFirstSessionDiscount,
'method': _selected.id,
};
// 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 data = response['data'] as Map<String, dynamic>;
final paymentId = data['id'] as String;
ref.read(paymentDraftNotifierProvider.notifier).setPaymentId(paymentId);
if (!mounted) return;
context.push('/payment/waiting/$paymentId');
} on DioException catch (e) {
if (!mounted) return;
setState(() {
_submitting = false;
_error = _humanError(e);
});
} catch (_) {
if (!mounted) return;
setState(() {
_submitting = false;
_error = 'Gagal membuat sesi pembayaran.';
});
}
}
String _humanError(DioException e) {
final code = e.response?.data?['error']?['code'] as String?;
final status = e.response?.statusCode;
if (status == 422 || code == 'VALIDATION_ERROR' || code == 'INVALID_TIER') {
return 'Pilihan durasi tidak valid.';
}
if (status == 403) return 'Sesi tidak diizinkan.';
if (status == 404) return 'Sesi pembayaran tidak ditemukan.';
return 'Gagal membuat sesi pembayaran.';
}
@override
Widget build(BuildContext context) {
final draft = ref.watch(paymentDraftNotifierProvider);
final amount = draft.priceIDR ?? 0;
final durationLabel = draft.durationMinutes != null
? 'sesi ${draft.durationMinutes} menit'
: 'sesi';
final amountLabel = formatRupiah(amount);
final recommended = _PayMethod.values.where((m) => m.recommended).toList();
final others = _PayMethod.values.where((m) => !m.recommended).toList();
return Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.chevron_left, color: HaloTokens.brandDark),
onPressed: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/payment/duration-pick');
}
},
),
title: const Text(
'cara bayar',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 18,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
),
),
centerTitle: false,
),
body: Column(
children: [
Padding(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s4,
HaloSpacing.s24,
HaloSpacing.s12,
),
child: Container(
padding: const EdgeInsets.all(HaloSpacing.s12),
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
border: Border.all(color: HaloTokens.border),
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'total bayar',
style: TextStyle(fontSize: 11.5, color: HaloTokens.inkSoft),
),
Text(
durationLabel,
style: const TextStyle(fontSize: 11, color: HaloTokens.inkMuted),
),
],
),
),
Text(
amountLabel,
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 22,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.5,
),
),
],
),
),
),
Expanded(
child: ListView(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s20,
HaloSpacing.s8,
HaloSpacing.s20,
HaloSpacing.s16,
),
children: [
const _SectionLabel('paling cepat'),
...recommended.map((m) => _MethodTile(
method: m,
selected: _selected == m,
onTap: () => setState(() => _selected = m),
large: true,
)),
const SizedBox(height: HaloSpacing.s8),
const _SectionLabel('e-wallet lain'),
...others.map((m) => _MethodTile(
method: m,
selected: _selected == m,
onTap: () => setState(() => _selected = m),
)),
],
),
),
if (_error != null)
Container(
margin: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
0,
HaloSpacing.s24,
HaloSpacing.s8,
),
padding: const EdgeInsets.all(HaloSpacing.s12),
decoration: BoxDecoration(
color: const Color(0xFFFFEBEB),
borderRadius: HaloRadius.md,
border: Border.all(color: HaloTokens.danger),
),
child: Row(
children: [
const Icon(Icons.error_outline, color: HaloTokens.danger, size: 18),
const SizedBox(width: HaloSpacing.s8),
Expanded(
child: Text(
_error!,
style: const TextStyle(color: HaloTokens.danger, fontSize: 13),
),
),
],
),
),
Container(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s12,
HaloSpacing.s24,
HaloSpacing.s32,
),
decoration: const BoxDecoration(
color: HaloTokens.bg,
border: Border(top: BorderSide(color: HaloTokens.border)),
),
child: HaloButton(
label: _submitting ? 'memproses...' : 'bayar $amountLabel',
size: HaloButtonSize.lg,
fullWidth: true,
onPressed: _submitting ? null : _onPay,
),
),
],
),
);
}
}
class _SectionLabel extends StatelessWidget {
final String label;
const _SectionLabel(this.label);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.fromLTRB(4, HaloSpacing.s8, 4, HaloSpacing.s8),
child: Text(
label,
style: const TextStyle(
fontSize: 11,
fontWeight: FontWeight.w600,
color: HaloTokens.inkSoft,
letterSpacing: 0.6,
),
),
);
}
}
class _MethodTile extends StatelessWidget {
final _PayMethod method;
final bool selected;
final VoidCallback onTap;
final bool large;
const _MethodTile({
required this.method,
required this.selected,
required this.onTap,
this.large = false,
});
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.only(bottom: HaloSpacing.s8),
child: Material(
color: selected ? HaloTokens.brandSofter : HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
borderRadius: HaloRadius.lg,
onTap: onTap,
child: AnimatedContainer(
duration: HaloMotion.fast,
padding: EdgeInsets.all(large ? HaloSpacing.s16 : HaloSpacing.s12),
decoration: BoxDecoration(
border: Border.all(
color: selected ? HaloTokens.brand : HaloTokens.border,
width: selected ? 2 : 1,
),
borderRadius: HaloRadius.lg,
),
child: Row(
children: [
Container(
width: large ? 40 : 36,
height: large ? 40 : 36,
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.md,
border: Border.all(color: HaloTokens.border),
),
alignment: Alignment.center,
child: Text(method.icon, style: TextStyle(fontSize: large ? 20 : 18)),
),
const SizedBox(width: HaloSpacing.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Text(
method.label,
style: TextStyle(
fontSize: large ? 14.5 : 13.5,
fontWeight: FontWeight.w600,
color: HaloTokens.ink,
),
),
if (method.recommended) ...[
const SizedBox(width: HaloSpacing.s8),
Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s8,
vertical: 2,
),
decoration: const BoxDecoration(
color: HaloTokens.mint,
borderRadius: HaloRadius.pill,
),
child: const Text(
'DIREKOMENDASIKAN',
style: TextStyle(
fontSize: 9,
fontWeight: FontWeight.w700,
color: Color(0xFF1F4D34),
letterSpacing: 0.4,
),
),
),
],
],
),
const SizedBox(height: 2),
Text(
method.sub,
style: TextStyle(
fontSize: large ? 11.5 : 11,
color: HaloTokens.inkSoft,
),
),
],
),
),
Container(
width: large ? 20 : 18,
height: large ? 20 : 18,
decoration: BoxDecoration(
shape: BoxShape.circle,
border: Border.all(
color: selected ? HaloTokens.brand : HaloTokens.border,
width: 2,
),
color: selected ? HaloTokens.brand : HaloTokens.surface,
),
child: selected
? Center(
child: Container(
width: large ? 8 : 6,
height: large ? 8 : 6,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: Colors.white,
),
),
)
: null,
),
],
),
),
),
),
);
}
}

View File

@@ -0,0 +1,318 @@
import 'dart:async';
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 '../../../core/api/api_client_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../state/payment_draft_provider.dart';
/// "Waiting payment" — placeholder QR + 20-minute countdown header. Polls the
/// backend every 3 seconds for status changes. On `confirmed` the payment is
/// considered paid; on `expired` we route to the expired screen.
///
/// Polling is paused while the app is backgrounded and resumed on foreground
/// (per the `WidgetsBindingObserver` pattern used elsewhere in the app).
class WaitingPaymentScreen extends ConsumerStatefulWidget {
final String paymentId;
const WaitingPaymentScreen({super.key, required this.paymentId});
@override
ConsumerState<WaitingPaymentScreen> createState() => _WaitingPaymentScreenState();
}
class _WaitingPaymentScreenState extends ConsumerState<WaitingPaymentScreen>
with WidgetsBindingObserver {
static const Duration _pollInterval = Duration(seconds: 3);
static const Duration _tickInterval = Duration(seconds: 1);
Timer? _ticker;
Timer? _poller;
DateTime? _expiresAt;
int _amount = 0;
String? _qrPayload;
bool _initialLoading = true;
bool _terminal = false;
String? _error;
Duration get _remaining {
final exp = _expiresAt;
if (exp == null) return Duration.zero;
final left = exp.difference(DateTime.now());
return left.isNegative ? Duration.zero : left;
}
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
Future.microtask(_loadInitial);
}
@override
void dispose() {
_ticker?.cancel();
_poller?.cancel();
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.resumed) {
_resumePolling();
} else if (state == AppLifecycleState.paused || state == AppLifecycleState.inactive) {
_poller?.cancel();
_poller = null;
}
}
Future<void> _loadInitial() async {
final session = await _fetchSession();
if (!mounted || session == null) return;
final expiresAtRaw = session['expires_at'] as String?;
final expiresAt = expiresAtRaw != null ? DateTime.tryParse(expiresAtRaw) : null;
setState(() {
_amount = (session['amount'] as int?) ?? 0;
_expiresAt = expiresAt;
_qrPayload = (session['qr_string'] as String?) ?? widget.paymentId;
_initialLoading = false;
});
_maybeHandleStatus(session);
_startTicker();
_resumePolling();
}
void _startTicker() {
_ticker?.cancel();
_ticker = Timer.periodic(_tickInterval, (_) {
if (!mounted) return;
// Trigger a rebuild to refresh the countdown label. Status routing
// happens off the polled response, not the local clock — backend is
// the source of truth for `expired`.
setState(() {});
});
}
void _resumePolling() {
if (_terminal) return;
_poller?.cancel();
_poller = Timer.periodic(_pollInterval, (_) => _pollOnce());
}
Future<void> _pollOnce() async {
final session = await _fetchSession();
if (!mounted || session == null) return;
_maybeHandleStatus(session);
}
Future<Map<String, dynamic>?> _fetchSession() async {
try {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/payment-sessions/${widget.paymentId}');
return response['data'] as Map<String, dynamic>?;
} catch (e) {
if (!mounted) return null;
setState(() => _error = 'Gagal memeriksa status pembayaran.');
return null;
}
}
void _maybeHandleStatus(Map<String, dynamic> session) {
final status = session['status'] as String?;
if (status == PaymentSessionStatus.confirmed ||
status == PaymentSessionStatus.consumed) {
_markTerminal();
// TODO(stage4): route to `/onboarding/notif-gate` once Stage 4 lands.
// For now, drop the user back home — Stage 5 will pick the pairing flow up.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.go('/');
});
} else if (status == PaymentSessionStatus.expired ||
status == PaymentSessionStatus.abandoned) {
_markTerminal();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
context.go('/payment/expired/${widget.paymentId}');
});
}
}
void _markTerminal() {
_terminal = true;
_ticker?.cancel();
_poller?.cancel();
}
String _countdownLabel() {
final r = _remaining;
final mm = r.inMinutes;
final ss = r.inSeconds % 60;
return '${mm.toString().padLeft(2, '0')}:${ss.toString().padLeft(2, '0')}';
}
@override
Widget build(BuildContext context) {
return PopScope(
canPop: true,
child: Scaffold(
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
elevation: 0,
leading: IconButton(
icon: const Icon(Icons.chevron_left, color: HaloTokens.brandDark),
onPressed: () {
if (context.canPop()) {
context.pop();
} else {
context.go('/home');
}
},
),
centerTitle: true,
title: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Text(
'kedaluwarsa dalam',
style: TextStyle(fontSize: 11, color: HaloTokens.inkMuted),
),
Text(
_initialLoading ? '--:--' : _countdownLabel(),
style: const TextStyle(
fontFamily: HaloTokens.fontMono,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.5,
),
),
],
),
),
body: _initialLoading
? const Center(child: CircularProgressIndicator())
: _buildContent(),
),
);
}
Widget _buildContent() {
final draft = ref.watch(paymentDraftNotifierProvider);
final amount = _amount > 0 ? _amount : (draft.priceIDR ?? 0);
return Column(
children: [
Expanded(
child: SingleChildScrollView(
padding: const EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s8,
HaloSpacing.s24,
HaloSpacing.s16,
),
child: Column(
children: [
Container(
padding: const EdgeInsets.all(HaloSpacing.s24),
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.xl,
border: Border.all(color: HaloTokens.border),
),
child: Column(
children: [
const Text(
'scan QRIS untuk bayar',
style: TextStyle(fontSize: 12, color: HaloTokens.inkSoft),
),
const SizedBox(height: HaloSpacing.s12),
Container(
padding: const EdgeInsets.all(HaloSpacing.s12),
decoration: BoxDecoration(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
border: Border.all(color: HaloTokens.border),
),
child: QrImageView(
data: _qrPayload ?? widget.paymentId,
size: 200,
version: QrVersions.auto,
backgroundColor: HaloTokens.surface,
eyeStyle: const QrEyeStyle(
eyeShape: QrEyeShape.square,
color: HaloTokens.ink,
),
dataModuleStyle: const QrDataModuleStyle(
dataModuleShape: QrDataModuleShape.square,
color: HaloTokens.ink,
),
),
),
const SizedBox(height: HaloSpacing.s12),
const Text(
'jumlah',
style: TextStyle(fontSize: 11.5, color: HaloTokens.inkSoft),
),
Text(
formatRupiah(amount),
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 24,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.5,
),
),
],
),
),
const SizedBox(height: HaloSpacing.s12),
Container(
padding: const EdgeInsets.all(HaloSpacing.s12),
decoration: BoxDecoration(
color: HaloTokens.brandSofter,
borderRadius: HaloRadius.md,
border: Border.all(color: HaloTokens.brandSoft),
),
child: Row(
children: [
Container(
width: 8,
height: 8,
decoration: const BoxDecoration(
shape: BoxShape.circle,
color: HaloTokens.brand,
),
),
const SizedBox(width: HaloSpacing.s8),
const Expanded(
child: Text(
'menunggu pembayaran kamu...',
style: TextStyle(
fontSize: 12,
color: HaloTokens.brandDark,
),
),
),
],
),
),
if (_error != null) ...[
const SizedBox(height: HaloSpacing.s8),
Text(
_error!,
style: const TextStyle(fontSize: 12, color: HaloTokens.danger),
),
],
],
),
),
),
],
);
}
}