category local
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
import 'package:bloc/bloc.dart';
|
||||
import 'package:enaklo_pos/data/datasources/category_remote_datasource.dart';
|
||||
import 'dart:async';
|
||||
import 'dart:developer';
|
||||
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||
import 'package:enaklo_pos/data/repositories/category/category_repository.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
import 'package:freezed_annotation/freezed_annotation.dart';
|
||||
|
||||
part 'category_loader_event.dart';
|
||||
@@ -9,35 +11,310 @@ part 'category_loader_bloc.freezed.dart';
|
||||
|
||||
class CategoryLoaderBloc
|
||||
extends Bloc<CategoryLoaderEvent, CategoryLoaderState> {
|
||||
final CategoryRemoteDatasource _datasource;
|
||||
CategoryLoaderBloc(this._datasource) : super(CategoryLoaderState.initial()) {
|
||||
on<_Get>((event, emit) async {
|
||||
emit(const _Loading());
|
||||
final result = await _datasource.getCategories(limit: 50);
|
||||
result.fold(
|
||||
(l) => emit(_Error(l)),
|
||||
(r) async {
|
||||
List<CategoryModel> categories = r.data.categories;
|
||||
categories.insert(
|
||||
0,
|
||||
CategoryModel(
|
||||
id: "",
|
||||
name: 'Semua',
|
||||
organizationId: '',
|
||||
businessType: '',
|
||||
metadata: {},
|
||||
createdAt: DateTime.now(),
|
||||
updatedAt: DateTime.now(),
|
||||
),
|
||||
);
|
||||
emit(_Loaded(categories, null));
|
||||
final CategoryRepository _categoryRepository = CategoryRepository.instance;
|
||||
|
||||
Timer? _searchDebounce;
|
||||
bool _isLoadingMore = false;
|
||||
|
||||
CategoryLoaderBloc() : super(const CategoryLoaderState.initial()) {
|
||||
on<_GetCategories>(_onGetCategories);
|
||||
on<_LoadMore>(_onLoadMore);
|
||||
on<_Refresh>(_onRefresh);
|
||||
on<_Search>(_onSearch);
|
||||
on<_SyncAll>(_onSyncAll);
|
||||
on<_GetAllCategories>(_onGetAllCategories);
|
||||
on<_ClearCache>(_onClearCache);
|
||||
on<_GetDatabaseStats>(_onGetDatabaseStats);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() {
|
||||
_searchDebounce?.cancel();
|
||||
return super.close();
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// GET CATEGORIES (Remote-first with local fallback)
|
||||
// ========================================
|
||||
Future<void> _onGetCategories(
|
||||
_GetCategories event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
emit(const CategoryLoaderState.loading());
|
||||
_isLoadingMore = false;
|
||||
|
||||
log('📱 Loading categories - isActive: ${event.isActive}, forceRemote: ${event.forceRemote}');
|
||||
|
||||
final result = await _categoryRepository.getCategories(
|
||||
page: 1,
|
||||
limit: 10,
|
||||
isActive: event.isActive,
|
||||
search: event.search,
|
||||
forceRemote: event.forceRemote,
|
||||
);
|
||||
|
||||
await result.fold(
|
||||
(failure) async {
|
||||
log('❌ Error loading categories: $failure');
|
||||
emit(CategoryLoaderState.error(failure));
|
||||
},
|
||||
(response) async {
|
||||
final categories = response.data.categories;
|
||||
final totalPages = response.data.totalPages;
|
||||
final hasReachedMax = categories.length < 10 || 1 >= totalPages;
|
||||
|
||||
log('✅ Categories loaded: ${categories.length}, hasReachedMax: $hasReachedMax');
|
||||
|
||||
emit(CategoryLoaderState.loaded(
|
||||
categories: categories,
|
||||
hasReachedMax: hasReachedMax,
|
||||
currentPage: 1,
|
||||
isLoadingMore: false,
|
||||
isActive: event.isActive,
|
||||
searchQuery: event.search,
|
||||
));
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// LOAD MORE CATEGORIES
|
||||
// ========================================
|
||||
Future<void> _onLoadMore(
|
||||
_LoadMore event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
final currentState = state;
|
||||
|
||||
if (currentState is! _Loaded ||
|
||||
currentState.hasReachedMax ||
|
||||
_isLoadingMore ||
|
||||
currentState.isLoadingMore) {
|
||||
log('⏹️ Load more blocked - state: ${currentState.runtimeType}, isLoadingMore: $_isLoadingMore');
|
||||
return;
|
||||
}
|
||||
|
||||
_isLoadingMore = true;
|
||||
emit(currentState.copyWith(isLoadingMore: true));
|
||||
|
||||
final nextPage = currentState.currentPage + 1;
|
||||
log('📄 Loading more categories - page: $nextPage');
|
||||
|
||||
try {
|
||||
final result = await _categoryRepository.getCategories(
|
||||
page: nextPage,
|
||||
limit: 10,
|
||||
isActive: currentState.isActive,
|
||||
search: currentState.searchQuery,
|
||||
);
|
||||
|
||||
await result.fold(
|
||||
(failure) async {
|
||||
log('❌ Error loading more categories: $failure');
|
||||
emit(currentState.copyWith(isLoadingMore: false));
|
||||
},
|
||||
(response) async {
|
||||
final newCategories = response.data.categories;
|
||||
final totalPages = response.data.totalPages;
|
||||
|
||||
// Prevent duplicate categories
|
||||
final currentCategoryIds =
|
||||
currentState.categories.map((c) => c.id).toSet();
|
||||
final filteredNewCategories = newCategories
|
||||
.where((category) => !currentCategoryIds.contains(category.id))
|
||||
.toList();
|
||||
|
||||
final allCategories =
|
||||
List<CategoryModel>.from(currentState.categories)
|
||||
..addAll(filteredNewCategories);
|
||||
|
||||
final hasReachedMax =
|
||||
newCategories.length < 10 || nextPage >= totalPages;
|
||||
|
||||
log('✅ More categories loaded: ${filteredNewCategories.length} new, total: ${allCategories.length}');
|
||||
|
||||
emit(CategoryLoaderState.loaded(
|
||||
categories: allCategories,
|
||||
hasReachedMax: hasReachedMax,
|
||||
currentPage: nextPage,
|
||||
isLoadingMore: false,
|
||||
isActive: currentState.isActive,
|
||||
searchQuery: currentState.searchQuery,
|
||||
));
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
log('❌ Exception loading more categories: $e');
|
||||
emit(currentState.copyWith(isLoadingMore: false));
|
||||
} finally {
|
||||
_isLoadingMore = false;
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// REFRESH CATEGORIES
|
||||
// ========================================
|
||||
Future<void> _onRefresh(
|
||||
_Refresh event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
final currentState = state;
|
||||
bool isActive = true;
|
||||
String? searchQuery;
|
||||
|
||||
if (currentState is _Loaded) {
|
||||
isActive = currentState.isActive;
|
||||
searchQuery = currentState.searchQuery;
|
||||
}
|
||||
|
||||
_isLoadingMore = false;
|
||||
_searchDebounce?.cancel();
|
||||
|
||||
log('🔄 Refreshing categories');
|
||||
|
||||
// Clear local cache
|
||||
_categoryRepository.clearCache();
|
||||
|
||||
add(CategoryLoaderEvent.getCategories(
|
||||
isActive: isActive,
|
||||
search: searchQuery,
|
||||
forceRemote: true, // Force remote refresh
|
||||
));
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// SEARCH CATEGORIES
|
||||
// ========================================
|
||||
Future<void> _onSearch(
|
||||
_Search event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
// Cancel previous search
|
||||
_searchDebounce?.cancel();
|
||||
|
||||
// Debounce search for better UX
|
||||
_searchDebounce = Timer(Duration(milliseconds: 300), () async {
|
||||
emit(const CategoryLoaderState.loading());
|
||||
_isLoadingMore = false;
|
||||
|
||||
log('🔍 Searching categories: "${event.query}"');
|
||||
|
||||
final result = await _categoryRepository.getCategories(
|
||||
page: 1,
|
||||
limit: 20, // More results for search
|
||||
isActive: event.isActive,
|
||||
search: event.query,
|
||||
);
|
||||
|
||||
await result.fold(
|
||||
(failure) async {
|
||||
log('❌ Search error: $failure');
|
||||
emit(CategoryLoaderState.error(failure));
|
||||
},
|
||||
(response) async {
|
||||
final categories = response.data.categories;
|
||||
final totalPages = response.data.totalPages;
|
||||
final hasReachedMax = categories.length < 20 || 1 >= totalPages;
|
||||
|
||||
log('✅ Search results: ${categories.length} categories found');
|
||||
|
||||
emit(CategoryLoaderState.loaded(
|
||||
categories: categories,
|
||||
hasReachedMax: hasReachedMax,
|
||||
currentPage: 1,
|
||||
isLoadingMore: false,
|
||||
isActive: event.isActive,
|
||||
searchQuery: event.query,
|
||||
));
|
||||
},
|
||||
);
|
||||
});
|
||||
on<_SetCategoryId>((event, emit) async {
|
||||
var currentState = state as _Loaded;
|
||||
}
|
||||
|
||||
emit(_Loaded(currentState.categories, event.categoryId));
|
||||
});
|
||||
// ========================================
|
||||
// SYNC ALL CATEGORIES
|
||||
// ========================================
|
||||
Future<void> _onSyncAll(
|
||||
_SyncAll event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
emit(const CategoryLoaderState.syncing());
|
||||
|
||||
log('🔄 Starting full category sync...');
|
||||
|
||||
final result = await _categoryRepository.syncAllCategories();
|
||||
|
||||
await result.fold(
|
||||
(failure) async {
|
||||
log('❌ Sync failed: $failure');
|
||||
emit(CategoryLoaderState.syncError(failure));
|
||||
|
||||
// After sync error, try to load local data
|
||||
Timer(Duration(seconds: 2), () {
|
||||
add(const CategoryLoaderEvent.getCategories());
|
||||
});
|
||||
},
|
||||
(successMessage) async {
|
||||
log('✅ Sync completed: $successMessage');
|
||||
emit(CategoryLoaderState.syncSuccess(successMessage));
|
||||
|
||||
// After successful sync, load the updated data
|
||||
Timer(Duration(seconds: 1), () {
|
||||
add(const CategoryLoaderEvent.getCategories());
|
||||
});
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// GET ALL CATEGORIES (For Dropdown)
|
||||
// ========================================
|
||||
Future<void> _onGetAllCategories(
|
||||
_GetAllCategories event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
try {
|
||||
log('📋 Loading all categories for dropdown...');
|
||||
|
||||
final categories = await _categoryRepository.getAllCategories();
|
||||
|
||||
emit(CategoryLoaderState.allCategoriesLoaded(categories));
|
||||
log('✅ All categories loaded: ${categories.length}');
|
||||
} catch (e) {
|
||||
log('❌ Error loading all categories: $e');
|
||||
emit(CategoryLoaderState.error('Gagal memuat semua kategori: $e'));
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// GET DATABASE STATS
|
||||
// ========================================
|
||||
Future<void> _onGetDatabaseStats(
|
||||
_GetDatabaseStats event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
try {
|
||||
final stats = await _categoryRepository.getDatabaseStats();
|
||||
log('📊 Category database stats retrieved: $stats');
|
||||
|
||||
// You can emit a special state here if needed for UI updates
|
||||
// For now, just log the stats
|
||||
} catch (e) {
|
||||
log('❌ Error getting category database stats: $e');
|
||||
}
|
||||
}
|
||||
|
||||
// ========================================
|
||||
// CLEAR CACHE
|
||||
// ========================================
|
||||
Future<void> _onClearCache(
|
||||
_ClearCache event,
|
||||
Emitter<CategoryLoaderState> emit,
|
||||
) async {
|
||||
log('🧹 Manually clearing category cache');
|
||||
_categoryRepository.clearCache();
|
||||
|
||||
// Refresh current data after cache clear
|
||||
add(const CategoryLoaderEvent.refresh());
|
||||
}
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,26 @@ part of 'category_loader_bloc.dart';
|
||||
|
||||
@freezed
|
||||
class CategoryLoaderEvent with _$CategoryLoaderEvent {
|
||||
const factory CategoryLoaderEvent.get() = _Get;
|
||||
const factory CategoryLoaderEvent.setCategoryId(String categoryId) =
|
||||
_SetCategoryId;
|
||||
const factory CategoryLoaderEvent.getCategories({
|
||||
@Default(true) bool isActive,
|
||||
String? search,
|
||||
@Default(false) bool forceRemote,
|
||||
}) = _GetCategories;
|
||||
|
||||
const factory CategoryLoaderEvent.loadMore() = _LoadMore;
|
||||
|
||||
const factory CategoryLoaderEvent.refresh() = _Refresh;
|
||||
|
||||
const factory CategoryLoaderEvent.search({
|
||||
required String query,
|
||||
@Default(true) bool isActive,
|
||||
}) = _Search;
|
||||
|
||||
const factory CategoryLoaderEvent.syncAll() = _SyncAll;
|
||||
|
||||
const factory CategoryLoaderEvent.getAllCategories() = _GetAllCategories;
|
||||
|
||||
const factory CategoryLoaderEvent.getDatabaseStats() = _GetDatabaseStats;
|
||||
|
||||
const factory CategoryLoaderEvent.clearCache() = _ClearCache;
|
||||
}
|
||||
|
||||
@@ -3,8 +3,29 @@ part of 'category_loader_bloc.dart';
|
||||
@freezed
|
||||
class CategoryLoaderState with _$CategoryLoaderState {
|
||||
const factory CategoryLoaderState.initial() = _Initial;
|
||||
|
||||
const factory CategoryLoaderState.loading() = _Loading;
|
||||
const factory CategoryLoaderState.loaded(
|
||||
List<CategoryModel> categories, String? categoryId) = _Loaded;
|
||||
|
||||
const factory CategoryLoaderState.loaded({
|
||||
required List<CategoryModel> categories,
|
||||
required bool hasReachedMax,
|
||||
required int currentPage,
|
||||
required bool isLoadingMore,
|
||||
required bool isActive,
|
||||
String? searchQuery,
|
||||
}) = _Loaded;
|
||||
|
||||
const factory CategoryLoaderState.error(String message) = _Error;
|
||||
|
||||
// Sync-specific states
|
||||
const factory CategoryLoaderState.syncing() = _Syncing;
|
||||
|
||||
const factory CategoryLoaderState.syncSuccess(String message) = _SyncSuccess;
|
||||
|
||||
const factory CategoryLoaderState.syncError(String message) = _SyncError;
|
||||
|
||||
// For dropdown/all categories
|
||||
const factory CategoryLoaderState.allCategoriesLoaded(
|
||||
List<CategoryModel> categories,
|
||||
) = _AllCategoriesLoaded;
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
// ========================================
|
||||
// OFFLINE-ONLY HOMEPAGE - NO API CALLS
|
||||
// HOMEPAGE - LOCAL DATA ONLY, NO SYNC
|
||||
// lib/presentation/home/pages/home_page.dart
|
||||
// ========================================
|
||||
|
||||
import 'dart:developer';
|
||||
import 'package:enaklo_pos/core/components/flushbar.dart';
|
||||
import 'package:enaklo_pos/data/datasources/product/product_local_datasource.dart';
|
||||
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||
import 'package:enaklo_pos/presentation/home/bloc/category_loader/category_loader_bloc.dart';
|
||||
import 'package:enaklo_pos/presentation/home/bloc/current_outlet/current_outlet_bloc.dart';
|
||||
import 'package:enaklo_pos/presentation/home/bloc/product_loader/product_loader_bloc.dart';
|
||||
@@ -50,17 +50,10 @@ class _HomePageState extends State<HomePage> {
|
||||
final ScrollController scrollController = ScrollController();
|
||||
String searchQuery = '';
|
||||
|
||||
// Local database only
|
||||
Map<String, dynamic> _databaseStats = {};
|
||||
final ProductLocalDatasource _localDatasource =
|
||||
ProductLocalDatasource.instance;
|
||||
bool _isLoadingStats = true;
|
||||
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
_initializeLocalData();
|
||||
_loadProducts();
|
||||
_loadData();
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -70,48 +63,28 @@ class _HomePageState extends State<HomePage> {
|
||||
super.dispose();
|
||||
}
|
||||
|
||||
// Initialize local data only
|
||||
void _initializeLocalData() {
|
||||
_loadDatabaseStats();
|
||||
}
|
||||
void _loadData() {
|
||||
log('📱 Loading data from local database...');
|
||||
|
||||
// Load database statistics
|
||||
void _loadDatabaseStats() async {
|
||||
try {
|
||||
final stats = await _localDatasource.getDatabaseStats();
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
_databaseStats = stats;
|
||||
_isLoadingStats = false;
|
||||
});
|
||||
}
|
||||
log('📊 Local database stats: $stats');
|
||||
} catch (e) {
|
||||
log('❌ Error loading local stats: $e');
|
||||
setState(() {
|
||||
_isLoadingStats = false;
|
||||
});
|
||||
}
|
||||
}
|
||||
// Load categories from local database
|
||||
context
|
||||
.read<CategoryLoaderBloc>()
|
||||
.add(const CategoryLoaderEvent.getCategories());
|
||||
|
||||
void _loadProducts() {
|
||||
log('📱 Loading products from local database only...');
|
||||
|
||||
// Load products from local database only
|
||||
// Load products from local database
|
||||
context
|
||||
.read<ProductLoaderBloc>()
|
||||
.add(const ProductLoaderEvent.getProduct());
|
||||
|
||||
// Initialize other components
|
||||
context.read<CheckoutBloc>().add(CheckoutEvent.started(widget.items));
|
||||
context.read<CategoryLoaderBloc>().add(CategoryLoaderEvent.get());
|
||||
context.read<CurrentOutletBloc>().add(CurrentOutletEvent.currentOutlet());
|
||||
}
|
||||
|
||||
void _refreshLocalData() {
|
||||
void _refreshData() {
|
||||
log('🔄 Refreshing local data...');
|
||||
context.read<ProductLoaderBloc>().add(const ProductLoaderEvent.refresh());
|
||||
_loadDatabaseStats();
|
||||
context.read<CategoryLoaderBloc>().add(const CategoryLoaderEvent.refresh());
|
||||
}
|
||||
|
||||
void onCategoryTap(int index) {
|
||||
@@ -125,11 +98,9 @@ class _HomePageState extends State<HomePage> {
|
||||
ScrollNotification notification, String? categoryId) {
|
||||
if (notification is ScrollEndNotification &&
|
||||
scrollController.position.extentAfter == 0) {
|
||||
log('📄 Loading more local products for category: $categoryId');
|
||||
log('📄 Loading more products...');
|
||||
context.read<ProductLoaderBloc>().add(
|
||||
ProductLoaderEvent.loadMore(
|
||||
categoryId: categoryId,
|
||||
),
|
||||
ProductLoaderEvent.loadMore(),
|
||||
);
|
||||
return true;
|
||||
}
|
||||
@@ -142,7 +113,6 @@ class _HomePageState extends State<HomePage> {
|
||||
listener: (context, state) {
|
||||
state.maybeWhen(
|
||||
orElse: () {},
|
||||
loading: () {},
|
||||
success: () {
|
||||
Future.delayed(Duration(milliseconds: 300), () {
|
||||
AppFlushbar.showSuccess(context, 'Outlet berhasil diubah');
|
||||
@@ -160,81 +130,33 @@ class _HomePageState extends State<HomePage> {
|
||||
backgroundColor: AppColors.white,
|
||||
body: Column(
|
||||
children: [
|
||||
// Local database indicator
|
||||
_buildLocalModeIndicator(),
|
||||
// Simple local mode indicator
|
||||
_buildLocalIndicator(),
|
||||
|
||||
// Main content
|
||||
Expanded(
|
||||
child: Row(
|
||||
children: [
|
||||
// Left panel - Products
|
||||
// Left panel - Products with Categories
|
||||
Expanded(
|
||||
flex: 3,
|
||||
child: Align(
|
||||
alignment: AlignmentDirectional.topStart,
|
||||
child: BlocBuilder<CategoryLoaderBloc,
|
||||
CategoryLoaderState>(
|
||||
builder: (context, state) {
|
||||
return state.maybeWhen(
|
||||
orElse: () =>
|
||||
Center(child: CircularProgressIndicator()),
|
||||
loaded: (categories, categoryId) => Column(
|
||||
mainAxisAlignment: MainAxisAlignment.start,
|
||||
children: [
|
||||
// Enhanced home title with local stats
|
||||
_buildLocalHomeTitle(categoryId),
|
||||
|
||||
// Products section
|
||||
Expanded(
|
||||
child: BlocBuilder<ProductLoaderBloc,
|
||||
ProductLoaderState>(
|
||||
builder: (context, productState) {
|
||||
return CategoryTabBar(
|
||||
categories: categories,
|
||||
tabViews: categories.map((category) {
|
||||
return SizedBox(
|
||||
child: productState.maybeWhen(
|
||||
orElse: () =>
|
||||
_buildLoadingState(),
|
||||
loading: () =>
|
||||
_buildLoadingState(),
|
||||
loaded: (products,
|
||||
hasReachedMax,
|
||||
currentPage,
|
||||
isLoadingMore,
|
||||
categoryId,
|
||||
searchQuery) {
|
||||
if (products.isEmpty) {
|
||||
return _buildEmptyState(
|
||||
categoryId);
|
||||
}
|
||||
return _buildProductGrid(
|
||||
products,
|
||||
hasReachedMax,
|
||||
isLoadingMore,
|
||||
categoryId,
|
||||
currentPage,
|
||||
);
|
||||
},
|
||||
error: (message) =>
|
||||
_buildErrorState(
|
||||
message, categoryId),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
},
|
||||
),
|
||||
child:
|
||||
BlocBuilder<CategoryLoaderBloc, CategoryLoaderState>(
|
||||
builder: (context, categoryState) {
|
||||
return categoryState.maybeWhen(
|
||||
orElse: () => _buildCategoryLoadingState(),
|
||||
loading: () => _buildCategoryLoadingState(),
|
||||
error: (message) =>
|
||||
_buildCategoryErrorState(message),
|
||||
loaded: (categories, hasReachedMax, currentPage,
|
||||
isLoadingMore, isActive, searchQuery) =>
|
||||
_buildCategoryContent(categories),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
|
||||
// Right panel - Cart (unchanged)
|
||||
// Right panel - Cart
|
||||
Expanded(
|
||||
flex: 2,
|
||||
child: _buildCartSection(),
|
||||
@@ -249,8 +171,8 @@ class _HomePageState extends State<HomePage> {
|
||||
);
|
||||
}
|
||||
|
||||
// Local mode indicator
|
||||
Widget _buildLocalModeIndicator() {
|
||||
// Simple local mode indicator without sync
|
||||
Widget _buildLocalIndicator() {
|
||||
return Container(
|
||||
width: double.infinity,
|
||||
padding: EdgeInsets.symmetric(vertical: 8, horizontal: 16),
|
||||
@@ -261,9 +183,7 @@ class _HomePageState extends State<HomePage> {
|
||||
SizedBox(width: 8),
|
||||
Expanded(
|
||||
child: Text(
|
||||
_isLoadingStats
|
||||
? 'Mode Lokal - Memuat data...'
|
||||
: 'Mode Lokal - ${_databaseStats['total_products'] ?? 0} produk tersimpan',
|
||||
'Mode Lokal - Data tersimpan di perangkat',
|
||||
style: TextStyle(
|
||||
color: Colors.white,
|
||||
fontSize: 13,
|
||||
@@ -271,18 +191,10 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
),
|
||||
),
|
||||
if (_databaseStats.isNotEmpty) ...[
|
||||
Text(
|
||||
'${(_databaseStats['database_size_mb'] ?? 0.0).toStringAsFixed(1)} MB',
|
||||
style: TextStyle(
|
||||
color: Colors.white.withOpacity(0.8),
|
||||
fontSize: 11,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 8),
|
||||
],
|
||||
|
||||
// Only refresh button
|
||||
InkWell(
|
||||
onTap: _refreshLocalData,
|
||||
onTap: _refreshData,
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(4),
|
||||
decoration: BoxDecoration(
|
||||
@@ -297,170 +209,125 @@ class _HomePageState extends State<HomePage> {
|
||||
);
|
||||
}
|
||||
|
||||
// Enhanced home title with local stats only
|
||||
Widget _buildLocalHomeTitle(String? categoryId) {
|
||||
Widget _buildCategoryLoadingState() {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
CircularProgressIndicator(color: AppColors.primary),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Memuat kategori...',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryErrorState(String message) {
|
||||
return Center(
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(Icons.error_outline, size: 48, color: Colors.red.shade400),
|
||||
SizedBox(height: 16),
|
||||
Text('Error Kategori',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600)),
|
||||
SizedBox(height: 8),
|
||||
Padding(
|
||||
padding: EdgeInsets.symmetric(horizontal: 32),
|
||||
child: Text(
|
||||
message,
|
||||
textAlign: TextAlign.center,
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
),
|
||||
SizedBox(height: 16),
|
||||
Button.filled(
|
||||
width: 120,
|
||||
onPressed: () {
|
||||
context
|
||||
.read<CategoryLoaderBloc>()
|
||||
.add(const CategoryLoaderEvent.getCategories());
|
||||
},
|
||||
label: 'Coba Lagi',
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildCategoryContent(List<CategoryModel> categories) {
|
||||
return Column(
|
||||
children: [
|
||||
// Simple home title
|
||||
_buildSimpleHomeTitle(),
|
||||
|
||||
// Products section with categories
|
||||
Expanded(
|
||||
child: BlocBuilder<ProductLoaderBloc, ProductLoaderState>(
|
||||
builder: (context, productState) {
|
||||
return CategoryTabBar(
|
||||
categories: categories,
|
||||
tabViews: categories.map((category) {
|
||||
return SizedBox(
|
||||
child: productState.maybeWhen(
|
||||
orElse: () => _buildLoadingState(),
|
||||
loading: () => _buildLoadingState(),
|
||||
loaded: (products, hasReachedMax, currentPage,
|
||||
isLoadingMore, categoryId, searchQuery) {
|
||||
if (products.isEmpty) {
|
||||
return _buildEmptyState(categoryId);
|
||||
}
|
||||
return _buildProductGrid(
|
||||
products,
|
||||
hasReachedMax,
|
||||
isLoadingMore,
|
||||
categoryId,
|
||||
currentPage,
|
||||
);
|
||||
},
|
||||
error: (message) =>
|
||||
_buildErrorState(message, category.id),
|
||||
),
|
||||
);
|
||||
}).toList(),
|
||||
);
|
||||
},
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
|
||||
// Simple home title
|
||||
Widget _buildSimpleHomeTitle() {
|
||||
return Container(
|
||||
padding: EdgeInsets.all(16),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.white,
|
||||
border: Border(bottom: BorderSide(color: Colors.grey.shade200)),
|
||||
),
|
||||
child: Column(
|
||||
children: [
|
||||
// Original HomeTitle with faster search
|
||||
HomeTitle(
|
||||
controller: searchController,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
searchQuery = value;
|
||||
});
|
||||
child: HomeTitle(
|
||||
controller: searchController,
|
||||
onChanged: (value) {
|
||||
setState(() {
|
||||
searchQuery = value;
|
||||
});
|
||||
|
||||
// Fast local search - no debounce needed for local data
|
||||
Future.delayed(Duration(milliseconds: 200), () {
|
||||
if (value == searchController.text) {
|
||||
log('🔍 Local search: "$value"');
|
||||
context.read<ProductLoaderBloc>().add(
|
||||
ProductLoaderEvent.searchProduct(
|
||||
categoryId: categoryId,
|
||||
query: value,
|
||||
),
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
),
|
||||
|
||||
// Local database stats
|
||||
if (_databaseStats.isNotEmpty) ...[
|
||||
SizedBox(height: 8),
|
||||
Row(
|
||||
children: [
|
||||
// Local storage indicator
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.storage,
|
||||
size: 12, color: Colors.blue.shade600),
|
||||
SizedBox(width: 3),
|
||||
Text(
|
||||
'Lokal',
|
||||
style: TextStyle(
|
||||
fontSize: 10,
|
||||
color: Colors.blue.shade600,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
|
||||
SizedBox(width: 8),
|
||||
|
||||
// Database stats chips
|
||||
_buildStatChip(
|
||||
'${_databaseStats['total_products'] ?? 0}',
|
||||
'produk',
|
||||
Icons.inventory_2,
|
||||
Colors.green,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
_buildStatChip(
|
||||
'${_databaseStats['total_variants'] ?? 0}',
|
||||
'varian',
|
||||
Icons.tune,
|
||||
Colors.orange,
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
_buildStatChip(
|
||||
'${_databaseStats['cache_entries'] ?? 0}',
|
||||
'cache',
|
||||
Icons.memory,
|
||||
Colors.purple,
|
||||
),
|
||||
|
||||
Spacer(),
|
||||
|
||||
// Clear cache button
|
||||
InkWell(
|
||||
onTap: () {
|
||||
_localDatasource.clearExpiredCache();
|
||||
_loadDatabaseStats();
|
||||
AppFlushbar.showSuccess(context, 'Cache dibersihkan');
|
||||
},
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(5),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.grey.shade100,
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
// Fast local search
|
||||
Future.delayed(Duration(milliseconds: 200), () {
|
||||
if (value == searchController.text) {
|
||||
log('🔍 Local search: "$value"');
|
||||
context.read<ProductLoaderBloc>().add(
|
||||
ProductLoaderEvent.searchProduct(
|
||||
query: value,
|
||||
),
|
||||
child: Icon(
|
||||
Icons.clear_all,
|
||||
size: 14,
|
||||
color: Colors.grey.shade600,
|
||||
),
|
||||
),
|
||||
),
|
||||
SizedBox(width: 4),
|
||||
// Refresh button
|
||||
InkWell(
|
||||
onTap: _refreshLocalData,
|
||||
child: Container(
|
||||
padding: EdgeInsets.all(5),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(5),
|
||||
),
|
||||
child: Icon(
|
||||
Icons.refresh,
|
||||
size: 14,
|
||||
color: AppColors.primary,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Widget _buildStatChip(
|
||||
String value, String label, IconData icon, Color color) {
|
||||
return Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 5, vertical: 2),
|
||||
decoration: BoxDecoration(
|
||||
color: color.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(6),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(icon, size: 10, color: color),
|
||||
SizedBox(width: 2),
|
||||
Text(
|
||||
value,
|
||||
style: TextStyle(
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: color,
|
||||
),
|
||||
),
|
||||
SizedBox(width: 1),
|
||||
Text(
|
||||
label,
|
||||
style: TextStyle(
|
||||
fontSize: 8,
|
||||
color: color.withOpacity(0.8),
|
||||
),
|
||||
),
|
||||
],
|
||||
);
|
||||
}
|
||||
});
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -473,7 +340,7 @@ class _HomePageState extends State<HomePage> {
|
||||
CircularProgressIndicator(color: AppColors.primary),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Memuat data lokal...',
|
||||
'Memuat data...',
|
||||
style: TextStyle(color: Colors.grey.shade600),
|
||||
),
|
||||
],
|
||||
@@ -491,12 +358,12 @@ class _HomePageState extends State<HomePage> {
|
||||
Text(
|
||||
searchQuery.isNotEmpty
|
||||
? 'Produk "$searchQuery" tidak ditemukan'
|
||||
: 'Belum ada data produk lokal',
|
||||
: 'Belum ada data produk',
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Text(
|
||||
'Tambahkan produk ke database lokal terlebih dahulu',
|
||||
'Data akan dimuat dari database lokal',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade600,
|
||||
fontSize: 12,
|
||||
@@ -542,18 +409,11 @@ class _HomePageState extends State<HomePage> {
|
||||
child: Column(
|
||||
mainAxisAlignment: MainAxisAlignment.center,
|
||||
children: [
|
||||
Icon(
|
||||
Icons.error_outline,
|
||||
size: 48,
|
||||
color: Colors.red.shade400,
|
||||
),
|
||||
Icon(Icons.error_outline, size: 48, color: Colors.red.shade400),
|
||||
SizedBox(height: 16),
|
||||
Text(
|
||||
'Error Database Lokal',
|
||||
style: TextStyle(
|
||||
fontSize: 16,
|
||||
fontWeight: FontWeight.w600,
|
||||
),
|
||||
'Error Database',
|
||||
style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600),
|
||||
),
|
||||
SizedBox(height: 8),
|
||||
Padding(
|
||||
@@ -588,61 +448,19 @@ class _HomePageState extends State<HomePage> {
|
||||
) {
|
||||
return Column(
|
||||
children: [
|
||||
// Product count with local indicator
|
||||
// Simple product count
|
||||
if (products.isNotEmpty)
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 16, vertical: 6),
|
||||
child: Row(
|
||||
children: [
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 4, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.blue.shade50,
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Row(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
children: [
|
||||
Icon(Icons.storage,
|
||||
size: 10, color: Colors.blue.shade600),
|
||||
SizedBox(width: 2),
|
||||
Text(
|
||||
'${products.length}',
|
||||
style: TextStyle(
|
||||
fontSize: 11,
|
||||
fontWeight: FontWeight.w600,
|
||||
color: Colors.blue.shade600,
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
SizedBox(width: 6),
|
||||
Text(
|
||||
'produk dari database lokal',
|
||||
'${products.length} produk ditemukan',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade600,
|
||||
fontSize: 11,
|
||||
fontSize: 12,
|
||||
),
|
||||
),
|
||||
if (currentPage > 1) ...[
|
||||
SizedBox(width: 6),
|
||||
Container(
|
||||
padding: EdgeInsets.symmetric(horizontal: 4, vertical: 1),
|
||||
decoration: BoxDecoration(
|
||||
color: AppColors.primary.withOpacity(0.1),
|
||||
borderRadius: BorderRadius.circular(4),
|
||||
),
|
||||
child: Text(
|
||||
'Hal $currentPage',
|
||||
style: TextStyle(
|
||||
color: AppColors.primary,
|
||||
fontSize: 9,
|
||||
fontWeight: FontWeight.w500,
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
Spacer(),
|
||||
if (isLoadingMore)
|
||||
SizedBox(
|
||||
@@ -657,7 +475,7 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
),
|
||||
|
||||
// Products grid - faster loading from local DB
|
||||
// Products grid
|
||||
Expanded(
|
||||
child: NotificationListener<ScrollNotification>(
|
||||
onNotification: (notification) =>
|
||||
@@ -666,7 +484,7 @@ class _HomePageState extends State<HomePage> {
|
||||
itemCount: products.length,
|
||||
controller: scrollController,
|
||||
padding: const EdgeInsets.all(16),
|
||||
cacheExtent: 200.0, // Bigger cache for smooth scrolling
|
||||
cacheExtent: 200.0,
|
||||
gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
|
||||
maxCrossAxisExtent: 180,
|
||||
mainAxisSpacing: 30,
|
||||
@@ -683,12 +501,12 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
),
|
||||
|
||||
// End of data indicator
|
||||
// End indicator
|
||||
if (hasReachedMax && products.isNotEmpty)
|
||||
Container(
|
||||
padding: EdgeInsets.all(8),
|
||||
child: Text(
|
||||
'Semua produk lokal telah dimuat',
|
||||
'Semua produk telah dimuat',
|
||||
style: TextStyle(
|
||||
color: Colors.grey.shade500,
|
||||
fontSize: 11,
|
||||
@@ -786,7 +604,7 @@ class _HomePageState extends State<HomePage> {
|
||||
),
|
||||
),
|
||||
|
||||
// Payment section (unchanged)
|
||||
// Payment section
|
||||
Padding(
|
||||
padding: const EdgeInsets.all(16.0).copyWith(top: 0),
|
||||
child: Column(
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import 'package:enaklo_pos/core/constants/colors.dart';
|
||||
import 'package:enaklo_pos/data/models/response/category_response_model.dart';
|
||||
import 'package:enaklo_pos/presentation/home/bloc/category_loader/category_loader_bloc.dart';
|
||||
import 'package:enaklo_pos/presentation/home/bloc/product_loader/product_loader_bloc.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_bloc/flutter_bloc.dart';
|
||||
@@ -37,9 +36,6 @@ class _CategoryTabBarState extends State<CategoryTabBar>
|
||||
context.read<ProductLoaderBloc>().add(
|
||||
ProductLoaderEvent.getProduct(categoryId: selectedCategoryId),
|
||||
);
|
||||
context
|
||||
.read<CategoryLoaderBloc>()
|
||||
.add(CategoryLoaderEvent.setCategoryId(selectedCategoryId ?? ""));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user