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,105 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
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
/// 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
/// backend via session_extensions → chat_sessions.
class PendingPaymentItem {
final String id;
final bool isExtension;
final int amount;
final int durationMinutes;
final String mode;
final DateTime createdAt;
final DateTime expiresAt;
final String? mitraId;
final String? mitraDisplayName;
const PendingPaymentItem({
required this.id,
required this.isExtension,
required this.amount,
required this.durationMinutes,
required this.mode,
required this.createdAt,
required this.expiresAt,
required this.mitraId,
required this.mitraDisplayName,
});
factory PendingPaymentItem.fromJson(Map<String, dynamic> json) {
return PendingPaymentItem(
id: json['id'] as String,
isExtension: json['is_extension'] as bool? ?? false,
amount: switch (json['amount']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 0,
_ => 0,
},
durationMinutes: switch (json['duration_minutes']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 0,
_ => 0,
},
mode: json['mode'] as String? ?? 'chat',
createdAt: DateTime.parse(json['created_at'] as String).toLocal(),
expiresAt: DateTime.parse(json['expires_at'] as String).toLocal(),
mitraId: json['mitra_id'] as String?,
mitraDisplayName: json['mitra_display_name'] as String?,
);
}
}
class PendingPaymentsData {
final List<PendingPaymentItem> items;
final int total;
const PendingPaymentsData({required this.items, required this.total});
static const empty = PendingPaymentsData(items: [], total: 0);
}
/// Customer-scoped pending payment sessions. Returns `empty` when the caller
/// has no auth identity — keeps SHome1st + the chat tab from issuing a 401.
///
/// Drives both the Pembayaran sub-tab list and the bottom-nav red dot via the
/// `pendingPaymentsCountProvider` derivative below.
final pendingPaymentsProvider =
FutureProvider<PendingPaymentsData>((ref) async {
final customerId = ref.watch(authProvider.select((s) {
final data = s.valueOrNull;
return switch (data) {
AuthAuthenticatedData d => d.profile['id'] as String?,
AuthAnonymousData d => d.customerId,
_ => null,
};
}));
if (customerId == null) return PendingPaymentsData.empty;
final api = ref.read(apiClientProvider);
final response =
await api.get('/api/client/payment-sessions/pending');
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()
.map(PendingPaymentItem.fromJson)
.toList();
return PendingPaymentsData(
items: items,
total: switch (data['total']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? items.length,
_ => items.length,
},
);
});
/// Lightweight derived count — feeds the bottom-nav red dot + the Pembayaran
/// sub-tab pill badge. Returns 0 while the underlying provider is loading or
/// has errored, so the badge never flickers from a transient state.
final pendingPaymentsCountProvider = Provider<int>((ref) {
final async = ref.watch(pendingPaymentsProvider);
return async.valueOrNull?.total ?? 0;
});

View File

