Phase 3.1 WIP: Riverpod migration (client_app Auth + ChatOpening)
- Add phase3.1 requirement and implementation plan docs - Add Riverpod dependencies to both client_app and mitra_app - Wrap both app roots with ProviderScope - Migrate client_app AuthBloc → AuthNotifier (@riverpod annotation) - Migrate client_app ChatOpeningBloc → chatPricingProvider (FutureProvider) - Update router to use Riverpod-based auth state for redirects - Update all auth screens (display name, register, OTP, force register) - Update home screen and pricing bottom sheet - Add android:usesCleartextTraffic for dev HTTP access on both apps - mitra_app prepared with ProviderScope + ApiClient provider (blocs next) Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
8
client_app/lib/core/api/api_client_provider.dart
Normal file
8
client_app/lib/core/api/api_client_provider.dart
Normal file
@@ -0,0 +1,8 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'api_client.dart';
|
||||
|
||||
part 'api_client_provider.g.dart';
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
ApiClient apiClient(Ref ref) => ApiClient();
|
||||
26
client_app/lib/core/api/api_client_provider.g.dart
Normal file
26
client_app/lib/core/api/api_client_provider.g.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'api_client_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$apiClientHash() => r'90c807f03b90249684265cc91739139c2c89eeb9';
|
||||
|
||||
/// See also [apiClient].
|
||||
@ProviderFor(apiClient)
|
||||
final apiClientProvider = Provider<ApiClient>.internal(
|
||||
apiClient,
|
||||
name: r'apiClientProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$apiClientHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef ApiClientRef = ProviderRef<ApiClient>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
198
client_app/lib/core/auth/auth_notifier.dart
Normal file
198
client_app/lib/core/auth/auth_notifier.dart
Normal file
@@ -0,0 +1,198 @@
|
||||
import 'dart:async';
|
||||
import 'package:firebase_auth/firebase_auth.dart';
|
||||
import 'package:google_sign_in/google_sign_in.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import 'package:shared_preferences/shared_preferences.dart';
|
||||
import 'package:sign_in_with_apple/sign_in_with_apple.dart';
|
||||
import '../api/api_client.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
|
||||
part 'auth_notifier.g.dart';
|
||||
|
||||
// States
|
||||
sealed class AuthData {
|
||||
const AuthData();
|
||||
}
|
||||
|
||||
class AuthInitialData extends AuthData {
|
||||
const AuthInitialData();
|
||||
}
|
||||
|
||||
class AuthAuthenticatedData extends AuthData {
|
||||
final Map<String, dynamic> profile;
|
||||
const AuthAuthenticatedData(this.profile);
|
||||
}
|
||||
|
||||
class AuthAnonymousData extends AuthData {
|
||||
final String customerId;
|
||||
final String displayName;
|
||||
const AuthAnonymousData({required this.customerId, required this.displayName});
|
||||
}
|
||||
|
||||
class AuthOtpSentData extends AuthData {
|
||||
final String verificationId;
|
||||
const AuthOtpSentData(this.verificationId);
|
||||
}
|
||||
|
||||
class AuthForceRegisterData extends AuthData {
|
||||
final String customerId;
|
||||
final String displayName;
|
||||
const AuthForceRegisterData({required this.customerId, required this.displayName});
|
||||
}
|
||||
|
||||
@Riverpod(keepAlive: true)
|
||||
class Auth extends _$Auth {
|
||||
FirebaseAuth get _auth => FirebaseAuth.instance;
|
||||
ApiClient get _apiClient => ref.read(apiClientProvider);
|
||||
|
||||
@override
|
||||
FutureOr<AuthData> build() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final customerId = prefs.getString('anonymous_customer_id');
|
||||
final displayName = prefs.getString('anonymous_display_name');
|
||||
final currentUser = _auth.currentUser;
|
||||
|
||||
if (currentUser != null && currentUser.isAnonymous && customerId != null && displayName != null) {
|
||||
try {
|
||||
final config = await _apiClient.get('/api/shared/config/anonymity');
|
||||
final anonymityEnabled = config['data']['anonymity_enabled'] as bool;
|
||||
if (!anonymityEnabled) {
|
||||
return AuthForceRegisterData(customerId: customerId, displayName: displayName);
|
||||
}
|
||||
return AuthAnonymousData(customerId: customerId, displayName: displayName);
|
||||
} catch (_) {
|
||||
return AuthAnonymousData(customerId: customerId, displayName: displayName);
|
||||
}
|
||||
} else if (currentUser != null && !currentUser.isAnonymous) {
|
||||
return await _verifyAndReturn();
|
||||
}
|
||||
return const AuthInitialData();
|
||||
}
|
||||
|
||||
Future<void> loginAnonymous(String displayName) async {
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
await _auth.signInAnonymously();
|
||||
final response = await _apiClient.post(
|
||||
'/api/shared/customer/anonymous',
|
||||
data: {'display_name': displayName},
|
||||
);
|
||||
final customer = response['data'] as Map<String, dynamic>;
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.setString('anonymous_customer_id', customer['id'] as String);
|
||||
await prefs.setString('anonymous_display_name', customer['display_name'] as String);
|
||||
state = AsyncData(AuthAnonymousData(
|
||||
customerId: customer['id'] as String,
|
||||
displayName: customer['display_name'] as String,
|
||||
));
|
||||
} catch (e) {
|
||||
state = AsyncError('Failed to continue as guest. Please try again.', StackTrace.current);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> loginGoogle() async {
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
final googleUser = await GoogleSignIn().signIn();
|
||||
if (googleUser == null) {
|
||||
state = const AsyncData(AuthInitialData());
|
||||
return;
|
||||
}
|
||||
final googleAuth = await googleUser.authentication;
|
||||
final credential = GoogleAuthProvider.credential(
|
||||
accessToken: googleAuth.accessToken,
|
||||
idToken: googleAuth.idToken,
|
||||
);
|
||||
await _auth.signInWithCredential(credential);
|
||||
state = AsyncData(await _verifyAndReturn());
|
||||
} catch (e) {
|
||||
state = AsyncError('Google sign-in failed. Please try again.', StackTrace.current);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> loginApple() async {
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
final appleCredential = await SignInWithApple.getAppleIDCredential(
|
||||
scopes: [AppleIDAuthorizationScopes.email],
|
||||
);
|
||||
final oauthCredential = OAuthProvider('apple.com').credential(
|
||||
idToken: appleCredential.identityToken,
|
||||
accessToken: appleCredential.authorizationCode,
|
||||
);
|
||||
await _auth.signInWithCredential(oauthCredential);
|
||||
state = AsyncData(await _verifyAndReturn());
|
||||
} catch (e) {
|
||||
state = AsyncError('Apple sign-in failed. Please try again.', StackTrace.current);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> requestOtp(String phone) async {
|
||||
state = const AsyncLoading();
|
||||
final completer = Completer<void>();
|
||||
await _auth.verifyPhoneNumber(
|
||||
phoneNumber: phone,
|
||||
verificationCompleted: (_) {
|
||||
if (!completer.isCompleted) completer.complete();
|
||||
},
|
||||
verificationFailed: (e) {
|
||||
state = AsyncError('Failed to send OTP. Please try again.', StackTrace.current);
|
||||
if (!completer.isCompleted) completer.complete();
|
||||
},
|
||||
codeSent: (verificationId, _) {
|
||||
state = AsyncData(AuthOtpSentData(verificationId));
|
||||
if (!completer.isCompleted) completer.complete();
|
||||
},
|
||||
codeAutoRetrievalTimeout: (_) {
|
||||
if (!completer.isCompleted) completer.complete();
|
||||
},
|
||||
);
|
||||
await completer.future;
|
||||
}
|
||||
|
||||
Future<void> verifyOtp(String verificationId, String smsCode) async {
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
final credential = PhoneAuthProvider.credential(
|
||||
verificationId: verificationId,
|
||||
smsCode: smsCode,
|
||||
);
|
||||
await _auth.signInWithCredential(credential);
|
||||
state = AsyncData(await _verifyAndReturn());
|
||||
} catch (e) {
|
||||
state = AsyncError('Invalid OTP. Please try again.', StackTrace.current);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> linkAccount() async {
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
final customerId = prefs.getString('anonymous_customer_id');
|
||||
if (customerId == null || _auth.currentUser == null) return;
|
||||
|
||||
state = const AsyncLoading();
|
||||
try {
|
||||
await _apiClient.post('/api/shared/customer/link', data: {
|
||||
'customer_id': customerId,
|
||||
'firebase_uid': _auth.currentUser!.uid,
|
||||
});
|
||||
await prefs.remove('anonymous_customer_id');
|
||||
await prefs.remove('anonymous_display_name');
|
||||
state = AsyncData(await _verifyAndReturn());
|
||||
} catch (e) {
|
||||
state = AsyncError('Failed to link account. Please try again.', StackTrace.current);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> logout() async {
|
||||
await _auth.signOut();
|
||||
final prefs = await SharedPreferences.getInstance();
|
||||
await prefs.remove('anonymous_customer_id');
|
||||
await prefs.remove('anonymous_display_name');
|
||||
state = const AsyncData(AuthInitialData());
|
||||
}
|
||||
|
||||
Future<AuthData> _verifyAndReturn() async {
|
||||
final response = await _apiClient.post('/api/client/auth/verify');
|
||||
return AuthAuthenticatedData(response['data'] as Map<String, dynamic>);
|
||||
}
|
||||
}
|
||||
24
client_app/lib/core/auth/auth_notifier.g.dart
Normal file
24
client_app/lib/core/auth/auth_notifier.g.dart
Normal file
@@ -0,0 +1,24 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'auth_notifier.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$authHash() => r'8cb877e94ccf4366b574ffe8c8b4b63321340b6d';
|
||||
|
||||
/// See also [Auth].
|
||||
@ProviderFor(Auth)
|
||||
final authProvider = AsyncNotifierProvider<Auth, AuthData>.internal(
|
||||
Auth.new,
|
||||
name: r'authProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$authHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
typedef _$Auth = AsyncNotifier<AuthData>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
49
client_app/lib/core/chat/chat_opening_provider.dart
Normal file
49
client_app/lib/core/chat/chat_opening_provider.dart
Normal file
@@ -0,0 +1,49 @@
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:riverpod_annotation/riverpod_annotation.dart';
|
||||
import '../api/api_client_provider.dart';
|
||||
|
||||
part 'chat_opening_provider.g.dart';
|
||||
|
||||
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,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
class PricingData {
|
||||
final List<PriceTier> tiers;
|
||||
final bool freeTrialEligible;
|
||||
final int freeTrialDurationMinutes;
|
||||
|
||||
const PricingData({
|
||||
required this.tiers,
|
||||
required this.freeTrialEligible,
|
||||
this.freeTrialDurationMinutes = 5,
|
||||
});
|
||||
}
|
||||
|
||||
@riverpod
|
||||
Future<PricingData> chatPricing(Ref ref) async {
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
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>;
|
||||
|
||||
return PricingData(
|
||||
tiers: tiers,
|
||||
freeTrialEligible: freeTrial['eligible'] as bool? ?? false,
|
||||
freeTrialDurationMinutes: freeTrial['duration_minutes'] as int? ?? 5,
|
||||
);
|
||||
}
|
||||
26
client_app/lib/core/chat/chat_opening_provider.g.dart
Normal file
26
client_app/lib/core/chat/chat_opening_provider.g.dart
Normal file
@@ -0,0 +1,26 @@
|
||||
// GENERATED CODE - DO NOT MODIFY BY HAND
|
||||
|
||||
part of 'chat_opening_provider.dart';
|
||||
|
||||
// **************************************************************************
|
||||
// RiverpodGenerator
|
||||
// **************************************************************************
|
||||
|
||||
String _$chatPricingHash() => r'53ca829d46f7ba3b481e7a6b54482c62f9fe3ad0';
|
||||
|
||||
/// See also [chatPricing].
|
||||
@ProviderFor(chatPricing)
|
||||
final chatPricingProvider = AutoDisposeFutureProvider<PricingData>.internal(
|
||||
chatPricing,
|
||||
name: r'chatPricingProvider',
|
||||
debugGetCreateSourceHash:
|
||||
const bool.fromEnvironment('dart.vm.product') ? null : _$chatPricingHash,
|
||||
dependencies: null,
|
||||
allTransitiveDependencies: null,
|
||||
);
|
||||
|
||||
@Deprecated('Will be removed in 3.0. Use Ref instead')
|
||||
// ignore: unused_element
|
||||
typedef ChatPricingRef = AutoDisposeFutureProviderRef<PricingData>;
|
||||
// ignore_for_file: type=lint
|
||||
// ignore_for_file: subtype_of_sealed_class, invalid_use_of_internal_member, invalid_use_of_visible_for_testing_member, deprecated_member_use_from_same_package
|
||||
@@ -1,15 +1,15 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/auth/auth_bloc.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/auth/auth_notifier.dart';
|
||||
|
||||
class DisplayNameScreen extends StatefulWidget {
|
||||
class DisplayNameScreen extends ConsumerStatefulWidget {
|
||||
const DisplayNameScreen({super.key});
|
||||
|
||||
@override
|
||||
State<DisplayNameScreen> createState() => _DisplayNameScreenState();
|
||||
ConsumerState<DisplayNameScreen> createState() => _DisplayNameScreenState();
|
||||
}
|
||||
|
||||
class _DisplayNameScreenState extends State<DisplayNameScreen> {
|
||||
class _DisplayNameScreenState extends ConsumerState<DisplayNameScreen> {
|
||||
final _controller = TextEditingController();
|
||||
|
||||
@override
|
||||
@@ -21,46 +21,46 @@ class _DisplayNameScreenState extends State<DisplayNameScreen> {
|
||||
void _submit() {
|
||||
final name = _controller.text.trim();
|
||||
if (name.isEmpty) return;
|
||||
context.read<AuthBloc>().add(AnonymousLoginRequested(name));
|
||||
ref.read(authProvider.notifier).loginAnonymous(name);
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(state.message)));
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(title: const Text('Siapa namamu?')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text('Pilih nama yang ingin kamu gunakan. Nama ini tidak akan terlihat oleh siapapun selain mitra kamu.'),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nama panggilan',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _submit(),
|
||||
final authState = ref.watch(authProvider);
|
||||
final isLoading = authState is AsyncLoading;
|
||||
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
if (next is AsyncError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Siapa namamu?')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text('Pilih nama yang ingin kamu gunakan. Nama ini tidak akan terlihat oleh siapapun selain mitra kamu.'),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _controller,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nama panggilan',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton(
|
||||
onPressed: state is AuthLoading ? null : _submit,
|
||||
child: state is AuthLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Lanjut'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
textInputAction: TextInputAction.done,
|
||||
onSubmitted: (_) => _submit(),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton(
|
||||
onPressed: isLoading ? null : _submit,
|
||||
child: isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Lanjut'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/auth/auth_bloc.dart';
|
||||
import '../../../core/auth/auth_notifier.dart';
|
||||
|
||||
/// Shown when anonymity is disabled by admin.
|
||||
/// User must link their account. Display name is pre-filled.
|
||||
class ForceRegisterScreen extends StatefulWidget {
|
||||
class ForceRegisterScreen extends ConsumerStatefulWidget {
|
||||
const ForceRegisterScreen({super.key});
|
||||
|
||||
@override
|
||||
State<ForceRegisterScreen> createState() => _ForceRegisterScreenState();
|
||||
ConsumerState<ForceRegisterScreen> createState() => _ForceRegisterScreenState();
|
||||
}
|
||||
|
||||
class _ForceRegisterScreenState extends State<ForceRegisterScreen> {
|
||||
class _ForceRegisterScreenState extends ConsumerState<ForceRegisterScreen> {
|
||||
final _phoneController = TextEditingController();
|
||||
|
||||
@override
|
||||
@@ -23,80 +23,77 @@ class _ForceRegisterScreenState extends State<ForceRegisterScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthOtpSent) {
|
||||
context.push('/auth/otp', extra: _phoneController.text.trim());
|
||||
}
|
||||
if (state is AuthAuthenticated) {
|
||||
// After linking, link account to existing anonymous record
|
||||
context.read<AuthBloc>().add(LinkAccountRequested());
|
||||
}
|
||||
if (state is AuthError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(state.message)));
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(title: const Text('Verifikasi Akun')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Untuk melanjutkan, kamu perlu mendaftarkan akun.',
|
||||
style: TextStyle(fontSize: 16),
|
||||
final authState = ref.watch(authProvider);
|
||||
final isLoading = authState is AsyncLoading;
|
||||
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
final data = next.valueOrNull;
|
||||
if (data is AuthOtpSentData) {
|
||||
context.push('/auth/otp', extra: _phoneController.text.trim());
|
||||
}
|
||||
if (data is AuthAuthenticatedData) {
|
||||
// After social login succeeds, link account to existing anonymous record
|
||||
ref.read(authProvider.notifier).linkAccount();
|
||||
}
|
||||
if (next is AsyncError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Verifikasi Akun')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
const Text(
|
||||
'Untuk melanjutkan, kamu perlu mendaftarkan akun.',
|
||||
style: TextStyle(fontSize: 16),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.g_mobiledata),
|
||||
onPressed: isLoading ? null
|
||||
: () => ref.read(authProvider.notifier).loginGoogle(),
|
||||
label: const Text('Lanjut dengan Google'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.apple),
|
||||
onPressed: isLoading ? null
|
||||
: () => ref.read(authProvider.notifier).loginApple(),
|
||||
label: const Text('Lanjut dengan Apple'),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Row(children: [
|
||||
Expanded(child: Divider()),
|
||||
Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Text('atau')),
|
||||
Expanded(child: Divider()),
|
||||
]),
|
||||
),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nomor HP',
|
||||
hintText: '+628xxxxxxxxxx',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton.icon(
|
||||
icon: const Icon(Icons.g_mobiledata),
|
||||
onPressed: state is AuthLoading ? null
|
||||
: () => context.read<AuthBloc>().add(GoogleLoginRequested()),
|
||||
label: const Text('Lanjut dengan Google'),
|
||||
),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton.icon(
|
||||
icon: const Icon(Icons.apple),
|
||||
onPressed: state is AuthLoading ? null
|
||||
: () => context.read<AuthBloc>().add(AppleLoginRequested()),
|
||||
label: const Text('Lanjut dengan Apple'),
|
||||
),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Row(children: [
|
||||
Expanded(child: Divider()),
|
||||
Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Text('atau')),
|
||||
Expanded(child: Divider()),
|
||||
]),
|
||||
),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nomor HP',
|
||||
hintText: '+628xxxxxxxxxx',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton(
|
||||
onPressed: state is AuthLoading ? null : () {
|
||||
final phone = _phoneController.text.trim();
|
||||
if (phone.isEmpty) return;
|
||||
context.read<AuthBloc>().add(PhoneOtpRequested(phone));
|
||||
},
|
||||
child: state is AuthLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Kirim OTP'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton(
|
||||
onPressed: isLoading ? null : () {
|
||||
final phone = _phoneController.text.trim();
|
||||
if (phone.isEmpty) return;
|
||||
ref.read(authProvider.notifier).requestOtp(phone);
|
||||
},
|
||||
child: isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Kirim OTP'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,17 +1,28 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import '../../../core/auth/auth_bloc.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/auth/auth_notifier.dart';
|
||||
|
||||
class OtpScreen extends StatefulWidget {
|
||||
class OtpScreen extends ConsumerStatefulWidget {
|
||||
final String phone;
|
||||
const OtpScreen({super.key, required this.phone});
|
||||
|
||||
@override
|
||||
State<OtpScreen> createState() => _OtpScreenState();
|
||||
ConsumerState<OtpScreen> createState() => _OtpScreenState();
|
||||
}
|
||||
|
||||
class _OtpScreenState extends State<OtpScreen> {
|
||||
class _OtpScreenState extends ConsumerState<OtpScreen> {
|
||||
final _otpController = TextEditingController();
|
||||
String? _verificationId;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
// Capture verification ID from current state
|
||||
final data = ref.read(authProvider).valueOrNull;
|
||||
if (data is AuthOtpSentData) {
|
||||
_verificationId = data.verificationId;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
@@ -21,46 +32,51 @@ class _OtpScreenState extends State<OtpScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(state.message)));
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(title: const Text('Masukkan OTP')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Kode OTP telah dikirim ke ${widget.phone}'),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _otpController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Kode OTP',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
final authState = ref.watch(authProvider);
|
||||
final isLoading = authState is AsyncLoading;
|
||||
|
||||
// Update verification ID if state changes
|
||||
final data = authState.valueOrNull;
|
||||
if (data is AuthOtpSentData) {
|
||||
_verificationId = data.verificationId;
|
||||
}
|
||||
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
if (next is AsyncError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Masukkan OTP')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
Text('Kode OTP telah dikirim ke ${widget.phone}'),
|
||||
const SizedBox(height: 24),
|
||||
TextField(
|
||||
controller: _otpController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Kode OTP',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton(
|
||||
onPressed: state is AuthLoading ? null : () {
|
||||
final otp = _otpController.text.trim();
|
||||
if (otp.length != 6) return;
|
||||
final verificationId = (state is AuthOtpSent) ? state.verificationId : '';
|
||||
context.read<AuthBloc>().add(OtpVerified(verificationId, otp));
|
||||
},
|
||||
child: state is AuthLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Verifikasi'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
keyboardType: TextInputType.number,
|
||||
maxLength: 6,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton(
|
||||
onPressed: isLoading ? null : () {
|
||||
final otp = _otpController.text.trim();
|
||||
if (otp.length != 6 || _verificationId == null) return;
|
||||
ref.read(authProvider.notifier).verifyOtp(_verificationId!, otp);
|
||||
},
|
||||
child: isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Verifikasi'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,16 +1,16 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../../core/auth/auth_bloc.dart';
|
||||
import '../../../core/auth/auth_notifier.dart';
|
||||
|
||||
class RegisterScreen extends StatefulWidget {
|
||||
class RegisterScreen extends ConsumerStatefulWidget {
|
||||
const RegisterScreen({super.key});
|
||||
|
||||
@override
|
||||
State<RegisterScreen> createState() => _RegisterScreenState();
|
||||
ConsumerState<RegisterScreen> createState() => _RegisterScreenState();
|
||||
}
|
||||
|
||||
class _RegisterScreenState extends State<RegisterScreen> {
|
||||
class _RegisterScreenState extends ConsumerState<RegisterScreen> {
|
||||
final _phoneController = TextEditingController();
|
||||
|
||||
@override
|
||||
@@ -21,71 +21,68 @@ class _RegisterScreenState extends State<RegisterScreen> {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return BlocListener<AuthBloc, AuthState>(
|
||||
listener: (context, state) {
|
||||
if (state is AuthOtpSent) {
|
||||
context.push('/auth/otp', extra: _phoneController.text.trim());
|
||||
}
|
||||
if (state is AuthError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(state.message)));
|
||||
}
|
||||
},
|
||||
child: Scaffold(
|
||||
appBar: AppBar(title: const Text('Masuk / Daftar')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton.icon(
|
||||
icon: const Icon(Icons.g_mobiledata),
|
||||
onPressed: state is AuthLoading ? null
|
||||
: () => context.read<AuthBloc>().add(GoogleLoginRequested()),
|
||||
label: const Text('Lanjut dengan Google'),
|
||||
),
|
||||
final authState = ref.watch(authProvider);
|
||||
final isLoading = authState is AsyncLoading;
|
||||
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
final data = next.valueOrNull;
|
||||
if (data is AuthOtpSentData) {
|
||||
context.push('/auth/otp', extra: _phoneController.text.trim());
|
||||
}
|
||||
if (next is AsyncError) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text(next.error.toString())));
|
||||
}
|
||||
});
|
||||
|
||||
return Scaffold(
|
||||
appBar: AppBar(title: const Text('Masuk / Daftar')),
|
||||
body: Padding(
|
||||
padding: const EdgeInsets.all(24),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.stretch,
|
||||
children: [
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.g_mobiledata),
|
||||
onPressed: isLoading ? null
|
||||
: () => ref.read(authProvider.notifier).loginGoogle(),
|
||||
label: const Text('Lanjut dengan Google'),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton.icon(
|
||||
icon: const Icon(Icons.apple),
|
||||
onPressed: isLoading ? null
|
||||
: () => ref.read(authProvider.notifier).loginApple(),
|
||||
label: const Text('Lanjut dengan Apple'),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Row(children: [
|
||||
Expanded(child: Divider()),
|
||||
Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Text('atau')),
|
||||
Expanded(child: Divider()),
|
||||
]),
|
||||
),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nomor HP',
|
||||
hintText: '+628xxxxxxxxxx',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton.icon(
|
||||
icon: const Icon(Icons.apple),
|
||||
onPressed: state is AuthLoading ? null
|
||||
: () => context.read<AuthBloc>().add(AppleLoginRequested()),
|
||||
label: const Text('Lanjut dengan Apple'),
|
||||
),
|
||||
),
|
||||
const Padding(
|
||||
padding: EdgeInsets.symmetric(vertical: 24),
|
||||
child: Row(children: [
|
||||
Expanded(child: Divider()),
|
||||
Padding(padding: EdgeInsets.symmetric(horizontal: 12), child: Text('atau')),
|
||||
Expanded(child: Divider()),
|
||||
]),
|
||||
),
|
||||
TextField(
|
||||
controller: _phoneController,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Nomor HP',
|
||||
hintText: '+628xxxxxxxxxx',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) => ElevatedButton(
|
||||
onPressed: state is AuthLoading ? null : () {
|
||||
final phone = _phoneController.text.trim();
|
||||
if (phone.isEmpty) return;
|
||||
context.read<AuthBloc>().add(PhoneOtpRequested(phone));
|
||||
},
|
||||
child: state is AuthLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Kirim OTP'),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
keyboardType: TextInputType.phone,
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
ElevatedButton(
|
||||
onPressed: isLoading ? null : () {
|
||||
final phone = _phoneController.text.trim();
|
||||
if (phone.isEmpty) return;
|
||||
ref.read(authProvider.notifier).requestOtp(phone);
|
||||
},
|
||||
child: isLoading
|
||||
? const CircularProgressIndicator()
|
||||
: const Text('Kirim OTP'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
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 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import '../../../core/chat/chat_opening_provider.dart';
|
||||
import '../../../core/chat/session_closure_bloc.dart';
|
||||
import '../../../core/pairing/pairing_bloc.dart';
|
||||
|
||||
class PricingBottomSheet extends StatelessWidget {
|
||||
class PricingBottomSheet extends ConsumerWidget {
|
||||
/// If set, the bottom sheet is in "extension" mode — selecting a tier extends the session.
|
||||
final String? extensionSessionId;
|
||||
|
||||
@@ -16,14 +16,11 @@ class PricingBottomSheet extends StatelessWidget {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (_) => BlocProvider(
|
||||
create: (ctx) => ChatOpeningBloc(apiClient: ctx.read<ApiClient>())..add(LoadPricing()),
|
||||
child: MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider.value(value: context.read<PairingBloc>()),
|
||||
],
|
||||
child: const PricingBottomSheet(),
|
||||
),
|
||||
builder: (_) => MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider.value(value: context.read<PairingBloc>()),
|
||||
],
|
||||
child: const PricingBottomSheet(),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -33,14 +30,11 @@ class PricingBottomSheet extends StatelessWidget {
|
||||
return showModalBottomSheet(
|
||||
context: context,
|
||||
isScrollControlled: true,
|
||||
builder: (_) => BlocProvider(
|
||||
create: (ctx) => ChatOpeningBloc(apiClient: ctx.read<ApiClient>())..add(LoadPricing()),
|
||||
child: MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider.value(value: context.read<SessionClosureBloc>()),
|
||||
],
|
||||
child: PricingBottomSheet(extensionSessionId: sessionId),
|
||||
),
|
||||
builder: (_) => MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider.value(value: context.read<SessionClosureBloc>()),
|
||||
],
|
||||
child: PricingBottomSheet(extensionSessionId: sessionId),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -56,94 +50,83 @@ class PricingBottomSheet extends StatelessWidget {
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final isExtension = extensionSessionId != null;
|
||||
final pricingAsync = ref.watch(chatPricingProvider);
|
||||
|
||||
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: [
|
||||
Text(
|
||||
isExtension ? 'Perpanjang Durasi' : 'Pilih Durasi Curhat',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 16),
|
||||
if (!isExtension && 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();
|
||||
if (isExtension) {
|
||||
_requestExtension(
|
||||
context,
|
||||
sessionId: extensionSessionId!,
|
||||
durationMinutes: tier.durationMinutes,
|
||||
price: tier.price,
|
||||
);
|
||||
} else {
|
||||
_startPairing(
|
||||
context,
|
||||
durationMinutes: tier.durationMinutes,
|
||||
price: tier.price,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
)),
|
||||
],
|
||||
return pricingAsync.when(
|
||||
loading: () => const SizedBox(
|
||||
height: 200,
|
||||
child: Center(child: CircularProgressIndicator()),
|
||||
),
|
||||
error: (error, _) => SizedBox(
|
||||
height: 200,
|
||||
child: Center(child: Text('Gagal memuat harga. Coba lagi.')),
|
||||
),
|
||||
data: (pricing) => 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: [
|
||||
Text(
|
||||
isExtension ? 'Perpanjang Durasi' : 'Pilih Durasi Curhat',
|
||||
style: const TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
);
|
||||
},
|
||||
const SizedBox(height: 16),
|
||||
if (!isExtension && pricing.freeTrialEligible) ...[
|
||||
Card(
|
||||
color: Colors.green.shade50,
|
||||
child: ListTile(
|
||||
leading: const Icon(Icons.card_giftcard, color: Colors.green),
|
||||
title: Text('Free Trial (${pricing.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),
|
||||
],
|
||||
...pricing.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();
|
||||
if (isExtension) {
|
||||
_requestExtension(
|
||||
context,
|
||||
sessionId: extensionSessionId!,
|
||||
durationMinutes: tier.durationMinutes,
|
||||
price: tier.price,
|
||||
);
|
||||
} else {
|
||||
_startPairing(
|
||||
context,
|
||||
durationMinutes: tier.durationMinutes,
|
||||
price: tier.price,
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
)),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return const SizedBox.shrink();
|
||||
},
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,20 @@
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import '../../core/auth/auth_bloc.dart';
|
||||
import '../../core/api/api_client.dart';
|
||||
import '../../core/auth/auth_notifier.dart';
|
||||
import '../../core/api/api_client_provider.dart';
|
||||
import '../../core/pairing/pairing_bloc.dart';
|
||||
import '../chat/widgets/pricing_bottom_sheet.dart';
|
||||
|
||||
class HomeScreen extends StatefulWidget {
|
||||
class HomeScreen extends ConsumerStatefulWidget {
|
||||
const HomeScreen({super.key});
|
||||
|
||||
@override
|
||||
State<HomeScreen> createState() => _HomeScreenState();
|
||||
ConsumerState<HomeScreen> createState() => _HomeScreenState();
|
||||
}
|
||||
|
||||
class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
|
||||
class _HomeScreenState extends ConsumerState<HomeScreen> with WidgetsBindingObserver {
|
||||
Map<String, dynamic>? _activeSession;
|
||||
bool _loadingSession = true;
|
||||
|
||||
@@ -40,13 +41,12 @@ class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
|
||||
@override
|
||||
void didChangeDependencies() {
|
||||
super.didChangeDependencies();
|
||||
// Re-check when navigating back to this screen
|
||||
_checkActiveSession();
|
||||
}
|
||||
|
||||
Future<void> _checkActiveSession() async {
|
||||
try {
|
||||
final apiClient = context.read<ApiClient>();
|
||||
final apiClient = ref.read(apiClientProvider);
|
||||
final response = await apiClient.get('/api/client/chat/session/active');
|
||||
final data = response['data'];
|
||||
if (mounted) {
|
||||
@@ -62,6 +62,15 @@ class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
final authState = ref.watch(authProvider);
|
||||
final authData = authState.valueOrNull;
|
||||
|
||||
final displayName = switch (authData) {
|
||||
AuthAuthenticatedData d => d.profile['display_name'] as String? ?? '',
|
||||
AuthAnonymousData d => d.displayName,
|
||||
_ => '',
|
||||
};
|
||||
|
||||
return BlocListener<PairingBloc, PairingState>(
|
||||
listener: (context, state) {
|
||||
if (state is PairingSearching) {
|
||||
@@ -74,63 +83,53 @@ class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
|
||||
);
|
||||
}
|
||||
},
|
||||
child: BlocBuilder<AuthBloc, AuthState>(
|
||||
builder: (context, state) {
|
||||
final displayName = state is AuthAuthenticated
|
||||
? state.profile['display_name'] as String
|
||||
: state is AuthAnonymous
|
||||
? state.displayName
|
||||
: '';
|
||||
|
||||
return Scaffold(
|
||||
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()),
|
||||
),
|
||||
child: Scaffold(
|
||||
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: () => ref.read(authProvider.notifier).logout(),
|
||||
),
|
||||
],
|
||||
),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('Halo, $displayName!', style: const TextStyle(fontSize: 24)),
|
||||
const SizedBox(height: 32),
|
||||
if (_loadingSession)
|
||||
const CircularProgressIndicator()
|
||||
else if (_activeSession != null)
|
||||
_ActiveSessionCard(
|
||||
session: _activeSession!,
|
||||
onTap: () {
|
||||
final sessionId = _activeSession!['id'] as String;
|
||||
final mitraName = _activeSession!['mitra_display_name'] as String? ?? 'Bestie';
|
||||
context.push('/chat/session/$sessionId', extra: mitraName);
|
||||
},
|
||||
)
|
||||
else ...[
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
|
||||
),
|
||||
onPressed: () => PricingBottomSheet.show(context),
|
||||
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
body: Center(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(32),
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Text('Halo, $displayName!', style: const TextStyle(fontSize: 24)),
|
||||
const SizedBox(height: 32),
|
||||
if (_loadingSession)
|
||||
const CircularProgressIndicator()
|
||||
else if (_activeSession != null)
|
||||
_ActiveSessionCard(
|
||||
session: _activeSession!,
|
||||
onTap: () {
|
||||
final sessionId = _activeSession!['id'] as String;
|
||||
final mitraName = _activeSession!['mitra_display_name'] as String? ?? 'Bestie';
|
||||
context.push('/chat/session/$sessionId', extra: mitraName);
|
||||
},
|
||||
)
|
||||
else ...[
|
||||
const SizedBox(height: 16),
|
||||
ElevatedButton(
|
||||
style: ElevatedButton.styleFrom(
|
||||
padding: const EdgeInsets.symmetric(horizontal: 48, vertical: 16),
|
||||
),
|
||||
onPressed: () => PricingBottomSheet.show(context),
|
||||
child: const Text('Mulai Curhat', style: TextStyle(fontSize: 18)),
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -2,9 +2,9 @@ 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 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'core/api/api_client_provider.dart';
|
||||
import 'core/auth/auth_notifier.dart';
|
||||
import 'core/chat/chat_bloc.dart';
|
||||
import 'core/chat/session_closure_bloc.dart';
|
||||
import 'core/pairing/pairing_bloc.dart';
|
||||
@@ -16,68 +16,64 @@ void main() async {
|
||||
WidgetsFlutterBinding.ensureInitialized();
|
||||
await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
|
||||
|
||||
// Request notification permission
|
||||
final messaging = FirebaseMessaging.instance;
|
||||
await messaging.requestPermission();
|
||||
|
||||
runApp(const App());
|
||||
runApp(const ProviderScope(child: App()));
|
||||
}
|
||||
|
||||
class App extends StatefulWidget {
|
||||
class App extends ConsumerStatefulWidget {
|
||||
const App({super.key});
|
||||
|
||||
@override
|
||||
State<App> createState() => _AppState();
|
||||
ConsumerState<App> createState() => _AppState();
|
||||
}
|
||||
|
||||
class _AppState extends State<App> {
|
||||
final _apiClient = ApiClient();
|
||||
late final AuthBloc _authBloc;
|
||||
late final GoRouter _router;
|
||||
class _AppState extends ConsumerState<App> {
|
||||
bool _fcmRegistered = false;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_authBloc = AuthBloc(apiClient: _apiClient)..add(AppStarted());
|
||||
_router = buildRouter(_authBloc);
|
||||
NotificationService.initialize(_router);
|
||||
_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 (_) {}
|
||||
void _registerFcmToken() {
|
||||
if (_fcmRegistered) return;
|
||||
_fcmRegistered = true;
|
||||
Future(() async {
|
||||
try {
|
||||
final token = await FirebaseMessaging.instance.getToken();
|
||||
if (token != null) {
|
||||
await ref.read(apiClientProvider).post('/api/shared/device-token', data: {'token': token});
|
||||
}
|
||||
} catch (_) {
|
||||
_fcmRegistered = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_authBloc.close();
|
||||
_router.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
// Listen for auth changes to register FCM token
|
||||
ref.listen(authProvider, (prev, next) {
|
||||
final data = next.valueOrNull;
|
||||
if (data is AuthAuthenticatedData || data is AuthAnonymousData) {
|
||||
_registerFcmToken();
|
||||
}
|
||||
});
|
||||
|
||||
final router = ref.watch(routerProvider);
|
||||
final apiClient = ref.watch(apiClientProvider);
|
||||
|
||||
// Initialize notifications once router is available
|
||||
NotificationService.initialize(router);
|
||||
|
||||
// Keep BlocProviders for non-migrated blocs (will be removed as they're migrated)
|
||||
return MultiBlocProvider(
|
||||
providers: [
|
||||
BlocProvider.value(value: _authBloc),
|
||||
BlocProvider(create: (_) => PairingBloc(apiClient: _apiClient)),
|
||||
BlocProvider(create: (_) => ChatBloc(apiClient: _apiClient)),
|
||||
BlocProvider(create: (_) => SessionClosureBloc(apiClient: _apiClient)),
|
||||
RepositoryProvider.value(value: _apiClient),
|
||||
BlocProvider(create: (_) => PairingBloc(apiClient: apiClient)),
|
||||
BlocProvider(create: (_) => ChatBloc(apiClient: apiClient)),
|
||||
BlocProvider(create: (_) => SessionClosureBloc(apiClient: apiClient)),
|
||||
RepositoryProvider.value(value: apiClient),
|
||||
],
|
||||
child: MaterialApp.router(
|
||||
title: 'Halo Bestie',
|
||||
routerConfig: _router,
|
||||
routerConfig: router,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import 'dart:async';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_riverpod/flutter_riverpod.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'core/auth/auth_bloc.dart';
|
||||
import 'core/auth/auth_notifier.dart';
|
||||
import 'features/auth/screens/welcome_screen.dart';
|
||||
import 'features/auth/screens/display_name_screen.dart';
|
||||
import 'features/auth/screens/register_screen.dart';
|
||||
@@ -16,38 +16,43 @@ 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 {
|
||||
late final StreamSubscription _subscription;
|
||||
class RouterNotifier extends ChangeNotifier {
|
||||
final Ref _ref;
|
||||
|
||||
_BlocRefreshNotifier(AuthBloc bloc) {
|
||||
_subscription = bloc.stream.listen((_) => notifyListeners());
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
_subscription.cancel();
|
||||
super.dispose();
|
||||
RouterNotifier(this._ref) {
|
||||
_ref.listen(authProvider, (_, __) => notifyListeners());
|
||||
}
|
||||
}
|
||||
|
||||
GoRouter buildRouter(AuthBloc authBloc) {
|
||||
final routerProvider = Provider<GoRouter>((ref) => buildRouter(ref));
|
||||
|
||||
GoRouter buildRouter(Ref ref) {
|
||||
final notifier = RouterNotifier(ref);
|
||||
|
||||
return GoRouter(
|
||||
initialLocation: '/splash',
|
||||
refreshListenable: _BlocRefreshNotifier(authBloc),
|
||||
refreshListenable: notifier,
|
||||
redirect: (context, state) {
|
||||
final authState = authBloc.state;
|
||||
final authState = ref.read(authProvider);
|
||||
final isSplash = state.matchedLocation == '/splash';
|
||||
final isAuthRoute = state.matchedLocation.startsWith('/auth') ||
|
||||
state.matchedLocation == '/welcome';
|
||||
|
||||
// Show splash while loading
|
||||
if (authState is AuthLoading) return isSplash ? null : '/splash';
|
||||
if (authState is AsyncLoading) return isSplash ? null : '/splash';
|
||||
|
||||
if (authState is AuthAuthenticated || authState is AuthAnonymous) {
|
||||
final data = authState.valueOrNull;
|
||||
if (data == null) {
|
||||
// Error state — show login
|
||||
if (!isAuthRoute && !isSplash) return '/welcome';
|
||||
if (isSplash) return '/welcome';
|
||||
return null;
|
||||
}
|
||||
|
||||
if (data is AuthAuthenticatedData || data is AuthAnonymousData) {
|
||||
return (isSplash || isAuthRoute) ? '/home' : null;
|
||||
}
|
||||
if (authState is AuthForceRegister) return '/auth/force-register';
|
||||
if (data is AuthForceRegisterData) return '/auth/force-register';
|
||||
if (!isAuthRoute && !isSplash) return '/welcome';
|
||||
if (isSplash) return '/welcome';
|
||||
return null;
|
||||
|
||||
Reference in New Issue
Block a user