category local

This commit is contained in:
efrilm
2025-09-20 04:36:22 +07:00
parent c12d6525fa
commit 5b980d237f
12 changed files with 3443 additions and 515 deletions
+162 -344
View File
@@ -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(