Files
kooltab/lib/views/product_form_view.dart
T

496 lines
16 KiB
Dart

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:go_router/go_router.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path/path.dart' as path;
import 'package:path_provider/path_provider.dart';
import 'package:provider/provider.dart';
import 'package:sentry_flutter/sentry_flutter.dart';
import '../models/product.dart';
import '../viewmodels/product_list_view_model.dart';
import '../l10n/app_localizations.dart';
import '../l10n/app_localizations_helpers.dart';
class ProductFormView extends StatefulWidget {
final String? productId;
const ProductFormView({super.key, this.productId});
bool get isEditing => productId != null;
@override
State<ProductFormView> createState() => _ProductFormViewState();
}
class _ProductFormViewState extends State<ProductFormView> {
final _formKey = GlobalKey<FormState>();
final _nameController = TextEditingController();
final _priceController = TextEditingController();
final _stockController = TextEditingController();
final _lowStockController = TextEditingController();
String? _selectedCategory;
final _categoryController = TextEditingController();
final _imagePicker = ImagePicker();
Product? _existingProduct;
String? _imagePath;
bool _hasImage = false;
bool _isLoading = true;
bool _isSaving = false;
@override
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_loadProductIfNeeded();
});
}
Future<void> _loadProductIfNeeded() async {
final l10n = AppLocalizations.of(context);
if (!widget.isEditing) {
setState(() => _isLoading = false);
return;
}
try {
final viewModel = context.read<ProductListViewModel>();
final product = await viewModel.getProductById(widget.productId!);
if (!mounted) return;
if (product == null) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.productNotFound)));
context.go('/products');
return;
}
_existingProduct = product;
_nameController.text = product.name;
_selectedCategory = product.category;
_priceController.text = (product.priceInCents / 100).toStringAsFixed(2);
_stockController.text = product.stockQuantity.toString();
_lowStockController.text = product.lowStockThreshold.toString();
_imagePath = product.imagePath;
_hasImage = product.imagePath != null && product.imagePath!.isNotEmpty;
setState(() => _isLoading = false);
} catch (e, stack) {
Sentry.captureException(e, stackTrace: stack);
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.couldNotLoadProduct)));
context.go('/products');
}
}
@override
void dispose() {
_nameController.dispose();
_priceController.dispose();
_stockController.dispose();
_lowStockController.dispose();
super.dispose();
}
Future<String> _copyImageToAppFolder(XFile pickedFile) async {
final appDirectory = await getApplicationSupportDirectory();
final imagesDirectory = Directory(
path.join(appDirectory.path, 'product_images'),
);
if (!await imagesDirectory.exists()) {
await imagesDirectory.create(recursive: true);
}
final extension = path.extension(pickedFile.path);
final fileName =
'product_${DateTime.now().millisecondsSinceEpoch}$extension';
final newPath = path.join(imagesDirectory.path, fileName);
final copiedFile = await File(pickedFile.path).copy(newPath);
return copiedFile.path;
}
Future<void> _pickImage() async {
final pickedFile = await _imagePicker.pickImage(
source: ImageSource.gallery,
imageQuality: 80,
maxWidth: 1000,
maxHeight: 1000,
);
if (pickedFile == null) return;
final copiedImagePath = await _copyImageToAppFolder(pickedFile);
if (!mounted) return;
setState(() {
_imagePath = copiedImagePath;
_hasImage = true;
});
}
int _parsePriceToCents(String value) {
final normalized = value.replaceAll(',', '.');
final euros = double.tryParse(normalized) ?? 0;
return (euros * 100).round();
}
Future<void> _save() async {
final l10n = AppLocalizations.of(context);
if (!_formKey.currentState!.validate()) return;
if (_imagePath == null || _imagePath!.isEmpty) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.chooseImage)));
return;
}
if (_selectedCategory == null) {
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.selectCategory)));
return;
}
setState(() => _isSaving = true);
final viewModel = context.read<ProductListViewModel>();
final name = _nameController.text.trim();
final category = _selectedCategory!;
final priceInCents = _parsePriceToCents(_priceController.text);
final stockQuantity = int.tryParse(_stockController.text) ?? 0;
final lowStockThreshold = int.tryParse(_lowStockController.text) ?? 0;
try {
if (widget.isEditing) {
final updatedProduct = _existingProduct!.copyWith(
name: name,
category: category,
priceInCents: priceInCents,
stockQuantity: stockQuantity,
lowStockThreshold: lowStockThreshold,
imagePath: _imagePath,
);
await viewModel.updateProduct(updatedProduct);
} else {
await viewModel.addProduct(
name: name,
category: category,
priceInCents: priceInCents,
stockQuantity: stockQuantity,
lowStockThreshold: lowStockThreshold,
imagePath: _imagePath,
);
}
} catch (e, stack) {
Sentry.captureException(e, stackTrace: stack);
if (!mounted) return;
setState(() => _isSaving = false);
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.couldNotSaveProduct)));
return;
}
if (!mounted) return;
setState(() => _isSaving = false);
context.go('/products');
}
Future<void> _delete() async {
if (!widget.isEditing) return;
final l10n = AppLocalizations.of(context);
final confirmed = await showDialog<bool>(
context: context,
builder: (dialogContext) {
return AlertDialog(
title: Text(l10n.deleteProduct),
content: Text(l10n.deleteProductDescription),
actions: [
TextButton(
onPressed: () => Navigator.of(dialogContext).pop(false),
child: Text(l10n.cancel),
),
FilledButton(
onPressed: () => Navigator.of(dialogContext).pop(true),
child: Text(l10n.delete),
),
],
);
},
);
if (confirmed != true) return;
final viewModel = context.read<ProductListViewModel>();
try {
await viewModel.deleteProduct(widget.productId!);
} catch (e, stack) {
Sentry.captureException(e, stackTrace: stack);
if (!mounted) return;
ScaffoldMessenger.of(
context,
).showSnackBar(SnackBar(content: Text(l10n.couldNotDeleteProduct)));
return;
}
if (!mounted) return;
context.go('/products');
}
Widget _buildImagePicker(BuildContext context) {
final l10n = AppLocalizations.of(context);
return InkWell(
onTap: _pickImage,
borderRadius: BorderRadius.circular(12),
child: Container(
height: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(12),
border: Border.all(color: Theme.of(context).colorScheme.outline),
),
clipBehavior: Clip.antiAlias,
child: _hasImage
? Stack(
fit: StackFit.expand,
children: [
Image.file(
File(_imagePath!),
fit: BoxFit.fitHeight,
cacheWidth: 1000,
errorBuilder: (context, error, stackTrace) => Center(
child: Icon(
Icons.broken_image_outlined,
size: 48,
color: Theme.of(context).colorScheme.outline,
),
),
),
Positioned(
right: 12,
bottom: 12,
child: FilledButton.icon(
onPressed: _pickImage,
icon: const Icon(Icons.image),
label: Text(l10n.changeImage),
),
),
],
)
: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(Icons.add_photo_alternate_outlined, size: 48),
const SizedBox(height: 12),
Text(
l10n.chooseProductImage,
style: Theme.of(context).textTheme.titleMedium,
),
],
),
),
),
);
}
@override
Widget build(BuildContext context) {
final l10n = AppLocalizations.of(context);
final title = widget.isEditing ? l10n.editProduct : l10n.addProduct;
return Scaffold(
appBar: AppBar(
title: Text(title),
leading: IconButton(
icon: const Icon(Icons.arrow_back),
onPressed: () => context.go('/products'),
),
actions: [
if (widget.isEditing)
IconButton(
onPressed: _delete,
icon: const Icon(Icons.delete_outline),
),
],
),
resizeToAvoidBottomInset: true,
body: _isLoading
? const Center(child: CircularProgressIndicator())
: Center(
child: ConstrainedBox(
constraints: const BoxConstraints(maxWidth: 720),
child: Form(
key: _formKey,
child: ListView(
keyboardDismissBehavior:
ScrollViewKeyboardDismissBehavior.onDrag,
padding: const EdgeInsets.all(24),
children: [
_buildImagePicker(context),
const SizedBox(height: 24),
TextFormField(
controller: _nameController,
decoration: InputDecoration(
labelText: l10n.productName,
border: OutlineInputBorder(),
),
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return l10n.enterProductName;
}
return null;
},
),
const SizedBox(height: 16),
Consumer<ProductListViewModel>(
builder: (context, viewModel, child) {
return LayoutBuilder(
builder: (context, constraints) {
return DropdownMenu<String>(
width: constraints.maxWidth,
initialSelection: _selectedCategory,
enableFilter: true,
enableSearch: true,
controller: _categoryController,
requestFocusOnTap: true,
label: Text(l10n.category),
hintText: l10n.selectCategory,
dropdownMenuEntries: viewModel.categories
.map(
(category) => DropdownMenuEntry<String>(
value: category,
label: l10n.categoryLabel(category),
),
)
.toList(),
onSelected: (value) {
setState(() {
_selectedCategory = value;
});
FocusScope.of(context).nextFocus();
},
);
},
);
},
),
const SizedBox(height: 16),
TextFormField(
controller: _priceController,
decoration: InputDecoration(
labelText: l10n.price,
prefixText: '€ ',
border: OutlineInputBorder(),
),
keyboardType: const TextInputType.numberWithOptions(
decimal: true,
),
textInputAction: TextInputAction.next,
validator: (value) {
if (value == null || value.trim().isEmpty) {
return l10n.enterPrice;
}
final normalized = value.replaceAll(',', '.');
final price = double.tryParse(normalized);
if (price == null || price < 0) {
return l10n.enterValidPrice;
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _stockController,
decoration: InputDecoration(
labelText: l10n.stock,
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.next,
validator: (value) {
final number = int.tryParse(value ?? '');
if (number == null || number < 0) {
return l10n.enterValidStock;
}
return null;
},
),
const SizedBox(height: 16),
TextFormField(
controller: _lowStockController,
decoration: InputDecoration(
labelText: l10n.lowStockThreshold,
border: OutlineInputBorder(),
),
keyboardType: TextInputType.number,
textInputAction: TextInputAction.done,
onFieldSubmitted: (_) {
FocusScope.of(context).unfocus();
},
validator: (value) {
final number = int.tryParse(value ?? '');
if (number == null || number < 0) {
return l10n.enterValidThreshold;
}
return null;
},
),
const SizedBox(height: 24),
FilledButton.icon(
onPressed: _isSaving ? null : _save,
icon: _isSaving
? const SizedBox(
width: 18,
height: 18,
child: CircularProgressIndicator(
strokeWidth: 2,
),
)
: const Icon(Icons.save),
label: Text(
widget.isEditing ? l10n.confirm : l10n.addProduct,
),
),
],
),
),
),
),
);
}
}