Compare commits

..

8 Commits

Author SHA1 Message Date
Mohammed Al-Samarraie
eebec9b7a2 Remove unused Google ML Kit dependencies and streamline face detection logic 2026-03-14 15:03:40 +03:00
Mohammed Al-Samarraie
0606e26ef7 34w43 2026-03-14 11:21:41 +03:00
Daniah Ayad Al-sultani
8b0d849f1b location has been enabled in addition to sending the domain 2026-02-22 14:06:02 +03:00
Daniah Ayad Al-sultani
f616a2c104 chnages has been made 2026-02-22 11:18:10 +03:00
Daniah Ayad Al-sultani
3a9e7ca8db loading indicater has been added 2026-02-17 17:19:53 +03:00
Daniah Ayad Al-sultani
5117fbdabe the user name of the employee is being displayed 2026-02-17 16:51:13 +03:00
Daniah Ayad Al-sultani
bb6f3931ce Merge branch 'master' of https://git.delta.iq/dania/finger_print_app 2026-02-17 16:14:40 +03:00
Daniah Ayad Al-sultani
2022245810 chnages has been made for the interactive face camera 2026-02-17 16:14:37 +03:00
42 changed files with 2709 additions and 410 deletions

View File

@@ -1,7 +1,10 @@
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.USE_BIOMETRIC" />
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.autofocus" android:required="false" />
<application

View File

@@ -1,5 +1,5 @@
package com.example.coda_project
import io.flutter.embedding.android.FlutterActivity
import io.flutter.embedding.android.FlutterFragmentActivity
class MainActivity : FlutterActivity()
class MainActivity : FlutterFragmentActivity()

View File

@@ -1,5 +1,5 @@
# Uncomment this line to define a global platform for your project
# platform :ios, '12.0'
platform :ios, '15.5'
# CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true'

View File

@@ -4,6 +4,12 @@ PODS:
- Flutter (1.0.0)
- flutter_native_splash (2.4.3):
- Flutter
- geolocator_apple (1.2.0):
- Flutter
- FlutterMacOS
- local_auth_darwin (0.0.1):
- Flutter
- FlutterMacOS
- shared_preferences_foundation (0.0.1):
- Flutter
- FlutterMacOS
@@ -12,6 +18,8 @@ DEPENDENCIES:
- camera_avfoundation (from `.symlinks/plugins/camera_avfoundation/ios`)
- Flutter (from `Flutter`)
- flutter_native_splash (from `.symlinks/plugins/flutter_native_splash/ios`)
- geolocator_apple (from `.symlinks/plugins/geolocator_apple/darwin`)
- local_auth_darwin (from `.symlinks/plugins/local_auth_darwin/darwin`)
- shared_preferences_foundation (from `.symlinks/plugins/shared_preferences_foundation/darwin`)
EXTERNAL SOURCES:
@@ -21,6 +29,10 @@ EXTERNAL SOURCES:
:path: Flutter
flutter_native_splash:
:path: ".symlinks/plugins/flutter_native_splash/ios"
geolocator_apple:
:path: ".symlinks/plugins/geolocator_apple/darwin"
local_auth_darwin:
:path: ".symlinks/plugins/local_auth_darwin/darwin"
shared_preferences_foundation:
:path: ".symlinks/plugins/shared_preferences_foundation/darwin"
@@ -28,8 +40,10 @@ SPEC CHECKSUMS:
camera_avfoundation: be3be85408cd4126f250386828e9b1dfa40ab436
Flutter: e0871f40cf51350855a761d2e70bf5af5b9b5de7
flutter_native_splash: c32d145d68aeda5502d5f543ee38c192065986cf
geolocator_apple: ab36aa0e8b7d7a2d7639b3b4e48308394e8cef5e
local_auth_darwin: d2e8c53ef0c4f43c646462e3415432c4dab3ae19
shared_preferences_foundation: 9e1978ff2562383bd5676f64ec4e9aa8fa06a6f7
PODFILE CHECKSUM: 4305caec6b40dde0ae97be1573c53de1882a07e5
PODFILE CHECKSUM: 9580a49fa2c095d51100c20f258df867100b916b
COCOAPODS: 1.16.2

View File

@@ -454,7 +454,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;
@@ -584,7 +584,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
MTL_ENABLE_DEBUG_INFO = YES;
ONLY_ACTIVE_ARCH = YES;
SDKROOT = iphoneos;
@@ -635,7 +635,7 @@
GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
GCC_WARN_UNUSED_FUNCTION = YES;
GCC_WARN_UNUSED_VARIABLE = YES;
IPHONEOS_DEPLOYMENT_TARGET = 12.0;
IPHONEOS_DEPLOYMENT_TARGET = 15.5;
MTL_ENABLE_DEBUG_INFO = NO;
SDKROOT = iphoneos;
SUPPORTED_PLATFORMS = iphoneos;

View File

@@ -51,5 +51,11 @@
<string>We need access to your camera to capture photos for face recognition.</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select photos.</string>
</dict>
<key>NSLocationWhenInUseUsageDescription</key>
<string>We need your location to verify your attendance at the workplace.</string>
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>We need your location to verify your attendance at the workplace.</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>We need your location to verify your attendance at the workplace.</string>
</dict>
</plist>

View File

@@ -0,0 +1,16 @@
class AppUrls {
static const String themeLogoBase = 'https://hrm.go.iq/Images/';
static String buildThemeLogoUrl(String logoFileName) {
if (logoFileName.isEmpty) return '';
// If backend ever returns a full URL, keep it
final lower = logoFileName.toLowerCase();
if (lower.startsWith('http://') || lower.startsWith('https://')) {
return logoFileName;
}
// Encode spaces/special chars (important!)
return themeLogoBase + Uri.encodeComponent(logoFileName);
}
}

View File

@@ -32,6 +32,12 @@ import '../../domain/usecases/get_salary_summary_usecase.dart';
import '../../domain/usecases/change_password_usecase.dart';
import '../../presentation/blocs/login/login_bloc.dart';
import '../../presentation/blocs/change_password/change_password_bloc.dart';
import '../../data/datasources/theme_remote_data_source.dart';
import '../../data/repositories/theme_repository_impl.dart';
import '../../domain/repositories/theme_repository.dart';
import '../../domain/usecases/get_theme_usecase.dart';
import '../../presentation/blocs/theme/theme_cubit.dart';
import '../location/location_service.dart';
final sl = GetIt.instance;
@@ -124,4 +130,18 @@ Future<void> initializeDependencies() async {
sl.registerLazySingleton(() => CreateAdvanceUseCase(repository: sl()));
sl.registerLazySingleton(() => GetAdvancesUseCase(repository: sl()));
// Theme
sl.registerLazySingleton<ThemeRemoteDataSource>(
() => ThemeRemoteDataSourceImpl(apiClient: sl()),
);
sl.registerLazySingleton<ThemeRepository>(
() => ThemeRepositoryImpl(remote: sl()),
);
sl.registerLazySingleton(() => GetThemeUseCase(sl()));
sl.registerFactory(() => ThemeCubit(getThemeUseCase: sl()));
sl.registerLazySingleton<LocationService>(() => LocationService());
}

