add auth, format

This commit is contained in:
Phuoc Nguyen
2025-11-07 11:52:06 +07:00
parent 24a8508fce
commit 3803bd26e0
173 changed files with 8505 additions and 7116 deletions

View File

@@ -17,14 +17,16 @@ import 'package:worker/core/database/hive_service.dart';
/// - Sync state tracking
class DatabaseManager {
DatabaseManager({HiveService? hiveService})
: _hiveService = hiveService ?? HiveService();
: _hiveService = hiveService ?? HiveService();
final HiveService _hiveService;
/// Get a box safely
Box<T> _getBox<T>(String boxName) {
if (!_hiveService.isBoxOpen(boxName)) {
throw HiveError('Box $boxName is not open. Initialize HiveService first.');
throw HiveError(
'Box $boxName is not open. Initialize HiveService first.',
);
}
return _hiveService.getBox<T>(boxName);
}
@@ -49,11 +51,7 @@ class DatabaseManager {
}
/// Get a value from a box
T? get<T>({
required String boxName,
required String key,
T? defaultValue,
}) {
T? get<T>({required String boxName, required String key, T? defaultValue}) {
try {
final box = _getBox<T>(boxName);
return box.get(key, defaultValue: defaultValue);
@@ -65,10 +63,7 @@ class DatabaseManager {
}
/// Delete a value from a box
Future<void> delete({
required String boxName,
required String key,
}) async {
Future<void> delete({required String boxName, required String key}) async {
try {
final box = _getBox<dynamic>(boxName);
await box.delete(key);
@@ -81,10 +76,7 @@ class DatabaseManager {
}
/// Check if a key exists in a box
bool exists({
required String boxName,
required String key,
}) {
bool exists({required String boxName, required String key}) {
try {
final box = _getBox<dynamic>(boxName);
return box.containsKey(key);
@@ -138,10 +130,7 @@ class DatabaseManager {
// ==================== Cache Operations ====================
/// Save data to cache with timestamp
Future<void> saveToCache<T>({
required String key,
required T data,
}) async {
Future<void> saveToCache<T>({required String key, required T data}) async {
try {
final cacheBox = _getBox<dynamic>(HiveBoxNames.cacheBox);
await cacheBox.put(key, {
@@ -159,10 +148,7 @@ class DatabaseManager {
/// Get data from cache
///
/// Returns null if cache is expired or doesn't exist
T? getFromCache<T>({
required String key,
Duration? maxAge,
}) {
T? getFromCache<T>({required String key, Duration? maxAge}) {
try {
final cacheBox = _getBox<dynamic>(HiveBoxNames.cacheBox);
final cachedData = cacheBox.get(key) as Map<dynamic, dynamic>?;
@@ -193,10 +179,7 @@ class DatabaseManager {
}
/// Check if cache is valid (exists and not expired)
bool isCacheValid({
required String key,
Duration? maxAge,
}) {
bool isCacheValid({required String key, Duration? maxAge}) {
try {
final cacheBox = _getBox<dynamic>(HiveBoxNames.cacheBox);
final cachedData = cacheBox.get(key) as Map<dynamic, dynamic>?;
@@ -244,7 +227,9 @@ class DatabaseManager {
await cacheBox.delete(key);
}
debugPrint('DatabaseManager: Cleared ${keysToDelete.length} expired cache entries');
debugPrint(
'DatabaseManager: Cleared ${keysToDelete.length} expired cache entries',
);
} catch (e, stackTrace) {
debugPrint('DatabaseManager: Error clearing expired cache: $e');
debugPrint('StackTrace: $stackTrace');
@@ -281,10 +266,7 @@ class DatabaseManager {
}
/// Check if data needs sync
bool needsSync({
required String dataType,
required Duration syncInterval,
}) {
bool needsSync({required String dataType, required Duration syncInterval}) {
final lastSync = getLastSyncTime(dataType);
if (lastSync == null) return true;
@@ -296,22 +278,12 @@ class DatabaseManager {
// ==================== Settings Operations ====================
/// Save a setting
Future<void> saveSetting<T>({
required String key,
required T value,
}) async {
await save(
boxName: HiveBoxNames.settingsBox,
key: key,
value: value,
);
Future<void> saveSetting<T>({required String key, required T value}) async {
await save(boxName: HiveBoxNames.settingsBox, key: key, value: value);
}
/// Get a setting
T? getSetting<T>({
required String key,
T? defaultValue,
}) {
T? getSetting<T>({required String key, T? defaultValue}) {
return get(
boxName: HiveBoxNames.settingsBox,
key: key,
@@ -328,7 +300,9 @@ class DatabaseManager {
// Check queue size limit
if (queueBox.length >= HiveDatabaseConfig.maxOfflineQueueSize) {
debugPrint('DatabaseManager: Offline queue is full, removing oldest item');
debugPrint(
'DatabaseManager: Offline queue is full, removing oldest item',
);
await queueBox.deleteAt(0);
}
@@ -386,10 +360,7 @@ class DatabaseManager {
try {
if (_hiveService.isBoxOpen(boxName)) {
final box = _getBox<dynamic>(boxName);
stats[boxName] = {
'count': box.length,
'keys': box.keys.length,
};
stats[boxName] = {'count': box.length, 'keys': box.keys.length};
}
} catch (e) {
stats[boxName] = {'error': e.toString()};

View File

@@ -5,9 +5,7 @@ import 'package:hive_ce_flutter/hive_flutter.dart';
import 'package:path_provider/path_provider.dart';
import 'package:worker/core/constants/storage_constants.dart';
import 'package:worker/features/favorites/data/models/favorite_model.dart';
// TODO: Re-enable when build_runner generates this file successfully
// import 'package:worker/hive_registrar.g.dart';
import 'package:worker/hive_registrar.g.dart';
/// Hive CE (Community Edition) Database Service
///
@@ -92,40 +90,45 @@ class HiveService {
debugPrint('HiveService: Registering type adapters...');
// Register all adapters using the auto-generated extension
// This automatically registers:
// - CachedDataAdapter (typeId: 30)
// - All enum adapters (typeIds: 20-29)
// TODO: Re-enable when build_runner generates hive_registrar.g.dart successfully
// Hive.registerAdapters();
// This automatically registers all model and enum adapters
Hive.registerAdapters();
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.memberTier) ? "" : ""} MemberTier adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.userType) ? "" : ""} UserType adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.orderStatus) ? "" : ""} OrderStatus adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.projectStatus) ? "" : ""} ProjectStatus adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.projectType) ? "" : ""} ProjectType adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.transactionType) ? "" : ""} TransactionType adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.giftStatus) ? "" : ""} GiftStatus adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.paymentStatus) ? "" : ""} PaymentStatus adapter');
// NotificationType adapter not needed - notification model uses String type
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.paymentMethod) ? "" : ""} PaymentMethod adapter');
debugPrint('HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.cachedData) ? "" : ""} CachedData adapter');
// Register model type adapters manually
// FavoriteModel adapter (typeId: 28)
if (!Hive.isAdapterRegistered(HiveTypeIds.favoriteModel)) {
Hive.registerAdapter(FavoriteModelAdapter());
debugPrint('HiveService: ✓ FavoriteModel adapter registered');
}
// TODO: Register other model type adapters when created
// Example:
// - UserModel (typeId: 0)
// - ProductModel (typeId: 1)
// - CartItemModel (typeId: 2)
// - OrderModel (typeId: 3)
// - ProjectModel (typeId: 4)
// - LoyaltyTransactionModel (typeId: 5)
// etc.
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.loyaltyTier) ? "" : ""} LoyaltyTier adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.userRole) ? "" : ""} UserRole adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.orderStatus) ? "" : ""} OrderStatus adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.projectType) ? "" : ""} ProjectType adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.entryType) ? "" : ""} EntryType adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.giftStatus) ? "" : ""} GiftStatus adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.paymentStatus) ? "" : ""} PaymentStatus adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.paymentMethod) ? "" : ""} PaymentMethod adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.cachedData) ? "" : ""} CachedData adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.favoriteModel) ? "" : ""} FavoriteModel adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.productModel) ? "" : ""} ProductModel adapter',
);
debugPrint(
'HiveService: ${Hive.isAdapterRegistered(HiveTypeIds.userModel) ? "" : ""} UserModel adapter',
);
debugPrint('HiveService: Type adapters registered successfully');
}
@@ -188,21 +191,23 @@ class HiveService {
/// Handles schema version upgrades and data migrations.
Future<void> _performMigrations() async {
final settingsBox = Hive.box<dynamic>(HiveBoxNames.settingsBox);
final currentVersion = settingsBox.get(
HiveKeys.schemaVersion,
defaultValue: 0,
) as int;
final currentVersion =
settingsBox.get(HiveKeys.schemaVersion, defaultValue: 0) as int;
debugPrint('HiveService: Current schema version: $currentVersion');
debugPrint('HiveService: Target schema version: ${HiveDatabaseConfig.currentSchemaVersion}');
debugPrint(
'HiveService: Target schema version: ${HiveDatabaseConfig.currentSchemaVersion}',
);
if (currentVersion < HiveDatabaseConfig.currentSchemaVersion) {
debugPrint('HiveService: Performing migrations...');
// Perform migrations sequentially
for (int version = currentVersion + 1;
version <= HiveDatabaseConfig.currentSchemaVersion;
version++) {
for (
int version = currentVersion + 1;
version <= HiveDatabaseConfig.currentSchemaVersion;
version++
) {
await _migrateToVersion(version);
}
@@ -278,10 +283,9 @@ class HiveService {
/// Clear expired cache entries
Future<void> _clearExpiredCache() async {
final cacheBox = Hive.box<dynamic>(HiveBoxNames.cacheBox);
// TODO: Implement cache expiration logic
// This will be implemented when cache models are created
// final cacheBox = Hive.box<dynamic>(HiveBoxNames.cacheBox);
debugPrint('HiveService: Cleared expired cache entries');
}
@@ -291,14 +295,17 @@ class HiveService {
final queueBox = Hive.box<dynamic>(HiveBoxNames.offlineQueueBox);
if (queueBox.length > HiveDatabaseConfig.maxOfflineQueueSize) {
final itemsToRemove = queueBox.length - HiveDatabaseConfig.maxOfflineQueueSize;
final itemsToRemove =
queueBox.length - HiveDatabaseConfig.maxOfflineQueueSize;
// Remove oldest items
for (int i = 0; i < itemsToRemove; i++) {
await queueBox.deleteAt(0);
}
debugPrint('HiveService: Removed $itemsToRemove old items from offline queue');
debugPrint(
'HiveService: Removed $itemsToRemove old items from offline queue',
);
}
}