Files
halobestie-clone/mitra_app/lib/features/home/home_screen.dart
ramadhan sjamsani 89afd01899 Phase 3.5: Mitra Chat Request History (backend route + mitra app screens)
Replaces the home-screen pending-requests banner with a "Riwayat
Permintaan" CTA that opens a list of the mitra's last 20 chat requests
(any status). Pending rows pin to the top; non-pending rows open a
read-only detail screen with a "Lihat percakapan" CTA on accepted rows.

Backend:
- New service `getRecentRequestsForMitra(mitraId, { limit })` capped at
  20, pending pinned via `(response IS NULL AND status='pending_acceptance')
  DESC`. Customer call_name returned verbatim, with `'Anonim'` only as
  null-safety fallback (no anonymity-flag masking — see project memory).
- New route `GET /api/mitra/chat-requests/recent`. Strictly per-mitra
  scoped via the existing `resolveMitra` preHandler.

Mitra app:
- New `RequestResponse` enum in core/constants.dart.
- New Riverpod notifier `requestHistoryProvider` (AsyncValue<List<...>>,
  keepAlive) — pull-to-refresh + screen-mount fetch only, no WS.
- Two new screens (history list + detail) and two new GoRoutes.
- Home screen: `_PendingRequestsBanner` removed → `_RequestHistoryButton`
  Card with red count badge. Live count comes from the existing
  chatRequestProvider so nothing changes about the WS-driven badge math.

Plan + acceptance criteria in requirement/phase3.5-plan.md. flutter
analyze clean (zero new issues). Backend smoke-tested against real DB.
Real-device E2E pending.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-27 18:59:17 +08:00

215 lines
6.8 KiB
Dart

import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../core/auth/auth_notifier.dart';
import '../../core/status/status_notifier.dart';
import '../../core/chat/chat_request_notifier.dart';
import '../../core/chat/unread_notifier.dart';
class HomeScreen extends ConsumerWidget {
const HomeScreen({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
final authState = ref.watch(mitraAuthProvider);
final authData = authState.valueOrNull;
final displayName = authData is MitraAuthAuthenticatedData
? authData.profile['display_name'] as String
: '';
// Load pending requests if mitra is already online
final statusState = ref.watch(onlineStatusProvider);
if (statusState is StatusLoadedData && statusState.isOnline) {
final requestState = ref.watch(chatRequestProvider);
if (requestState is ChatRequestIdleData) {
Future.microtask(() {
ref.read(chatRequestProvider.notifier).startListening();
ref.read(chatRequestProvider.notifier).loadPendingRequests();
});
}
}
// Listen for status changes to start/stop chat request listening
ref.listen(onlineStatusProvider, (prev, next) {
if (next is StatusLoadedData && next.isOnline) {
ref.read(chatRequestProvider.notifier).startListening();
ref.read(chatRequestProvider.notifier).loadPendingRequests();
} else if (next is StatusLoadedData && !next.isOnline) {
ref.read(chatRequestProvider.notifier).stopListening();
}
});
return Scaffold(
appBar: AppBar(
title: const Text('Halo Bestie Mitra'),
actions: [
IconButton(
icon: const Icon(Icons.logout),
onPressed: () => ref.read(mitraAuthProvider.notifier).logout(),
),
],
),
body: Padding(
padding: const EdgeInsets.all(24),
child: Column(
children: [
Text('Halo, $displayName!', style: const TextStyle(fontSize: 24)),
const SizedBox(height: 32),
const _StatusToggle(),
const SizedBox(height: 16),
const _ActiveSessionsButton(),
],
),
),
);
}
}
class _StatusToggle extends ConsumerWidget {
const _StatusToggle();
@override
Widget build(BuildContext context, WidgetRef ref) {
final statusState = ref.watch(onlineStatusProvider);
final isOnline = statusState is StatusLoadedData && statusState.isOnline;
final isLoading = statusState is StatusLoadingData;
return Card(
child: Padding(
padding: const EdgeInsets.all(16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
isOnline ? 'Online' : 'Offline',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
color: isOnline ? Colors.green : Colors.grey,
),
),
Text(
isOnline
? 'Kamu siap menerima chat'
: 'Aktifkan untuk menerima chat',
style: const TextStyle(fontSize: 14, color: Colors.grey),
),
],
),
isLoading
? const SizedBox(
width: 24,
height: 24,
child: CircularProgressIndicator(strokeWidth: 2),
)
: Switch(
value: isOnline,
activeColor: Colors.green,
onChanged: (_) {
final notifier = ref.read(onlineStatusProvider.notifier);
if (isOnline) {
notifier.toggleOffline();
} else {
notifier.toggleOnline();
}
},
),
],
),
),
);
}
}
class _ActiveSessionsButton extends ConsumerWidget {
const _ActiveSessionsButton();
@override
Widget build(BuildContext context, WidgetRef ref) {
final unreadCounts = ref.watch(unreadSessionsProvider);
final totalUnread = unreadCounts.values.fold(0, (a, b) => a + b);
return Column(
children: [
Card(
child: ListTile(
leading: Badge(
isLabelVisible: totalUnread > 0,
label: Text('$totalUnread'),
child: const Icon(Icons.chat_bubble_outline),
),
title: const Text('Sesi Aktif'),
trailing: const Icon(Icons.chevron_right),
onTap: () => context.push('/sessions'),
),
),
const _RequestHistoryButton(),
Card(
child: ListTile(
leading: const Icon(Icons.history),
title: const Text('Riwayat Chat'),
trailing: const Icon(Icons.chevron_right),
onTap: () => context.push('/chat/history'),
),
),
],
);
}
}
class _RequestHistoryButton extends ConsumerWidget {
const _RequestHistoryButton();
@override
Widget build(BuildContext context, WidgetRef ref) {
// Watch state to rebuild when requests arrive/clear; count comes from
// the notifier which tracks both displayed + queued requests.
ref.watch(chatRequestProvider);
final count = ref.read(chatRequestProvider.notifier).activeRequestCount;
final hasPending = count > 0;
final trailing = hasPending
? Row(
mainAxisSize: MainAxisSize.min,
children: [
Container(
padding:
const EdgeInsets.symmetric(horizontal: 8, vertical: 2),
decoration: BoxDecoration(
color: Colors.red,
borderRadius: BorderRadius.circular(999),
),
child: Text(
'$count',
style: const TextStyle(
color: Colors.white,
fontWeight: FontWeight.bold,
fontSize: 12,
),
),
),
const SizedBox(width: 4),
const Icon(Icons.chevron_right),
],
)
: const Icon(Icons.chevron_right);
return Card(
child: ListTile(
leading: const Icon(Icons.notifications_outlined),
title: const Text('Riwayat Permintaan'),
subtitle: Text(
hasPending
? '$count permintaan baru'
: 'Lihat permintaan chat sebelumnya',
),
trailing: trailing,
onTap: () => context.push('/chat/requests/history'),
),
);
}
}