Phase 4 Stage 8: returning-user shell + Tanya Admin sheet

Bestie Choice Sheet on home Mulai Curhat CTA. When the user has at
least one prior session (bestieHistoryHasItemsProvider hits the chat-
sessions history endpoint), the CTA opens a HaloBottomSheet with two
cards: 'bestie yang udah kenal' -> /chat/history, 'bestie baru' ->
/payment/entry. Empty history -> direct to /payment/entry.

Bestie history list visual upgrade: HaloOrb (mitraId seed) + name +
last-session date + topic pills + sessions count + ONLINE pill.
Backend getCustomerHistory now returns topics, mitra_is_online,
sessions_count in a single payload (no per-row presence round-trip).

BestieOfflinePopup with two variants (returning | new_) replacing the
legacy BestieUnavailableDialog. tanya admin ghost CTA on both variants
opens the new TanyaAdminSheet. Stage 5's targeted-wait declined stub
+ Stage 7's chat-screen 409 stub + searching-screen call site all
migrated to the real component.

TanyaAdminSheet: HaloBottomSheet with WA + Telegram buttons, deeplinks
fetched via supportHandlesProvider (CC-config-driven). url_launcher
added to client_app; ios LSApplicationQueriesSchemes covers
https/http/whatsapp/tg.

Stage 2's OTP-blocked popup hubungi admin SnackBar stub also migrated
to TanyaAdminSheet.

Dev-only POST /internal/_test/seed-history-session lets Maestro 08
flow seed a history row before exercising the choice sheet.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-10 17:47:02 +08:00
parent d454fd39db
commit 862fc35a40
23 changed files with 1122 additions and 215 deletions

View File