View File

@@ -0,0 +1,24 @@
import 'package:geolocator/geolocator.dart';
class LocationService {
Future<Position?> getCurrentPosition() async {
// 1) service enabled?
final serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) return null;
// 2) permission
var permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
}
if (permission == LocationPermission.denied ||
permission == LocationPermission.deniedForever) {
return null;
}
// 3) get location (geolocator v13+ API)
return Geolocator.getCurrentPosition(
locationSettings: const LocationSettings(accuracy: LocationAccuracy.high),
);
}
}

View File

@@ -10,23 +10,24 @@ class ApiClient {
ApiClient({required this.dio, this.sharedPreferences}) {
dio.options = BaseOptions(
baseUrl: baseUrl,
connectTimeout: const Duration(seconds: 30),
receiveTimeout: const Duration(seconds: 30),
headers: {
'Content-Type': 'application/json',
'accept': 'text/plain',
},
connectTimeout: const Duration(seconds: 60),
receiveTimeout: const Duration(seconds: 60),
headers: {'Content-Type': 'application/json', 'accept': 'text/plain'},
);
// Add interceptor to add token to requests
dio.interceptors.add(
InterceptorsWrapper(
onRequest: (options, handler) async {
// Skip auth if the request explicitly opts out
final skipAuth = options.extra['skipAuth'] == true;
if (!skipAuth) {
// Get token from SharedPreferences
final token = sharedPreferences?.getString(_tokenKey);
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
}
return handler.next(options);
},
),

View File

@@ -13,11 +13,17 @@ abstract class AttendanceRemoteDataSource {
Future<AttendanceResponseDto> login({
required String employeeId,
required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
});
Future<AttendanceResponseDto> logout({
required String employeeId,
required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
});
Future<List<AttendanceRecordDto>> getAttendanceRecords({
@@ -26,6 +32,8 @@ abstract class AttendanceRemoteDataSource {
Future<List<OvertimeDto>> getExtraHours({required String employeeId});
Future<List<RewardDto>> getRewards({required String employeeId});
Future<List<PunishmentDto>> getPunishments({required String employeeId});
Future<AttendanceRecordDto?> getLastRecord({required String employeeId});
Future<bool> hasActiveLogin({required String employeeId});
Future<SalaryResponseDto> calculateSalary({
required String employeeId,
required int month,
@@ -41,11 +49,18 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
Future<AttendanceResponseDto> login({
required String employeeId,
required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}) async {
try {
final formData = FormData.fromMap({
'EmployeeId': employeeId,
'FaceImage': await MultipartFile.fromFile(faceImage.path),
'IsAuth': localAuth.toString(),
'Domain': 'hrm.go.iq',
if (latitude != null) 'Latitude': latitude,
if (longitude != null) 'Longitude': longitude,
});
final response = await apiClient.post(
@@ -105,11 +120,17 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
Future<AttendanceResponseDto> logout({
required String employeeId,
required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}) async {
try {
final formData = FormData.fromMap({
'EmployeeId': employeeId,
'FaceImage': await MultipartFile.fromFile(faceImage.path),
'IsAuth': localAuth.toString(),
if (latitude != null) 'Latitude': latitude,
if (longitude != null) 'Longitude': longitude,
});
final response = await apiClient.post(
@@ -171,12 +192,10 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
queryParameters: {'IsDeleted': false, 'EmployeeId': employeeId},
);
if (response.statusCode == 200) {
if (response.statusCode == 200 || response.statusCode == 201) {
final data = response.data;
if (data is Map<String, dynamic> &&
data['data'] != null &&
data['data']['items'] is List) {
final items = data['data']['items'] as List;
if (data is Map<String, dynamic>) {
final items = (data['data'] ?? data['Data'])?['items'] as List? ?? [];
return items.map((e) => AttendanceRecordDto.fromJson(e)).toList();
}
return [];
@@ -187,15 +206,82 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
}
} on DioException catch (e) {
throw ServerException(
message: e.message ?? 'Unknown error',
statusCode: e.response?.statusCode,
);
_handleDioError(e, 'فشل في جلب البيانات');
rethrow; // Should not reach here due to _handleDioError throwing
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
@override
Future<AttendanceRecordDto?> getLastRecord({
required String employeeId,
}) async {
try {
final response = await apiClient.get(
'/Attendance',
queryParameters: {
'IsDeleted': false,
'EmployeeId': employeeId,
'PageNumber': 1,
'PageSize': 1,
'SortBy': 'CreatedAt',
'SortDescending': true,
},
);
if (response.statusCode == 200 || response.statusCode == 201) {
final data = response.data;
if (data is Map<String, dynamic>) {
final items = (data['data'] ?? data['Data'])?['items'] as List? ?? [];
if (items.isNotEmpty) {
return AttendanceRecordDto.fromJson(items.first);
}
}
return null;
} else {
throw ServerException(
message: 'فشل في جلب آخر سجل',
statusCode: response.statusCode,
);
}
} on DioException catch (e) {
_handleDioError(e, 'فشل في جلب آخر سجل');
rethrow;
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
@override
Future<bool> hasActiveLogin({required String employeeId}) async {
try {
final last = await getLastRecord(employeeId: employeeId);
if (last == null) return false;
// The API enforces a DAILY check ("Employee already logged in today")
// So we check: has a login TODAY, regardless of logout status
if (last.login != null) {
final now = DateTime.now();
final loginDate = last.login!;
if (loginDate.year == now.year &&
loginDate.month == now.month &&
loginDate.day == now.day) {
// Logged in today — if no logout, definitely active
// If logout exists, they already completed today's cycle
return last.logout == null;
}
}
return false;
} catch (e) {
// If the check fails, let the user try — the API will reject if needed
print('hasActiveLogin check failed: $e');
return false;
}
}
@override
Future<List<OvertimeDto>> getExtraHours({required String employeeId}) async {
try {
@@ -204,7 +290,7 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
queryParameters: {'IsDeleted': false, 'EmployeeId': employeeId},
);
if (response.statusCode == 200) {
if (response.statusCode == 200 || response.statusCode == 201) {
final responseData = response.data;
if (responseData is Map<String, dynamic>) {
@@ -222,11 +308,10 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
}
} on DioException catch (e) {
throw ServerException(
message: e.message ?? 'Unknown error',
statusCode: e.response?.statusCode,
);
_handleDioError(e, 'فشل في جلب البيانات');
rethrow;
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
@@ -239,7 +324,7 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
queryParameters: {'IsDeleted': false, 'EmployeeId': employeeId},
);
if (response.statusCode == 200) {
if (response.statusCode == 200 || response.statusCode == 201) {
final responseData = response.data;
if (responseData is Map<String, dynamic>) {
return RewardListResponseDto.fromJson(responseData).items;
@@ -252,11 +337,10 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
}
} on DioException catch (e) {
throw ServerException(
message: e.message ?? 'Unknown error',
statusCode: e.response?.statusCode,
);
_handleDioError(e, 'فشل في جلب المكافآت');
rethrow;
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
@@ -271,7 +355,7 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
queryParameters: {'IsDeleted': false, 'EmployeeId': employeeId},
);
if (response.statusCode == 200) {
if (response.statusCode == 200 || response.statusCode == 201) {
final responseData = response.data;
if (responseData is Map<String, dynamic>) {
return PunishmentListResponseDto.fromJson(responseData).items;
@@ -284,11 +368,10 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
}
} on DioException catch (e) {
throw ServerException(
message: e.message ?? 'Unknown error',
statusCode: e.response?.statusCode,
);
_handleDioError(e, 'فشل في جلب البيانات');
rethrow;
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
@@ -309,17 +392,12 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
},
);
print('Salary Response Status: ${response.statusCode}');
if (response.statusCode == 200 || response.statusCode == 201) {
final responseData = response.data;
print(
'Salary Response Data: $responseData (${responseData.runtimeType})',
);
if (responseData is Map<String, dynamic>) {
return SalaryResponseDto.fromJson(responseData);
} else if (responseData is num) {
// Handle case where API returns raw number
return SalaryResponseDto(
isSuccess: true,
message: 'Success',
@@ -327,7 +405,6 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
} else if (responseData is String &&
double.tryParse(responseData) != null) {
// Handle case where API returns raw numeric string
return SalaryResponseDto(
isSuccess: true,
message: 'Success',
@@ -335,23 +412,49 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
);
} else {
throw ServerException(
message: 'استجابة غير صحيحة من الخادم: $responseData',
message: 'استجابة غير صحيحة من الخادم',
statusCode: response.statusCode,
);
}
} else {
throw ServerException(
message: 'فشل في حساب الراتب (Status: ${response.statusCode})',
message: 'فشل في حساب الراتب',
statusCode: response.statusCode,
);
}
} on DioException catch (e) {
throw ServerException(
message: e.message ?? 'Unknown error',
statusCode: e.response?.statusCode,
);
_handleDioError(e, 'فشل في حساب الراتب');
rethrow;
} catch (e) {
if (e is ServerException || e is NetworkException) rethrow;
throw ServerException(message: 'خطأ غير متوقع');
}
}
void _handleDioError(DioException e, String defaultMessage) {
if (e.type == DioExceptionType.connectionTimeout ||
e.type == DioExceptionType.receiveTimeout) {
throw NetworkException(message: 'انتهت مهلة الاتصال');
} else if (e.type == DioExceptionType.connectionError) {
throw NetworkException(message: 'لا يوجد اتصال بالانترنيت');
} else if (e.response?.statusCode == 500) {
throw ServerException(message: 'خطأ في الخادم يرجى المحاولة لاحقا');
} else if (e.response != null) {
final data = e.response?.data;
String? message;
if (data is Map<String, dynamic>) {
message = data['message']?.toString() ?? data['error']?.toString();
} else if (data is String) {
message = data;
}
throw ServerException(
message: message ?? defaultMessage,
statusCode: e.response?.statusCode,
);
} else {
throw NetworkException(message: 'خطأ في الانترنيت يرجى المحاولة لاحقا');
}
}
}

View File

@@ -0,0 +1,49 @@
import 'package:flutter/foundation.dart';
import '../../core/error/exceptions.dart';
import '../../core/network/api_client.dart';
import '../dto/theme_response_dto.dart';
abstract class ThemeRemoteDataSource {
Future<ThemeDataDto> getTheme();
}
class ThemeRemoteDataSourceImpl implements ThemeRemoteDataSource {
final ApiClient apiClient;
ThemeRemoteDataSourceImpl({required this.apiClient});
@override
Future<ThemeDataDto> getTheme() async {
try {
debugPrint('[ThemeDataSource] Calling GET /Theme (with auth)...');
final res = await apiClient.get('/Theme'); // ✅ no custom headers
debugPrint('[ThemeDataSource] Status: ${res.statusCode}');
debugPrint('[ThemeDataSource] Data: ${res.data}');
if (res.statusCode == 200) {
final dto = ThemeResponseDto.fromJson(
Map<String, dynamic>.from(res.data),
);
if (dto.isSuccess && dto.data != null) {
debugPrint('[ThemeDataSource] ✅ logo = ${dto.data!.logo}');
return dto.data!;
}
throw ServerException(message: dto.message ?? 'Theme request failed');
}
throw ServerException(
message: 'Theme request failed (code ${res.statusCode})',
);
} on ServerException {
rethrow;
} catch (e, stack) {
debugPrint('[ThemeDataSource] ❌ Exception: $e');
debugPrint('[ThemeDataSource] ❌ Stack: $stack');
throw ServerException(message: e.toString());
}
}
}

View File

@@ -6,12 +6,15 @@ abstract class UserLocalDataSource {
Future<void> clearCache();
Future<void> cacheEmployeeId(String id);
Future<String?> getCachedEmployeeId();
Future<void> cacheFullName(String name);
Future<String?> getCachedFullName();
}
class UserLocalDataSourceImpl implements UserLocalDataSource {
final SharedPreferences sharedPreferences;
static const String _tokenKey = 'user_token';
static const String _employeeIdKey = 'employee_id';
static const String _fullNameKey = 'full_name';
UserLocalDataSourceImpl({required this.sharedPreferences});
@@ -26,9 +29,13 @@ class UserLocalDataSourceImpl implements UserLocalDataSource {
}
@override
Future<void> clearCache() async {
await sharedPreferences.remove(_tokenKey);
await sharedPreferences.remove(_employeeIdKey);
Future<void> cacheFullName(String name) async {
await sharedPreferences.setString(_fullNameKey, name);
}
@override
Future<String?> getCachedFullName() async {
return sharedPreferences.getString(_fullNameKey);
}
@override
@@ -40,4 +47,11 @@ class UserLocalDataSourceImpl implements UserLocalDataSource {
Future<String?> getCachedEmployeeId() async {
return sharedPreferences.getString(_employeeIdKey);
}
@override
Future<void> clearCache() async {
await sharedPreferences.remove(_tokenKey);
await sharedPreferences.remove(_employeeIdKey);
await sharedPreferences.remove(_fullNameKey);
}
}

View File

@@ -0,0 +1,36 @@
class ThemeResponseDto {
final int statusCode;
final bool isSuccess;
final String? message;
final ThemeDataDto? data;
ThemeResponseDto({
required this.statusCode,
required this.isSuccess,
required this.message,
required this.data,
});
factory ThemeResponseDto.fromJson(Map<String, dynamic> json) {
return ThemeResponseDto(
statusCode: json['statusCode'] ?? 0,
isSuccess: json['isSuccess'] ?? false,
message: json['message']?.toString(),
data: json['data'] == null ? null : ThemeDataDto.fromJson(json['data']),
);
}
}
class ThemeDataDto {
final String name;
final String logo;
ThemeDataDto({required this.name, required this.logo});
factory ThemeDataDto.fromJson(Map<String, dynamic> json) {
return ThemeDataDto(
name: (json['name'] ?? '').toString(),
logo: (json['logo'] ?? '').toString(),
);
}
}

View File

@@ -18,6 +18,9 @@ class AttendanceRepositoryImpl implements AttendanceRepository {
final dto = await remoteDataSource.login(
employeeId: request.employeeId,
faceImage: request.faceImage,
localAuth: request.localAuth,
latitude: request.latitude,
longitude: request.longitude,
);
return AttendanceResponseModel(
@@ -34,6 +37,9 @@ class AttendanceRepositoryImpl implements AttendanceRepository {
final dto = await remoteDataSource.logout(
employeeId: request.employeeId,
faceImage: request.faceImage,
localAuth: request.localAuth,
latitude: request.latitude,
longitude: request.longitude,
);
return AttendanceResponseModel(
@@ -133,6 +139,34 @@ class AttendanceRepositoryImpl implements AttendanceRepository {
.toList();
}
@override
Future<AttendanceModel?> getLastRecord({required String employeeId}) async {
final dto = await remoteDataSource.getLastRecord(employeeId: employeeId);
if (dto == null) return null;
int? hours;
if (dto.login != null && dto.logout != null) {
hours = dto.logout!.difference(dto.login!).inHours;
}
return AttendanceModel(
id: dto.id,
employeeId: dto.employeeId,
date: dto.createdAt ?? dto.login,
loginTime: dto.login,
logoutTime: dto.logout,
workHours: hours,
createdAt: dto.createdAt ?? dto.login,
reason: dto.reason,
isDeleted: dto.isDeleted,
);
}
@override
Future<bool> hasActiveLogin({required String employeeId}) async {
return remoteDataSource.hasActiveLogin(employeeId: employeeId);
}
@override
Future<SalaryModel> calculateSalary({
required String employeeId,

View File

@@ -41,6 +41,9 @@ class AuthRepositoryImpl implements AuthRepository {
if (responseDto.data?.employeeId != null) {
print("AUTH_REPO: Caching EmployeeId: ${responseDto.data!.employeeId}");
await localDataSource.cacheEmployeeId(responseDto.data!.employeeId!);
if (responseDto.data!.fullName != null) {
await localDataSource.cacheFullName(responseDto.data!.fullName!);
}
} else {
print("AUTH_REPO: EmployeeId is NULL in response!");
}

View File

@@ -0,0 +1,32 @@
import 'package:dartz/dartz.dart';
import '../../core/config/app_urls.dart';
import '../../core/error/failures.dart';
import '../../core/error/exceptions.dart';
import '../../domain/models/theme_model.dart';
import '../../domain/repositories/theme_repository.dart';
import '../datasources/theme_remote_data_source.dart';
class ThemeRepositoryImpl implements ThemeRepository {
final ThemeRemoteDataSource remote;
ThemeRepositoryImpl({required this.remote});
@override
Future<Either<Failure, ThemeModel>> getTheme() async {
try {
final dto = await remote.getTheme();
return Right(
ThemeModel(
name: dto.name,
logo: dto.logo,
logoUrl: AppUrls.buildThemeLogoUrl(dto.logo),
),
);
} on ServerException catch (e) {
return Left(ServerFailure(e.message));
} catch (e) {
return Left(ServerFailure(e.toString()));
}
}
}

View File

@@ -3,6 +3,17 @@ import 'dart:io';
class AttendanceLoginRequest {
final String employeeId;
final File faceImage;
final bool localAuth;
AttendanceLoginRequest({required this.employeeId, required this.faceImage});
// ✅ NEW
final double? latitude;
final double? longitude;
AttendanceLoginRequest({
required this.employeeId,
required this.faceImage,
this.localAuth = false,
this.latitude,
this.longitude,
});
}

View File

@@ -3,6 +3,17 @@ import 'dart:io';
class AttendanceLogoutRequest {
final String employeeId;
final File faceImage;
final bool localAuth;
AttendanceLogoutRequest({required this.employeeId, required this.faceImage});
// ✅ NEW
final double? latitude;
final double? longitude;
AttendanceLogoutRequest({
required this.employeeId,
required this.faceImage,
this.localAuth = false,
this.latitude,
this.longitude,
});
}

View File

@@ -0,0 +1,8 @@
class LocationPayload {
final double lat;
final double lng;
const LocationPayload({required this.lat, required this.lng});
Map<String, dynamic> toJson() => {'latitude': lat, 'longitude': lng};
}

View File

@@ -0,0 +1,11 @@
class ThemeModel {
final String name;
final String logo;
final String logoUrl;
const ThemeModel({
required this.name,
required this.logo,
required this.logoUrl,
});
}

View File

@@ -20,6 +20,8 @@ abstract class AttendanceRepository {
Future<List<OvertimeModel>> getExtraHours({required String employeeId});
Future<List<ExtraPaymentModel>> getRewards({required String employeeId});
Future<List<ExtraPaymentModel>> getPunishments({required String employeeId});
Future<AttendanceModel?> getLastRecord({required String employeeId});
Future<bool> hasActiveLogin({required String employeeId});
Future<SalaryModel> calculateSalary({
required String employeeId,
required int month,

View File

@@ -0,0 +1,7 @@
import 'package:dartz/dartz.dart';
import '../../core/error/failures.dart';
import '../models/theme_model.dart';
abstract class ThemeRepository {
Future<Either<Failure, ThemeModel>> getTheme();
}

View File

@@ -0,0 +1,11 @@
import 'package:dartz/dartz.dart';
import '../../core/error/failures.dart';
import '../models/theme_model.dart';
import '../repositories/theme_repository.dart';
class GetThemeUseCase {
final ThemeRepository repo;
GetThemeUseCase(this.repo);
Future<Either<Failure, ThemeModel>> call() => repo.getTheme();
}

View File

@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import 'core/di/injection_container.dart';
import 'presentation/blocs/theme/theme_cubit.dart';
import 'presentation/screens/splash_screen.dart';
void main() async {
@@ -12,7 +14,12 @@ void main() async {
// Initialize dependency injection
await initializeDependencies();
runApp(const CodaApp());
runApp(
BlocProvider(
create: (_) => sl<ThemeCubit>()..loadTheme(),
child: const CodaApp(),
),
);
} catch (e) {
debugPrint('CRITICAL INITIALIZATION ERROR: $e');
// If initialization fails, show a simple error screen instead of a broken app

View File

@@ -0,0 +1,56 @@
import 'package:flutter/foundation.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../../../domain/usecases/get_theme_usecase.dart';
import 'theme_state.dart';
class ThemeCubit extends Cubit<ThemeState> {
final GetThemeUseCase getThemeUseCase;
/// Base URL for loading theme images (logo, etc.)
static const String _imageBaseUrl = 'https://hrm.go.iq/Images/';
/// Guard against re-entrant / duplicate calls
bool _isLoading = false;
ThemeCubit({required this.getThemeUseCase}) : super(const ThemeInitial());
/// Load theme. Set [forceReload] to true after login to refresh.
Future<void> loadTheme({bool forceReload = false}) async {
// Prevent duplicate concurrent calls
if (_isLoading) {
debugPrint('[ThemeCubit] loadTheme() skipped — already loading');
return;
}
// If already loaded and not forced, skip
if (!forceReload && state is ThemeLoaded) {
debugPrint('[ThemeCubit] loadTheme() skipped — already loaded');
return;
}
_isLoading = true;
debugPrint('[ThemeCubit] loadTheme() called (forceReload=$forceReload)');
emit(const ThemeLoading());
final result = await getThemeUseCase();
_isLoading = false;
result.fold(
(failure) {
debugPrint('[ThemeCubit] ❌ FAILED: ${failure.message}');
emit(ThemeError(failure.message));
},
(theme) {
debugPrint(
'[ThemeCubit] ✅ Got theme — name: ${theme.name}, logo: ${theme.logo}',
);
// Build the full logo URL: https://hrm.go.iq/Images/{filename}
final encodedLogo = Uri.encodeFull(theme.logo);
final logoUrl = '$_imageBaseUrl$encodedLogo';
debugPrint('[ThemeCubit] 🖼️ Logo URL: $logoUrl');
emit(ThemeLoaded(theme: theme, logoUrl: logoUrl));
},
);
}
}

View File

@@ -0,0 +1,36 @@
import 'package:equatable/equatable.dart';
import '../../../domain/models/theme_model.dart';
abstract class ThemeState extends Equatable {
const ThemeState();
@override
List<Object?> get props => [];
}
class ThemeInitial extends ThemeState {
const ThemeInitial();
}
class ThemeLoading extends ThemeState {
const ThemeLoading();
}
class ThemeLoaded extends ThemeState {
final ThemeModel theme;
final String logoUrl;
const ThemeLoaded({required this.theme, required this.logoUrl});
@override
List<Object?> get props => [theme, logoUrl];
}
class ThemeError extends ThemeState {
final String message;
const ThemeError(this.message);
@override
List<Object?> get props => [message];
}

View File

@@ -0,0 +1,28 @@
import 'package:flutter/material.dart';
enum FaceHintType {
noFace,
tooDark,
tooClose,
tooFar,
notCentered,
lookStraight,
holdStill,
good,
}
class FaceFeedback {
final FaceHintType type;
final String message;
final double quality; // 0..1 (used for progress ring)
final Color borderColor;
FaceFeedback({
required this.type,
required this.message,
required this.quality,
required this.borderColor,
});
bool get isGood => type == FaceHintType.good;
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,7 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../blocs/theme/theme_cubit.dart';
import '../blocs/theme/theme_state.dart';
import '../widgets/app_background.dart';
import '../widgets/auth_form.dart';
import '../../core/di/injection_container.dart';
@@ -19,8 +21,32 @@ class AuthScreen extends StatelessWidget {
child: Column(
children: [
const SizedBox(height: 60),
// Logo
Center(child: Image.asset("assets/images/logo2.png", width: 200)),
// Dynamic Logo from backend
Center(
child: BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, state) {
if (state is ThemeLoaded) {
return Image.network(
state.logoUrl,
width: 62,
height: 62,
errorBuilder:
(_, __, ___) =>
const Icon(Icons.image_not_supported),
);
}
return const Text(
'LOGO',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 2,
),
);
},
),
),
// const SizedBox(height: 15),
// Form - taking remaining space and centered
Expanded(child: Center(child: const AuthForm())),

View File

@@ -0,0 +1,533 @@
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:camera/camera.dart';
import 'package:flutter/material.dart';
import '../../core/error/exceptions.dart';
import 'package:local_auth/local_auth.dart';
class OvalCameraCapturePage extends StatefulWidget {
final bool isLogin;
final Future<void> Function(File image, {required bool localAuth}) onCapture;
const OvalCameraCapturePage({
super.key,
this.isLogin = true,
required this.onCapture,
});
@override
State<OvalCameraCapturePage> createState() => _OvalCameraCapturePageState();
}
class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
CameraController? _cameraController;
bool _isCameraInitialized = false;
String? _errorMessage;
bool _isSuccess = false;
bool _isSubmitting = false;
// Timer countdown
int _countdown = 3;
Timer? _countdownTimer;
bool _countdownStarted = false;
// Local auth for 422
final LocalAuthentication _localAuth = LocalAuthentication();
bool _handlingAuth422 = false;
File? _lastCapturedFile;
@override
void initState() {
super.initState();
_initializeCamera();
}
@override
void dispose() {
_countdownTimer?.cancel();
_cameraController?.dispose();
super.dispose();
}
Future<void> _initializeCamera() async {
try {
setState(() {
_errorMessage = null;
_isCameraInitialized = false;
_isSuccess = false;
_isSubmitting = false;
_countdown = 3;
_countdownStarted = false;
});
await _cameraController?.dispose();
_cameraController = null;
final cameras = await availableCameras();
if (cameras.isEmpty) {
if (!mounted) return;
setState(() {
_errorMessage = "لا توجد كاميرات متاحة على هذا الجهاز";
_isCameraInitialized = false;
});
return;
}
final front = cameras.where(
(c) => c.lensDirection == CameraLensDirection.front,
);
final selectedCamera = front.isNotEmpty ? front.first : cameras.first;
_cameraController = CameraController(
selectedCamera,
ResolutionPreset.medium,
enableAudio: false,
);
await _cameraController!.initialize();
if (!mounted) return;
setState(() {
_isCameraInitialized = true;
});
_startCountdown();
} catch (e) {
if (!mounted) return;
setState(() {
_errorMessage = "خطأ في تهيئة الكاميرا: $e";
_isCameraInitialized = false;
});
}
}
void _startCountdown() {
if (_countdownStarted) return;
_countdownStarted = true;
_countdown = 3;
_countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (!mounted) {
timer.cancel();
return;
}
setState(() {
_countdown--;
});
if (_countdown <= 0) {
timer.cancel();
_captureAndSubmit();
}
});
}
Future<bool?> _showLocalAuthDialog() {
return showDialog<bool>(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: const Text('فشل التحقق بالوجه', textAlign: TextAlign.center),
content: const Text(
'لم يتم التعرف على الوجه.\n\nيرجى استخدام بصمة الإصبع أو رمز القفل (PIN/النمط) للمتابعة.',
textAlign: TextAlign.center,
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('إلغاء'),
),
ElevatedButton(
onPressed: () => Navigator.pop(context, true),
child: const Text('استخدام البصمة / رمز القفل'),
),
],
),
);
}
Future<bool> _authenticateLocally() async {
try {
final isSupported = await _localAuth.isDeviceSupported();
if (!isSupported) return false;
return await _localAuth.authenticate(
localizedReason: 'تأكيد هويتك لإكمال تسجيل الحضور.',
options: const AuthenticationOptions(
biometricOnly: false,
stickyAuth: true,
useErrorDialogs: true,
),
);
} catch (_) {
return false;
}
}
void _stopCameraCompletely() {
_countdownTimer?.cancel();
try {
_cameraController?.dispose();
_cameraController = null;
} catch (e) {
debugPrint("Error stopping camera: $e");
}
}
Future<void> _captureAndSubmit() async {
if (_cameraController == null) return;
if (_isSubmitting || _isSuccess) return;
setState(() {
_isSubmitting = true;
_errorMessage = null;
});
try {
if (_cameraController == null ||
!_cameraController!.value.isInitialized) {
_handleScanError("الكاميرا غير جاهزة، حاول مرة أخرى");
return;
}
final xFile = await _cameraController!.takePicture();
final file = File(xFile.path);
_lastCapturedFile = file;
await widget.onCapture(file, localAuth: false);
if (mounted) {
setState(() {
_isSuccess = true;
_isSubmitting = false;
});
Future.delayed(const Duration(seconds: 1), () {
if (mounted) {
Navigator.of(context).pop(true);
}
});
}
} on ServerException catch (e) {
final msg = e.message.toLowerCase();
if (e.statusCode == 422 || msg.contains('face verification failed')) {
await _handleFaceVerificationFailed422(e);
return;
}
if (msg.contains('already logged in') ||
msg.contains('مسجل دخول بالفعل')) {
_stopCameraCompletely();
if (mounted) {
showDialog(
context: context,
barrierDismissible: false,
builder: (_) => AlertDialog(
title: const Text('تنبيه', textAlign: TextAlign.center),
content: const Text(
'أنت مسجل دخول بالفعل، لا يمكنك تسجيل الدخول مرة أخرى.',
textAlign: TextAlign.center,
),
actions: [
TextButton(
onPressed: () {
Navigator.of(context).pop();
Navigator.of(context).pop();
},
child: const Text('حسناً'),
),
],
),
);
}
return;
}
_handleScanError(e.message);
} on NetworkException catch (e) {
_handleScanError(e.message);
} on CameraException catch (e) {
_handleScanError("فشل التقاط الصورة: ${e.description ?? e.code}");
} catch (e) {
_handleScanError("حدث خطأ غير متوقع: $e");
}
}
void _handleScanError(String msg) {
if (!mounted) return;
setState(() {
_isSubmitting = false;
_errorMessage = msg;
_countdown = 3;
_countdownStarted = false;
});
// Restart countdown after error
_startCountdown();
}
Future<void> _handleFaceVerificationFailed422(ServerException e) async {
if (!mounted) return;
if (_handlingAuth422) return;
_handlingAuth422 = true;
setState(() {
_isSubmitting = false;
_errorMessage = null;
});
final proceed = await _showLocalAuthDialog();
if (proceed != true) {
_handlingAuth422 = false;
_stopCameraCompletely();
if (!mounted) return;
Navigator.of(context).pop(false);
return;
}
final ok = await _authenticateLocally();
if (!ok) {
_handlingAuth422 = false;
_stopCameraCompletely();
if (!mounted) return;
Navigator.of(context).pop("local_auth_failed");
return;
}
final file = _lastCapturedFile;
if (file == null) {
_handlingAuth422 = false;
_stopCameraCompletely();
if (!mounted) return;
Navigator.of(context).pop("retry_missing_file");
return;
}
setState(() {
_isSubmitting = true;
});
try {
await widget.onCapture(file, localAuth: true);
if (!mounted) return;
setState(() {
_isSuccess = true;
_isSubmitting = false;
});
Future.delayed(const Duration(seconds: 1), () {
if (mounted) Navigator.of(context).pop(true);
});
} on ServerException catch (_) {
_handlingAuth422 = false;
_stopCameraCompletely();
if (!mounted) return;
Navigator.of(context).pop("retry_failed");
} catch (_) {
_handlingAuth422 = false;
_stopCameraCompletely();
if (!mounted) return;
Navigator.of(context).pop("retry_failed");
}
}
@override
Widget build(BuildContext context) {
if (_errorMessage != null && !_isCameraInitialized) {
return Scaffold(
backgroundColor: Colors.black,
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.error, color: Colors.red, size: 48),
const SizedBox(height: 16),
Text(_errorMessage!, style: const TextStyle(color: Colors.white)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: _initializeCamera,
child: const Text("إعادة المحاولة"),
),
],
),
),
);
}
if (!_isCameraInitialized || _cameraController == null) {
return const Scaffold(
backgroundColor: Colors.black,
body: Center(child: CircularProgressIndicator(color: Colors.red)),
);
}
return Scaffold(
backgroundColor: Colors.black,
body: Stack(
fit: StackFit.expand,
children: [
Center(child: CameraPreview(_cameraController!)),
CustomPaint(
painter: _OvalOverlayPainter(
borderColor: _isSuccess
? Colors.greenAccent
: (_countdown <= 1 ? Colors.orangeAccent : Colors.white70),
progress: _countdownStarted
? ((3 - _countdown) / 3).clamp(0.0, 1.0)
: 0,
),
),
Positioned(
top: 60,
left: 0,
right: 0,
child: Column(
children: [
Text(
widget.isLogin ? "تسجيل الدخول" : "تسجيل خروج",
style: const TextStyle(
color: Colors.white,
fontSize: 24,
fontWeight: FontWeight.bold,
fontFamily: 'Cairo',
),
),
const SizedBox(height: 10),
Container(
padding: const EdgeInsets.symmetric(
horizontal: 16,
vertical: 8,
),
decoration: BoxDecoration(
color: Colors.black54,
borderRadius: BorderRadius.circular(20),
),
child: Text(
_isSubmitting
? "جاري التحقق..."
: _isSuccess
? "تم بنجاح"
: "التقاط الصورة خلال $_countdown ثانية",
style: TextStyle(
color: _isSuccess ? Colors.greenAccent : Colors.white,
fontSize: 16,
fontWeight: FontWeight.w600,
),
),
),
],
),
),
// Countdown number in center
if (!_isSubmitting && !_isSuccess && _countdown > 0)
Center(
child: Text(
'$_countdown',
style: TextStyle(
color: Colors.white.withOpacity(0.7),
fontSize: 80,
fontWeight: FontWeight.bold,
),
),
),
if (_isSubmitting)
const Center(child: CircularProgressIndicator(color: Colors.white)),
if (_isSuccess)
const Center(
child: Icon(Icons.check_circle, color: Colors.green, size: 80),
),
if (_errorMessage != null && _isCameraInitialized)
Positioned(
bottom: 20,
left: 0,
right: 0,
child: Container(
color: Colors.black54,
padding: const EdgeInsets.all(8),
child: Text(
_errorMessage!,
style: const TextStyle(color: Colors.red),
textAlign: TextAlign.center,
),
),
),
],
),
);
}
}
class _OvalOverlayPainter extends CustomPainter {
final Color borderColor;
final double progress;
_OvalOverlayPainter({required this.borderColor, required this.progress});
@override
void paint(Canvas canvas, Size size) {
final width = size.width * 0.75;
final height = size.height * 0.55;
final center = Offset(size.width / 2, size.height / 2);
final ovalRect = Rect.fromCenter(
center: center,
width: width,
height: height,
);
final screenPath =
Path()..addRect(Rect.fromLTWH(0, 0, size.width, size.height));
final ovalPath = Path()..addOval(ovalRect);
final overlayPath = Path.combine(
PathOperation.difference,
screenPath,
ovalPath,
);
final bgPaint = Paint()
..color = Colors.black.withOpacity(0.6)
..style = PaintingStyle.fill;
canvas.drawPath(overlayPath, bgPaint);
final borderPaint = Paint()
..color = borderColor
..style = PaintingStyle.stroke
..strokeWidth = 4.0;
canvas.drawOval(ovalRect, borderPaint);
if (progress > 0) {
final progressPaint = Paint()
..color = Colors.greenAccent
..style = PaintingStyle.stroke
..strokeWidth = 6.0
..strokeCap = StrokeCap.round;
final startAngle = -math.pi / 2;
final sweepAngle = 2 * math.pi * progress;
canvas.drawArc(
ovalRect.inflate(10),
startAngle,
sweepAngle,
false,
progressPaint,
);
}
}
@override
bool shouldRepaint(covariant _OvalOverlayPainter oldDelegate) {
return oldDelegate.borderColor != borderColor ||
oldDelegate.progress != progress;
}
}

View File

@@ -51,7 +51,6 @@ class _FinanceScreenState extends State<FinanceScreen> {
void _triggerLoad() {
if (_employeeId != null && _employeeId!.isNotEmpty) {
if (_financeBloc.state is FinanceInitial) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
@@ -62,6 +61,12 @@ class _FinanceScreenState extends State<FinanceScreen> {
);
}
}
Future<void> _onRefresh() async {
_triggerLoad();
await _financeBloc.stream.firstWhere(
(state) => state is FinanceLoaded || state is FinanceError,
);
}
@override
@@ -71,9 +76,14 @@ class _FinanceScreenState extends State<FinanceScreen> {
child: Directionality(
textDirection: TextDirection.ltr,
child: SafeArea(
child: RefreshIndicator(
onRefresh: _onRefresh,
color: const Color(0xFF0A6B4A),
child: CustomScrollView(
controller: scrollController,
physics: const BouncingScrollPhysics(),
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
slivers: [
SliverToBoxAdapter(
child: SettingsBar(
@@ -130,7 +140,8 @@ class _FinanceScreenState extends State<FinanceScreen> {
);
if (date != null && mounted) {
setState(() => selectedDate = date);
if (_employeeId != null && _employeeId!.isNotEmpty) {
if (_employeeId != null &&
_employeeId!.isNotEmpty) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
@@ -145,7 +156,8 @@ class _FinanceScreenState extends State<FinanceScreen> {
onCategoryChanged: (category) {
if (category != null) {
setState(() => currentCategory = category);
if (_employeeId != null && _employeeId!.isNotEmpty) {
if (_employeeId != null &&
_employeeId!.isNotEmpty) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
@@ -213,6 +225,7 @@ class _FinanceScreenState extends State<FinanceScreen> {
),
),
),
),
);
}
}

View File

@@ -223,6 +223,10 @@ class _HolidayScreenState extends State<HolidayScreen> {
);
}
Future<void> _onRefresh() async {
await Future.wait([_loadVacationsFromAPI(), _loadAdvancesFromAPI()]);
}
AdvanceRequest _convertAdvanceToAdvanceRequest(AdvanceDataModel advance) {
// Convert state (0=waiting, 1=approved, 2=denied) to status string
String status = "waiting";
@@ -248,9 +252,14 @@ class _HolidayScreenState extends State<HolidayScreen> {
// ⭐ MAIN CONTENT - CUSTOM SCROLL VIEW
// ---------------------------------------------------------
SafeArea(
child: RefreshIndicator(
onRefresh: _onRefresh,
color: const Color(0xFF0A6B4A),
child: CustomScrollView(
controller: _scrollController,
physics: const BouncingScrollPhysics(),
physics: const AlwaysScrollableScrollPhysics(
parent: BouncingScrollPhysics(),
),
slivers: [
// SETTINGS BAR
SliverToBoxAdapter(
@@ -367,6 +376,7 @@ class _HolidayScreenState extends State<HolidayScreen> {
],
),
),
),
// ---------------------------------------------------------
// ⭐ FLOATING ACTION BUTTONS

View File

@@ -1,6 +1,9 @@
import 'dart:async';
import 'package:coda_project/presentation/screens/auth_screen.dart';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import '../blocs/theme/theme_cubit.dart';
import '../blocs/theme/theme_state.dart';
import '../widgets/onboarding_page.dart';
import '../widgets/onboarding_button.dart';
@@ -88,7 +91,29 @@ class _OnboardingScreenState extends State<OnboardingScreen> {
Column(
children: [
const SizedBox(height: 70),
Image.asset("assets/images/logo2.png", width: 200),
// Dynamic Logo from backend
BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, state) {
if (state is ThemeLoaded) {
return Image.network(
state.logoUrl,
width: 62,
height: 62,
errorBuilder:
(_, __, ___) => const Icon(Icons.image_not_supported),
);
}
return const Text(
'LOGO',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 2,
),
);
},
),
/// PAGEVIEW (SVG + TEXT ONLY)
Expanded(

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_native_splash/flutter_native_splash.dart';
import '../blocs/theme/theme_cubit.dart';
import '../blocs/theme/theme_state.dart';
import 'onboarding_screen.dart';
import 'main_screen.dart';
import '../../core/di/injection_container.dart';
@@ -31,7 +34,7 @@ class _SplashScreenState extends State<SplashScreen> {
final token = await sl<UserLocalDataSource>().getCachedUserToken();
if (token != null && token.isNotEmpty) {
// Token exists, navigate directly to MainPage
// Token exists — go to MainPage (theme already loaded in main.dart)
Navigator.pushReplacement(
context,
MaterialPageRoute(builder: (_) => const MainPage()),
@@ -65,7 +68,30 @@ class _SplashScreenState extends State<SplashScreen> {
fit: BoxFit.cover,
),
),
child: Center(child: Image.asset("assets/images/logo.png", width: 200)),
child: Center(
child: BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, state) {
if (state is ThemeLoaded) {
return Image.network(
state.logoUrl,
width: 62,
height: 62,
errorBuilder:
(_, __, ___) => const Icon(Icons.image_not_supported),
);
}
return const Text(
'LOGO',
style: TextStyle(
fontSize: 36,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 2,
),
);
},
),
),
),
);
}

View File

@@ -17,6 +17,22 @@ class UserSettingsScreen extends StatefulWidget {
class _UserSettingsScreenState extends State<UserSettingsScreen> {
bool _notificationsOn = false;
String _userName = 'اسم الموظف';
@override
void initState() {
super.initState();
_loadUserName();
}
Future<void> _loadUserName() async {
final name = await sl<UserLocalDataSource>().getCachedFullName();
if (mounted) {
setState(() {
_userName = name ?? 'اسم الموظف';
});
}
}
@override
Widget build(BuildContext context) {
@@ -84,8 +100,8 @@ class _UserSettingsScreenState extends State<UserSettingsScreen> {
const SizedBox(height: 10),
/// -------------------- USER NAME --------------------
const Text(
"اسم الموظف",
Text(
_userName,
style: TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart';
import '../blocs/theme/theme_cubit.dart';
import '../blocs/theme/theme_state.dart';
class SettingsBar extends StatelessWidget {
final int selectedIndex;
@@ -12,7 +15,7 @@ class SettingsBar extends StatelessWidget {
super.key,
required this.selectedIndex,
required this.onTap,
this.showBackButton = false, // to switch between back button and settings icons
this.showBackButton = false,
this.onBackTap,
required this.iconPaths,
});
@@ -25,10 +28,28 @@ class SettingsBar extends StatelessWidget {
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Row(
children: [
Image.asset('assets/images/logo2.png', width: 150, height: 40),
],
// Dynamic Logo from backend
BlocBuilder<ThemeCubit, ThemeState>(
builder: (context, state) {
if (state is ThemeLoaded) {
return Image.network(
state.logoUrl,
width: 62,
height: 62,
errorBuilder:
(_, __, ___) => const Icon(Icons.image_not_supported),
);
}
return const Text(
'LOGO',
style: TextStyle(
fontSize: 28,
fontWeight: FontWeight.bold,
color: Colors.white,
letterSpacing: 2,
),
);
},
),
Row(
children: [
@@ -50,11 +71,10 @@ class SettingsBar extends StatelessWidget {
],
),
child: Center(
// Always use Flutter's built-in back icon pointing to the right
child: const Icon(
Icons.arrow_forward, // Changed to arrow_forward for RTL
Icons.arrow_forward,
size: 26,
color: Colors.black, // Adjust color as needed
color: Colors.black,
),
),
),
@@ -65,7 +85,6 @@ class SettingsBar extends StatelessWidget {
...iconPaths.asMap().entries.map((entry) {
final index = entry.key;
final iconPath = entry.value;
// final isSelected = selectedIndex == index;
return Padding(
padding: const EdgeInsets.only(left: 10),

View File

@@ -5,8 +5,12 @@
import FlutterMacOS
import Foundation
import geolocator_apple
import local_auth_darwin
import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) {
GeolocatorPlugin.register(with: registry.registrar(forPlugin: "GeolocatorPlugin"))
LocalAuthPlugin.register(with: registry.registrar(forPlugin: "LocalAuthPlugin"))
SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
}

View File

@@ -209,6 +209,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter:
dependency: "direct main"
description: flutter
@@ -272,6 +280,54 @@ packages:
description: flutter
source: sdk
version: "0.0.0"
geolocator:
dependency: "direct main"
description:
name: geolocator
sha256: f62bcd90459e63210bbf9c35deb6a51c521f992a78de19a1fe5c11704f9530e2
url: "https://pub.dev"
source: hosted
version: "13.0.4"
geolocator_android:
dependency: transitive
description:
name: geolocator_android
sha256: fcb1760a50d7500deca37c9a666785c047139b5f9ee15aa5469fae7dbbe3170d
url: "https://pub.dev"
source: hosted
version: "4.6.2"
geolocator_apple:
dependency: transitive
description:
name: geolocator_apple
sha256: dbdd8789d5aaf14cf69f74d4925ad1336b4433a6efdf2fce91e8955dc921bf22
url: "https://pub.dev"
source: hosted
version: "2.3.13"
geolocator_platform_interface:
dependency: transitive
description:
name: geolocator_platform_interface
sha256: "30cb64f0b9adcc0fb36f628b4ebf4f731a2961a0ebd849f4b56200205056fe67"
url: "https://pub.dev"
source: hosted
version: "4.2.6"
geolocator_web:
dependency: transitive
description:
name: geolocator_web
sha256: b1ae9bdfd90f861fde8fd4f209c37b953d65e92823cb73c7dee1fa021b06f172
url: "https://pub.dev"
source: hosted
version: "4.1.3"
geolocator_windows:
dependency: transitive
description:
name: geolocator_windows
sha256: "175435404d20278ffd220de83c2ca293b73db95eafbdc8131fe8609be1421eb6"
url: "https://pub.dev"
source: hosted
version: "0.2.5"
get_it:
dependency: "direct main"
description:
@@ -360,6 +416,46 @@ packages:
url: "https://pub.dev"
source: hosted
version: "5.1.1"
local_auth:
dependency: "direct main"
description:
name: local_auth
sha256: "434d854cf478f17f12ab29a76a02b3067f86a63a6d6c4eb8fbfdcfe4879c1b7b"
url: "https://pub.dev"
source: hosted
version: "2.3.0"
local_auth_android:
dependency: transitive
description:
name: local_auth_android
sha256: "48924f4a8b3cc45994ad5993e2e232d3b00788a305c1bf1c7db32cef281ce9a3"
url: "https://pub.dev"
source: hosted
version: "1.0.52"
local_auth_darwin:
dependency: transitive
description:
name: local_auth_darwin
sha256: "0e9706a8543a4a2eee60346294d6a633dd7c3ee60fae6b752570457c4ff32055"
url: "https://pub.dev"
source: hosted
version: "1.6.0"
local_auth_platform_interface:
dependency: transitive
description:
name: local_auth_platform_interface
sha256: f98b8e388588583d3f781f6806e4f4c9f9e189d898d27f0c249b93a1973dd122
url: "https://pub.dev"
source: hosted
version: "1.1.0"
local_auth_windows:
dependency: transitive
description:
name: local_auth_windows
sha256: bc4e66a29b0fdf751aafbec923b5bed7ad6ed3614875d8151afe2578520b2ab5
url: "https://pub.dev"
source: hosted
version: "1.0.11"
matcher:
dependency: transitive
description:
@@ -613,6 +709,14 @@ packages:
url: "https://pub.dev"
source: hosted
version: "2.3.1"
uuid:
dependency: transitive
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
url: "https://pub.dev"
source: hosted
version: "4.5.3"
vector_graphics:
dependency: transitive
description:

View File

@@ -20,6 +20,9 @@ dependencies:
flutter_bloc: ^8.1.6
intl: ^0.19.0
local_auth: ^2.1.8
geolocator: ^13.0.1
dev_dependencies:
flutter_test:
sdk: flutter

View File

@@ -6,6 +6,12 @@
#include "generated_plugin_registrant.h"
#include <geolocator_windows/geolocator_windows.h>
#include <local_auth_windows/local_auth_plugin.h>
void RegisterPlugins(flutter::PluginRegistry* registry) {
GeolocatorWindowsRegisterWithRegistrar(
registry->GetRegistrarForPlugin("GeolocatorWindows"));
LocalAuthPluginRegisterWithRegistrar(
registry->GetRegistrarForPlugin("LocalAuthPlugin"));
}

View File

@@ -3,6 +3,8 @@
#
list(APPEND FLUTTER_PLUGIN_LIST
geolocator_windows
local_auth_windows
)
list(APPEND FLUTTER_FFI_PLUGIN_LIST