feat: Refactor repositories and modules to remove FirebaseAuth dependency and utilize DataConnectService

This commit is contained in:
Achintha Isuru
2026-02-16 17:49:34 -05:00
parent 21f0e2ee89
commit 39bb17d981
9 changed files with 121 additions and 177 deletions

View File

@@ -41,7 +41,7 @@ class ClientSignUpPage extends StatelessWidget {
final TranslationsClientAuthenticationSignUpPageEn i18n = t.client_authentication.sign_up_page; final TranslationsClientAuthenticationSignUpPageEn i18n = t.client_authentication.sign_up_page;
final ClientAuthBloc authBloc = Modular.get<ClientAuthBloc>(); final ClientAuthBloc authBloc = Modular.get<ClientAuthBloc>();
return BlocProvider.value( return BlocProvider<ClientAuthBloc>.value(
value: authBloc, value: authBloc,
child: BlocConsumer<ClientAuthBloc, ClientAuthState>( child: BlocConsumer<ClientAuthBloc, ClientAuthState>(
listener: (BuildContext context, ClientAuthState state) { listener: (BuildContext context, ClientAuthState state) {

View File

@@ -54,7 +54,6 @@ class BillingBloc extends Bloc<BillingEvent, BillingState>
_getSpendingBreakdown.call(state.period), _getSpendingBreakdown.call(state.period),
]); ]);
final double currentBill = results[0] as double;
final double savings = results[1] as double; final double savings = results[1] as double;
final List<Invoice> pendingInvoices = results[2] as List<Invoice>; final List<Invoice> pendingInvoices = results[2] as List<Invoice>;
final List<Invoice> invoiceHistory = results[3] as List<Invoice>; final List<Invoice> invoiceHistory = results[3] as List<Invoice>;

View File

@@ -6,8 +6,7 @@ import '../../domain/repositories/client_create_order_repository_interface.dart'
/// Implementation of [ClientCreateOrderRepositoryInterface]. /// Implementation of [ClientCreateOrderRepositoryInterface].
/// ///
/// This implementation coordinates data access for order creation by delegating /// This implementation coordinates data access for order creation by [DataConnectService] from the shared
/// to the [OrderRepositoryMock] and [ExampleConnector] from the shared
/// Data Connect package. /// Data Connect package.
/// ///
/// It follows the KROW Clean Architecture by keeping the data layer focused /// It follows the KROW Clean Architecture by keeping the data layer focused

View File

@@ -22,8 +22,8 @@ class CoverageDashboard extends StatelessWidget {
int totalConfirmed = 0; int totalConfirmed = 0;
double todayCost = 0; double todayCost = 0;
for (final s in shifts) { for (final dynamic s in shifts) {
final int needed = s['workersNeeded'] as int? ?? 0; final int needed = (s as Map<String, dynamic>)['workersNeeded'] as int? ?? 0;
final int confirmed = s['filled'] as int? ?? 0; final int confirmed = s['filled'] as int? ?? 0;
final double rate = s['hourlyRate'] as double? ?? 0.0; final double rate = s['hourlyRate'] as double? ?? 0.0;
final double hours = s['hours'] as double? ?? 0.0; final double hours = s['hours'] as double? ?? 0.0;
@@ -39,10 +39,10 @@ class CoverageDashboard extends StatelessWidget {
final int unfilledPositions = totalNeeded - totalConfirmed; final int unfilledPositions = totalNeeded - totalConfirmed;
final int checkedInCount = applications final int checkedInCount = applications
.where((a) => (a as Map)['checkInTime'] != null) .where((dynamic a) => (a as Map<String, dynamic>)['checkInTime'] != null)
.length; .length;
final int lateWorkersCount = applications final int lateWorkersCount = applications
.where((a) => (a as Map)['status'] == 'LATE') .where((dynamic a) => (a as Map<String, dynamic>)['status'] == 'LATE')
.length; .length;
final bool isCoverageGood = coveragePercent >= 90; final bool isCoverageGood = coveragePercent >= 90;

View File

@@ -1,6 +1,6 @@
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter_modular/flutter_modular.dart'; import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_core/core.dart'; import 'package:krow_core/core.dart';
import 'package:krow_data_connect/krow_data_connect.dart';
import 'src/data/repositories_impl/settings_repository_impl.dart'; import 'src/data/repositories_impl/settings_repository_impl.dart';
import 'src/domain/repositories/settings_repository_interface.dart'; import 'src/domain/repositories/settings_repository_interface.dart';
import 'src/domain/usecases/sign_out_usecase.dart'; import 'src/domain/usecases/sign_out_usecase.dart';
@@ -9,20 +9,19 @@ import 'src/presentation/pages/client_settings_page.dart';
/// A [Module] for the client settings feature. /// A [Module] for the client settings feature.
class ClientSettingsModule extends Module { class ClientSettingsModule extends Module {
@override
List<Module> get imports => <Module>[DataConnectModule()];
@override @override
void binds(Injector i) { void binds(Injector i) {
// Repositories // Repositories
i.addLazySingleton<SettingsRepositoryInterface>( i.addLazySingleton<SettingsRepositoryInterface>(SettingsRepositoryImpl.new);
() => SettingsRepositoryImpl(firebaseAuth: FirebaseAuth.instance),
);
// UseCases // UseCases
i.addLazySingleton(SignOutUseCase.new); i.addLazySingleton(SignOutUseCase.new);
// BLoCs // BLoCs
i.add<ClientSettingsBloc>( i.add<ClientSettingsBloc>(ClientSettingsBloc.new);
() => ClientSettingsBloc(signOutUseCase: i.get<SignOutUseCase>()),
);
} }
@override @override

View File

@@ -1,23 +1,21 @@
import 'package:firebase_auth/firebase_auth.dart'; import 'package:krow_data_connect/krow_data_connect.dart' as dc;
import '../../domain/repositories/settings_repository_interface.dart'; import '../../domain/repositories/settings_repository_interface.dart';
/// Implementation of [SettingsRepositoryInterface]. /// Implementation of [SettingsRepositoryInterface].
/// ///
/// This implementation delegates authentication operations to [FirebaseAuth]. /// This implementation delegates authentication operations to [DataConnectService].
class SettingsRepositoryImpl implements SettingsRepositoryInterface { class SettingsRepositoryImpl implements SettingsRepositoryInterface {
/// Creates a [SettingsRepositoryImpl] with the required [_firebaseAuth]. /// Creates a [SettingsRepositoryImpl] with the required [_service].
const SettingsRepositoryImpl({required this.firebaseAuth}); const SettingsRepositoryImpl({required dc.DataConnectService service}) : _service = service;
/// The Firebase Auth instance. /// The Data Connect service.
final FirebaseAuth firebaseAuth; final dc.DataConnectService _service;
@override @override
Future<void> signOut() async { Future<void> signOut() async {
try { return _service.run(() async {
await firebaseAuth.signOut(); await _service.auth.signOut();
} catch (e) { });
throw Exception('Error signing out: ${e.toString()}');
}
} }
} }

View File

@@ -1,4 +1,3 @@
import 'package:firebase_auth/firebase_auth.dart' as firebase;
import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc; import 'package:firebase_data_connect/firebase_data_connect.dart' as fdc;
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:krow_data_connect/krow_data_connect.dart' as dc; import 'package:krow_data_connect/krow_data_connect.dart' as dc;
@@ -6,151 +5,132 @@ import 'package:krow_domain/krow_domain.dart' as domain;
import '../../domain/repositories/i_view_orders_repository.dart'; import '../../domain/repositories/i_view_orders_repository.dart';
/// Implementation of [IViewOrdersRepository] using Data Connect. /// Implementation of [IViewOrdersRepository] using Data Connect.
class ViewOrdersRepositoryImpl class ViewOrdersRepositoryImpl implements IViewOrdersRepository {
with dc.DataErrorHandler final dc.DataConnectService _service;
implements IViewOrdersRepository {
final firebase.FirebaseAuth _firebaseAuth;
final dc.ExampleConnector _dataConnect;
ViewOrdersRepositoryImpl({ ViewOrdersRepositoryImpl({
required firebase.FirebaseAuth firebaseAuth, required dc.DataConnectService service,
required dc.ExampleConnector dataConnect, }) : _service = service;
}) : _firebaseAuth = firebaseAuth,
_dataConnect = dataConnect;
@override @override
Future<List<domain.OrderItem>> getOrdersForRange({ Future<List<domain.OrderItem>> getOrdersForRange({
required DateTime start, required DateTime start,
required DateTime end, required DateTime end,
}) async { }) async {
final String? businessId = dc.ClientSessionStore.instance.session?.business?.id; return _service.run(() async {
if (businessId == null || businessId.isEmpty) { final String businessId = await _service.getBusinessId();
await _firebaseAuth.signOut();
throw Exception('Business is missing. Please sign in again.');
}
final fdc.Timestamp startTimestamp = _toTimestamp(_startOfDay(start));
final fdc.Timestamp endTimestamp = _toTimestamp(_endOfDay(end));
final fdc.QueryResult<dc.ListShiftRolesByBusinessAndDateRangeData,
dc.ListShiftRolesByBusinessAndDateRangeVariables> result =
await executeProtected(() => _dataConnect
.listShiftRolesByBusinessAndDateRange(
businessId: businessId,
start: startTimestamp,
end: endTimestamp,
)
.execute());
print(
'ViewOrders range start=${start.toIso8601String()} end=${end.toIso8601String()} shiftRoles=${result.data.shiftRoles.length}',
);
final String businessName =
dc.ClientSessionStore.instance.session?.business?.businessName ??
'Your Company';
return result.data.shiftRoles.map((dc.ListShiftRolesByBusinessAndDateRangeShiftRoles shiftRole) {
final DateTime? shiftDate = shiftRole.shift.date?.toDateTime().toLocal();
final String dateStr = shiftDate == null
? ''
: DateFormat('yyyy-MM-dd').format(shiftDate);
final String startTime = _formatTime(shiftRole.startTime);
final String endTime = _formatTime(shiftRole.endTime);
final int filled = shiftRole.assigned ?? 0;
final int workersNeeded = shiftRole.count;
final double hours = shiftRole.hours ?? 0;
final double totalValue = shiftRole.totalValue ?? 0;
final double hourlyRate = _hourlyRate(shiftRole.totalValue, shiftRole.hours);
// final String status = filled >= workersNeeded ? 'filled' : 'open';
final String status = shiftRole.shift.status?.stringValue ?? 'OPEN';
final fdc.Timestamp startTimestamp = _service.toTimestamp(_startOfDay(start));
final fdc.Timestamp endTimestamp = _service.toTimestamp(_endOfDay(end));
final fdc.QueryResult<dc.ListShiftRolesByBusinessAndDateRangeData,
dc.ListShiftRolesByBusinessAndDateRangeVariables> result =
await _service.connector
.listShiftRolesByBusinessAndDateRange(
businessId: businessId,
start: startTimestamp,
end: endTimestamp,
)
.execute();
print( print(
'ViewOrders item: date=$dateStr status=$status shiftId=${shiftRole.shiftId} ' 'ViewOrders range start=${start.toIso8601String()} end=${end.toIso8601String()} shiftRoles=${result.data.shiftRoles.length}',
'roleId=${shiftRole.roleId} start=${shiftRole.startTime?.toJson()} '
'end=${shiftRole.endTime?.toJson()} hours=$hours totalValue=$totalValue',
); );
final String eventName = final String businessName =
shiftRole.shift.order.eventName ?? shiftRole.shift.title; dc.ClientSessionStore.instance.session?.business?.businessName ?? 'Your Company';
return domain.OrderItem( return result.data.shiftRoles.map((dc.ListShiftRolesByBusinessAndDateRangeShiftRoles shiftRole) {
id: _shiftRoleKey(shiftRole.shiftId, shiftRole.roleId), final DateTime? shiftDate = shiftRole.shift.date?.toDateTime().toLocal();
orderId: shiftRole.shift.order.id, final String dateStr = shiftDate == null ? '' : DateFormat('yyyy-MM-dd').format(shiftDate);
title: '${shiftRole.role.name} - $eventName', final String startTime = _formatTime(shiftRole.startTime);
clientName: businessName, final String endTime = _formatTime(shiftRole.endTime);
status: status, final int filled = shiftRole.assigned ?? 0;
date: dateStr, final int workersNeeded = shiftRole.count;
startTime: startTime, final double hours = shiftRole.hours ?? 0;
endTime: endTime, final double totalValue = shiftRole.totalValue ?? 0;
location: shiftRole.shift.location ?? '', final double hourlyRate = _hourlyRate(shiftRole.totalValue, shiftRole.hours);
locationAddress: shiftRole.shift.locationAddress ?? '', // final String status = filled >= workersNeeded ? 'filled' : 'open';
filled: filled, final String status = shiftRole.shift.status?.stringValue ?? 'OPEN';
workersNeeded: workersNeeded,
hourlyRate: hourlyRate, print(
hours: hours, 'ViewOrders item: date=$dateStr status=$status shiftId=${shiftRole.shiftId} '
totalValue: totalValue, 'roleId=${shiftRole.roleId} start=${shiftRole.startTime?.toJson()} '
confirmedApps: const <Map<String, dynamic>>[], 'end=${shiftRole.endTime?.toJson()} hours=$hours totalValue=$totalValue',
); );
}).toList();
final String eventName = shiftRole.shift.order.eventName ?? shiftRole.shift.title;
return domain.OrderItem(
id: _shiftRoleKey(shiftRole.shiftId, shiftRole.roleId),
orderId: shiftRole.shift.order.id,
title: '${shiftRole.role.name} - $eventName',
clientName: businessName,
status: status,
date: dateStr,
startTime: startTime,
endTime: endTime,
location: shiftRole.shift.location ?? '',
locationAddress: shiftRole.shift.locationAddress ?? '',
filled: filled,
workersNeeded: workersNeeded,
hourlyRate: hourlyRate,
hours: hours,
totalValue: totalValue,
confirmedApps: const <Map<String, dynamic>>[],
);
}).toList();
});
} }
@override @override
Future<Map<String, List<Map<String, dynamic>>>> getAcceptedApplicationsForDay( Future<Map<String, List<Map<String, dynamic>>>> getAcceptedApplicationsForDay(
DateTime day, DateTime day,
) async { ) async {
final String? businessId = dc.ClientSessionStore.instance.session?.business?.id; return _service.run(() async {
if (businessId == null || businessId.isEmpty) { final String businessId = await _service.getBusinessId();
await _firebaseAuth.signOut();
throw Exception('Business is missing. Please sign in again.');
}
final fdc.Timestamp dayStart = _toTimestamp(_startOfDay(day)); final fdc.Timestamp dayStart = _service.toTimestamp(_startOfDay(day));
final fdc.Timestamp dayEnd = _toTimestamp(_endOfDay(day)); final fdc.Timestamp dayEnd = _service.toTimestamp(_endOfDay(day));
final fdc.QueryResult<dc.ListAcceptedApplicationsByBusinessForDayData, final fdc.QueryResult<dc.ListAcceptedApplicationsByBusinessForDayData,
dc.ListAcceptedApplicationsByBusinessForDayVariables> result = dc.ListAcceptedApplicationsByBusinessForDayVariables> result =
await executeProtected(() => _dataConnect await _service.connector
.listAcceptedApplicationsByBusinessForDay( .listAcceptedApplicationsByBusinessForDay(
businessId: businessId, businessId: businessId,
dayStart: dayStart, dayStart: dayStart,
dayEnd: dayEnd, dayEnd: dayEnd,
) )
.execute()); .execute();
print(
'ViewOrders day=${day.toIso8601String()} applications=${result.data.applications.length}',
);
final Map<String, List<Map<String, dynamic>>> grouped = <String, List<Map<String, dynamic>>>{};
for (final dc.ListAcceptedApplicationsByBusinessForDayApplications application in result.data.applications) {
print( print(
'ViewOrders app: shiftId=${application.shiftId} roleId=${application.roleId} ' 'ViewOrders day=${day.toIso8601String()} applications=${result.data.applications.length}',
'checkIn=${application.checkInTime?.toJson()} checkOut=${application.checkOutTime?.toJson()}',
); );
final String key = _shiftRoleKey(application.shiftId, application.roleId);
grouped.putIfAbsent(key, () => <Map<String, dynamic>>[]); final Map<String, List<Map<String, dynamic>>> grouped = <String, List<Map<String, dynamic>>>{};
grouped[key]!.add(<String, dynamic>{ for (final dc.ListAcceptedApplicationsByBusinessForDayApplications application
'id': application.id, in result.data.applications) {
'worker_id': application.staff.id, print(
'worker_name': application.staff.fullName, 'ViewOrders app: shiftId=${application.shiftId} roleId=${application.roleId} '
'status': 'confirmed', 'checkIn=${application.checkInTime?.toJson()} checkOut=${application.checkOutTime?.toJson()}',
'photo_url': application.staff.photoUrl, );
'phone': application.staff.phone, final String key = _shiftRoleKey(application.shiftId, application.roleId);
'rating': application.staff.averageRating, grouped.putIfAbsent(key, () => <Map<String, dynamic>>[]);
}); grouped[key]!.add(<String, dynamic>{
} 'id': application.id,
return grouped; 'worker_id': application.staff.id,
'worker_name': application.staff.fullName,
'status': 'confirmed',
'photo_url': application.staff.photoUrl,
'phone': application.staff.phone,
'rating': application.staff.averageRating,
});
}
return grouped;
});
} }
String _shiftRoleKey(String shiftId, String roleId) { String _shiftRoleKey(String shiftId, String roleId) {
return '$shiftId:$roleId'; return '$shiftId:$roleId';
} }
fdc.Timestamp _toTimestamp(DateTime dateTime) {
final DateTime utc = dateTime.toUtc();
final int seconds = utc.millisecondsSinceEpoch ~/ 1000;
final int nanoseconds = (utc.microsecondsSinceEpoch % 1000000) * 1000;
return fdc.Timestamp(nanoseconds, seconds);
}
DateTime _startOfDay(DateTime dateTime) { DateTime _startOfDay(DateTime dateTime) {
return DateTime(dateTime.year, dateTime.month, dateTime.day); return DateTime(dateTime.year, dateTime.month, dateTime.day);
} }

View File

@@ -80,23 +80,6 @@ class _ViewOrderCardState extends State<ViewOrderCard> {
} }
} }
/// Formats the date string for display.
String _formatDate({required String dateStr}) {
try {
final DateTime date = DateTime.parse(dateStr);
final DateTime now = DateTime.now();
final DateTime today = DateTime(now.year, now.month, now.day);
final DateTime tomorrow = today.add(const Duration(days: 1));
final DateTime checkDate = DateTime(date.year, date.month, date.day);
if (checkDate == today) return t.client_view_orders.card.today;
if (checkDate == tomorrow) return t.client_view_orders.card.tomorrow;
return DateFormat('EEE, MMM d').format(date);
} catch (_) {
return dateStr;
}
}
/// Formats the time string for display. /// Formats the time string for display.
String _formatTime({required String timeStr}) { String _formatTime({required String timeStr}) {
if (timeStr.isEmpty) return ''; if (timeStr.isEmpty) return '';
@@ -829,10 +812,7 @@ class _OrderEditSheetState extends State<_OrderEditSheet> {
final String dateText = orderDate == null final String dateText = orderDate == null
? widget.order.date ? widget.order.date
: DateFormat('yyyy-MM-dd').format(orderDate); : DateFormat('yyyy-MM-dd').format(orderDate);
final String location = firstShift.order.teamHub?.hubName ?? final String location = firstShift.order.teamHub.hubName;
firstShift.locationAddress ??
firstShift.location ??
widget.order.locationAddress;
_dateController.text = dateText; _dateController.text = dateText;
_globalLocationController.text = location; _globalLocationController.text = location;

View File

@@ -1,7 +1,6 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_modular/flutter_modular.dart'; import 'package:flutter_modular/flutter_modular.dart';
import 'package:krow_data_connect/krow_data_connect.dart'; import 'package:krow_data_connect/krow_data_connect.dart';
import 'package:firebase_auth/firebase_auth.dart' as firebase;
import 'data/repositories/view_orders_repository_impl.dart'; import 'data/repositories/view_orders_repository_impl.dart';
import 'domain/repositories/i_view_orders_repository.dart'; import 'domain/repositories/i_view_orders_repository.dart';
@@ -21,24 +20,14 @@ class ViewOrdersModule extends Module {
@override @override
void binds(Injector i) { void binds(Injector i) {
// Repositories // Repositories
i.add<IViewOrdersRepository>( i.add<IViewOrdersRepository>(ViewOrdersRepositoryImpl.new);
() => ViewOrdersRepositoryImpl(
firebaseAuth: firebase.FirebaseAuth.instance,
dataConnect: ExampleConnector.instance,
),
);
// UseCases // UseCases
i.add(GetOrdersUseCase.new); i.add(GetOrdersUseCase.new);
i.add(GetAcceptedApplicationsForDayUseCase.new); i.add(GetAcceptedApplicationsForDayUseCase.new);
// BLoCs // BLoCs
i.add( i.add(ViewOrdersCubit.new);
() => ViewOrdersCubit(
getOrdersUseCase: i.get<GetOrdersUseCase>(),
getAcceptedAppsUseCase: i.get<GetAcceptedApplicationsForDayUseCase>(),
),
);
} }
@override @override