feat: Add bulk delete and merge functionality for inventory items with DTOs and API endpoints
Test Suite / test (24.15.0) (push) Has been cancelled
Test Suite / test (24.15.0) (push) Has been cancelled
This commit is contained in:
@@ -5,13 +5,27 @@ import 'package:go_router/go_router.dart';
|
||||
import '../../../core/api/api_error_mapper.dart';
|
||||
import '../../../core/l10n/l10n.dart';
|
||||
import '../../../core/ui/async_state_views.dart';
|
||||
import '../../auth/data/auth_providers.dart';
|
||||
import '../data/inventory_providers.dart';
|
||||
import 'swipeable_inventory_tile.dart';
|
||||
|
||||
class InventoryScreen extends ConsumerWidget {
|
||||
class InventoryScreen extends ConsumerStatefulWidget {
|
||||
const InventoryScreen({super.key});
|
||||
|
||||
@override
|
||||
ConsumerState<InventoryScreen> createState() => _InventoryScreenState();
|
||||
}
|
||||
|
||||
class _InventoryScreenState extends ConsumerState<InventoryScreen> {
|
||||
final Set<int> _selectedIds = <int>{};
|
||||
|
||||
static const _locationOptions = <String>['', 'Kyl', 'Frys', 'Skafferi'];
|
||||
|
||||
static const _weightOrVolumeUnits = <String>{
|
||||
'g', 'gram', 'mg', 'milligram', 'hg', 'hektogram', 'kg', 'kilo', 'kilogram',
|
||||
'ml', 'milliliter', 'cl', 'centiliter', 'dl', 'deciliter', 'l', 'liter',
|
||||
};
|
||||
|
||||
List<({String value, String label})> _sortOptions(BuildContext context) => [
|
||||
(value: '', label: context.l10n.inventorySortLatest),
|
||||
(value: 'nameAsc', label: context.l10n.inventorySortNameAsc),
|
||||
@@ -20,6 +34,232 @@ class InventoryScreen extends ConsumerWidget {
|
||||
(value: 'l1CategoryAsc', label: 'L1-kategori (A-O)'),
|
||||
];
|
||||
|
||||
void _startSelection(int id) {
|
||||
setState(() {
|
||||
_selectedIds.add(id);
|
||||
});
|
||||
}
|
||||
|
||||
void _toggleSelection(int id) {
|
||||
setState(() {
|
||||
if (_selectedIds.contains(id)) {
|
||||
_selectedIds.remove(id);
|
||||
} else {
|
||||
_selectedIds.add(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
void _clearSelection() {
|
||||
setState(() {
|
||||
_selectedIds.clear();
|
||||
});
|
||||
}
|
||||
|
||||
void _selectAllVisible(List<dynamic> visibleItems) {
|
||||
setState(() {
|
||||
_selectedIds
|
||||
..clear()
|
||||
..addAll(visibleItems.map<int>((item) => item.id as int));
|
||||
});
|
||||
}
|
||||
|
||||
bool _isWeightOrVolumeUnit(String unit) {
|
||||
return _weightOrVolumeUnits.contains(unit.trim().toLowerCase());
|
||||
}
|
||||
|
||||
String _preferredUnit(List<String> units) {
|
||||
for (final unit in units) {
|
||||
if (_isWeightOrVolumeUnit(unit)) return unit;
|
||||
}
|
||||
return units.first;
|
||||
}
|
||||
|
||||
Future<String?> _askMergeTargetUnit(BuildContext context, List<String> units) async {
|
||||
if (units.isEmpty) return null;
|
||||
if (units.length == 1) return units.first;
|
||||
|
||||
var selected = _preferredUnit(units);
|
||||
|
||||
return showDialog<String>(
|
||||
context: context,
|
||||
builder: (dialogContext) => StatefulBuilder(
|
||||
builder: (dialogContext, setDialogState) => AlertDialog(
|
||||
title: const Text('Välj enhet för merge'),
|
||||
content: Column(
|
||||
mainAxisSize: MainAxisSize.min,
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
const Text(
|
||||
'Poster har olika enhet. Välj vilken enhet den sammanslagna posten ska använda.',
|
||||
),
|
||||
const SizedBox(height: 12),
|
||||
DropdownButtonFormField<String>(
|
||||
initialValue: selected,
|
||||
decoration: const InputDecoration(
|
||||
labelText: 'Enhet',
|
||||
border: OutlineInputBorder(),
|
||||
),
|
||||
items: units
|
||||
.map(
|
||||
(unit) => DropdownMenuItem<String>(
|
||||
value: unit,
|
||||
child: Text(unit),
|
||||
),
|
||||
)
|
||||
.toList(),
|
||||
onChanged: (value) {
|
||||
if (value == null) return;
|
||||
setDialogState(() => selected = value);
|
||||
},
|
||||
),
|
||||
],
|
||||
),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(context.l10n.cancelAction),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, selected),
|
||||
child: const Text('Merge'),
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _mergeSelected(BuildContext context, List<dynamic> allItems) async {
|
||||
final selectedItems = allItems
|
||||
.where((item) => _selectedIds.contains(item.id))
|
||||
.toList();
|
||||
|
||||
if (selectedItems.length < 2) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Välj minst två poster för merge.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final productIds = selectedItems.map((item) => item.productId).toSet();
|
||||
if (productIds.length > 1) {
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Valda poster måste ha samma produkt för merge.')),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
final units = <String>[];
|
||||
final seenUnits = <String>{};
|
||||
for (final item in selectedItems) {
|
||||
final unit = (item.unit as String).trim();
|
||||
final key = unit.toLowerCase();
|
||||
if (seenUnits.add(key)) {
|
||||
units.add(unit);
|
||||
}
|
||||
}
|
||||
|
||||
final targetUnit = await _askMergeTargetUnit(context, units);
|
||||
if (!context.mounted || targetUnit == null) return;
|
||||
|
||||
try {
|
||||
final token = await ref.read(authStateProvider.future);
|
||||
final ids = selectedItems.map<int>((item) => item.id as int).toList();
|
||||
await ref.read(inventoryRepositoryProvider).mergeInventoryItems(
|
||||
ids,
|
||||
targetUnit: units.length > 1 ? targetUnit : null,
|
||||
token: token,
|
||||
);
|
||||
ref.invalidate(inventoryProvider);
|
||||
if (!mounted) return;
|
||||
setState(() => _selectedIds.clear());
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
const SnackBar(content: Text('Poster sammanslagna.')),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
buildCopyableErrorSnackBar(context, mapErrorToUserMessage(e, context)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _deleteSelected(BuildContext context, List<dynamic> allItems) async {
|
||||
final ids = allItems
|
||||
.where((item) => _selectedIds.contains(item.id))
|
||||
.map<int>((item) => item.id as int)
|
||||
.toList();
|
||||
if (ids.isEmpty) return;
|
||||
|
||||
final confirmed = await showDialog<bool>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Ta bort markerade poster'),
|
||||
content: Text('Vill du verkligen ta bort ${ids.length} markerade poster?'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, false),
|
||||
child: Text(context.l10n.cancelAction),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, true),
|
||||
child: Text(context.l10n.deleteAction),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (confirmed != true || !context.mounted) return;
|
||||
|
||||
try {
|
||||
final token = await ref.read(authStateProvider.future);
|
||||
await ref.read(inventoryRepositoryProvider).bulkDeleteInventoryItems(ids, token: token);
|
||||
ref.invalidate(inventoryProvider);
|
||||
if (!mounted) return;
|
||||
setState(() => _selectedIds.clear());
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(content: Text('${ids.length} poster borttagna.')),
|
||||
);
|
||||
} catch (e) {
|
||||
if (!mounted) return;
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
buildCopyableErrorSnackBar(context, mapErrorToUserMessage(e, context)),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> _openBulkActions(BuildContext context, List<dynamic> allItems) async {
|
||||
if (_selectedIds.isEmpty) return;
|
||||
final action = await showDialog<String>(
|
||||
context: context,
|
||||
builder: (dialogContext) => AlertDialog(
|
||||
title: const Text('Hantera markerade poster'),
|
||||
content: Text('Du har markerat ${_selectedIds.length} poster. Välj åtgärd.'),
|
||||
actions: [
|
||||
TextButton(
|
||||
onPressed: () => Navigator.pop(dialogContext),
|
||||
child: Text(context.l10n.cancelAction),
|
||||
),
|
||||
OutlinedButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, 'delete'),
|
||||
child: Text(context.l10n.deleteAction),
|
||||
),
|
||||
FilledButton(
|
||||
onPressed: () => Navigator.pop(dialogContext, 'merge'),
|
||||
child: const Text('Merge'),
|
||||
),
|
||||
],
|
||||
),
|
||||
);
|
||||
|
||||
if (action == 'merge') {
|
||||
await _mergeSelected(context, allItems);
|
||||
} else if (action == 'delete') {
|
||||
await _deleteSelected(context, allItems);
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
final location = ref.watch(inventoryLocationFilterProvider);
|
||||
@@ -33,6 +273,17 @@ class InventoryScreen extends ConsumerWidget {
|
||||
onRetry: () => ref.invalidate(inventoryProvider),
|
||||
),
|
||||
data: (items) {
|
||||
final itemIds = items.map((item) => item.id).toSet();
|
||||
final staleIds = _selectedIds.where((id) => !itemIds.contains(id)).toList();
|
||||
if (staleIds.isNotEmpty) {
|
||||
WidgetsBinding.instance.addPostFrameCallback((_) {
|
||||
if (!mounted) return;
|
||||
setState(() {
|
||||
_selectedIds.removeWhere((id) => !itemIds.contains(id));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
final visibleItems = [...items];
|
||||
if (sort == 'l1CategoryAsc') {
|
||||
visibleItems.sort((a, b) {
|
||||
@@ -125,6 +376,48 @@ class InventoryScreen extends ConsumerWidget {
|
||||
),
|
||||
);
|
||||
|
||||
final selectedSection = _selectedIds.isEmpty
|
||||
? const SizedBox.shrink()
|
||||
: Padding(
|
||||
padding: const EdgeInsets.fromLTRB(12, 4, 12, 4),
|
||||
child: Card(
|
||||
child: Padding(
|
||||
padding: const EdgeInsets.all(12),
|
||||
child: Column(
|
||||
crossAxisAlignment: CrossAxisAlignment.start,
|
||||
children: [
|
||||
Text(
|
||||
'${_selectedIds.length} markerade poster',
|
||||
style: Theme.of(context).textTheme.titleSmall,
|
||||
),
|
||||
const SizedBox(height: 8),
|
||||
Wrap(
|
||||
spacing: 8,
|
||||
runSpacing: 8,
|
||||
children: [
|
||||
FilledButton.icon(
|
||||
onPressed: () => _openBulkActions(context, items),
|
||||
icon: const Icon(Icons.playlist_add_check),
|
||||
label: const Text('Hantera markerade'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: () => _selectAllVisible(visibleItems),
|
||||
icon: const Icon(Icons.select_all),
|
||||
label: const Text('Markera alla synliga'),
|
||||
),
|
||||
OutlinedButton.icon(
|
||||
onPressed: _clearSelection,
|
||||
icon: const Icon(Icons.deselect),
|
||||
label: const Text('Avmarkera'),
|
||||
),
|
||||
],
|
||||
),
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
if (visibleItems.isEmpty) {
|
||||
return Stack(
|
||||
children: [
|
||||
@@ -133,6 +426,7 @@ class InventoryScreen extends ConsumerWidget {
|
||||
padding: const EdgeInsets.only(bottom: 88),
|
||||
children: [
|
||||
headerSection,
|
||||
selectedSection,
|
||||
filterSection,
|
||||
EmptyStateView(title: context.l10n.inventoryEmpty),
|
||||
],
|
||||
@@ -155,13 +449,26 @@ class InventoryScreen extends ConsumerWidget {
|
||||
ListView.separated(
|
||||
key: const PageStorageKey<String>('inventory-main-list'),
|
||||
padding: const EdgeInsets.only(bottom: 88),
|
||||
itemCount: visibleItems.length + 2,
|
||||
itemCount: visibleItems.length + (_selectedIds.isEmpty ? 2 : 3),
|
||||
separatorBuilder: (_, __) => const Divider(height: 1),
|
||||
itemBuilder: (context, index) {
|
||||
if (index == 0) return filterSection;
|
||||
if (index == 1) return headerSection;
|
||||
final item = visibleItems[index - 2];
|
||||
return SwipeableInventoryTile(item: item);
|
||||
if (_selectedIds.isNotEmpty && index == 2) return selectedSection;
|
||||
final item = visibleItems[index - (_selectedIds.isEmpty ? 2 : 3)];
|
||||
return SwipeableInventoryTile(
|
||||
item: item,
|
||||
selectableMode: _selectedIds.isNotEmpty,
|
||||
selected: _selectedIds.contains(item.id),
|
||||
onToggleSelected: () => _toggleSelection(item.id),
|
||||
onLongPress: () {
|
||||
if (_selectedIds.isEmpty) {
|
||||
_startSelection(item.id);
|
||||
} else {
|
||||
_toggleSelection(item.id);
|
||||
}
|
||||
},
|
||||
);
|
||||
},
|
||||
),
|
||||
Positioned(
|
||||
|
||||
@@ -52,8 +52,19 @@ String _fmtStep(double step) =>
|
||||
/// know the gesture is available without any extra instruction.
|
||||
class SwipeableInventoryTile extends ConsumerStatefulWidget {
|
||||
final InventoryItem item;
|
||||
final bool selectableMode;
|
||||
final bool selected;
|
||||
final VoidCallback? onToggleSelected;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
const SwipeableInventoryTile({super.key, required this.item});
|
||||
const SwipeableInventoryTile({
|
||||
super.key,
|
||||
required this.item,
|
||||
this.selectableMode = false,
|
||||
this.selected = false,
|
||||
this.onToggleSelected,
|
||||
this.onLongPress,
|
||||
});
|
||||
|
||||
@override
|
||||
ConsumerState<SwipeableInventoryTile> createState() =>
|
||||
@@ -74,14 +85,14 @@ class _SwipeableInventoryTileState
|
||||
// ── Gesture handlers ────────────────────────────────────────────────────
|
||||
|
||||
void _onUpdate(DragUpdateDetails d) {
|
||||
if (_acting) return;
|
||||
if (_acting || widget.selectableMode) return;
|
||||
setState(() {
|
||||
_drag = (_drag + d.delta.dx).clamp(-_maxReveal, _maxReveal);
|
||||
});
|
||||
}
|
||||
|
||||
void _onEnd(DragEndDetails d) {
|
||||
if (_acting) return;
|
||||
if (_acting || widget.selectableMode) return;
|
||||
if (_drag > _threshold) {
|
||||
_adjust(1);
|
||||
} else if (_drag < -_threshold) {
|
||||
@@ -144,10 +155,28 @@ class _SwipeableInventoryTileState
|
||||
final stepLabel = _fmtStep(step);
|
||||
final unit = widget.item.unit;
|
||||
|
||||
final foreground = _ForegroundTile(
|
||||
item: widget.item,
|
||||
acting: _acting,
|
||||
selectableMode: widget.selectableMode,
|
||||
selected: widget.selected,
|
||||
onToggleSelected: widget.onToggleSelected,
|
||||
onLongPress: widget.onLongPress,
|
||||
);
|
||||
|
||||
if (widget.selectableMode) {
|
||||
return GestureDetector(
|
||||
onLongPress: widget.onLongPress,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: foreground,
|
||||
);
|
||||
}
|
||||
|
||||
return GestureDetector(
|
||||
onHorizontalDragUpdate: _onUpdate,
|
||||
onHorizontalDragEnd: _onEnd,
|
||||
onHorizontalDragCancel: _snapBack,
|
||||
onLongPress: widget.onLongPress,
|
||||
behavior: HitTestBehavior.opaque,
|
||||
child: ClipRect(
|
||||
child: Stack(
|
||||
@@ -226,7 +255,7 @@ class _SwipeableInventoryTileState
|
||||
// ── Foreground tile ─────────────────────────────────────────
|
||||
Transform.translate(
|
||||
offset: Offset(_drag, 0),
|
||||
child: _ForegroundTile(item: widget.item, acting: _acting),
|
||||
child: foreground,
|
||||
),
|
||||
],
|
||||
),
|
||||
@@ -240,8 +269,19 @@ class _SwipeableInventoryTileState
|
||||
class _ForegroundTile extends ConsumerWidget {
|
||||
final InventoryItem item;
|
||||
final bool acting;
|
||||
final bool selectableMode;
|
||||
final bool selected;
|
||||
final VoidCallback? onToggleSelected;
|
||||
final VoidCallback? onLongPress;
|
||||
|
||||
const _ForegroundTile({required this.item, required this.acting});
|
||||
const _ForegroundTile({
|
||||
required this.item,
|
||||
required this.acting,
|
||||
this.selectableMode = false,
|
||||
this.selected = false,
|
||||
this.onToggleSelected,
|
||||
this.onLongPress,
|
||||
});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context, WidgetRef ref) {
|
||||
@@ -258,16 +298,24 @@ class _ForegroundTile extends ConsumerWidget {
|
||||
// Opaque background so the tile sits on top of the reveal panels.
|
||||
color: theme.colorScheme.surface,
|
||||
child: ListTile(
|
||||
title: Text(item.productName),
|
||||
leading: selectableMode
|
||||
? Checkbox(
|
||||
value: selected,
|
||||
onChanged: (_) => onToggleSelected?.call(),
|
||||
)
|
||||
: null,
|
||||
title: Text(item.displayName),
|
||||
// Subtitle: small swipe-hint icon + text on the same row.
|
||||
subtitle: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.swap_horiz,
|
||||
size: 13,
|
||||
color: theme.colorScheme.outline,
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
if (!selectableMode) ...[
|
||||
Icon(
|
||||
Icons.swap_horiz,
|
||||
size: 13,
|
||||
color: theme.colorScheme.outline,
|
||||
),
|
||||
const SizedBox(width: 3),
|
||||
],
|
||||
Expanded(
|
||||
child: Text(
|
||||
subtitleText,
|
||||
@@ -282,8 +330,11 @@ class _ForegroundTile extends ConsumerWidget {
|
||||
height: 24,
|
||||
child: CircularProgressIndicator(strokeWidth: 2),
|
||||
)
|
||||
: _TrailingActions(item: item),
|
||||
onTap: () => context.push('/inventory/${item.id}'),
|
||||
: (selectableMode ? null : _TrailingActions(item: item)),
|
||||
onTap: selectableMode
|
||||
? onToggleSelected
|
||||
: () => context.push('/inventory/${item.id}'),
|
||||
onLongPress: onLongPress,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user