Phase 3 scaffold: chat engine (WebSocket, FCM, pricing, timer, extension, history)
- Backend: WebSocket plugin, chat/pricing/timer/extension/closure/notification services - Client app: ChatBloc, pricing dialog, chat screen with message status, extension/goodbye flow, history - Mitra app: MitraChatBloc, ExtensionBloc, chat screen, extension accept/reject, history - Control center: free trial, extension timeout, early end config toggles - DB migration: chat_messages, session_closures, session_extensions, customer_transactions tables Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
385
client_app/lib/core/chat/chat_bloc.dart
Normal file
385
client_app/lib/core/chat/chat_bloc.dart
Normal file
@@ -0,0 +1,385 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:web_socket_channel/web_socket_channel.dart';
|
||||
import '../api/api_client.dart';
|
||||
|
||||
// Events
|
||||
abstract class ChatEvent extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class ConnectChat extends ChatEvent {
|
||||
final String sessionId;
|
||||
ConnectChat(this.sessionId);
|
||||
@override
|
||||
List<Object?> get props => [sessionId];
|
||||
}
|
||||
|
||||
class DisconnectChat extends ChatEvent {}
|
||||
|
||||
class SendMessage extends ChatEvent {
|
||||
final String content;
|
||||
SendMessage(this.content);
|
||||
@override
|
||||
List<Object?> get props => [content];
|
||||
}
|
||||
|
||||
class SendTyping extends ChatEvent {}
|
||||
|
||||
class _MessageReceived extends ChatEvent {
|
||||
final Map<String, dynamic> data;
|
||||
_MessageReceived(this.data);
|
||||
@override
|
||||
List<Object?> get props => [data];
|
||||
}
|
||||
|
||||
class _ConnectionError extends ChatEvent {}
|
||||
|
||||
class MarkMessagesDelivered extends ChatEvent {
|
||||
final List<String> messageIds;
|
||||
MarkMessagesDelivered(this.messageIds);
|
||||
@override
|
||||
List<Object?> get props => [messageIds];
|
||||
}
|
||||
|
||||
class MarkMessagesRead extends ChatEvent {
|
||||
final List<String> messageIds;
|
||||
MarkMessagesRead(this.messageIds);
|
||||
@override
|
||||
List<Object?> get props => [messageIds];
|
||||
}
|
||||
|
||||
// States
|
||||
abstract class ChatState extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class ChatInitial extends ChatState {}
|
||||
class ChatConnecting extends ChatState {}
|
||||
|
||||
class ChatConnected extends ChatState {
|
||||
final List<ChatMessage> messages;
|
||||
final bool isOtherTyping;
|
||||
final int? remainingSeconds;
|
||||
final bool sessionExpired;
|
||||
final bool sessionPaused;
|
||||
final bool sessionClosing;
|
||||
final Map<String, dynamic>? extensionResponse;
|
||||
|
||||
ChatConnected({
|
||||
required this.messages,
|
||||
this.isOtherTyping = false,
|
||||
this.remainingSeconds,
|
||||
this.sessionExpired = false,
|
||||
this.sessionPaused = false,
|
||||
this.sessionClosing = false,
|
||||
this.extensionResponse,
|
||||
});
|
||||
|
||||
ChatConnected copyWith({
|
||||
List<ChatMessage>? messages,
|
||||
bool? isOtherTyping,
|
||||
int? remainingSeconds,
|
||||
bool? sessionExpired,
|
||||
bool? sessionPaused,
|
||||
bool? sessionClosing,
|
||||
Map<String, dynamic>? extensionResponse,
|
||||
}) {
|
||||
return ChatConnected(
|
||||
messages: messages ?? this.messages,
|
||||
isOtherTyping: isOtherTyping ?? this.isOtherTyping,
|
||||
remainingSeconds: remainingSeconds ?? this.remainingSeconds,
|
||||
sessionExpired: sessionExpired ?? this.sessionExpired,
|
||||
sessionPaused: sessionPaused ?? this.sessionPaused,
|
||||
sessionClosing: sessionClosing ?? this.sessionClosing,
|
||||
extensionResponse: extensionResponse ?? this.extensionResponse,
|
||||
);
|
||||
}
|
||||
|
||||
@override
|
||||
List<Object?> get props => [messages, isOtherTyping, remainingSeconds, sessionExpired, sessionPaused, sessionClosing, extensionResponse];
|
||||
}
|
||||
|
||||
class ChatError extends ChatState {
|
||||
final String message;
|
||||
ChatError(this.message);
|
||||
@override
|
||||
List<Object?> get props => [message];
|
||||
}
|
||||
|
||||
// Message model
|
||||
class ChatMessage {
|
||||
final String id;
|
||||
final String senderType;
|
||||
final String content;
|
||||
final String type;
|
||||
final String status; // sending, sent, delivered, read
|
||||
final DateTime createdAt;
|
||||
|
||||
ChatMessage({
|
||||
required this.id,
|
||||
required this.senderType,
|
||||
required this.content,
|
||||
this.type = 'text',
|
||||
this.status = 'sent',
|
||||
required this.createdAt,
|
||||
});
|
||||
|
||||
ChatMessage copyWith({String? status}) {
|
||||
return ChatMessage(
|
||||
id: id,
|
||||
senderType: senderType,
|
||||
content: content,
|
||||
type: type,
|
||||
status: status ?? this.status,
|
||||
createdAt: createdAt,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Bloc
|
||||
class ChatBloc extends Bloc<ChatEvent, ChatState> {
|
||||
final ApiClient apiClient;
|
||||
WebSocketChannel? _channel;
|
||||
StreamSubscription? _wsSubscription;
|
||||
Timer? _typingTimer;
|
||||
|
||||
ChatBloc({required this.apiClient}) : super(ChatInitial()) {
|
||||
on<ConnectChat>(_onConnect);
|
||||
on<DisconnectChat>(_onDisconnect);
|
||||
on<SendMessage>(_onSendMessage);
|
||||
on<SendTyping>(_onSendTyping);
|
||||
on<_MessageReceived>(_onMessageReceived);
|
||||
on<_ConnectionError>(_onConnectionError);
|
||||
on<MarkMessagesDelivered>(_onMarkDelivered);
|
||||
on<MarkMessagesRead>(_onMarkRead);
|
||||
}
|
||||
|
||||
Future<void> _onConnect(ConnectChat event, Emitter<ChatState> emit) async {
|
||||
emit(ChatConnecting());
|
||||
|
||||
try {
|
||||
// Load existing messages from API
|
||||
final response = await apiClient.get(
|
||||
'/api/shared/chat/${event.sessionId}/messages',
|
||||
);
|
||||
final messagesData = response['data'] as List<dynamic>;
|
||||
final messages = messagesData.map((m) => ChatMessage(
|
||||
id: m['id'] as String,
|
||||
senderType: m['sender_type'] as String,
|
||||
content: m['content'] as String,
|
||||
type: m['type'] as String? ?? 'text',
|
||||
status: m['status'] as String? ?? 'sent',
|
||||
createdAt: DateTime.parse(m['created_at'] as String),
|
||||
)).toList();
|
||||
|
||||
// Connect WebSocket
|
||||
final user = FirebaseAuth.instance.currentUser;
|
||||
final token = await user?.getIdToken();
|
||||
final wsUrl = ApiClient.baseUrl
|
||||
.replaceFirst('https://', 'wss://')
|
||||
.replaceFirst('http://', 'ws://');
|
||||
_channel = WebSocketChannel.connect(Uri.parse('$wsUrl/api/shared/ws'));
|
||||
|
||||
_wsSubscription = _channel!.stream.listen(
|
||||
(raw) {
|
||||
final data = jsonDecode(raw as String) as Map<String, dynamic>;
|
||||
add(_MessageReceived(data));
|
||||
},
|
||||
onError: (_) => add(_ConnectionError()),
|
||||
onDone: () => add(_ConnectionError()),
|
||||
);
|
||||
|
||||
// Send auth message
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'auth',
|
||||
'token': token,
|
||||
'session_id': event.sessionId,
|
||||
}));
|
||||
|
||||
emit(ChatConnected(messages: messages));
|
||||
} catch (e) {
|
||||
emit(ChatError('Gagal terhubung ke chat.'));
|
||||
}
|
||||
}
|
||||
|
||||
void _onDisconnect(DisconnectChat event, Emitter<ChatState> emit) {
|
||||
_cleanup();
|
||||
emit(ChatInitial());
|
||||
}
|
||||
|
||||
void _onSendMessage(SendMessage event, Emitter<ChatState> emit) {
|
||||
if (state is! ChatConnected || _channel == null) return;
|
||||
final current = state as ChatConnected;
|
||||
|
||||
// Add message locally with 'sending' status
|
||||
final tempId = 'temp_${DateTime.now().millisecondsSinceEpoch}';
|
||||
final msg = ChatMessage(
|
||||
id: tempId,
|
||||
senderType: 'customer',
|
||||
content: event.content,
|
||||
status: 'sending',
|
||||
createdAt: DateTime.now(),
|
||||
);
|
||||
|
||||
emit(current.copyWith(messages: [...current.messages, msg]));
|
||||
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'message',
|
||||
'content': event.content,
|
||||
'_temp_id': tempId,
|
||||
}));
|
||||
}
|
||||
|
||||
void _onSendTyping(SendTyping event, Emitter<ChatState> emit) {
|
||||
if (_channel == null) return;
|
||||
_channel!.sink.add(jsonEncode({'type': 'typing'}));
|
||||
}
|
||||
|
||||
void _onMarkDelivered(MarkMessagesDelivered event, Emitter<ChatState> emit) {
|
||||
if (_channel == null) return;
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'delivered',
|
||||
'message_ids': event.messageIds,
|
||||
}));
|
||||
}
|
||||
|
||||
void _onMarkRead(MarkMessagesRead event, Emitter<ChatState> emit) {
|
||||
if (_channel == null) return;
|
||||
_channel!.sink.add(jsonEncode({
|
||||
'type': 'read',
|
||||
'message_ids': event.messageIds,
|
||||
}));
|
||||
}
|
||||
|
||||
void _onMessageReceived(_MessageReceived event, Emitter<ChatState> emit) {
|
||||
if (state is! ChatConnected) return;
|
||||
final current = state as ChatConnected;
|
||||
final data = event.data;
|
||||
final type = data['type'] as String?;
|
||||
|
||||
switch (type) {
|
||||
case 'auth_ok':
|
||||
// Already connected
|
||||
break;
|
||||
|
||||
case 'message':
|
||||
final msg = ChatMessage(
|
||||
id: data['message_id'] as String,
|
||||
senderType: data['sender_type'] as String,
|
||||
content: data['content'] as String,
|
||||
type: data['message_type'] as String? ?? 'text',
|
||||
status: 'sent',
|
||||
createdAt: DateTime.parse(data['created_at'] as String),
|
||||
);
|
||||
emit(current.copyWith(messages: [...current.messages, msg]));
|
||||
// Auto-acknowledge delivery
|
||||
add(MarkMessagesDelivered([msg.id]));
|
||||
break;
|
||||
|
||||
case 'message_ack':
|
||||
final messageId = data['message_id'] as String;
|
||||
final status = data['status'] as String;
|
||||
final updatedMessages = current.messages.map((m) {
|
||||
if (m.status == 'sending') {
|
||||
return m.copyWith(status: status);
|
||||
}
|
||||
return m;
|
||||
}).toList();
|
||||
// Replace temp ID with real ID
|
||||
final idx = updatedMessages.indexWhere((m) => m.status == status && m.senderType == 'customer');
|
||||
if (idx >= 0) {
|
||||
final old = updatedMessages[idx];
|
||||
updatedMessages[idx] = ChatMessage(
|
||||
id: messageId,
|
||||
senderType: old.senderType,
|
||||
content: old.content,
|
||||
type: old.type,
|
||||
status: status,
|
||||
createdAt: old.createdAt,
|
||||
);
|
||||
}
|
||||
emit(current.copyWith(messages: updatedMessages));
|
||||
break;
|
||||
|
||||
case 'message_status':
|
||||
final messageIds = (data['message_ids'] as List<dynamic>).cast<String>();
|
||||
final status = data['status'] as String;
|
||||
final updatedMessages = current.messages.map((m) {
|
||||
if (messageIds.contains(m.id)) {
|
||||
return m.copyWith(status: status);
|
||||
}
|
||||
return m;
|
||||
}).toList();
|
||||
emit(current.copyWith(messages: updatedMessages));
|
||||
break;
|
||||
|
||||
case 'typing':
|
||||
emit(current.copyWith(isOtherTyping: true));
|
||||
_typingTimer?.cancel();
|
||||
_typingTimer = Timer(const Duration(seconds: 3), () {
|
||||
if (state is ChatConnected) {
|
||||
emit((state as ChatConnected).copyWith(isOtherTyping: false));
|
||||
}
|
||||
});
|
||||
break;
|
||||
|
||||
case 'session_timer':
|
||||
final remaining = data['remaining_seconds'] as int?;
|
||||
emit(current.copyWith(remainingSeconds: remaining));
|
||||
break;
|
||||
|
||||
case 'session_expired':
|
||||
emit(current.copyWith(sessionExpired: true));
|
||||
break;
|
||||
|
||||
case 'session_paused':
|
||||
emit(current.copyWith(sessionPaused: true));
|
||||
break;
|
||||
|
||||
case 'session_resumed':
|
||||
emit(current.copyWith(sessionPaused: false, sessionExpired: false));
|
||||
break;
|
||||
|
||||
case 'session_closing':
|
||||
emit(current.copyWith(sessionClosing: true));
|
||||
break;
|
||||
|
||||
case 'extension_response':
|
||||
emit(current.copyWith(extensionResponse: data));
|
||||
break;
|
||||
|
||||
case 'session_completed':
|
||||
_cleanup();
|
||||
break;
|
||||
|
||||
case 'error':
|
||||
// Keep connected but show error
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
void _onConnectionError(_ConnectionError event, Emitter<ChatState> emit) {
|
||||
// Could implement reconnection logic here
|
||||
}
|
||||
|
||||
void _cleanup() {
|
||||
_wsSubscription?.cancel();
|
||||
_wsSubscription = null;
|
||||
_channel?.sink.close();
|
||||
_channel = null;
|
||||
_typingTimer?.cancel();
|
||||
_typingTimer = null;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_cleanup();
|
||||
return super.close();
|
||||
}
|
||||
}
|
||||
87
client_app/lib/core/chat/chat_opening_bloc.dart
Normal file
87
client_app/lib/core/chat/chat_opening_bloc.dart
Normal file
@@ -0,0 +1,87 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../api/api_client.dart';
|
||||
|
||||
// Events
|
||||
abstract class ChatOpeningEvent extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class LoadPricing extends ChatOpeningEvent {}
|
||||
|
||||
// States
|
||||
abstract class ChatOpeningState extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class PricingInitial extends ChatOpeningState {}
|
||||
class PricingLoading extends ChatOpeningState {}
|
||||
|
||||
class PricingLoaded extends ChatOpeningState {
|
||||
final List<PriceTier> tiers;
|
||||
final bool freeTrialEligible;
|
||||
final int freeTrialDurationMinutes;
|
||||
|
||||
PricingLoaded({
|
||||
required this.tiers,
|
||||
required this.freeTrialEligible,
|
||||
this.freeTrialDurationMinutes = 5,
|
||||
});
|
||||
|
||||
@override
|
||||
List<Object?> get props => [tiers, freeTrialEligible, freeTrialDurationMinutes];
|
||||
}
|
||||
|
||||
class PricingError extends ChatOpeningState {
|
||||
final String message;
|
||||
PricingError(this.message);
|
||||
@override
|
||||
List<Object?> get props => [message];
|
||||
}
|
||||
|
||||
// Model
|
||||
class PriceTier {
|
||||
final int durationMinutes;
|
||||
final int price;
|
||||
final String label;
|
||||
|
||||
PriceTier({required this.durationMinutes, required this.price, required this.label});
|
||||
|
||||
factory PriceTier.fromJson(Map<String, dynamic> json) {
|
||||
return PriceTier(
|
||||
durationMinutes: json['duration_minutes'] as int,
|
||||
price: json['price'] as int,
|
||||
label: json['label'] as String,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Bloc
|
||||
class ChatOpeningBloc extends Bloc<ChatOpeningEvent, ChatOpeningState> {
|
||||
final ApiClient apiClient;
|
||||
|
||||
ChatOpeningBloc({required this.apiClient}) : super(PricingInitial()) {
|
||||
on<LoadPricing>(_onLoadPricing);
|
||||
}
|
||||
|
||||
Future<void> _onLoadPricing(LoadPricing event, Emitter<ChatOpeningState> emit) async {
|
||||
emit(PricingLoading());
|
||||
try {
|
||||
final response = await apiClient.get('/api/client/chat/pricing');
|
||||
final data = response['data'] as Map<String, dynamic>;
|
||||
final tiersJson = data['tiers'] as List<dynamic>;
|
||||
final tiers = tiersJson.map((t) => PriceTier.fromJson(t as Map<String, dynamic>)).toList();
|
||||
final freeTrial = data['free_trial'] as Map<String, dynamic>;
|
||||
|
||||
emit(PricingLoaded(
|
||||
tiers: tiers,
|
||||
freeTrialEligible: freeTrial['eligible'] as bool? ?? false,
|
||||
freeTrialDurationMinutes: freeTrial['duration_minutes'] as int? ?? 5,
|
||||
));
|
||||
} catch (e) {
|
||||
emit(PricingError('Gagal memuat harga. Coba lagi.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
90
client_app/lib/core/chat/session_closure_bloc.dart
Normal file
90
client_app/lib/core/chat/session_closure_bloc.dart
Normal file
@@ -0,0 +1,90 @@
|
||||
import 'package:equatable/equatable.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../api/api_client.dart';
|
||||
|
||||
// Events
|
||||
abstract class SessionClosureEvent extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class RequestExtension extends SessionClosureEvent {
|
||||
final String sessionId;
|
||||
final int durationMinutes;
|
||||
final int price;
|
||||
RequestExtension({required this.sessionId, required this.durationMinutes, required this.price});
|
||||
@override
|
||||
List<Object?> get props => [sessionId, durationMinutes, price];
|
||||
}
|
||||
|
||||
class DeclineExtension extends SessionClosureEvent {}
|
||||
|
||||
class SubmitGoodbye extends SessionClosureEvent {
|
||||
final String sessionId;
|
||||
final String message;
|
||||
SubmitGoodbye({required this.sessionId, required this.message});
|
||||
@override
|
||||
List<Object?> get props => [sessionId, message];
|
||||
}
|
||||
|
||||
// States
|
||||
abstract class SessionClosureState extends Equatable {
|
||||
@override
|
||||
List<Object?> get props => [];
|
||||
}
|
||||
|
||||
class ClosureInitial extends SessionClosureState {}
|
||||
class ExtendingWaitingMitra extends SessionClosureState {}
|
||||
|
||||
class ClosureShowGoodbye extends SessionClosureState {}
|
||||
|
||||
class ClosureSubmitting extends SessionClosureState {}
|
||||
|
||||
class ClosureComplete extends SessionClosureState {}
|
||||
|
||||
class ClosureError extends SessionClosureState {
|
||||
final String message;
|
||||
ClosureError(this.message);
|
||||
@override
|
||||
List<Object?> get props => [message];
|
||||
}
|
||||
|
||||
// Bloc
|
||||
class SessionClosureBloc extends Bloc<SessionClosureEvent, SessionClosureState> {
|
||||
final ApiClient apiClient;
|
||||
|
||||
SessionClosureBloc({required this.apiClient}) : super(ClosureInitial()) {
|
||||
on<RequestExtension>(_onRequestExtension);
|
||||
on<DeclineExtension>(_onDeclineExtension);
|
||||
on<SubmitGoodbye>(_onSubmitGoodbye);
|
||||
}
|
||||
|
||||
Future<void> _onRequestExtension(RequestExtension event, Emitter<SessionClosureState> emit) async {
|
||||
emit(ExtendingWaitingMitra());
|
||||
try {
|
||||
await apiClient.post('/api/client/chat/session/${event.sessionId}/extend', data: {
|
||||
'duration_minutes': event.durationMinutes,
|
||||
'price': event.price,
|
||||
});
|
||||
// Response will come via WebSocket (ChatBloc handles it)
|
||||
} catch (e) {
|
||||
emit(ClosureError('Gagal meminta perpanjangan.'));
|
||||
}
|
||||
}
|
||||
|
||||
void _onDeclineExtension(DeclineExtension event, Emitter<SessionClosureState> emit) {
|
||||
emit(ClosureShowGoodbye());
|
||||
}
|
||||
|
||||
Future<void> _onSubmitGoodbye(SubmitGoodbye event, Emitter<SessionClosureState> emit) async {
|
||||
emit(ClosureSubmitting());
|
||||
try {
|
||||
await apiClient.post('/api/shared/sessions/${event.sessionId}/close-message', data: {
|
||||
'message': event.message,
|
||||
});
|
||||
emit(ClosureComplete());
|
||||
} catch (e) {
|
||||
emit(ClosureError('Gagal mengirim pesan penutup.'));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,6 +12,16 @@ abstract class PairingEvent extends Equatable {
|
||||
}
|
||||
|
||||
class RequestPairing extends PairingEvent {}
|
||||
|
||||
class RequestPairingWithTier extends PairingEvent {
|
||||
final int? durationMinutes;
|
||||
final int? price;
|
||||
final bool isFreeTrial;
|
||||
RequestPairingWithTier({this.durationMinutes, this.price, this.isFreeTrial = false});
|
||||
@override
|
||||
List<Object?> get props => [durationMinutes, price, isFreeTrial];
|
||||
}
|
||||
|
||||
class CancelPairing extends PairingEvent {}
|
||||
|
||||
class _PairingStatusUpdate extends PairingEvent {
|
||||
@@ -71,29 +81,42 @@ class PairingBloc extends Bloc<PairingEvent, PairingState> {
|
||||
|
||||
PairingBloc({required this.apiClient}) : super(PairingInitial()) {
|
||||
on<RequestPairing>(_onRequestPairing);
|
||||
on<RequestPairingWithTier>(_onRequestPairingWithTier);
|
||||
on<CancelPairing>(_onCancelPairing);
|
||||
on<_PairingStatusUpdate>(_onStatusUpdate);
|
||||
on<_PairingTimeout>(_onTimeout);
|
||||
}
|
||||
|
||||
Future<void> _onRequestPairing(RequestPairing event, Emitter<PairingState> emit) async {
|
||||
// Reset to initial so BlocListener can detect new errors
|
||||
await _doPairingRequest(emit, {});
|
||||
}
|
||||
|
||||
Future<void> _onRequestPairingWithTier(RequestPairingWithTier event, Emitter<PairingState> emit) async {
|
||||
final body = <String, dynamic>{};
|
||||
if (event.isFreeTrial) {
|
||||
body['is_free_trial'] = true;
|
||||
} else {
|
||||
body['duration_minutes'] = event.durationMinutes;
|
||||
body['price'] = event.price;
|
||||
}
|
||||
await _doPairingRequest(emit, body);
|
||||
}
|
||||
|
||||
Future<void> _doPairingRequest(Emitter<PairingState> emit, Map<String, dynamic> body) async {
|
||||
if (state is! PairingInitial) {
|
||||
emit(PairingInitial());
|
||||
}
|
||||
try {
|
||||
final response = await apiClient.post('/api/client/chat/request');
|
||||
final response = await apiClient.post('/api/client/chat/request', data: body);
|
||||
final data = response['data'] as Map<String, dynamic>;
|
||||
final sessionId = data['id'] as String;
|
||||
|
||||
emit(PairingSearching(sessionId));
|
||||
|
||||
// Start 60s local timeout as a safety net
|
||||
_timeoutTimer = Timer(const Duration(seconds: 60), () {
|
||||
add(_PairingTimeout());
|
||||
});
|
||||
|
||||
// Listen to SSE for status updates
|
||||
_listenToSSE(sessionId);
|
||||
} on DioException catch (e) {
|
||||
final code = e.response?.data?['error']?['code'];
|
||||
@@ -101,6 +124,8 @@ class PairingBloc extends Bloc<PairingEvent, PairingState> {
|
||||
emit(PairingNoBestie());
|
||||
} else if (code == 'ALREADY_ACTIVE') {
|
||||
emit(PairingError('Kamu sudah memiliki sesi aktif.'));
|
||||
} else if (code == 'FREE_TRIAL_INELIGIBLE') {
|
||||
emit(PairingError('Kamu tidak memenuhi syarat untuk free trial.'));
|
||||
} else {
|
||||
emit(PairingError('Gagal memulai. Coba lagi.'));
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/api/api_client.dart';
|
||||
|
||||
class ChatHistoryScreen extends StatefulWidget {
|
||||
const ChatHistoryScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ChatHistoryScreen> createState() => _ChatHistoryScreenState();
|
||||
}
|
||||
|
||||
class _ChatHistoryScreenState extends State<ChatHistoryScreen> {
|
||||
List<Map<String, dynamic>> _sessions = [];
|
||||
bool _loading = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadHistory();
|
||||
}
|
||||
|
||||
Future<void> _loadHistory() async {
|
||||
try {
|
||||
final api = context.read<ApiClient>();
|
||||
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);
|
||||
}
|
||||
}
|
||||
|
||||
@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.builder(
|
||||
itemCount: _sessions.length,
|
||||
itemBuilder: (context, index) {
|
||||
final s = _sessions[index];
|
||||
final mitraName = s['mitra_display_name'] as String? ?? 'Bestie';
|
||||
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: Text(mitraName),
|
||||
subtitle: Text([
|
||||
if (endedAt != null) '${endedAt.day}/${endedAt.month}/${endedAt.year}',
|
||||
if (duration != null) '$duration menit',
|
||||
if (closureMsg != null) '"$closureMsg"',
|
||||
].join(' - ')),
|
||||
trailing: const Icon(Icons.chevron_right),
|
||||
onTap: () => context.push('/chat/history/${s['id']}'),
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
352
client_app/lib/features/chat/screens/chat_screen.dart
Normal file
352
client_app/lib/features/chat/screens/chat_screen.dart
Normal file
@@ -0,0 +1,352 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/chat/chat_bloc.dart';
|
||||
import '../../../core/chat/session_closure_bloc.dart';
|
||||
import '../widgets/pricing_bottom_sheet.dart';
|
||||
|
||||
class ChatScreen extends StatefulWidget {
|
||||
final String sessionId;
|
||||
final String mitraName;
|
||||
|
||||
const ChatScreen({super.key, required this.sessionId, required this.mitraName});
|
||||
|
||||
@override
|
||||
State<ChatScreen> createState() => _ChatScreenState();
|
||||
}
|
||||
|
||||
class _ChatScreenState extends State<ChatScreen> {
|
||||
final _messageController = TextEditingController();
|
||||
final _scrollController = ScrollController();
|
||||
Timer? _typingThrottle;
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_messageController.dispose();
|
||||
_scrollController.dispose();
|
||||
_typingThrottle?.cancel();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
void _scrollToBottom() {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (_scrollController.hasClients) {
|
||||
_scrollController.animateTo(
|
||||
_scrollController.position.maxScrollExtent,
|
||||
duration: const Duration(milliseconds: 200),
|
||||
curve: Curves.easeOut,
|
||||
);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _onTextChanged(String text) {
|
||||
if (_typingThrottle?.isActive ?? false) return;
|
||||
context.read<ChatBloc>().add(SendTyping());
|
||||
_typingThrottle = Timer(const Duration(seconds: 2), () {});
|
||||
}
|
||||
|
||||
void _sendMessage() {
|
||||
final text = _messageController.text.trim();
|
||||
if (text.isEmpty) return;
|
||||
context.read<ChatBloc>().add(SendMessage(text));
|
||||
_messageController.clear();
|
||||
_scrollToBottom();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return MultiBlocListener(
|
||||
listeners: [
|
||||
BlocListener<ChatBloc, ChatState>(
|
||||
listenWhen: (prev, curr) {
|
||||
if (prev is ChatConnected && curr is ChatConnected) {
|
||||
return prev.sessionExpired != curr.sessionExpired ||
|
||||
prev.sessionClosing != curr.sessionClosing ||
|
||||
prev.messages.length != curr.messages.length;
|
||||
}
|
||||
return true;
|
||||
},
|
||||
listener: (context, state) {
|
||||
if (state is ChatConnected) {
|
||||
if (state.sessionClosing) {
|
||||
context.read<SessionClosureBloc>().add(DeclineExtension());
|
||||
}
|
||||
_scrollToBottom();
|
||||
// Auto-mark received messages as read
|
||||
final unread = state.messages
|
||||
.where((m) => m.senderType == 'mitra' && m.status != 'read')
|
||||
.map((m) => m.id)
|
||||
.toList();
|
||||
if (unread.isNotEmpty) {
|
||||
context.read<ChatBloc>().add(MarkMessagesRead(unread));
|
||||
}
|
||||
}
|
||||
},
|
||||
),
|
||||
BlocListener<SessionClosureBloc, SessionClosureState>(
|
||||
listener: (context, state) {
|
||||
if (state is ClosureComplete) {
|
||||
context.go('/home');
|
||||
}
|
||||
},
|
||||
),
|
||||
],
|
||||
child: Scaffold(
|
||||
appBar: AppBar(
|
||||
title: Text(widget.mitraName),
|
||||
automaticallyImplyLeading: false,
|
||||
actions: [
|
||||
BlocBuilder<ChatBloc, ChatState>(
|
||||
builder: (context, state) {
|
||||
if (state is ChatConnected && state.remainingSeconds != null) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.only(right: 16),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'${state.remainingSeconds}s',
|
||||
style: TextStyle(
|
||||
color: state.remainingSeconds! < 30 ? Colors.red : null,
|
||||
fontWeight: FontWeight.bold,
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
body: BlocBuilder<ChatBloc, ChatState>(
|
||||
builder: (context, state) {
|
||||
if (state is ChatConnecting) {
|
||||
return const Center(child: CircularProgressIndicator());
|
||||
}
|
||||
if (state is ChatError) {
|
||||
return Center(child: Text(state.message));
|
||||
}
|
||||
if (state is ChatConnected) {
|
||||
return _buildChatBody(context, state);
|
||||
}
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildChatBody(BuildContext context, ChatConnected state) {
|
||||
// Show session expired dialog
|
||||
if (state.sessionExpired) {
|
||||
return _buildExpiredView(context);
|
||||
}
|
||||
|
||||
// Show goodbye input
|
||||
final closureState = context.watch<SessionClosureBloc>().state;
|
||||
if (closureState is ClosureShowGoodbye || closureState is ClosureSubmitting) {
|
||||
return _buildGoodbyeView(context, closureState);
|
||||
}
|
||||
|
||||
if (state.sessionPaused) {
|
||||
return _buildPausedView();
|
||||
}
|
||||
|
||||
return Column(
|
||||
children: [
|
||||
Expanded(
|
||||
child: ListView.builder(
|
||||
controller: _scrollController,
|
||||
padding: const EdgeInsets.all(16),
|
||||
itemCount: state.messages.length,
|
||||
itemBuilder: (context, index) {
|
||||
final msg = state.messages[index];
|
||||
final isMe = msg.senderType == 'customer';
|
||||
return _buildMessageBubble(msg, isMe);
|
||||
},
|
||||
),
|
||||
),
|
||||
if (state.isOtherTyping)
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 4),
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Text('Bestie sedang mengetik...', style: TextStyle(color: Colors.grey, fontSize: 12)),
|
||||
),
|
||||
),
|
||||
_buildInputBar(context, state),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildMessageBubble(ChatMessage msg, bool isMe) {
|
||||
return Align(
|
||||
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
|
||||
decoration: BoxDecoration(
|
||||
color: isMe ? Colors.blue.shade100 : Colors.grey.shade200,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(msg.content, style: const TextStyle(fontSize: 15)),
|
||||
const SizedBox(height: 4),
|
||||
Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Text(
|
||||
'${msg.createdAt.hour.toString().padLeft(2, '0')}:${msg.createdAt.minute.toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 10, color: Colors.grey),
|
||||
),
|
||||
if (isMe) ...[
|
||||
const SizedBox(width: 4),
|
||||
_buildStatusIcon(msg.status),
|
||||
],
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatusIcon(String status) {
|
||||
switch (status) {
|
||||
case 'sending':
|
||||
return const Icon(Icons.access_time, size: 14, color: Colors.grey);
|
||||
case 'sent':
|
||||
return const Icon(Icons.check, size: 14, color: Colors.grey);
|
||||
case 'delivered':
|
||||
return const Icon(Icons.done_all, size: 14, color: Colors.grey);
|
||||
case 'read':
|
||||
return const Icon(Icons.done_all, size: 14, color: Colors.blue);
|
||||
default:
|
||||
return const SizedBox.shrink();
|
||||
}
|
||||
}
|
||||
|
||||
Widget _buildInputBar(BuildContext context, ChatConnected state) {
|
||||
return SafeArea(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(8),
|
||||
child: Row(
|
||||
children: [
|
||||
Expanded(
|
||||
child: TextField(
|
||||
controller: _messageController,
|
||||
onChanged: _onTextChanged,
|
||||
textInputAction: TextInputAction.send,
|
||||
onSubmitted: (_) => _sendMessage(),
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Ketik pesan...',
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(24)),
|
||||
contentPadding: const EdgeInsets.symmetric(horizontal: 16, vertical: 10),
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.send, color: Colors.blue),
|
||||
onPressed: _sendMessage,
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildExpiredView(BuildContext context) {
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.timer_off, size: 64, color: Colors.orange),
|
||||
const SizedBox(height: 16),
|
||||
const Text('Waktu sesi habis', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('Apakah kamu ingin memperpanjang sesi?', textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: () => PricingBottomSheet.show(context),
|
||||
child: const Text('Perpanjang Sesi'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
TextButton(
|
||||
onPressed: () => context.read<SessionClosureBloc>().add(DeclineExtension()),
|
||||
child: const Text('Tidak, akhiri sesi'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildGoodbyeView(BuildContext context, SessionClosureState closureState) {
|
||||
final controller = TextEditingController();
|
||||
return Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
const Icon(Icons.waving_hand, size: 64, color: Colors.amber),
|
||||
const SizedBox(height: 16),
|
||||
const Text('Pesan Penutup', style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold)),
|
||||
const SizedBox(height: 8),
|
||||
const Text('Tuliskan pesan terakhirmu untuk Bestie', textAlign: TextAlign.center),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: controller,
|
||||
maxLines: 3,
|
||||
decoration: InputDecoration(
|
||||
hintText: 'Terima kasih, Bestie...',
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
onPressed: closureState is ClosureSubmitting
|
||||
? null
|
||||
: () {
|
||||
final text = controller.text.trim();
|
||||
if (text.isNotEmpty) {
|
||||
context.read<SessionClosureBloc>().add(
|
||||
SubmitGoodbye(sessionId: widget.sessionId, message: text),
|
||||
);
|
||||
}
|
||||
},
|
||||
child: closureState is ClosureSubmitting
|
||||
? const SizedBox(width: 20, height: 20, child: CircularProgressIndicator(strokeWidth: 2))
|
||||
: const Text('Kirim & Selesai'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildPausedView() {
|
||||
return const Center(
|
||||
child: Padding(
|
||||
padding: EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
CircularProgressIndicator(),
|
||||
SizedBox(height: 24),
|
||||
Text('Menunggu konfirmasi Bestie...', style: TextStyle(fontSize: 18)),
|
||||
SizedBox(height: 8),
|
||||
Text('Chat dijeda sementara', style: TextStyle(color: Colors.grey)),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/api/api_client.dart';
|
||||
|
||||
class ChatTranscriptScreen extends StatefulWidget {
|
||||
final String sessionId;
|
||||
|
||||
const ChatTranscriptScreen({super.key, required this.sessionId});
|
||||
|
||||
@override
|
||||
State<ChatTranscriptScreen> createState() => _ChatTranscriptScreenState();
|
||||
}
|
||||
|
||||
class _ChatTranscriptScreenState extends State<ChatTranscriptScreen> {
|
||||
List<Map<String, dynamic>> _messages = [];
|
||||
List<Map<String, dynamic>> _closures = [];
|
||||
bool _loading = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_loadTranscript();
|
||||
}
|
||||
|
||||
Future<void> _loadTranscript() async {
|
||||
try {
|
||||
final api = context.read<ApiClient>();
|
||||
final response = await api.get('/api/shared/chat/${widget.sessionId}/transcript');
|
||||
final data = response['data'] as Map<String, dynamic>;
|
||||
setState(() {
|
||||
_messages = (data['messages'] as List<dynamic>).cast<Map<String, dynamic>>();
|
||||
_closures = (data['closures'] as List<dynamic>).cast<Map<String, dynamic>>();
|
||||
_loading = false;
|
||||
});
|
||||
} catch (_) {
|
||||
setState(() => _loading = false);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Transkrip Chat')),
|
||||
body: _loading
|
||||
? const Center(child: CircularProgressIndicator())
|
||||
: ListView(
|
||||
padding: const EdgeInsets.all(16),
|
||||
children: [
|
||||
..._messages.map((m) {
|
||||
final isMe = m['sender_type'] == 'customer';
|
||||
final time = DateTime.parse(m['created_at'] as String).toLocal();
|
||||
return Align(
|
||||
alignment: isMe ? Alignment.centerRight : Alignment.centerLeft,
|
||||
child: Container(
|
||||
margin: const EdgeInsets.symmetric(vertical: 4),
|
||||
padding: const EdgeInsets.symmetric(horizontal: 14, vertical: 10),
|
||||
constraints: BoxConstraints(maxWidth: MediaQuery.of(context).size.width * 0.75),
|
||||
decoration: BoxDecoration(
|
||||
color: isMe ? Colors.blue.shade100 : Colors.grey.shade200,
|
||||
borderRadius: BorderRadius.circular(16),
|
||||
),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.end,
|
||||
children: [
|
||||
Text(m['content'] as String, style: const TextStyle(fontSize: 15)),
|
||||
const SizedBox(height: 4),
|
||||
Text(
|
||||
'${time.hour.toString().padLeft(2, '0')}:${time.minute.toString().padLeft(2, '0')}',
|
||||
style: const TextStyle(fontSize: 10, color: Colors.grey),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}),
|
||||
if (_closures.isNotEmpty) ...[
|
||||
const Divider(height: 32),
|
||||
const Text('Pesan Penutup', style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16)),
|
||||
const SizedBox(height: 8),
|
||||
..._closures.map((c) => Card(
|
||||
child: ListTile(
|
||||
title: Text(c['user_type'] == 'customer' ? 'Kamu' : 'Bestie'),
|
||||
subtitle: Text(c['message'] as String),
|
||||
),
|
||||
)),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
119
client_app/lib/features/chat/widgets/pricing_bottom_sheet.dart
Normal file
119
client_app/lib/features/chat/widgets/pricing_bottom_sheet.dart
Normal file
@@ -0,0 +1,119 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/api/api_client.dart';
|
||||
import '../../../core/chat/chat_opening_bloc.dart';
|
||||
import '../../../core/pairing/pairing_bloc.dart';
|
||||
|
||||
class PricingBottomSheet extends StatelessWidget {
|
||||
const PricingBottomSheet({super.key});
|
||||
|
||||
static Future<void> show(BuildContext context) {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (_) => BlocProvider(
|
||||
create: (ctx) => ChatOpeningBloc(apiClient: ctx.read<ApiClient>())..add(LoadPricing()),
|
||||
child: const PricingBottomSheet(),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
String _formatPrice(int price) {
|
||||
final str = price.toString();
|
||||
final buffer = StringBuffer();
|
||||
for (var i = 0; i < str.length; i++) {
|
||||
if (i > 0 && (str.length - i) % 3 == 0) buffer.write('.');
|
||||
buffer.write(str[i]);
|
||||
}
|
||||
return 'Rp $buffer';
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocBuilder<ChatOpeningBloc, ChatOpeningState>(
|
||||
builder: (context, state) {
|
||||
if (state is PricingLoading || state is PricingInitial) {
|
||||
return const SizedBox(
|
||||
height: 200,
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
);
|
||||
}
|
||||
|
||||
if (state is PricingError) {
|
||||
return SizedBox(
|
||||
height: 200,
|
||||
child: Center(child: Text(state.message)),
|
||||
);
|
||||
}
|
||||
|
||||
if (state is PricingLoaded) {
|
||||
return DraggableScrollableSheet(
|
||||
initialChildSize: 0.6,
|
||||
minChildSize: 0.4,
|
||||
maxChildSize: 0.8,
|
||||
expand: false,
|
||||
builder: (_, scrollController) {
|
||||
return Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: ListView(
|
||||
controller: scrollController,
|
||||
children: [
|
||||
const Text(
|
||||
'Pilih Durasi Curhat',
|
||||
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (state.freeTrialEligible) ...[
|
||||
Card(
|
||||
color: Colors.green.shade50,
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.card_giftcard, color: Colors.green),
|
||||
title: Text('Free Trial (${state.freeTrialDurationMinutes} Menit)'),
|
||||
subtitle: const Text('Gratis untuk pertama kali!'),
|
||||
trailing: const Icon(Icons.arrow_forward_ios, size: 16),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
_startPairing(context, isFreeTrial: true);
|
||||
},
|
||||
),
|
||||
),
|
||||
const Divider(height: 24),
|
||||
],
|
||||
...state.tiers.map((tier) => Card(
|
||||
child: ListTile(
|
||||
title: Text(tier.label),
|
||||
trailing: Text(
|
||||
_formatPrice(tier.price),
|
||||
style: const TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
|
||||
),
|
||||
onTap: () {
|
||||
Navigator.of(context).pop();
|
||||
_startPairing(
|
||||
context,
|
||||
durationMinutes: tier.durationMinutes,
|
||||
price: tier.price,
|
||||
);
|
||||
},
|
||||
),
|
||||
)),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
void _startPairing(BuildContext context, {bool isFreeTrial = false, int? durationMinutes, int? price}) {
|
||||
context.read<PairingBloc>().add(RequestPairingWithTier(
|
||||
durationMinutes: durationMinutes,
|
||||
price: price,
|
||||
isFreeTrial: isFreeTrial,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../core/auth/auth_bloc.dart';
|
||||
import '../../core/pairing/pairing_bloc.dart';
|
||||
import '../chat/widgets/pricing_bottom_sheet.dart';
|
||||
|
||||
class HomeScreen extends StatelessWidget {
|
||||
const HomeScreen({super.key});
|
||||
@@ -33,6 +34,10 @@ class HomeScreen extends StatelessWidget {
|
||||
appBar: AppBar(
|
||||
title: const Text('Halo Bestie'),
|
||||
actions: [
|
||||
IconButton(
|
||||
icon: const Icon(Icons.history),
|
||||
onPressed: () => context.push('/chat/history'),
|
||||
),
|
||||
IconButton(
|
||||
icon: const Icon(Icons.logout),
|
||||
onPressed: () => context.read<AuthBloc>().add(LogoutRequested()),
|
||||
@@ -51,7 +56,7 @@ class HomeScreen extends StatelessWidget {
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
|
||||
),
|
||||
onPressed: () => context.read<PairingBloc>().add(RequestPairing()),
|
||||
onPressed: () => PricingBottomSheet.show(context),
|
||||
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
],
|
||||
|
||||
@@ -1,9 +1,12 @@
|
||||
import 'package:firebase_core/firebase_core.dart';
|
||||
import 'package:firebase_messaging/firebase_messaging.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'core/api/api_client.dart';
|
||||
import 'core/auth/auth_bloc.dart';
|
||||
import 'core/chat/chat_bloc.dart';
|
||||
import 'core/chat/session_closure_bloc.dart';
|
||||
import 'core/pairing/pairing_bloc.dart';
|
||||
import 'firebase_options.dart';
|
||||
import 'router.dart';
|
||||
@@ -11,6 +14,11 @@ import 'router.dart';
|
||||
void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
|
||||
// Request notification permission
|
||||
final messaging = FirebaseMessaging.instance;
|
||||
await messaging.requestPermission();
|
||||
|
||||
runApp(const App());
|
||||
}
|
||||
|
||||
@@ -31,6 +39,21 @@ class _AppState extends State<App> {
|
||||
super.initState();
|
||||
_authBloc = AuthBloc(apiClient: _apiClient)..add(AppStarted());
|
||||
_router = buildRouter(_authBloc);
|
||||
_registerFcmToken();
|
||||
}
|
||||
|
||||
Future<void> _registerFcmToken() async {
|
||||
// Listen for auth state, then register token
|
||||
_authBloc.stream.listen((state) async {
|
||||
if (state is AuthAuthenticated || state is AuthAnonymous) {
|
||||
try {
|
||||
final token = await FirebaseMessaging.instance.getToken();
|
||||
if (token != null) {
|
||||
await _apiClient.post('/api/shared/device-token', data: {'token': token});
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -46,6 +69,8 @@ class _AppState extends State<App> {
|
||||
providers: [
|
||||
BlocProvider.value(value: _authBloc),
|
||||
BlocProvider(create: (_) => PairingBloc(apiClient: _apiClient)),
|
||||
BlocProvider(create: (_) => ChatBloc(apiClient: _apiClient)),
|
||||
BlocProvider(create: (_) => SessionClosureBloc(apiClient: _apiClient)),
|
||||
RepositoryProvider.value(value: _apiClient),
|
||||
],
|
||||
child: MaterialApp.router(
|
||||
|
||||
@@ -11,7 +11,9 @@ import 'features/home/home_screen.dart';
|
||||
import 'features/chat/screens/searching_screen.dart';
|
||||
import 'features/chat/screens/bestie_found_screen.dart';
|
||||
import 'features/chat/screens/no_bestie_screen.dart';
|
||||
import 'features/chat/screens/session_active_screen.dart';
|
||||
import 'features/chat/screens/chat_screen.dart';
|
||||
import 'features/chat/screens/chat_history_screen.dart';
|
||||
import 'features/chat/screens/chat_transcript_screen.dart';
|
||||
|
||||
/// Converts a BLoC stream into a ChangeNotifier for GoRouter's refreshListenable.
|
||||
class _BlocRefreshNotifier extends ChangeNotifier {
|
||||
@@ -64,11 +66,16 @@ GoRouter buildRouter(AuthBloc authBloc) {
|
||||
}),
|
||||
GoRoute(path: '/chat/no-bestie', builder: (_, __) => const NoBestieScreen()),
|
||||
GoRoute(path: '/chat/session/:sessionId', builder: (context, state) {
|
||||
return SessionActiveScreen(
|
||||
final extra = state.extra as Map<String, dynamic>?;
|
||||
return ChatScreen(
|
||||
sessionId: state.pathParameters['sessionId']!,
|
||||
mitraName: state.extra as String? ?? 'Bestie',
|
||||
mitraName: extra?['mitraName'] as String? ?? 'Bestie',
|
||||
);
|
||||
}),
|
||||
GoRoute(path: '/chat/history', builder: (_, __) => const ChatHistoryScreen()),
|
||||
GoRoute(path: '/chat/history/:sessionId', builder: (context, state) {
|
||||
return ChatTranscriptScreen(sessionId: state.pathParameters['sessionId']!);
|
||||
}),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import Foundation
|
||||
|
||||
import firebase_auth
|
||||
import firebase_core
|
||||
import firebase_messaging
|
||||
import google_sign_in_ios
|
||||
import shared_preferences_foundation
|
||||
import sign_in_with_apple
|
||||
@@ -14,6 +15,7 @@ import sign_in_with_apple
|
||||
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
|
||||
FLTFirebaseAuthPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseAuthPlugin"))
|
||||
FLTFirebaseCorePlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseCorePlugin"))
|
||||
FLTFirebaseMessagingPlugin.register(with: registry.registrar(forPlugin: "FLTFirebaseMessagingPlugin"))
|
||||
FLTGoogleSignInPlugin.register(with: registry.registrar(forPlugin: "FLTGoogleSignInPlugin"))
|
||||
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
|
||||
SignInWithApplePlugin.register(with: registry.registrar(forPlugin: "SignInWithApplePlugin"))
|
||||
|
||||
@@ -57,6 +57,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "1.19.1"
|
||||
crypto:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: crypto
|
||||
sha256: c8ea0233063ba03258fbcf2ca4d6dadfefe14f02fab57702265467a19f27fadf
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.0.7"
|
||||
dio:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -153,6 +161,30 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.17.5"
|
||||
firebase_messaging:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: firebase_messaging
|
||||
sha256: a1662cc95d9750a324ad9df349b873360af6f11414902021f130c68ec02267c4
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "14.9.4"
|
||||
firebase_messaging_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_messaging_platform_interface
|
||||
sha256: "87c4a922cb6f811cfb7a889bdbb3622702443c52a0271636cbc90d813ceac147"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "4.5.37"
|
||||
firebase_messaging_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: firebase_messaging_web
|
||||
sha256: "0d34dca01a7b103ed7f20138bffbb28eb0e61a677bf9e78a028a932e2c7322d5"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "3.8.7"
|
||||
flutter:
|
||||
dependency: "direct main"
|
||||
description: flutter
|
||||
@@ -557,6 +589,14 @@ packages:
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "0.5.1"
|
||||
web_socket_channel:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: web_socket_channel
|
||||
sha256: "58c6666b342a38816b2e7e50ed0f1e261959630becd4c879c4f26bfa14aa5a42"
|
||||
url: "https://pub.dev"
|
||||
source: hosted
|
||||
version: "2.4.5"
|
||||
xdg_directories:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -14,13 +14,15 @@ dependencies:
|
||||
# Firebase
|
||||
firebase_core: ^2.27.1
|
||||
firebase_auth: ^4.18.0
|
||||
firebase_messaging: ^14.7.15
|
||||
|
||||
# Social login
|
||||
google_sign_in: ^6.2.1
|
||||
sign_in_with_apple: ^6.1.0
|
||||
|
||||
# HTTP
|
||||
# HTTP & WebSocket
|
||||
dio: ^5.4.3
|
||||
web_socket_channel: ^2.4.5
|
||||
|
||||
# State management
|
||||
flutter_bloc: ^8.1.5
|
||||
|
||||
Reference in New Issue
Block a user