data sync page

This commit is contained in:
efrilm
2025-09-20 04:45:08 +07:00
parent 5b980d237f
commit 72a464b4c0
2 changed files with 85 additions and 50 deletions
@@ -2,6 +2,8 @@ import 'dart:async';
import 'dart:developer';
import 'package:bloc/bloc.dart';
import 'package:enaklo_pos/data/datasources/product/product_local_datasource.dart';
import 'package:enaklo_pos/data/datasources/category/category_local_datasource.dart';
import 'package:enaklo_pos/data/repositories/category/category_repository.dart';
import 'package:freezed_annotation/freezed_annotation.dart';
import '../../../data/datasources/product_remote_datasource.dart';
@@ -9,7 +11,7 @@ part 'data_sync_event.dart';
part 'data_sync_state.dart';
part 'data_sync_bloc.freezed.dart';
enum SyncStep { products, categories, variants, completed }
enum SyncStep { categories, products, variants, completed }
class SyncStats {
final int totalProducts;
@@ -26,9 +28,13 @@ class SyncStats {
}
class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
final ProductRemoteDatasource _remoteDatasource = ProductRemoteDatasource();
final ProductLocalDatasource _localDatasource =
final ProductRemoteDatasource _productRemoteDatasource =
ProductRemoteDatasource();
final ProductLocalDatasource _productLocalDatasource =
ProductLocalDatasource.instance;
final CategoryLocalDatasource _categoryLocalDatasource =
CategoryLocalDatasource.instance;
final CategoryRepository _categoryRepository = CategoryRepository.instance;
Timer? _progressTimer;
bool _isCancelled = false;
@@ -48,36 +54,75 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
_StartSync event,
Emitter<DataSyncState> emit,
) async {
log('🔄 Starting data sync...');
log('🔄 Starting full data sync (categories + products)...');
_isCancelled = false;
try {
// Step 1: Clear existing local data
emit(const DataSyncState.syncing(
SyncStep.products, 0.1, 'Membersihkan data lama...'));
await _localDatasource.clearAllProducts();
SyncStep.categories, 0.05, 'Membersihkan data lama...'));
await _productLocalDatasource.clearAllProducts();
await _categoryLocalDatasource.clearAllCategories();
if (_isCancelled) return;
// Step 2: Sync products
// Step 2: Sync categories first (products depend on categories)
await _syncCategories(emit);
if (_isCancelled) return;
// Step 3: Sync products
await _syncProducts(emit);
if (_isCancelled) return;
// Step 3: Generate final stats
// Step 4: Generate final stats
emit(const DataSyncState.syncing(
SyncStep.completed, 0.9, 'Menyelesaikan sinkronisasi...'));
SyncStep.completed, 0.95, 'Menyelesaikan sinkronisasi...'));
final stats = await _generateSyncStats();
emit(DataSyncState.completed(stats));
log('Sync completed successfully');
log('Full sync completed successfully');
} catch (e) {
log('❌ Sync failed: $e');
emit(DataSyncState.error('Gagal sinkronisasi: $e'));
}
}
Future<void> _syncCategories(Emitter<DataSyncState> emit) async {
log('📁 Syncing categories...');
emit(const DataSyncState.syncing(
SyncStep.categories,
0.1,
'Mengunduh kategori...',
));
try {
// Use CategoryRepository sync method
final result = await _categoryRepository.syncAllCategories();
await result.fold(
(failure) async {
throw Exception('Gagal sync kategori: $failure');
},
(successMessage) async {
log('✅ Categories sync completed: $successMessage');
emit(const DataSyncState.syncing(
SyncStep.categories,
0.2,
'Kategori berhasil diunduh',
));
},
);
} catch (e) {
log('❌ Category sync failed: $e');
throw Exception('Gagal sync kategori: $e');
}
}
Future<void> _syncProducts(Emitter<DataSyncState> emit) async {
log('📦 Syncing products...');
@@ -88,10 +133,10 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
bool shouldContinue = true;
while (!_isCancelled && shouldContinue) {
// Calculate accurate progress based on total count
// Calculate accurate progress (categories = 0.2, products = 0.2-0.9)
double progress = 0.2;
if (totalCount != null && (totalCount ?? 0) > 0) {
progress = 0.2 + (totalSynced / (totalCount ?? 0)) * 0.6;
progress = 0.2 + (totalSynced / (totalCount ?? 0)) * 0.7;
}
emit(DataSyncState.syncing(
@@ -102,7 +147,7 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
: 'Mengunduh produk... ($totalSynced produk)',
));
final result = await _remoteDatasource.getProducts(
final result = await _productRemoteDatasource.getProducts(
page: page,
limit: 50, // Bigger batch for sync
);
@@ -128,7 +173,7 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
}
// Save to local database in batches
await _localDatasource.saveProductsBatch(products);
await _productLocalDatasource.saveProductsBatch(products);
totalSynced += products.length;
page++;
@@ -154,8 +199,8 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
}
emit(DataSyncState.syncing(
SyncStep.completed,
0.8,
SyncStep.products,
0.9,
'Produk berhasil diunduh ($totalSynced dari ${totalCount ?? totalSynced})',
));
@@ -163,13 +208,15 @@ class DataSyncBloc extends Bloc<DataSyncEvent, DataSyncState> {
}
Future<SyncStats> _generateSyncStats() async {
final dbStats = await _localDatasource.getDatabaseStats();
final productStats = await _productLocalDatasource.getDatabaseStats();
final categoryStats = await _categoryLocalDatasource.getDatabaseStats();
return SyncStats(
totalProducts: dbStats['total_products'] ?? 0,
totalCategories: dbStats['total_categories'] ?? 0,
totalVariants: dbStats['total_variants'] ?? 0,
databaseSizeMB: dbStats['database_size_mb'] ?? 0.0,
totalProducts: productStats['total_products'] ?? 0,
totalCategories: categoryStats['total_categories'] ?? 0,
totalVariants: productStats['total_variants'] ?? 0,
databaseSizeMB: (productStats['database_size_mb'] ?? 0.0) +
(categoryStats['database_size_mb'] ?? 0.0),
);
}