@@ -3,140 +3,323 @@ 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/widgets.dart';
import '../../home/providers/bestie_history_provider.dart';
/// Chat history with per-row "Curhat lagi" CTA.
/// Phase 4 Stage 8 — `BestieHistoryList`.
///
/// Tapping "Curhat lagi" routes to the payment screen with the targeted
/// mitra id + display name as extras. The payment screen then:
/// 1. POSTs `/api/client/payment-sessions` with `targeted_mitra_id`
/// 2. On confirm, fires `pairingNotifier.startTargetedSearch(...)` instead
/// of the general `startSearch(...)`.
/// Renders past sessions with the v4 visual: orb + name + last-session date
/// + topic chips + sessions count + ONLINE pill (per-row, sourced from the
/// `mitra_is_online` field on the history payload).
///
/// The CTA is per-row (not per-unique-mitra).
class ChatHistoryScreen extends ConsumerStatefulWidget {
/// Tapping a row routes to the targeted "Curhat lagi" payment flow when the
/// row references a known mitra; closing-state rows still drop into the
/// session screen so the user can finish the goodbye composer. Otherwise we
/// fall back to the transcript view.
class ChatHistoryScreen extends ConsumerWidget {
const ChatHistoryScreen({super.key});
@override
ConsumerState<ChatHistoryScreen> createState() => _ChatHistoryScreenState();
}
Widget build(BuildContext context, WidgetRef ref) {
final historyAsync = ref.watch(bestieHistoryProvider);
final fullSessionsAsync = ref.watch(_rawHistoryProvider);
class _ChatHistoryScreenState extends ConsumerState<ChatHistoryScreen> {
List<Map<String, dynamic>> _sessions = [];
bool _loading = true;
@override
void initState() {
super.initState();
_loadHistory();
}
Future<void> _loadHistory() async {
try {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/chat/history');
final items = (response['data']['items'] as List<dynamic>).cast<Map<String, dynamic>>();
setState(() {
_sessions = items;
_loading = false;
});
} catch (_) {
setState(() => _loading = false);
}
}
void _onCurhatLagiPressed(Map<String, dynamic> session) {
// The mitra id field on the history payload is `mitra_id` per existing
// backend convention. If absent (older rows), don't render the CTA.
final mitraId = session['mitra_id'] as String?;
if (mitraId == null) return;
final mitraName = session['mitra_display_name'] as String? ?? 'Bestie';
context.push('/payment', extra: <String, dynamic>{
'targetedMitraId': mitraId,
'mitraName': mitraName,
'topicSensitivity': TopicSensitivity.regular,
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Riwayat Chat')),
body: _loading
? const Center(child: CircularProgressIndicator())
: _sessions.isEmpty
? const Center(child: Text('Belum ada riwayat chat'))
: ListView.separated(
itemCount: _sessions.length,
separatorBuilder: (_, __) => const Divider(height: 1),
itemBuilder: (context, index) {
final s = _sessions[index];
final sessionId = s['id'] as String;
final mitraId = s['mitra_id'] as String?;
final mitraName = s['mitra_display_name'] as String? ?? 'Bestie';
final status = s['status'] as String?;
final isClosing = status == 'closing';
final endedAt = s['ended_at'] != null
? DateTime.parse(s['ended_at'] as String).toLocal()
: null;
final duration = s['duration_minutes'] as int?;
final closureMsg = s['customer_closure_message'] as String?;
return ListTile(
leading: const CircleAvatar(child: Icon(Icons.person)),
title: Row(
children: [
Flexible(child: Text(mitraName, overflow: TextOverflow.ellipsis)),
if (isClosing) ...[
const SizedBox(width: 8),
const _OutstandingClosureBadge(),
],
],
),
subtitle: Text([
if (endedAt != null) '${endedAt.day}/${endedAt.month}/${endedAt.year}',
if (duration != null) '$duration menit',
if (closureMsg != null) '"$closureMsg"',
].join(' - ')),
// Curhat-lagi CTA renders inline; transcript view is
// still reachable by tapping the row body (or, for
// closing sessions, the active chat — same as before).
trailing: !isClosing && mitraId != null
? OutlinedButton(
style: OutlinedButton.styleFrom(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
),
onPressed: () => _onCurhatLagiPressed(s),
child: const Text('Curhat lagi'),
)
: const Icon(Icons.chevron_right),
onTap: () => isClosing
? context.push('/chat/session/$sessionId', extra: mitraName)
: context.push('/chat/history/$sessionId'),
);
},
backgroundColor: HaloTokens.bg,
appBar: AppBar(
backgroundColor: HaloTokens.bg,
foregroundColor: HaloTokens.ink,
elevation: 0,
title: const Text(
'Riwayat Chat',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontWeight: FontWeight.w700,
),
),
),
body: historyAsync.when(
loading: () => const Center(child: CircularProgressIndicator()),
error: (_, __) => const Center(
child: Text(
'gagal memuat riwayat. tarik untuk muat ulang.',
style: TextStyle(fontFamily: HaloTokens.fontBody),
),
),
data: (items) {
if (items.isEmpty) {
return const Center(
child: Text(
'Belum ada riwayat chat',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
color: HaloTokens.inkSoft,
),
),
);
}
return RefreshIndicator(
onRefresh: () async {
ref.invalidate(bestieHistoryProvider);
ref.invalidate(_rawHistoryProvider);
await ref.read(bestieHistoryProvider.future);
},
child: ListView.separated(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s16,
vertical: HaloSpacing.s12,
),
itemCount: items.length,
separatorBuilder: (_, __) => const SizedBox(height: HaloSpacing.s12),
itemBuilder: (context, index) {
final item = items[index];
final raw = fullSessionsAsync.valueOrNull?[index];
final isClosing = raw?['status'] == SessionStatus.closing;
return _BestieRow(
item: item,
isClosing: isClosing,
onTap: () {
if (isClosing && raw != null) {
context.push(
'/chat/session/${item.sessionId}',
extra: item.mitraName,
);
return;
}
context.push('/chat/history/${item.sessionId}');
},
onCurhatLagi: item.mitraId == null || isClosing
? null
: () => context.push('/payment', extra: <String, dynamic>{
'targetedMitraId': item.mitraId,
'mitraName': item.mitraName,
'topicSensitivity': TopicSensitivity.regular,
}),
);
},
),
);
},
),
);
}
}
class _OutstandingClosureBadge extends StatelessWidget {
const _OutstandingClosureBadge();
/// Raw history payload — used to read fields the v4 `BestieHistoryItem`
/// model doesn't surface (currently `status`, for the closing-row branch).
final _rawHistoryProvider = FutureProvider<List<Map<String, dynamic>>>((ref) async {
final api = ref.read(apiClientProvider);
final response = await api.get('/api/client/chat/history');
return ((response['data']['items'] as List?) ?? const []).cast<Map<String, dynamic>>();
});
class _BestieRow extends StatelessWidget {
final BestieHistoryItem item;
final bool isClosing;
final VoidCallback onTap;
final VoidCallback? onCurhatLagi;
const _BestieRow({
required this.item,
required this.isClosing,
required this.onTap,
required this.onCurhatLagi,
});
@override
Widget build(BuildContext context) {
return Material(
color: HaloTokens.surface,
borderRadius: HaloRadius.lg,
child: InkWell(
onTap: onTap,
borderRadius: HaloRadius.lg,
child: Padding(
padding: const EdgeInsets.all(HaloSpacing.s16),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
HaloOrb(
size: 56,
seed: (item.mitraId ?? item.mitraName).hashCode,
label: item.mitraName,
),
const SizedBox(width: HaloSpacing.s12),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Flexible(
child: Text(
item.mitraName,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 16,
fontWeight: FontWeight.w700,
color: HaloTokens.ink,
),
),
),
if (item.mitraIsOnline) ...[
const SizedBox(width: HaloSpacing.s8),
const _OnlinePill(),
],
if (isClosing) ...[
const SizedBox(width: HaloSpacing.s8),
const _ClosingBadge(),
],
],
),
const SizedBox(height: 2),
Text(
[
if (item.endedAt != null) _formatDate(item.endedAt!),
'${item.sessionsCount} sesi',
].join(' · '),
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 12.5,
color: HaloTokens.inkSoft,
),
),
],
),
),
],
),
if (item.topics.isNotEmpty) ...[
const SizedBox(height: HaloSpacing.s12),
Wrap(
spacing: HaloSpacing.s8,
runSpacing: HaloSpacing.s8,
children: item.topics
.take(3)
.map((t) => _TopicPill(label: t))
.toList(),
),
],
if (onCurhatLagi != null) ...[
const SizedBox(height: HaloSpacing.s12),
Align(
alignment: Alignment.centerRight,
child: HaloButton(
label: 'curhat lagi',
size: HaloButtonSize.sm,
variant: HaloButtonVariant.secondary,
onPressed: onCurhatLagi,
),
),
],
],
),
),
),
);
}
String _formatDate(DateTime d) =>
'${d.day.toString().padLeft(2, '0')}/${d.month.toString().padLeft(2, '0')}/${d.year}';
}
class _OnlinePill extends StatelessWidget {
const _OnlinePill();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Colors.amber.shade100,
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Colors.amber.shade700, width: 0.5),
color: HaloTokens.success.withAlpha(36),
borderRadius: BorderRadius.circular(999),
),
child: const Row(
mainAxisSize: MainAxisSize.min,
children: [
_Dot(color: HaloTokens.success),
SizedBox(width: 4),
Text(
'ONLINE',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w700,
letterSpacing: 0.6,
color: HaloTokens.success,
),
),
],
),
);
}
}
class _Dot extends StatelessWidget {
final Color color;
const _Dot({required this.color});
@override
Widget build(BuildContext context) {
return Container(
width: 6,
height: 6,
decoration: BoxDecoration(color: color, shape: BoxShape.circle),
);
}
}
class _TopicPill extends StatelessWidget {
final String label;
const _TopicPill({required this.label});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s12,
vertical: 4,
),
decoration: BoxDecoration(
color: HaloTokens.brandSofter,
borderRadius: BorderRadius.circular(999),
),
child: Text(
'Belum ditutup',
style: TextStyle(
fontSize: 10,
color: Colors.amber.shade900,
label,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 11.5,
fontWeight: FontWeight.w600,
color: HaloTokens.brandDark,
),
),
);
}
}
class _ClosingBadge extends StatelessWidget {
const _ClosingBadge();
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: HaloTokens.accentSoft,
borderRadius: BorderRadius.circular(999),
),
child: const Text(
'Belum ditutup',
style: TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 10,
fontWeight: FontWeight.w600,
color: HaloTokens.brandDark,
),
),
);

