Compare commits

...

6 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
40 changed files with 1793 additions and 942 deletions

View File

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

View File

@@ -1,5 +1,5 @@
package com.example.coda_project 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 # 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. # CocoaPods analytics sends network stats synchronously affecting flutter build latency.
ENV['COCOAPODS_DISABLE_STATS'] = 'true' ENV['COCOAPODS_DISABLE_STATS'] = 'true'

View File

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

View File

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

View File

@@ -45,11 +45,17 @@
<true/> <true/>
<key>UIApplicationSupportsIndirectInputEvents</key> <key>UIApplicationSupportsIndirectInputEvents</key>
<true/> <true/>
<key>UIStatusBarHidden</key> <key>UIStatusBarHidden</key>
<false/> <false/>
<key>NSCameraUsageDescription</key> <key>NSCameraUsageDescription</key>
<string>We need access to your camera to capture photos for face recognition.</string> <string>We need access to your camera to capture photos for face recognition.</string>
<key>NSPhotoLibraryUsageDescription</key> <key>NSPhotoLibraryUsageDescription</key>
<string>We need access to your photo library to select photos.</string> <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> </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 '../../domain/usecases/change_password_usecase.dart';
import '../../presentation/blocs/login/login_bloc.dart'; import '../../presentation/blocs/login/login_bloc.dart';
import '../../presentation/blocs/change_password/change_password_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; final sl = GetIt.instance;
@@ -124,4 +130,18 @@ Future<void> initializeDependencies() async {
sl.registerLazySingleton(() => CreateAdvanceUseCase(repository: sl())); sl.registerLazySingleton(() => CreateAdvanceUseCase(repository: sl()));
sl.registerLazySingleton(() => GetAdvancesUseCase(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

@@ -19,10 +19,14 @@ class ApiClient {
dio.interceptors.add( dio.interceptors.add(
InterceptorsWrapper( InterceptorsWrapper(
onRequest: (options, handler) async { onRequest: (options, handler) async {
// Get token from SharedPreferences // Skip auth if the request explicitly opts out
final token = sharedPreferences?.getString(_tokenKey); final skipAuth = options.extra['skipAuth'] == true;
if (token != null && token.isNotEmpty) { if (!skipAuth) {
options.headers['Authorization'] = 'Bearer $token'; // Get token from SharedPreferences
final token = sharedPreferences?.getString(_tokenKey);
if (token != null && token.isNotEmpty) {
options.headers['Authorization'] = 'Bearer $token';
}
} }
return handler.next(options); return handler.next(options);
}, },

View File

@@ -13,11 +13,17 @@ abstract class AttendanceRemoteDataSource {
Future<AttendanceResponseDto> login({ Future<AttendanceResponseDto> login({
required String employeeId, required String employeeId,
required File faceImage, required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}); });
Future<AttendanceResponseDto> logout({ Future<AttendanceResponseDto> logout({
required String employeeId, required String employeeId,
required File faceImage, required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}); });
Future<List<AttendanceRecordDto>> getAttendanceRecords({ Future<List<AttendanceRecordDto>> getAttendanceRecords({
@@ -43,11 +49,18 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
Future<AttendanceResponseDto> login({ Future<AttendanceResponseDto> login({
required String employeeId, required String employeeId,
required File faceImage, required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}) async { }) async {
try { try {
final formData = FormData.fromMap({ final formData = FormData.fromMap({
'EmployeeId': employeeId, 'EmployeeId': employeeId,
'FaceImage': await MultipartFile.fromFile(faceImage.path), '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( final response = await apiClient.post(
@@ -107,11 +120,17 @@ class AttendanceRemoteDataSourceImpl implements AttendanceRemoteDataSource {
Future<AttendanceResponseDto> logout({ Future<AttendanceResponseDto> logout({
required String employeeId, required String employeeId,
required File faceImage, required File faceImage,
bool localAuth = false,
double? latitude,
double? longitude,
}) async { }) async {
try { try {
final formData = FormData.fromMap({ final formData = FormData.fromMap({
'EmployeeId': employeeId, 'EmployeeId': employeeId,
'FaceImage': await MultipartFile.fromFile(faceImage.path), 'FaceImage': await MultipartFile.fromFile(faceImage.path),
'IsAuth': localAuth.toString(),
if (latitude != null) 'Latitude': latitude,
if (longitude != null) 'Longitude': longitude,
}); });
final response = await apiClient.post( final response = await apiClient.post(

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> clearCache();
Future<void> cacheEmployeeId(String id); Future<void> cacheEmployeeId(String id);
Future<String?> getCachedEmployeeId(); Future<String?> getCachedEmployeeId();
Future<void> cacheFullName(String name);
Future<String?> getCachedFullName();
} }
class UserLocalDataSourceImpl implements UserLocalDataSource { class UserLocalDataSourceImpl implements UserLocalDataSource {
final SharedPreferences sharedPreferences; final SharedPreferences sharedPreferences;
static const String _tokenKey = 'user_token'; static const String _tokenKey = 'user_token';
static const String _employeeIdKey = 'employee_id'; static const String _employeeIdKey = 'employee_id';
static const String _fullNameKey = 'full_name';
UserLocalDataSourceImpl({required this.sharedPreferences}); UserLocalDataSourceImpl({required this.sharedPreferences});
@@ -26,9 +29,13 @@ class UserLocalDataSourceImpl implements UserLocalDataSource {
} }
@override @override
Future<void> clearCache() async { Future<void> cacheFullName(String name) async {
await sharedPreferences.remove(_tokenKey); await sharedPreferences.setString(_fullNameKey, name);
await sharedPreferences.remove(_employeeIdKey); }
@override
Future<String?> getCachedFullName() async {
return sharedPreferences.getString(_fullNameKey);
} }
@override @override
@@ -40,4 +47,11 @@ class UserLocalDataSourceImpl implements UserLocalDataSource {
Future<String?> getCachedEmployeeId() async { Future<String?> getCachedEmployeeId() async {
return sharedPreferences.getString(_employeeIdKey); 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( final dto = await remoteDataSource.login(
employeeId: request.employeeId, employeeId: request.employeeId,
faceImage: request.faceImage, faceImage: request.faceImage,
localAuth: request.localAuth,
latitude: request.latitude,
longitude: request.longitude,
); );
return AttendanceResponseModel( return AttendanceResponseModel(
@@ -34,6 +37,9 @@ class AttendanceRepositoryImpl implements AttendanceRepository {
final dto = await remoteDataSource.logout( final dto = await remoteDataSource.logout(
employeeId: request.employeeId, employeeId: request.employeeId,
faceImage: request.faceImage, faceImage: request.faceImage,
localAuth: request.localAuth,
latitude: request.latitude,
longitude: request.longitude,
); );
return AttendanceResponseModel( return AttendanceResponseModel(

View File

@@ -41,6 +41,9 @@ class AuthRepositoryImpl implements AuthRepository {
if (responseDto.data?.employeeId != null) { if (responseDto.data?.employeeId != null) {
print("AUTH_REPO: Caching EmployeeId: ${responseDto.data!.employeeId}"); print("AUTH_REPO: Caching EmployeeId: ${responseDto.data!.employeeId}");
await localDataSource.cacheEmployeeId(responseDto.data!.employeeId!); await localDataSource.cacheEmployeeId(responseDto.data!.employeeId!);
if (responseDto.data!.fullName != null) {
await localDataSource.cacheFullName(responseDto.data!.fullName!);
}
} else { } else {
print("AUTH_REPO: EmployeeId is NULL in response!"); 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 { class AttendanceLoginRequest {
final String employeeId; final String employeeId;
final File faceImage; 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 { class AttendanceLogoutRequest {
final String employeeId; final String employeeId;
final File faceImage; 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

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

File diff suppressed because it is too large Load Diff

View File

@@ -1,5 +1,7 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.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/app_background.dart';
import '../widgets/auth_form.dart'; import '../widgets/auth_form.dart';
import '../../core/di/injection_container.dart'; import '../../core/di/injection_container.dart';
@@ -19,8 +21,32 @@ class AuthScreen extends StatelessWidget {
child: Column( child: Column(
children: [ children: [
const SizedBox(height: 60), const SizedBox(height: 60),
// Logo // Dynamic Logo from backend
Center(child: Image.asset("assets/images/logo2.png", width: 200)), 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), // const SizedBox(height: 15),
// Form - taking remaining space and centered // Form - taking remaining space and centered
Expanded(child: Center(child: const AuthForm())), Expanded(child: Center(child: const AuthForm())),

View File

@@ -1,21 +1,16 @@
import 'dart:async'; import 'dart:async';
import 'dart:io'; import 'dart:io';
import 'dart:math' as math; import 'dart:math' as math;
import 'dart:typed_data';
import 'package:flutter/foundation.dart';
import 'package:camera/camera.dart'; import 'package:camera/camera.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:google_mlkit_face_detection/google_mlkit_face_detection.dart';
import '../../core/error/exceptions.dart'; import '../../core/error/exceptions.dart';
import '../face/face_feedback.dart'; import 'package:local_auth/local_auth.dart';
class OvalCameraCapturePage extends StatefulWidget { class OvalCameraCapturePage extends StatefulWidget {
final bool isLogin; final bool isLogin;
final Future<void> Function(File image) onCapture; final Future<void> Function(File image, {required bool localAuth}) onCapture;
const OvalCameraCapturePage({ const OvalCameraCapturePage({
super.key, super.key,
@@ -35,54 +30,27 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
bool _isSuccess = false; bool _isSuccess = false;
bool _isSubmitting = false; bool _isSubmitting = false;
bool _isStreaming = false;
// Smart feedback // Timer countdown
FaceFeedback _feedback = FaceFeedback( int _countdown = 3;
type: FaceHintType.noFace, Timer? _countdownTimer;
message: "ضع وجهك داخل الإطار", bool _countdownStarted = false;
quality: 0,
borderColor: Colors.white70,
);
double _progress = 0; // Local auth for 422
bool _isDetecting = false; final LocalAuthentication _localAuth = LocalAuthentication();
int _frameCount = 0; bool _handlingAuth422 = false;
File? _lastCapturedFile;
// Stability tracking
Rect? _lastFaceRect;
int _stableFrames = 0;
bool _showManualCapture = false;
Timer? _manualCaptureTimer;
String _debugInfo = "Initializing...";
late final FaceDetector _faceDetector = FaceDetector(
options: FaceDetectorOptions(
performanceMode: FaceDetectorMode.fast,
enableTracking: true,
enableClassification: true,
enableLandmarks: false,
enableContours: false,
),
);
static const int _throttleEveryNFrames = 5;
static const int _stableFramesNeeded = 3;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
// Go straight to camera — no network calls here
_initializeCamera(); _initializeCamera();
} }
@override @override
void dispose() { void dispose() {
_manualCaptureTimer?.cancel(); _countdownTimer?.cancel();
_stopImageStream();
_cameraController?.dispose(); _cameraController?.dispose();
_faceDetector.close();
super.dispose(); super.dispose();
} }
@@ -93,9 +61,8 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
_isCameraInitialized = false; _isCameraInitialized = false;
_isSuccess = false; _isSuccess = false;
_isSubmitting = false; _isSubmitting = false;
_progress = 0; _countdown = 3;
_stableFrames = 0; _countdownStarted = false;
_lastFaceRect = null;
}); });
await _cameraController?.dispose(); await _cameraController?.dispose();
@@ -120,10 +87,6 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
selectedCamera, selectedCamera,
ResolutionPreset.medium, ResolutionPreset.medium,
enableAudio: false, enableAudio: false,
imageFormatGroup:
Platform.isAndroid
? ImageFormatGroup.yuv420
: ImageFormatGroup.bgra8888,
); );
await _cameraController!.initialize(); await _cameraController!.initialize();
@@ -132,21 +95,9 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
setState(() { setState(() {
_isCameraInitialized = true; _isCameraInitialized = true;
_isStreaming = false;
_showManualCapture = false;
_debugInfo = "Ready. Cam: ${selectedCamera.lensDirection}";
}); });
_manualCaptureTimer?.cancel(); _startCountdown();
_manualCaptureTimer = Timer(const Duration(seconds: 10), () {
if (mounted && _isCameraInitialized && !_isSuccess && !_isSubmitting) {
setState(() {
_showManualCapture = true;
});
}
});
_startSmartStream();
} catch (e) { } catch (e) {
if (!mounted) return; if (!mounted) return;
setState(() { setState(() {
@@ -156,119 +107,73 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
} }
} }
void _startSmartStream() { void _startCountdown() {
if (_cameraController == null || !_cameraController!.value.isInitialized) { if (_countdownStarted) return;
return; _countdownStarted = true;
} _countdown = 3;
if (_isStreaming) return;
_isStreaming = true; _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
if (!mounted) {
timer.cancel();
return;
}
try { setState(() {
_cameraController!.startImageStream((CameraImage image) async { _countdown--;
if (!mounted) return;
if (_isSubmitting || _isSuccess) return;
_frameCount++;
if (_frameCount % _throttleEveryNFrames != 0) return;
if (_isDetecting) return;
_isDetecting = true;
try {
final inputImage = _toInputImage(
image,
_cameraController!.description,
);
if (inputImage == null) {
_isDetecting = false;
return;
}
final faces = await _faceDetector.processImage(inputImage);
if (faces.isEmpty) {
_stableFrames = 0;
_applyFeedback(
FaceFeedback(
type: FaceHintType.noFace,
message: "ضع وجهك داخل الإطار",
quality: 0,
borderColor: Colors.white70,
),
);
_isDetecting = false;
return;
}
final face = faces.first;
final brightness = _estimateBrightness(image);
final rotation =
inputImage.metadata?.rotation ?? InputImageRotation.rotation0deg;
final feedback = _evaluate(
face: face,
brightness: brightness,
image: image,
rotation: rotation,
);
_applyFeedback(feedback);
if (feedback.isGood) {
_stableFrames++;
_progress = (_stableFrames / _stableFramesNeeded).clamp(0.0, 1.0);
if (_stableFrames >= _stableFramesNeeded) {
if (mounted) {
setState(() {
_debugInfo = "جاري التحقق من الصورة...";
});
}
_isDetecting = false;
await _captureAndSubmit();
return;
}
} else {
if (_stableFrames > 0) _stableFrames--;
_progress = (_stableFrames / _stableFramesNeeded).clamp(0.0, 1.0);
}
if (mounted && !_isSubmitting && !_isSuccess) {
setState(() {
_debugInfo =
"Faces: ${faces.length} | Bright: ${brightness.toStringAsFixed(1)}\n"
"Msg: ${feedback.message} | Stable: $_stableFrames";
});
}
} catch (e) {
debugPrint("Face detection error: $e");
} finally {
_isDetecting = false;
}
}); });
} catch (e) {
debugPrint("Error starting image stream: $e"); if (_countdown <= 0) {
_isStreaming = false; timer.cancel();
} _captureAndSubmit();
}
});
} }
Future<void> _stopImageStream() async { Future<bool?> _showLocalAuthDialog() {
if (!_isStreaming || _cameraController == null) return; 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 { try {
await _cameraController!.stopImageStream(); final isSupported = await _localAuth.isDeviceSupported();
_isStreaming = false; if (!isSupported) return false;
} catch (e) {
debugPrint("Error stopping image stream: $e"); return await _localAuth.authenticate(
localizedReason: 'تأكيد هويتك لإكمال تسجيل الحضور.',
options: const AuthenticationOptions(
biometricOnly: false,
stickyAuth: true,
useErrorDialogs: true,
),
);
} catch (_) {
return false;
} }
} }
void _stopCameraCompletely() { void _stopCameraCompletely() {
_manualCaptureTimer?.cancel(); _countdownTimer?.cancel();
try { try {
if (_isStreaming && _cameraController != null) {
_cameraController!.stopImageStream();
_isStreaming = false;
}
_cameraController?.dispose(); _cameraController?.dispose();
_cameraController = null; _cameraController = null;
} catch (e) { } catch (e) {
@@ -276,114 +181,6 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
} }
} }
FaceFeedback _evaluate({
required Face face,
required double brightness,
required CameraImage image,
required InputImageRotation rotation,
}) {
// 1) lighting
if (brightness < 40) {
return FaceFeedback(
type: FaceHintType.tooDark,
message: "المكان مظلم — انتقل لمكان أكثر إضاءة",
quality: 0.1,
borderColor: Colors.orangeAccent,
);
}
// 2) head pose
final yaw = (face.headEulerAngleY ?? 0).abs();
final pitch = (face.headEulerAngleX ?? 0).abs();
if (yaw > 20 || pitch > 20) {
return FaceFeedback(
type: FaceHintType.lookStraight,
message: "انظر مباشرةً للكاميرا",
quality: 0.2,
borderColor: Colors.orangeAccent,
);
}
// 3) distance estimate
double frameWidth = image.width.toDouble();
double frameHeight = image.height.toDouble();
if (rotation == InputImageRotation.rotation90deg ||
rotation == InputImageRotation.rotation270deg) {
final temp = frameWidth;
frameWidth = frameHeight;
frameHeight = temp;
}
final box = face.boundingBox;
final frameArea = frameWidth * frameHeight;
final faceArea = box.width * box.height;
final ratio = faceArea / frameArea;
if (ratio < 0.05) {
return FaceFeedback(
type: FaceHintType.tooFar,
message: "اقترب قليلاً",
quality: 0.3,
borderColor: Colors.orangeAccent,
);
}
if (ratio > 0.8) {
return FaceFeedback(
type: FaceHintType.tooClose,
message: "ابتعد قليلاً",
quality: 0.3,
borderColor: Colors.orangeAccent,
);
}
// 4) centered
final faceCenter = Offset(box.center.dx, box.center.dy);
final frameCenter = Offset(frameWidth / 2, frameHeight / 2);
final dist = (faceCenter - frameCenter).distance;
final maxAllowed = math.min(frameWidth, frameHeight) * 0.4;
if (dist > maxAllowed) {
return FaceFeedback(
type: FaceHintType.notCentered,
message: "وسط وجهك داخل الإطار",
quality: 0.4,
borderColor: Colors.orangeAccent,
);
}
// 5) stability
if (_lastFaceRect != null) {
final moved = (box.center - _lastFaceRect!.center).distance;
if (moved > 40) {
_lastFaceRect = box;
return FaceFeedback(
type: FaceHintType.holdStill,
message: "ثبت الهاتف وابقَ ثابتاً",
quality: 0.5,
borderColor: Colors.orangeAccent,
);
}
}
_lastFaceRect = box;
return FaceFeedback(
type: FaceHintType.good,
message: "ممتاز — ثبت قليلاً",
quality: 1.0,
borderColor: Colors.greenAccent,
);
}
void _applyFeedback(FaceFeedback f) {
if (!mounted) return;
if (_feedback.type != f.type || _feedback.message != f.message) {
setState(() {
_feedback = f;
});
}
}
Future<void> _captureAndSubmit() async { Future<void> _captureAndSubmit() async {
if (_cameraController == null) return; if (_cameraController == null) return;
if (_isSubmitting || _isSuccess) return; if (_isSubmitting || _isSuccess) return;
@@ -394,11 +191,6 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
}); });
try { try {
await _stopImageStream();
// Small delay to let camera settle after stopping stream
await Future.delayed(const Duration(milliseconds: 200));
if (_cameraController == null || if (_cameraController == null ||
!_cameraController!.value.isInitialized) { !_cameraController!.value.isInitialized) {
_handleScanError("الكاميرا غير جاهزة، حاول مرة أخرى"); _handleScanError("الكاميرا غير جاهزة، حاول مرة أخرى");
@@ -408,7 +200,9 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
final xFile = await _cameraController!.takePicture(); final xFile = await _cameraController!.takePicture();
final file = File(xFile.path); final file = File(xFile.path);
await widget.onCapture(file); _lastCapturedFile = file;
await widget.onCapture(file, localAuth: false);
if (mounted) { if (mounted) {
setState(() { setState(() {
@@ -423,33 +217,35 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
}); });
} }
} on ServerException catch (e) { } on ServerException catch (e) {
// Check if this is an "already logged in" error from the API
final msg = e.message.toLowerCase(); final msg = e.message.toLowerCase();
if (e.statusCode == 422 || msg.contains('face verification failed')) {
await _handleFaceVerificationFailed422(e);
return;
}
if (msg.contains('already logged in') || if (msg.contains('already logged in') ||
msg.contains('مسجل دخول بالفعل')) { msg.contains('مسجل دخول بالفعل')) {
// Stop camera and go back with a dialog
_stopCameraCompletely(); _stopCameraCompletely();
if (mounted) { if (mounted) {
showDialog( showDialog(
context: context, context: context,
barrierDismissible: false, barrierDismissible: false,
builder: builder: (_) => AlertDialog(
(_) => AlertDialog( title: const Text('تنبيه', textAlign: TextAlign.center),
title: const Text('تنبيه', textAlign: TextAlign.center), content: const Text(
content: const Text( 'أنت مسجل دخول بالفعل، لا يمكنك تسجيل الدخول مرة أخرى.',
'أنت مسجل دخول بالفعل، لا يمكنك تسجيل الدخول مرة أخرى.', textAlign: TextAlign.center,
textAlign: TextAlign.center, ),
), actions: [
actions: [ TextButton(
TextButton( onPressed: () {
onPressed: () { Navigator.of(context).pop();
Navigator.of(context).pop(); // Close dialog Navigator.of(context).pop();
Navigator.of(context).pop(); // Go back from camera },
}, child: const Text('حسناً'),
child: const Text('حسناً'),
),
],
), ),
],
),
); );
} }
return; return;
@@ -469,150 +265,81 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
setState(() { setState(() {
_isSubmitting = false; _isSubmitting = false;
_errorMessage = msg; _errorMessage = msg;
_progress = 0; _countdown = 3;
_stableFrames = 0; _countdownStarted = false;
}); });
if (_cameraController != null && // Restart countdown after error
_cameraController!.value.isInitialized && _startCountdown();
!_isStreaming) {
_startSmartStream();
}
} }
double _estimateBrightness(CameraImage image) { Future<void> _handleFaceVerificationFailed422(ServerException e) async {
if (image.planes.isEmpty) return 0; if (!mounted) return;
final bytes = image.planes[0].bytes; if (_handlingAuth422) return;
if (bytes.isEmpty) return 0;
const step = 100; _handlingAuth422 = true;
int sum = 0;
int count = 0;
for (int i = 0; i < bytes.length; i += step) {
sum += bytes[i];
count++;
}
return count == 0 ? 0 : (sum / count);
}
InputImage? _toInputImage(CameraImage image, CameraDescription camera) { setState(() {
final sensorOrientation = camera.sensorOrientation; _isSubmitting = false;
InputImageRotation? rotation; _errorMessage = null;
});
if (Platform.isIOS) { final proceed = await _showLocalAuthDialog();
rotation = _rotationIntToImageRotation(sensorOrientation); if (proceed != true) {
} else if (Platform.isAndroid) { _handlingAuth422 = false;
var rotationCompensation = _stopCameraCompletely();
_orientations[_cameraController!.value.deviceOrientation]; if (!mounted) return;
if (rotationCompensation == null) return null; Navigator.of(context).pop(false);
if (camera.lensDirection == CameraLensDirection.front) { return;
rotationCompensation = (sensorOrientation + rotationCompensation) % 360;
} else {
rotationCompensation =
(sensorOrientation - rotationCompensation + 360) % 360;
}
rotation = _rotationIntToImageRotation(rotationCompensation);
}
if (rotation == null) return null;
if (Platform.isAndroid) {
final nv21 = _convertYUV420ToNV21(image);
return InputImage.fromBytes(
bytes: nv21,
metadata: InputImageMetadata(
size: Size(image.width.toDouble(), image.height.toDouble()),
rotation: rotation,
format: InputImageFormat.nv21,
bytesPerRow: image.width,
),
);
} }
// iOS BGRA8888 final ok = await _authenticateLocally();
if (image.planes.length == 1) { if (!ok) {
return InputImage.fromBytes( _handlingAuth422 = false;
bytes: image.planes.first.bytes, _stopCameraCompletely();
metadata: InputImageMetadata( if (!mounted) return;
size: Size(image.width.toDouble(), image.height.toDouble()), Navigator.of(context).pop("local_auth_failed");
rotation: rotation, return;
format: InputImageFormat.bgra8888,
bytesPerRow: image.planes.first.bytesPerRow,
),
);
} }
return null; final file = _lastCapturedFile;
} if (file == null) {
_handlingAuth422 = false;
Uint8List _convertYUV420ToNV21(CameraImage image) { _stopCameraCompletely();
final int width = image.width; if (!mounted) return;
final int height = image.height; Navigator.of(context).pop("retry_missing_file");
return;
final yPlane = image.planes[0];
final uPlane = image.planes[1];
final vPlane = image.planes[2];
final int ySize = width * height;
final int uvSize = ySize ~/ 2;
final Uint8List nv21 = Uint8List(ySize + uvSize);
// Y Channel
if (yPlane.bytesPerRow == width) {
nv21.setAll(0, yPlane.bytes);
} else {
int offset = 0;
for (int i = 0; i < height; i++) {
nv21.setRange(
offset,
offset + width,
yPlane.bytes,
i * yPlane.bytesPerRow,
);
offset += width;
}
} }
// UV Channel (NV21 is VU interleaved) setState(() {
final int uvWidth = width ~/ 2; _isSubmitting = true;
final int uvHeight = height ~/ 2; });
final int uvPixelStride = uPlane.bytesPerPixel ?? 1;
int uvIndex = ySize; try {
await widget.onCapture(file, localAuth: true);
for (int row = 0; row < uvHeight; row++) { if (!mounted) return;
final int srcIndex = row * uPlane.bytesPerRow; setState(() {
for (int col = 0; col < uvWidth; col++) { _isSuccess = true;
final int pixelIndex = srcIndex + (col * uvPixelStride); _isSubmitting = false;
nv21[uvIndex++] = vPlane.bytes[pixelIndex]; });
nv21[uvIndex++] = uPlane.bytes[pixelIndex];
}
}
return nv21; Future.delayed(const Duration(seconds: 1), () {
} if (mounted) Navigator.of(context).pop(true);
});
InputImageRotation _rotationIntToImageRotation(int rotation) { } on ServerException catch (_) {
switch (rotation) { _handlingAuth422 = false;
case 90: _stopCameraCompletely();
return InputImageRotation.rotation90deg; if (!mounted) return;
case 180: Navigator.of(context).pop("retry_failed");
return InputImageRotation.rotation180deg; } catch (_) {
case 270: _handlingAuth422 = false;
return InputImageRotation.rotation270deg; _stopCameraCompletely();
default: if (!mounted) return;
return InputImageRotation.rotation0deg; Navigator.of(context).pop("retry_failed");
} }
} }
static final _orientations = {
DeviceOrientation.portraitUp: 0,
DeviceOrientation.landscapeLeft: 90,
DeviceOrientation.portraitDown: 180,
DeviceOrientation.landscapeRight: 270,
};
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (_errorMessage != null && !_isCameraInitialized) { if (_errorMessage != null && !_isCameraInitialized) {
@@ -651,8 +378,12 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
Center(child: CameraPreview(_cameraController!)), Center(child: CameraPreview(_cameraController!)),
CustomPaint( CustomPaint(
painter: _OvalOverlayPainter( painter: _OvalOverlayPainter(
borderColor: _feedback.borderColor, borderColor: _isSuccess
progress: _progress, ? Colors.greenAccent
: (_countdown <= 1 ? Colors.orangeAccent : Colors.white70),
progress: _countdownStarted
? ((3 - _countdown) / 3).clamp(0.0, 1.0)
: 0,
), ),
), ),
Positioned( Positioned(
@@ -681,9 +412,13 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
borderRadius: BorderRadius.circular(20), borderRadius: BorderRadius.circular(20),
), ),
child: Text( child: Text(
_feedback.message, _isSubmitting
? "جاري التحقق..."
: _isSuccess
? "تم بنجاح"
: "التقاط الصورة خلال $_countdown ثانية",
style: TextStyle( style: TextStyle(
color: _feedback.borderColor, color: _isSuccess ? Colors.greenAccent : Colors.white,
fontSize: 16, fontSize: 16,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
), ),
@@ -692,6 +427,18 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
], ],
), ),
), ),
// 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) if (_isSubmitting)
const Center(child: CircularProgressIndicator(color: Colors.white)), const Center(child: CircularProgressIndicator(color: Colors.white)),
if (_isSuccess) if (_isSuccess)
@@ -713,41 +460,6 @@ class _OvalCameraCapturePageState extends State<OvalCameraCapturePage> {
), ),
), ),
), ),
Positioned(
bottom: 50,
left: 10,
right: 10,
child: Text(
_debugInfo,
style: const TextStyle(
color: Colors.yellow,
fontSize: 12,
backgroundColor: Colors.black54,
),
textAlign: TextAlign.center,
),
),
if (_showManualCapture && !_isSubmitting && !_isSuccess)
Positioned(
bottom: 110,
left: 0,
right: 0,
child: Center(
child: ElevatedButton.icon(
onPressed: _captureAndSubmit,
icon: const Icon(Icons.camera_alt),
label: const Text("التقاط يدوياً"),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.redAccent,
foregroundColor: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 24,
vertical: 12,
),
),
),
),
),
], ],
), ),
); );
@@ -780,28 +492,25 @@ class _OvalOverlayPainter extends CustomPainter {
ovalPath, ovalPath,
); );
final bgPaint = final bgPaint = Paint()
Paint() ..color = Colors.black.withOpacity(0.6)
..color = Colors.black.withOpacity(0.6) ..style = PaintingStyle.fill;
..style = PaintingStyle.fill;
canvas.drawPath(overlayPath, bgPaint); canvas.drawPath(overlayPath, bgPaint);
final borderPaint = final borderPaint = Paint()
Paint() ..color = borderColor
..color = borderColor ..style = PaintingStyle.stroke
..style = PaintingStyle.stroke ..strokeWidth = 4.0;
..strokeWidth = 4.0;
canvas.drawOval(ovalRect, borderPaint); canvas.drawOval(ovalRect, borderPaint);
if (progress > 0) { if (progress > 0) {
final progressPaint = final progressPaint = Paint()
Paint() ..color = Colors.greenAccent
..color = Colors.greenAccent ..style = PaintingStyle.stroke
..style = PaintingStyle.stroke ..strokeWidth = 6.0
..strokeWidth = 6.0 ..strokeCap = StrokeCap.round;
..strokeCap = StrokeCap.round;
final startAngle = -math.pi / 2; final startAngle = -math.pi / 2;
final sweepAngle = 2 * math.pi * progress; final sweepAngle = 2 * math.pi * progress;

View File

@@ -51,19 +51,24 @@ class _FinanceScreenState extends State<FinanceScreen> {
void _triggerLoad() { void _triggerLoad() {
if (_employeeId != null && _employeeId!.isNotEmpty) { if (_employeeId != null && _employeeId!.isNotEmpty) {
if (_financeBloc.state is FinanceInitial) { _financeBloc.add(
_financeBloc.add( LoadFinanceDataEvent(
LoadFinanceDataEvent( employeeId: _employeeId!,
employeeId: _employeeId!, category: currentCategory,
category: currentCategory, month: selectedDate.month,
month: selectedDate.month, year: selectedDate.year,
year: selectedDate.year, ),
), );
);
}
} }
} }
Future<void> _onRefresh() async {
_triggerLoad();
await _financeBloc.stream.firstWhere(
(state) => state is FinanceLoaded || state is FinanceError,
);
}
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return BlocProvider.value( return BlocProvider.value(
@@ -71,145 +76,153 @@ class _FinanceScreenState extends State<FinanceScreen> {
child: Directionality( child: Directionality(
textDirection: TextDirection.ltr, textDirection: TextDirection.ltr,
child: SafeArea( child: SafeArea(
child: CustomScrollView( child: RefreshIndicator(
controller: scrollController, onRefresh: _onRefresh,
physics: const BouncingScrollPhysics(), color: const Color(0xFF0A6B4A),
slivers: [ child: CustomScrollView(
SliverToBoxAdapter( controller: scrollController,
child: SettingsBar( physics: const AlwaysScrollableScrollPhysics(
selectedIndex: 0, parent: BouncingScrollPhysics(),
showBackButton: false,
iconPaths: const [
'assets/images/user.svg',
'assets/images/ball.svg',
],
onTap: (index) {
if (index == 0) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const UserSettingsScreen(),
),
);
} else if (index == 1) {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => const NotificationsScreen(),
),
);
}
},
),
), ),
const SliverToBoxAdapter(child: SizedBox(height: 5)), slivers: [
SliverToBoxAdapter(
/// SUMMARY CARD child: SettingsBar(
SliverToBoxAdapter( selectedIndex: 0,
child: BlocBuilder<FinanceBloc, FinanceState>( showBackButton: false,
buildWhen: (previous, current) => current is FinanceLoaded, iconPaths: const [
builder: (context, state) { 'assets/images/user.svg',
String amount = "0"; 'assets/images/ball.svg',
if (state is FinanceLoaded) { ],
amount = state.netSalary.toStringAsFixed(0); onTap: (index) {
amount = amount.replaceAllMapped( if (index == 0) {
RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'), Navigator.push(
(Match m) => '${m[1]},', context,
); MaterialPageRoute(
} builder: (context) => const UserSettingsScreen(),
),
return FinanceSummaryCard(
totalAmount: amount,
currentCategory: currentCategory,
onCalendarTap: () async {
final date = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime(2030),
); );
if (date != null && mounted) { } else if (index == 1) {
setState(() => selectedDate = date); Navigator.push(
if (_employeeId != null && _employeeId!.isNotEmpty) { context,
_financeBloc.add( MaterialPageRoute(
LoadFinanceDataEvent( builder: (context) => const NotificationsScreen(),
employeeId: _employeeId!, ),
category: currentCategory, );
month: selectedDate.month, }
year: selectedDate.year, },
), ),
);
}
}
},
onCategoryChanged: (category) {
if (category != null) {
setState(() => currentCategory = category);
if (_employeeId != null && _employeeId!.isNotEmpty) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
category: currentCategory,
month: selectedDate.month,
year: selectedDate.year,
),
);
}
}
},
);
},
), ),
), const SliverToBoxAdapter(child: SizedBox(height: 5)),
/// DATA LIST /// SUMMARY CARD
BlocBuilder<FinanceBloc, FinanceState>( SliverToBoxAdapter(
builder: (context, state) { child: BlocBuilder<FinanceBloc, FinanceState>(
if (state is FinanceLoading || state is FinanceInitial) { buildWhen: (previous, current) => current is FinanceLoaded,
return const SliverToBoxAdapter( builder: (context, state) {
child: Center( String amount = "0";
child: Padding( if (state is FinanceLoaded) {
padding: EdgeInsets.all(20.0), amount = state.netSalary.toStringAsFixed(0);
child: CircularProgressIndicator(), amount = amount.replaceAllMapped(
), RegExp(r'(\d{1,3})(?=(\d{3})+(?!\d))'),
), (Match m) => '${m[1]},',
); );
} else if (state is FinanceLoaded) { }
if (state.records.isEmpty) {
return FinanceSummaryCard(
totalAmount: amount,
currentCategory: currentCategory,
onCalendarTap: () async {
final date = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2020),
lastDate: DateTime(2030),
);
if (date != null && mounted) {
setState(() => selectedDate = date);
if (_employeeId != null &&
_employeeId!.isNotEmpty) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
category: currentCategory,
month: selectedDate.month,
year: selectedDate.year,
),
);
}
}
},
onCategoryChanged: (category) {
if (category != null) {
setState(() => currentCategory = category);
if (_employeeId != null &&
_employeeId!.isNotEmpty) {
_financeBloc.add(
LoadFinanceDataEvent(
employeeId: _employeeId!,
category: currentCategory,
month: selectedDate.month,
year: selectedDate.year,
),
);
}
}
},
);
},
),
),
/// DATA LIST
BlocBuilder<FinanceBloc, FinanceState>(
builder: (context, state) {
if (state is FinanceLoading || state is FinanceInitial) {
return const SliverToBoxAdapter( return const SliverToBoxAdapter(
child: Center( child: Center(
child: Padding( child: Padding(
padding: EdgeInsets.all(20.0), padding: EdgeInsets.all(20.0),
child: Text("لا توجد سجلات"), child: CircularProgressIndicator(),
),
),
);
} else if (state is FinanceLoaded) {
if (state.records.isEmpty) {
return const SliverToBoxAdapter(
child: Center(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text("لا توجد سجلات"),
),
),
);
}
return SliverList(
delegate: SliverChildBuilderDelegate((context, index) {
return WorkDayCard(record: state.records[index]);
}, childCount: state.records.length),
);
} else if (state is FinanceError) {
return SliverToBoxAdapter(
child: Center(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text(
state.message,
style: const TextStyle(color: Colors.red),
textAlign: TextAlign.center,
),
), ),
), ),
); );
} }
return SliverList( return const SliverToBoxAdapter(child: SizedBox());
delegate: SliverChildBuilderDelegate((context, index) { },
return WorkDayCard(record: state.records[index]); ),
}, childCount: state.records.length),
);
} else if (state is FinanceError) {
return SliverToBoxAdapter(
child: Center(
child: Padding(
padding: EdgeInsets.all(20.0),
child: Text(
state.message,
style: const TextStyle(color: Colors.red),
textAlign: TextAlign.center,
),
),
),
);
}
return const SliverToBoxAdapter(child: SizedBox());
},
),
const SliverToBoxAdapter(child: SizedBox(height: 120)), const SliverToBoxAdapter(child: SizedBox(height: 120)),
], ],
),
), ),
), ),
), ),

View File

@@ -223,6 +223,10 @@ class _HolidayScreenState extends State<HolidayScreen> {
); );
} }
Future<void> _onRefresh() async {
await Future.wait([_loadVacationsFromAPI(), _loadAdvancesFromAPI()]);
}
AdvanceRequest _convertAdvanceToAdvanceRequest(AdvanceDataModel advance) { AdvanceRequest _convertAdvanceToAdvanceRequest(AdvanceDataModel advance) {
// Convert state (0=waiting, 1=approved, 2=denied) to status string // Convert state (0=waiting, 1=approved, 2=denied) to status string
String status = "waiting"; String status = "waiting";
@@ -248,123 +252,129 @@ class _HolidayScreenState extends State<HolidayScreen> {
// ⭐ MAIN CONTENT - CUSTOM SCROLL VIEW // ⭐ MAIN CONTENT - CUSTOM SCROLL VIEW
// --------------------------------------------------------- // ---------------------------------------------------------
SafeArea( SafeArea(
child: CustomScrollView( child: RefreshIndicator(
controller: _scrollController, onRefresh: _onRefresh,
physics: const BouncingScrollPhysics(), color: const Color(0xFF0A6B4A),
slivers: [ child: CustomScrollView(
// SETTINGS BAR controller: _scrollController,
SliverToBoxAdapter( physics: const AlwaysScrollableScrollPhysics(
child: Padding( parent: BouncingScrollPhysics(),
padding: const EdgeInsets.only(top: 8), ),
// First, make sure you have your screens defined slivers: [
// SETTINGS BAR
SliverToBoxAdapter(
child: Padding(
padding: const EdgeInsets.only(top: 8),
// First, make sure you have your screens defined
// Then in your main widget: // Then in your main widget:
child: SettingsBar( child: SettingsBar(
selectedIndex: 0, selectedIndex: 0,
showBackButton: false, showBackButton: false,
iconPaths: [ iconPaths: [
'assets/images/user.svg', 'assets/images/user.svg',
'assets/images/ball.svg', 'assets/images/ball.svg',
], ],
onTap: (index) { onTap: (index) {
if (index == 0) { if (index == 0) {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => UserSettingsScreen(), builder: (context) => UserSettingsScreen(),
), ),
); );
} else if (index == 1) { } else if (index == 1) {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (context) => NotificationsScreen(), builder: (context) => NotificationsScreen(),
), ),
); );
} }
}, },
),
), ),
), ),
),
const SliverToBoxAdapter(child: SizedBox(height: 5)), const SliverToBoxAdapter(child: SizedBox(height: 5)),
// TABS SECTION // TABS SECTION
SliverToBoxAdapter( SliverToBoxAdapter(
child: SizedBox( child: SizedBox(
height: 55, height: 55,
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
// الأجازات // الأجازات
GestureDetector( GestureDetector(
onTap: () => setState(() => activeTab = 1), onTap: () => setState(() => activeTab = 1),
child: Column( child: Column(
children: [ children: [
Text( Text(
"الأجازات", "الأجازات",
style: TextStyle( style: TextStyle(
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: color:
activeTab == 1 activeTab == 1
? const Color(0xFF8EFDC2) ? const Color(0xFF8EFDC2)
: const Color(0x9EFFFFFF), : const Color(0x9EFFFFFF),
),
), ),
), if (activeTab == 1)
if (activeTab == 1) Container(
Container( width: 60,
width: 60, height: 2,
height: 2, margin: const EdgeInsets.only(top: 4),
margin: const EdgeInsets.only(top: 4), color: const Color(0xFF8EFDC2),
color: const Color(0xFF8EFDC2), ),
), ],
], ),
), ),
),
const SizedBox(width: 70), const SizedBox(width: 70),
// السلف // السلف
GestureDetector( GestureDetector(
onTap: () => setState(() => activeTab = 0), onTap: () => setState(() => activeTab = 0),
child: Column( child: Column(
children: [ children: [
Text( Text(
"السلف", "السلف",
style: TextStyle( style: TextStyle(
fontSize: 22, fontSize: 22,
fontWeight: FontWeight.w600, fontWeight: FontWeight.w600,
color: color:
activeTab == 0 activeTab == 0
? const Color(0xFF8EFDC2) ? const Color(0xFF8EFDC2)
: const Color(0x9EFFFFFF), : const Color(0x9EFFFFFF),
),
), ),
), if (activeTab == 0)
if (activeTab == 0) Container(
Container( width: 60,
width: 60, height: 2,
height: 2, margin: const EdgeInsets.only(top: 4),
margin: const EdgeInsets.only(top: 4), color: const Color(0xFF8EFDC2),
color: const Color(0xFF8EFDC2), ),
), ],
], ),
), ),
), ],
], ),
), ),
), ),
),
const SliverToBoxAdapter(child: SizedBox(height: 20)), const SliverToBoxAdapter(child: SizedBox(height: 20)),
// CONTENT LISTS // CONTENT LISTS
activeTab == 1 activeTab == 1
? _buildLeaveRequestsSliver() ? _buildLeaveRequestsSliver()
: _buildAdvanceRequestsSliver(), : _buildAdvanceRequestsSliver(),
const SliverToBoxAdapter(child: SizedBox(height: 120)), const SliverToBoxAdapter(child: SizedBox(height: 120)),
], ],
),
), ),
), ),

View File

@@ -1,6 +1,9 @@
import 'dart:async'; import 'dart:async';
import 'package:coda_project/presentation/screens/auth_screen.dart'; import 'package:coda_project/presentation/screens/auth_screen.dart';
import 'package:flutter/material.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_page.dart';
import '../widgets/onboarding_button.dart'; import '../widgets/onboarding_button.dart';
@@ -88,7 +91,29 @@ class _OnboardingScreenState extends State<OnboardingScreen> {
Column( Column(
children: [ children: [
const SizedBox(height: 70), 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) /// PAGEVIEW (SVG + TEXT ONLY)
Expanded( Expanded(

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_native_splash/flutter_native_splash.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 'onboarding_screen.dart';
import 'main_screen.dart'; import 'main_screen.dart';
import '../../core/di/injection_container.dart'; import '../../core/di/injection_container.dart';
@@ -31,7 +34,7 @@ class _SplashScreenState extends State<SplashScreen> {
final token = await sl<UserLocalDataSource>().getCachedUserToken(); final token = await sl<UserLocalDataSource>().getCachedUserToken();
if (token != null && token.isNotEmpty) { if (token != null && token.isNotEmpty) {
// Token exists, navigate directly to MainPage // Token exists — go to MainPage (theme already loaded in main.dart)
Navigator.pushReplacement( Navigator.pushReplacement(
context, context,
MaterialPageRoute(builder: (_) => const MainPage()), MaterialPageRoute(builder: (_) => const MainPage()),
@@ -65,7 +68,30 @@ class _SplashScreenState extends State<SplashScreen> {
fit: BoxFit.cover, 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> { class _UserSettingsScreenState extends State<UserSettingsScreen> {
bool _notificationsOn = false; 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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
@@ -84,8 +100,8 @@ class _UserSettingsScreenState extends State<UserSettingsScreen> {
const SizedBox(height: 10), const SizedBox(height: 10),
/// -------------------- USER NAME -------------------- /// -------------------- USER NAME --------------------
const Text( Text(
"اسم الموظف", _userName,
style: TextStyle( style: TextStyle(
fontSize: 25, fontSize: 25,
fontWeight: FontWeight.bold, fontWeight: FontWeight.bold,

View File

@@ -1,5 +1,8 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_svg/flutter_svg.dart'; import 'package:flutter_svg/flutter_svg.dart';
import '../blocs/theme/theme_cubit.dart';
import '../blocs/theme/theme_state.dart';
class SettingsBar extends StatelessWidget { class SettingsBar extends StatelessWidget {
final int selectedIndex; final int selectedIndex;
@@ -12,7 +15,7 @@ class SettingsBar extends StatelessWidget {
super.key, super.key,
required this.selectedIndex, required this.selectedIndex,
required this.onTap, required this.onTap,
this.showBackButton = false, // to switch between back button and settings icons this.showBackButton = false,
this.onBackTap, this.onBackTap,
required this.iconPaths, required this.iconPaths,
}); });
@@ -25,10 +28,28 @@ class SettingsBar extends StatelessWidget {
child: Row( child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
Row( // Dynamic Logo from backend
children: [ BlocBuilder<ThemeCubit, ThemeState>(
Image.asset('assets/images/logo2.png', width: 150, height: 40), 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( Row(
children: [ children: [
@@ -50,11 +71,10 @@ class SettingsBar extends StatelessWidget {
], ],
), ),
child: Center( child: Center(
// Always use Flutter's built-in back icon pointing to the right
child: const Icon( child: const Icon(
Icons.arrow_forward, // Changed to arrow_forward for RTL Icons.arrow_forward,
size: 26, 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) { ...iconPaths.asMap().entries.map((entry) {
final index = entry.key; final index = entry.key;
final iconPath = entry.value; final iconPath = entry.value;
// final isSelected = selectedIndex == index;
return Padding( return Padding(
padding: const EdgeInsets.only(left: 10), padding: const EdgeInsets.only(left: 10),
@@ -102,4 +121,4 @@ class SettingsBar extends StatelessWidget {
), ),
); );
} }
} }

View File

@@ -5,8 +5,12 @@
import FlutterMacOS import FlutterMacOS
import Foundation import Foundation
import geolocator_apple
import local_auth_darwin
import shared_preferences_foundation import shared_preferences_foundation
func RegisterGeneratedPlugins(registry: FlutterPluginRegistry) { 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")) SharedPreferencesPlugin.register(with: registry.registrar(forPlugin: "SharedPreferencesPlugin"))
} }

View File

@@ -209,6 +209,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.0.1" version: "7.0.1"
fixnum:
dependency: transitive
description:
name: fixnum
sha256: b6dc7065e46c974bc7c5f143080a6764ec7a4be6da1285ececdc37be96de53be
url: "https://pub.dev"
source: hosted
version: "1.1.1"
flutter: flutter:
dependency: "direct main" dependency: "direct main"
description: flutter description: flutter
@@ -272,6 +280,54 @@ packages:
description: flutter description: flutter
source: sdk source: sdk
version: "0.0.0" 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: get_it:
dependency: "direct main" dependency: "direct main"
description: description:
@@ -280,22 +336,6 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "7.7.0" version: "7.7.0"
google_mlkit_commons:
dependency: transitive
description:
name: google_mlkit_commons
sha256: "7e9a6d6e66b44aa8cfe944bda9bc3346c52486dd890ca49e5bc98845cda40d7f"
url: "https://pub.dev"
source: hosted
version: "0.9.0"
google_mlkit_face_detection:
dependency: "direct main"
description:
name: google_mlkit_face_detection
sha256: "65988405c884fd84a4ccc8bded7b5e3e4c33362f6f4eaaa94818bdaaba7bab7d"
url: "https://pub.dev"
source: hosted
version: "0.12.0"
html: html:
dependency: transitive dependency: transitive
description: description:
@@ -376,6 +416,46 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "5.1.1" 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: matcher:
dependency: transitive dependency: transitive
description: description:
@@ -629,6 +709,14 @@ packages:
url: "https://pub.dev" url: "https://pub.dev"
source: hosted source: hosted
version: "2.3.1" version: "2.3.1"
uuid:
dependency: transitive
description:
name: uuid
sha256: "1fef9e8e11e2991bb773070d4656b7bd5d850967a2456cfc83cf47925ba79489"
url: "https://pub.dev"
source: hosted
version: "4.5.3"
vector_graphics: vector_graphics:
dependency: transitive dependency: transitive
description: description:

View File

@@ -19,7 +19,9 @@ dependencies:
shared_preferences: ^2.2.2 shared_preferences: ^2.2.2
flutter_bloc: ^8.1.6 flutter_bloc: ^8.1.6
intl: ^0.19.0 intl: ^0.19.0
google_mlkit_face_detection: ^0.12.0
local_auth: ^2.1.8
geolocator: ^13.0.1
dev_dependencies: dev_dependencies:
flutter_test: flutter_test:

View File

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

View File

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