feat(shopping-list): add shopping list feature with flyer integration
Test Suite / backend-pr-quick (push) Has been skipped
Test Suite / quick-import-pr-quick (push) Has been skipped
Test Suite / backend-full (push) Successful in 5m8s
Test Suite / flutter-quality (push) Failing after 1m41s

This commit introduces a comprehensive shopping list feature with the following key changes:

Backend:
- Added ShoppingListItem model with relations to User, Product, and Category
- Added new fields to FlyerSession for source file metadata
- Added categoryId field to FlyerItem model
- Implemented session source file retrieval endpoint
- Added endpoint for updating flyer session items with category assignment
- Added endpoint for planning flyer selections to shopping list
- Implemented backfillCategoriesMine for AI-assisted category assignment
- Added ShoppingListModule and integrated with FlyerSelectionModule

Frontend:
- Added ShoppingListScreen and navigation route
- Implemented API paths and client methods for shopping list operations
- Added category tree loading for shopping list item creation
- Integrated shopping list functionality in flyer import tab
- Added category backfill trigger in inventory screen
- Updated FlyerImportItem model with categoryId support
- Added methods for updating flyer session items and retrieving source files

Database:
- Added new Prisma migration for flyer source metadata and shopping list items
- Updated schema with new relations and indexes

The shopping list feature allows users to:
1. Plan flyer selections directly to their shopping list
2. View and manage their shopping list items
3. Update flyer session items with proper categorization
4. Retrieve original flyer source files
5. Automatically backfill categories for uncategorized products
This commit is contained in:
Nils-Johan Gynther
2026-05-20 09:07:30 +02:00
parent 996f0d774b
commit a1a2c33427
37 changed files with 1843 additions and 102 deletions
@@ -1,9 +1,16 @@
import 'package:file_picker/file_picker.dart';
import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../core/api/api_paths.dart';
import '../../../core/api/api_providers.dart';
import '../../../core/ui/category_then_product_picker.dart';
import '../../admin/domain/admin_category_node.dart';
import '../../../core/utils/pdf_opener.dart';
import '../../auth/data/auth_providers.dart';
import '../../shopping_list/data/shopping_list_providers.dart';
import '../data/flyer_import_session.dart';
import '../data/import_providers.dart';
import '../domain/flyer_import_item.dart';
@@ -21,15 +28,38 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
bool _isLoading = false;
bool _isSaving = false;
PlatformFile? _pickedFile;
Uint8List? _restoredSourceBytes;
List<AdminCategoryNode> _categoryTree = const [];
FlyerImportResult? _result;
final Map<int, bool> _selected = {};
@override
void initState() {
super.initState();
_loadCategoryTree();
_restoreSession();
}
Future<void> _loadCategoryTree() async {
try {
final token = await ref.read(authStateProvider.future);
final api = ref.read(apiClientProvider);
final categoryData = await api.getJson(CategoryApiPaths.tree, token: token);
final categoryList = categoryData is List<dynamic>
? categoryData
: (categoryData is Map<String, dynamic> && categoryData['items'] is List<dynamic>)
? categoryData['items'] as List<dynamic>
: const <dynamic>[];
final tree = categoryList
.map((e) => AdminCategoryNode.fromJson(Map<String, dynamic>.from(e as Map)))
.toList();
if (!mounted) return;
setState(() => _categoryTree = tree);
} catch (_) {
// Kategoriträdet är valfritt för att visa listan.
}
}
Future<void> _restoreSession() async {
final notifier = ref.read(flyerImportSessionProvider.notifier);
await notifier.restore();
@@ -53,10 +83,12 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
: session.selected;
setState(() {
_result = serverResult;
_restoredSourceBytes = null;
_selected
..clear()
..addAll(selected);
});
await _loadRestoredSourceIfNeeded(serverResult, token);
notifier.setImportedResult(
result: serverResult,
selected: selected,
@@ -78,10 +110,12 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
};
setState(() {
_result = latest;
_restoredSourceBytes = null;
_selected
..clear()
..addAll(selected);
});
await _loadRestoredSourceIfNeeded(latest, token);
notifier.setImportedResult(
result: latest,
selected: selected,
@@ -100,6 +134,7 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
if (!mounted || session?.result == null) return;
setState(() {
_result = session!.result;
_restoredSourceBytes = null;
_selected
..clear()
..addAll(session.selected);
@@ -107,6 +142,20 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
}
}
Future<void> _loadRestoredSourceIfNeeded(FlyerImportResult result, String? token) async {
if (result.sessionId == null || result.sourceAvailable != true) return;
if (_pickedFile?.bytes != null) return;
try {
final repo = ref.read(importRepositoryProvider);
final bytes = await repo.getFlyerSourceBytes(sessionId: result.sessionId!, token: token);
if (!mounted) return;
setState(() => _restoredSourceBytes = bytes);
} catch (_) {
if (!mounted) return;
setState(() => _restoredSourceBytes = null);
}
}
Future<void> _pickFile() async {
final result = await FilePicker.pickFiles(
type: FileType.custom,
@@ -138,6 +187,7 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
}
setState(() {
_result = parsed;
_restoredSourceBytes = null;
_selected
..clear()
..addAll(selected);
@@ -159,10 +209,12 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
if (result?.sessionId == null) return;
final itemsToSave = <Map<String, dynamic>>[];
final selectedItemIds = <int>[];
for (var i = 0; i < result!.items.length; i++) {
final item = result.items[i];
final isSelected = _selected[i] == true;
if (!isSelected || item.flyerItemId == null) continue;
selectedItemIds.add(item.flyerItemId!);
itemsToSave.add({
'itemId': item.flyerItemId,
'plannedQuantity': 1,
@@ -187,9 +239,23 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
items: itemsToSave,
token: token,
);
final shopping = await repo.planFlyerSelectionsToShoppingList(
sessionId: result.sessionId!,
itemIds: selectedItemIds,
token: token,
);
if (!mounted) return;
final created = (shopping['created'] as num?)?.toInt() ?? 0;
final updated = (shopping['updated'] as num?)?.toInt() ?? 0;
ref.invalidate(shoppingListItemsProvider);
ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: Text('${saved.length} varor planerade.')),
SnackBar(
content: Text('${saved.length} planerade. Inköpslista: $created tillagda, $updated uppdaterade.'),
action: SnackBarAction(
label: 'Öppna',
onPressed: () => context.go('/inkopslista'),
),
),
);
} catch (e) {
if (mounted) showErrorDialog(context, 'Kunde inte planera varor: $e');
@@ -198,6 +264,141 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
}
}
Future<void> _editItem(int index, FlyerImportItem item) async {
final sessionId = _result?.sessionId;
final itemId = item.flyerItemId;
if (sessionId == null || itemId == null) return;
final nameController = TextEditingController(text: item.rawName);
int? selectedCategoryId = item.categoryId;
String? selectedCategoryPath = item.category;
final payload = await showDialog<({String name, int? categoryId, String? categoryPath})>(
context: context,
builder: (context) {
return StatefulBuilder(
builder: (context, setLocalState) {
return AlertDialog(
title: const Text('Redigera rad'),
content: SizedBox(
width: 420,
child: Column(
mainAxisSize: MainAxisSize.min,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
TextField(
controller: nameController,
decoration: const InputDecoration(
labelText: 'Namn',
border: OutlineInputBorder(),
),
),
const SizedBox(height: 12),
Text(
selectedCategoryPath == null || selectedCategoryPath!.isEmpty
? 'Ingen kategori vald'
: selectedCategoryPath!,
),
const SizedBox(height: 8),
Wrap(
spacing: 8,
children: [
OutlinedButton.icon(
onPressed: _categoryTree.isEmpty
? null
: () async {
final selected = await CategoryThenProductPicker.showCategorySheet(
context,
categoryTree: _categoryTree,
preselectedCategoryId: selectedCategoryId,
);
if (selected == null) return;
setLocalState(() {
selectedCategoryId = selected.id;
selectedCategoryPath = selected.path;
});
},
icon: const Icon(Icons.category_outlined),
label: const Text('Välj kategori'),
),
TextButton(
onPressed: () {
setLocalState(() {
selectedCategoryId = null;
selectedCategoryPath = null;
});
},
child: const Text('Rensa'),
),
],
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.of(context).pop(),
child: const Text('Avbryt'),
),
FilledButton(
onPressed: () {
Navigator.of(context).pop((
name: nameController.text.trim(),
categoryId: selectedCategoryId,
categoryPath: selectedCategoryPath,
));
},
child: const Text('Spara'),
),
],
);
},
);
},
);
nameController.dispose();
if (payload == null || payload.name.isEmpty) return;
try {
final token = await ref.read(authStateProvider.future);
final repo = ref.read(importRepositoryProvider);
final updated = await repo.updateFlyerSessionItem(
sessionId: sessionId,
itemId: itemId,
rawName: payload.name,
categoryId: payload.categoryId,
token: token,
);
if (!mounted) return;
final result = _result;
if (result == null) return;
final nextItems = [...result.items];
nextItems[index] = updated;
final nextResult = FlyerImportResult(
sessionId: result.sessionId,
items: nextItems,
warnings: result.warnings,
sourceAvailable: result.sourceAvailable,
sourceFileName: result.sourceFileName,
sourceMimeType: result.sourceMimeType,
sourceFileSize: result.sourceFileSize,
);
setState(() {
_result = nextResult;
});
ref.read(flyerImportSessionProvider.notifier).setImportedResult(
result: nextResult,
selected: Map<int, bool>.from(_selected),
fileName: _pickedFile?.name ?? result.sourceFileName,
);
} catch (e) {
if (!mounted) return;
showErrorDialog(context, 'Kunde inte uppdatera rad: $e');
}
}
String _formatPrice(double? price, String? unit) {
if (price == null) return '';
final raw = price.toStringAsFixed(2).replaceAll('.', ',');
@@ -320,10 +521,10 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
Widget _buildFlyerPreview(ThemeData theme) {
final file = _pickedFile;
final bytes = file?.bytes;
final bytes = file?.bytes ?? _restoredSourceBytes;
if (bytes == null) return const SizedBox.shrink();
final filename = file?.name ?? '';
final filename = file?.name ?? _result?.sourceFileName ?? '';
final fallbackExt = filename.contains('.') ? filename.split('.').last : '';
final ext = (file?.extension ?? fallbackExt).toLowerCase();
final isImage = ['png', 'jpg', 'jpeg', 'webp', 'bmp'].contains(ext);
@@ -339,7 +540,7 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
color: theme.colorScheme.primary,
),
title: const Text('Flyerförhandsvisning'),
subtitle: Text(file?.name ?? ''),
subtitle: Text(filename),
trailing: isImage
? null
: OutlinedButton.icon(
@@ -449,11 +650,17 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
setState(() => _selected[index] = checked);
ref.read(flyerImportSessionProvider.notifier).setSelected(index, checked);
},
title: Row(
children: [
Expanded(child: Text(item.rawName)),
const SizedBox(width: 8),
_buildQualityBadge(item, theme),
title: Row(
children: [
Expanded(child: Text(item.rawName)),
IconButton(
tooltip: 'Redigera',
visualDensity: VisualDensity.compact,
icon: const Icon(Icons.edit_outlined, size: 18),
onPressed: () => _editItem(index, item),
),
const SizedBox(width: 8),
_buildQualityBadge(item, theme),
const SizedBox(width: 8),
_buildOfferBadge(item, theme),
],
@@ -461,8 +668,10 @@ class _FlyerImportTabState extends ConsumerState<FlyerImportTab> {
subtitle: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
if (priceText.isNotEmpty) Text('Pris: $priceText'),
if (comparisonText.isNotEmpty) Text('Jämförpris: $comparisonText'),
if (priceText.isNotEmpty) Text('Pris: $priceText'),
if ((item.category ?? '').trim().isNotEmpty)
Text('Kategori: ${item.category}'),
if (comparisonText.isNotEmpty) Text('Jämförpris: $comparisonText'),
if (limitText != null && limitText.isNotEmpty)
Text(
'Begränsning: $limitText',