@@ -0,0 +1,172 @@
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../../../core/api/api_client_provider.dart';
import '../../../core/auth/auth_notifier.dart';
/// One row in the Chat Tab > Selesai sub-tab.
///
/// Closed-session details that survive into history: who, when, how long,
/// what closing message was left. The factory tolerates the same number /
/// string ambiguity bestieHistoryProvider already handles (postgres.js
/// stringifies bigint counts).
class SelesaiHistoryItem {
final String sessionId;
final String? mitraId;
final String mitraName;
final DateTime? endedAt;
final int? durationMinutes;
final String mode;
final String? mitraClosureMessage;
final String? customerClosureMessage;
final int sessionsCount;
final bool mitraIsOnline;
const SelesaiHistoryItem({
required this.sessionId,
required this.mitraId,
required this.mitraName,
required this.endedAt,
required this.durationMinutes,
required this.mode,
required this.mitraClosureMessage,
required this.customerClosureMessage,
required this.sessionsCount,
required this.mitraIsOnline,
});
factory SelesaiHistoryItem.fromJson(Map<String, dynamic> json) {
final endedAtRaw = json['ended_at'];
final createdAtRaw = json['created_at'];
return SelesaiHistoryItem(
sessionId: json['id'] as String,
mitraId: json['mitra_id'] as String?,
mitraName: json['mitra_display_name'] as String? ?? 'Bestie',
endedAt: endedAtRaw is String
? DateTime.tryParse(endedAtRaw)?.toLocal()
: (createdAtRaw is String
? DateTime.tryParse(createdAtRaw)?.toLocal()
: null),
durationMinutes: switch (json['duration_minutes']) {
num n => n.toInt(),
String s => int.tryParse(s),
_ => null,
},
mode: json['mode'] as String? ?? 'chat',
mitraClosureMessage: json['mitra_closure_message'] as String?,
customerClosureMessage: json['customer_closure_message'] as String?,
sessionsCount: switch (json['sessions_count']) {
num n => n.toInt(),
String s => int.tryParse(s) ?? 1,
_ => 1,
},
mitraIsOnline: json['mitra_is_online'] as bool? ?? false,
);
}
/// Preview shown in the row: prefer the mitra's closing message (closer to
/// the partner's voice), fall back to the customer's, then to a generic
/// "selesai" placeholder so empty rows still render.
String get previewText =>
(mitraClosureMessage?.trim().isNotEmpty == true
? mitraClosureMessage
: (customerClosureMessage?.trim().isNotEmpty == true
? customerClosureMessage
: 'sesi selesai'))!;
}
/// Persistent paginated state — accumulated items + cursor + flags.
class SelesaiHistoryState {
final List<SelesaiHistoryItem> items;
final String? nextCursor;
final bool hasMore;
final bool loadingMore;
const SelesaiHistoryState({
this.items = const [],
this.nextCursor,
this.hasMore = false,
this.loadingMore = false,
});
SelesaiHistoryState copyWith({
List<SelesaiHistoryItem>? items,
String? nextCursor,
bool? hasMore,
bool? loadingMore,
bool clearCursor = false,
}) =>
SelesaiHistoryState(
items: items ?? this.items,
nextCursor: clearCursor ? null : (nextCursor ?? this.nextCursor),
hasMore: hasMore ?? this.hasMore,
loadingMore: loadingMore ?? this.loadingMore,
);
}
/// Cursor-paginated Selesai history. First fetch returns the freshest 20 rows;
/// `loadMore` appends the next page. Customer-scoped — switching account
/// resets the list automatically because the build re-runs.
class SelesaiHistoryNotifier
extends AsyncNotifier<SelesaiHistoryState> {
static const _pageLimit = 20;
@override
Future<SelesaiHistoryState> build() async {
final customerId = ref.watch(authProvider.select((s) {
final data = s.valueOrNull;
return switch (data) {
AuthAuthenticatedData d => d.profile['id'] as String?,
AuthAnonymousData d => d.customerId,
_ => null,
};
}));
if (customerId == null) return const SelesaiHistoryState();
return await _fetchPage(cursor: null);
}
Future<SelesaiHistoryState> _fetchPage({String? cursor}) async {
final api = ref.read(apiClientProvider);
final url = cursor == null
? '/api/client/chat/history?limit=$_pageLimit'
: '/api/client/chat/history?limit=$_pageLimit&cursor=${Uri.encodeQueryComponent(cursor)}';
final response = await api.get(url);
final data = response['data'] as Map<String, dynamic>? ?? const {};
final items = (data['items'] as List<dynamic>? ?? [])
.cast<Map<String, dynamic>>()
.map(SelesaiHistoryItem.fromJson)
.toList();
final existing = cursor == null ? <SelesaiHistoryItem>[] : (state.valueOrNull?.items ?? const []);
return SelesaiHistoryState(
items: [...existing, ...items],
nextCursor: data['next_cursor'] as String?,
hasMore: data['has_more'] as bool? ?? false,
);
}
/// Append the next page if any. No-op when already loading or no cursor.
Future<void> loadMore() async {
final current = state.valueOrNull;
if (current == null || !current.hasMore || current.loadingMore) return;
state = AsyncData(current.copyWith(loadingMore: true));
try {
final next = await _fetchPage(cursor: current.nextCursor);
state = AsyncData(next);
} catch (e, st) {
state = AsyncError(e, st);
}
}
/// Pull-to-refresh: drop the cursor and re-fetch from the top.
Future<void> refresh() async {
state = const AsyncLoading();
try {
state = AsyncData(await _fetchPage(cursor: null));
} catch (e, st) {
state = AsyncError(e, st);
}
}
}
final selesaiHistoryProvider =
AsyncNotifierProvider<SelesaiHistoryNotifier, SelesaiHistoryState>(
SelesaiHistoryNotifier.new,
);