View File

@@ -8,8 +8,8 @@ import '../../../core/chat/session_closure_notifier.dart';
import '../../../core/config/app_config_provider.dart';
import '../../../core/constants.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/halo_popup.dart';
import '../../../core/theme/widgets/halo_snackbar.dart';
import '../widgets/bestie_unavailable_dialog.dart';
import '../widgets/chat_expired_banner.dart';
import '../widgets/closing_message_sheet.dart';
import '../widgets/confirm_end_step1.dart';
@@ -169,13 +169,10 @@ class _ChatScreenState extends ConsumerState<ChatScreen> {
if (_rejectPopupShown) return;
_rejectPopupShown = true;
if (!mounted) return;
// TODO(stage8): replace with BestieOfflinePopup variant: 'returning'
await HaloPopup.show<void>(
await BestieOfflinePopup.show(
context,
title: 'bestie lagi balik...',
body: 'sesi belum bisa ditutup karena bestie masih nyaut. coba lagi sebentar ya.',
icon: const Text('🔄', style: TextStyle(fontSize: 40)),
primary: HaloPopupAction(label: 'oke', onPressed: () {}),
variant: BestieOfflineVariant.returning,
mitraName: widget.mitraName,
);
_rejectPopupShown = false;
// Reset closure state so the user can retry without a stale-error block.

View File

@@ -70,10 +70,11 @@ class _SearchingScreenState extends ConsumerState<SearchingScreen> {
if (next is PairingTargetedUnavailableData && !_unavailableDialogShown) {
_unavailableDialogShown = true;
// ignore: discarded_futures
BestieUnavailableDialog.show(
BestieOfflinePopup.show(
context,
paymentSessionId: next.paymentSessionId,
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _unavailableDialogShown = false;

View File

@@ -4,6 +4,7 @@ import 'package:go_router/go_router.dart';
import '../../../core/pairing/pairing_notifier.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../../core/theme/widgets/widgets.dart';
import '../widgets/bestie_unavailable_dialog.dart';
/// Phase 4 Stage 5 — `SWaitingBestie` overlay.
///
@@ -16,9 +17,9 @@ import '../../../core/theme/widgets/widgets.dart';
/// The countdown is purely cosmetic; the server owns the auto-reject timer.
/// - `accepted` (PairingBestieFoundData / PairingActiveData) — routes into
/// the chat screen immediately.
/// - `declined` (PairingTargetedUnavailableData) — shows the bestie-offline
/// popup. TODO(stage8): swap this stub for the proper BestieOfflinePopup
/// component once Stage 8 lands.
/// - `declined` (PairingTargetedUnavailableData) — shows the
/// [BestieOfflinePopup] returning variant; the popup may offer a
/// fallback-to-blast CTA when other besties are reachable.
class TargetedWaitingScreen extends ConsumerStatefulWidget {
final String mitraId;
const TargetedWaitingScreen({super.key, required this.mitraId});
@@ -58,21 +59,13 @@ class _TargetedWaitingScreenState extends ConsumerState<TargetedWaitingScreen> {
}
if (next is PairingTargetedUnavailableData && !_popupShown) {
_popupShown = true;
// TODO(stage8): replace stub with the production BestieOfflinePopup
// (Stage 8 owns the proper variant + fallback-to-blast surface).
// ignore: discarded_futures
HaloPopup.show(
BestieOfflinePopup.show(
context,
title: '${next.mitraName} lagi nggak online',
body:
'bestie kamu belum bisa nerima chat sekarang. coba bestie lain atau balik ke beranda dulu ya.',
primary: HaloPopupAction(
label: 'kembali ke home',
onPressed: () {
ref.read(pairingProvider.notifier).reset();
if (mounted) context.go('/home');
},
),
variant: BestieOfflineVariant.returning,
mitraName: next.mitraName,
paymentSessionId: next.paymentSessionId,
topicSensitivity: next.topicSensitivity,
).then((_) {
if (mounted) _popupShown = false;
});