Phase 4 Stage 10 client_app: Chat tab UI (3 sub-tabs + retire bestie_history)

Flutter half of Stage 10 — the new Chat tab landing in the bottom nav.
The CTA target swaps from /chat/history to /chat, which redirects into
/chat/aktif. Three sibling routes under a single ShellRoute share a
header + sub-tab pills + the existing HaloTabBar footer:

  /chat/aktif        — the current active session (0 or 1 row)
  /chat/pembayaran   — pending initial + extension payments
  /chat/selesai      — past sessions, cursor-paginated infinite scroll

URL is the source of truth for the active sub-tab so deep links, back
stack, and Maestro all agree on state.

New feature dir `lib/features/chat_tab/`:
- providers/pending_payments_provider.dart — FutureProvider against the
  Stage-10 backend endpoint, plus pendingPaymentsCountProvider for the
  red-dot derivative
- providers/selesai_history_provider.dart — AsyncNotifier over
  GET /api/client/chat/history; tracks accumulated items + next_cursor +
  hasMore; loadMore() and refresh()
- widgets/chat_row.dart — generic row used by all 3 sub-tabs, with
  optional PaymentAmountChip / DurationChip / 📞 Call indicator
- widgets/sub_tab_pill.dart — pill with active underline + optional
  numeric badge (null hides; matches Selesai's no-badge rule)
- screens/chat_tab_shell.dart — ShellRoute scaffold + ChatSubTab enum
- screens/{aktif,pembayaran,selesai}_view.dart — the three sub-tab bodies

Router (`router.dart`):
- /chat → redirect → /chat/aktif
- ShellRoute hosts /chat/aktif, /chat/pembayaran, /chat/selesai
- /chat/history retired; /chat/history/:sessionId → /chat/transcript/:sessionId
- ChatHistoryScreen import + file deleted

HaloTabBar (`features/home/widgets/halo_tab_bar.dart` — new in the
working tree from Stage 9 sweep): now a ConsumerWidget. Chat tab goes
to /chat. Red dot renders when pendingPaymentsCountProvider > 0.

Inbound call-site updates:
- bestie_choice_sheet.dart: /chat/history → /chat
- home_screen.dart history-row tap: /chat/history/:id → /chat/transcript/:id

This commit also carries the larger Stage 9 sweep + ESP-removal + USP
gate edits that were already staged in the working tree on
`home_screen.dart` and `router.dart` from the prior session.

flutter analyze: clean except for the pre-existing scaffold
test/widget_test.dart MyApp reference (unrelated, present on master).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-12 20:14:22 +08:00
parent 350b92f1f3
commit e3ea1d793e
13 changed files with 1943 additions and 478 deletions

View File

@@ -0,0 +1,111 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/active_session_notifier.dart';
import '../../../core/theme/halo_tokens.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > aktif sub-tab.
///
/// Always renders 0 or 1 row — backend caps the customer to one active
/// session. Row stays visible while the user is inside the live chat room
/// (per §10.6 decision 1: aktif represents state, not navigation).
class AktifView extends ConsumerWidget {
const AktifView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final async = ref.watch(activeSessionProvider);
return RefreshIndicator(
onRefresh: () => ref.read(activeSessionProvider.notifier).refresh(),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _Error(message: e.toString()),
data: (data) {
if (!data.hasSession) return const _Empty();
final session = data.session!;
final mitraName =
(session['mitra_display_name'] as String?) ?? 'Bestie';
return ListView(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
children: [
ChatRow(
seed: mitraName.codeUnits.fold<int>(0, (a, b) => a + b),
name: mitraName,
preview: _previewFor(data.unreadCount),
isLive: true,
isCall: (session['mode'] as String?) == 'call',
onTap: () {
final sessionId = session['id'] as String?;
if (sessionId == null) return;
context.push('/chat/session/$sessionId',
extra: {'mitraName': mitraName});
},
),
],
);
},
),
);
}
String _previewFor(int unread) =>
unread > 0 ? '$unread pesan baru' : 'lagi ngobrol nih';
}
class _Empty extends StatelessWidget {
const _Empty();
@override
Widget build(BuildContext context) => const _CenteredMessage(
text: 'belum ada chat di sini',
);
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _Error extends StatelessWidget {
final String message;
const _Error({required this.message});
@override
Widget build(BuildContext context) =>
_CenteredMessage(text: 'gagal memuat: $message');
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
// Wrap in a scroll view so RefreshIndicator works even on empty state.
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,139 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/chat/active_session_notifier.dart';
import '../../../core/theme/halo_tokens.dart';
import '../../home/widgets/halo_tab_bar.dart';
import '../providers/pending_payments_provider.dart';
import '../widgets/sub_tab_pill.dart';
/// Phase 4 Stage 10 — host scaffold for the Chat tab.
///
/// Wraps the three sub-tab views (`/chat/aktif`, `/chat/pembayaran`,
/// `/chat/selesai`) via `ShellRoute`. The header + sub-tab pills + bottom
/// `HaloTabBar` stay constant while only the body swaps.
class ChatTabShell extends ConsumerWidget {
final Widget child;
final ChatSubTab active;
const ChatTabShell({
super.key,
required this.child,
required this.active,
});
@override
Widget build(BuildContext context, WidgetRef ref) {
final activeSession = ref.watch(activeSessionProvider).valueOrNull;
final unreadCount =
activeSession?.hasSession == true ? activeSession!.unreadCount : 0;
final pendingCount = ref.watch(pendingPaymentsCountProvider);
return Scaffold(
backgroundColor: HaloTokens.bg,
body: SafeArea(
bottom: false,
child: Column(
children: [
const _Heading(),
_SubTabBar(
active: active,
aktifBadge: unreadCount,
pembayaranBadge: pendingCount,
),
Expanded(child: child),
const HaloTabBar(active: 'chat'),
],
),
),
);
}
}
enum ChatSubTab {
aktif('/chat/aktif', 'aktif'),
pembayaran('/chat/pembayaran', 'pembayaran'),
selesai('/chat/selesai', 'selesai');
final String path;
final String label;
const ChatSubTab(this.path, this.label);
}
class _Heading extends StatelessWidget {
const _Heading();
@override
Widget build(BuildContext context) {
return const Padding(
padding: EdgeInsets.fromLTRB(
HaloSpacing.s24,
HaloSpacing.s20,
HaloSpacing.s24,
HaloSpacing.s12,
),
child: Align(
alignment: Alignment.centerLeft,
child: Text(
'chat',
style: TextStyle(
fontFamily: HaloTokens.fontDisplay,
fontSize: 26,
fontWeight: FontWeight.w700,
color: HaloTokens.brandDark,
letterSpacing: -0.52,
),
),
),
);
}
}
class _SubTabBar extends StatelessWidget {
final ChatSubTab active;
final int aktifBadge;
final int pembayaranBadge;
const _SubTabBar({
required this.active,
required this.aktifBadge,
required this.pembayaranBadge,
});
@override
Widget build(BuildContext context) {
return Container(
padding: const EdgeInsets.symmetric(horizontal: HaloSpacing.s16),
decoration: const BoxDecoration(
border: Border(bottom: BorderSide(color: HaloTokens.border)),
),
child: Row(
children: [
SubTabPill(
label: 'aktif',
active: active == ChatSubTab.aktif,
badgeCount: aktifBadge,
onTap: () => _navigate(context, ChatSubTab.aktif),
),
SubTabPill(
label: 'pembayaran',
active: active == ChatSubTab.pembayaran,
badgeCount: pembayaranBadge,
onTap: () => _navigate(context, ChatSubTab.pembayaran),
),
SubTabPill(
label: 'selesai',
active: active == ChatSubTab.selesai,
badgeCount: null,
onTap: () => _navigate(context, ChatSubTab.selesai),
),
],
),
);
}
void _navigate(BuildContext context, ChatSubTab target) {
if (target == active) return;
context.go(target.path);
}
}

View File

@@ -0,0 +1,103 @@
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 '../providers/pending_payments_provider.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > pembayaran sub-tab.
///
/// Lists pending initial + extension payments. Row tap resumes the
/// waiting-payment screen for that payment session.
class PembayaranView extends ConsumerWidget {
const PembayaranView({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final async = ref.watch(pendingPaymentsProvider);
return RefreshIndicator(
onRefresh: () => ref.refresh(pendingPaymentsProvider.future),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _CenteredMessage(text: 'gagal memuat: $e'),
data: (data) {
if (data.items.isEmpty) {
return const _CenteredMessage(
text: 'belum ada pembayaran tertunda',
);
}
return ListView.builder(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
itemCount: data.items.length,
itemBuilder: (_, i) {
final item = data.items[i];
final name = item.mitraDisplayName ?? 'Bestie';
return ChatRow(
seed: name.codeUnits.fold<int>(0, (a, b) => a + b),
name: name,
preview: item.isExtension
? 'menunggu pembayaran perpanjangan'
: 'menunggu pembayaran sesi',
trailing: _relativeTime(item.createdAt),
chips: [PaymentAmountChip(amount: item.amount)],
isCall: item.mode == 'call',
onTap: () => context.push('/payment/waiting/${item.id}'),
);
},
);
},
),
);
}
}
/// Loose "2 mnt lalu" formatter — enough for the row trailing label without
/// dragging in `intl`. Mirrors the Figma copy style.
String _relativeTime(DateTime when) {
final delta = DateTime.now().difference(when);
if (delta.inSeconds < 60) return 'baru aja';
if (delta.inMinutes < 60) return '${delta.inMinutes} mnt lalu';
if (delta.inHours < 24) return '${delta.inHours} jam lalu';
if (delta.inDays < 7) return '${delta.inDays} hari lalu';
return '${(delta.inDays / 7).floor()} mgg lalu';
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}

View File

@@ -0,0 +1,148 @@
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 '../providers/selesai_history_provider.dart';
import '../widgets/chat_row.dart';
/// Chat-Tab > selesai sub-tab.
///
/// Cursor-paginated past sessions. Tap → read-only transcript at
/// `/chat/transcript/:sessionId` (renamed from the retired /chat/history/:id).
class SelesaiView extends ConsumerStatefulWidget {
const SelesaiView({super.key});
@override
ConsumerState<SelesaiView> createState() => _SelesaiViewState();
}
class _SelesaiViewState extends ConsumerState<SelesaiView> {
final _scroll = ScrollController();
@override
void initState() {
super.initState();
_scroll.addListener(_onScroll);
}
@override
void dispose() {
_scroll.removeListener(_onScroll);
_scroll.dispose();
super.dispose();
}
void _onScroll() {
// Trigger load-more when within ~400px of the bottom. The notifier no-ops
// if there's no cursor or another fetch is in flight.
if (!_scroll.hasClients) return;
final remaining = _scroll.position.maxScrollExtent - _scroll.position.pixels;
if (remaining < 400) {
ref.read(selesaiHistoryProvider.notifier).loadMore();
}
}
@override
Widget build(BuildContext context) {
final async = ref.watch(selesaiHistoryProvider);
return RefreshIndicator(
onRefresh: () => ref.read(selesaiHistoryProvider.notifier).refresh(),
color: HaloTokens.brand,
child: async.when(
loading: () => const _Loading(),
error: (e, _) => _CenteredMessage(text: 'gagal memuat: $e'),
data: (state) {
if (state.items.isEmpty) {
return const _CenteredMessage(text: 'belum ada riwayat curhat');
}
return ListView.builder(
controller: _scroll,
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s12,
),
itemCount: state.items.length + (state.hasMore ? 1 : 0),
itemBuilder: (_, i) {
if (i >= state.items.length) {
return const Padding(
padding: EdgeInsets.symmetric(vertical: HaloSpacing.s16),
child: Center(
child: SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(
strokeWidth: 2,
color: HaloTokens.brand,
),
),
),
);
}
final item = state.items[i];
return ChatRow(
seed: item.mitraName.codeUnits.fold<int>(0, (a, b) => a + b),
name: item.mitraName,
preview: item.previewText,
trailing: item.endedAt == null
? null
: _relativeTime(item.endedAt!),
chips: [
if (item.durationMinutes != null)
DurationChip(minutes: item.durationMinutes!),
],
isCall: item.mode == 'call',
onTap: () =>
context.push('/chat/transcript/${item.sessionId}'),
);
},
);
},
),
);
}
}
String _relativeTime(DateTime when) {
final delta = DateTime.now().difference(when);
if (delta.inSeconds < 60) return 'baru aja';
if (delta.inMinutes < 60) return '${delta.inMinutes} mnt lalu';
if (delta.inHours < 24) return '${delta.inHours} jam lalu';
if (delta.inDays < 7) return '${delta.inDays} hari lalu';
return '${(delta.inDays / 7).floor()} mgg lalu';
}
class _Loading extends StatelessWidget {
const _Loading();
@override
Widget build(BuildContext context) => const Center(
child: CircularProgressIndicator(color: HaloTokens.brand),
);
}
class _CenteredMessage extends StatelessWidget {
final String text;
const _CenteredMessage({required this.text});
@override
Widget build(BuildContext context) {
return ListView(
physics: const AlwaysScrollableScrollPhysics(),
children: [
Padding(
padding: const EdgeInsets.symmetric(
horizontal: HaloSpacing.s20,
vertical: HaloSpacing.s64,
),
child: Text(
text,
textAlign: TextAlign.center,
style: const TextStyle(
fontFamily: HaloTokens.fontBody,
fontSize: 13,
color: HaloTokens.inkMuted,
),
),
),
],
);
}
}