diff --git a/lib/models/post_item.dart b/lib/models/post_item.dart index 64c8c73..46b1b3f 100644 --- a/lib/models/post_item.dart +++ b/lib/models/post_item.dart @@ -236,4 +236,37 @@ class PostItem { isAussendung: true, ); } + + /// Create a copy of this PostItem with updated fields + PostItem copyWith({ + String? id, + String? title, + String? description, + String? imageUrl, + List? imageUrls, + DateTime? createdDate, + String? authorUid, + String? street, + String? category, + String? status, + String? pdfUrl, + String? webUrl, + bool? isAussendung, + }) { + return PostItem( + id: id ?? this.id, + title: title ?? this.title, + description: description ?? this.description, + imageUrl: imageUrl ?? this.imageUrl, + imageUrls: imageUrls ?? this.imageUrls, + createdDate: createdDate ?? this.createdDate, + authorUid: authorUid ?? this.authorUid, + street: street ?? this.street, + category: category ?? this.category, + status: status ?? this.status, + pdfUrl: pdfUrl ?? this.pdfUrl, + webUrl: webUrl ?? this.webUrl, + isAussendung: isAussendung ?? this.isAussendung, + ); + } } diff --git a/lib/screens/add_issue_screen.dart b/lib/screens/add_issue_screen.dart index 30233ec..f25c741 100644 --- a/lib/screens/add_issue_screen.dart +++ b/lib/screens/add_issue_screen.dart @@ -1,13 +1,18 @@ import 'dart:io'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; +import 'package:provider/provider.dart'; import '../models/post_item.dart'; +import '../services/auth_service.dart'; import '../services/firestore_service.dart'; import '../services/storage_service.dart'; class AddIssueScreen extends StatefulWidget { - const AddIssueScreen({super.key}); + final PostItem? issueToEdit; + + const AddIssueScreen({super.key, this.issueToEdit}); @override State createState() => _AddIssueScreenState(); @@ -22,8 +27,18 @@ class _AddIssueScreenState extends State { final StorageService _storageService = StorageService(); final List _selectedImages = []; + List _existingImageUrls = []; + String _selectedStatus = 'Gemeldet'; bool _isSaving = false; + bool get isEditing => widget.issueToEdit != null; + + final List _statuses = [ + 'Gemeldet', + 'In Bearbeitung', + 'Erledigt', + ]; + final List _streets = [ 'Hauptstraße', 'Seestraße', @@ -56,8 +71,31 @@ class _AddIssueScreenState extends State { @override void initState() { super.initState(); - _selectedStreet = _streets.first; - _selectedCategory = _categories.first; + if (widget.issueToEdit != null) { + final issue = widget.issueToEdit!; + _titleController.text = issue.title; + _descriptionController.text = issue.description; + if (issue.street != null && _streets.contains(issue.street)) { + _selectedStreet = issue.street; + } else { + _selectedStreet = _streets.first; + } + if (issue.category != null && _categories.contains(issue.category)) { + _selectedCategory = issue.category; + } else { + _selectedCategory = _categories.first; + } + _existingImageUrls = List.from(issue.imageUrls); + if (_existingImageUrls.isEmpty && issue.imageUrl.isNotEmpty) { + _existingImageUrls.add(issue.imageUrl); + } + if (issue.status != null && _statuses.contains(issue.status)) { + _selectedStatus = issue.status!; + } + } else { + _selectedStreet = _streets.first; + _selectedCategory = _categories.first; + } } @override @@ -68,9 +106,10 @@ class _AddIssueScreenState extends State { } Future _pickImage(ImageSource source) async { - if (_selectedImages.length >= 2) { + if (_existingImageUrls.length + _selectedImages.length >= 2) { ScaffoldMessenger.of(context).showSnackBar( - const SnackBar(content: Text('Es können maximal 2 Fotos hinzugefügt werden.')), + const SnackBar( + content: Text('Es können maximal 2 Fotos hinzugefügt werden.')), ); return; } @@ -136,43 +175,89 @@ class _AddIssueScreenState extends State { }); try { - final currentUserId = FirebaseAuth.instance.currentUser?.uid; + if (isEditing) { + // Delete removed old images from Storage + for (final oldUrl in widget.issueToEdit!.imageUrls) { + if (!_existingImageUrls.contains(oldUrl)) { + try { + await _storageService.deleteFileByUrl(oldUrl); + } catch (_) {} + } + } - // Upload selected images to Firebase Storage - final List uploadedUrls = []; - for (final file in _selectedImages) { - final url = await _storageService.uploadFile( - file: file, - collectionName: 'Issues', - optimize: true, + // Upload newly selected images to Storage + final List newlyUploadedUrls = []; + for (final file in _selectedImages) { + final url = await _storageService.uploadFile( + file: file, + collectionName: 'Issues', + optimize: true, + ); + newlyUploadedUrls.add(url); + } + + final allImages = [..._existingImageUrls, ...newlyUploadedUrls]; + + final updatedIssue = widget.issueToEdit!.copyWith( + title: _titleController.text.trim(), + description: _descriptionController.text.trim(), + imageUrl: allImages.isNotEmpty ? allImages.first : '', + imageUrls: allImages, + street: _selectedStreet, + category: _selectedCategory, + status: _selectedStatus, ); - uploadedUrls.add(url); + + await _firestoreService.updatePost('Issues', updatedIssue); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Mangel erfolgreich aktualisiert!'), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context, updatedIssue); + } else { + final currentUserId = FirebaseAuth.instance.currentUser?.uid; + + // Upload selected images to Firebase Storage + final List uploadedUrls = []; + for (final file in _selectedImages) { + final url = await _storageService.uploadFile( + file: file, + collectionName: 'Issues', + optimize: true, + ); + uploadedUrls.add(url); + } + + final newIssue = PostItem( + id: '', + title: _titleController.text.trim(), + description: _descriptionController.text.trim(), + imageUrl: uploadedUrls.isNotEmpty ? uploadedUrls.first : '', + imageUrls: uploadedUrls, + createdDate: DateTime.now(), + authorUid: currentUserId, + street: _selectedStreet, + category: _selectedCategory, + status: 'Gemeldet', + ); + + await _firestoreService.addPost('Issues', newIssue); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Mangel wurde erfolgreich gemeldet!'), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context, newIssue); } - - final newIssue = PostItem( - id: '', - title: _titleController.text.trim(), - description: _descriptionController.text.trim(), - imageUrl: uploadedUrls.isNotEmpty ? uploadedUrls.first : '', - imageUrls: uploadedUrls, - createdDate: DateTime.now(), - authorUid: currentUserId, - street: _selectedStreet, - category: _selectedCategory, - status: 'Gemeldet', - ); - - await _firestoreService.addPost('Issues', newIssue); - - if (!mounted) return; - - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Mangel wurde erfolgreich gemeldet!'), - backgroundColor: Colors.green, - ), - ); - Navigator.pop(context); } catch (e) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( @@ -192,9 +277,13 @@ class _AddIssueScreenState extends State { @override Widget build(BuildContext context) { + final auth = Provider.of(context, listen: false); + final isAdmin = auth.isAdmin; + final totalPhotos = _existingImageUrls.length + _selectedImages.length; + return Scaffold( appBar: AppBar( - title: const Text('Mangel melden'), + title: Text(isEditing ? 'Mangel bearbeiten' : 'Mangel melden'), ), body: SingleChildScrollView( padding: EdgeInsets.only( @@ -251,6 +340,26 @@ class _AddIssueScreenState extends State { .toList(), onChanged: (val) => setState(() => _selectedCategory = val), ), + if (isAdmin && isEditing) ...[ + const SizedBox(height: 16), + DropdownButtonFormField( + initialValue: _selectedStatus, + decoration: const InputDecoration( + labelText: 'Bearbeitungsstatus (Admin) *', + prefixIcon: Icon(Icons.assignment_turned_in_outlined), + border: OutlineInputBorder(), + ), + items: _statuses + .map((status) => DropdownMenuItem( + value: status, + child: Text(status), + )) + .toList(), + onChanged: (val) { + if (val != null) setState(() => _selectedStatus = val); + }, + ), + ], const SizedBox(height: 16), TextFormField( controller: _descriptionController, @@ -271,67 +380,127 @@ class _AddIssueScreenState extends State { style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14), ), const SizedBox(height: 8), - Row( - children: [ - ..._selectedImages.asMap().entries.map((entry) { - final index = entry.key; - final file = entry.value; - return Stack( - children: [ - Container( - margin: const EdgeInsets.only(right: 12), + SingleChildScrollView( + scrollDirection: Axis.horizontal, + child: Row( + children: [ + // Existing images from Firebase Storage + ..._existingImageUrls.asMap().entries.map((entry) { + final index = entry.key; + final url = entry.value; + return Stack( + children: [ + Container( + margin: const EdgeInsets.only(right: 12), + width: 110, + height: 80, + decoration: BoxDecoration( + border: Border.all(color: Colors.grey.shade400), + borderRadius: BorderRadius.circular(8), + ), + clipBehavior: Clip.antiAlias, + child: CachedNetworkImage( + imageUrl: url, + fit: BoxFit.cover, + placeholder: (ctx, u) => const Center( + child: CircularProgressIndicator(), + ), + errorWidget: (ctx, u, e) => Container( + color: Colors.grey.shade200, + child: const Icon(Icons.broken_image, size: 28), + ), + ), + ), + Positioned( + top: -4, + right: 4, + child: CircleAvatar( + radius: 14, + backgroundColor: Colors.black54, + child: IconButton( + padding: EdgeInsets.zero, + icon: const Icon(Icons.close, + color: Colors.white, size: 16), + tooltip: 'Foto entfernen', + onPressed: () { + setState(() { + _existingImageUrls.removeAt(index); + }); + }, + ), + ), + ), + ], + ); + }), + // Newly picked local image files + ..._selectedImages.asMap().entries.map((entry) { + final index = entry.key; + final file = entry.value; + return Stack( + children: [ + Container( + margin: const EdgeInsets.only(right: 12), + width: 110, + height: 80, + decoration: BoxDecoration( + border: Border.all(color: Colors.grey.shade400), + borderRadius: BorderRadius.circular(8), + image: DecorationImage( + image: FileImage(file), + fit: BoxFit.cover, + ), + ), + ), + Positioned( + top: -4, + right: 4, + child: CircleAvatar( + radius: 14, + backgroundColor: Colors.black54, + child: IconButton( + padding: EdgeInsets.zero, + icon: const Icon(Icons.close, + color: Colors.white, size: 16), + tooltip: 'Foto entfernen', + onPressed: () { + setState(() { + _selectedImages.removeAt(index); + }); + }, + ), + ), + ), + ], + ); + }), + if (totalPhotos < 2) + InkWell( + onTap: _showImageSourceModal, + child: Container( width: 110, height: 80, decoration: BoxDecoration( - border: Border.all(color: Colors.grey.shade400), + color: Colors.grey.shade200, borderRadius: BorderRadius.circular(8), - image: DecorationImage( - image: FileImage(file), - fit: BoxFit.cover, - ), + border: Border.all( + color: Colors.grey.shade400, + style: BorderStyle.solid), ), - ), - Positioned( - top: -4, - right: 4, - child: IconButton( - icon: const Icon(Icons.cancel, color: Colors.red), - onPressed: () { - setState(() { - _selectedImages.removeAt(index); - }); - }, + child: const Column( + mainAxisAlignment: MainAxisAlignment.center, + children: [ + Icon(Icons.add_a_photo, color: Colors.grey), + SizedBox(height: 4), + Text('Foto hinzufügen', + style: TextStyle( + fontSize: 11, color: Colors.black54)), + ], ), ), - ], - ); - }), - if (_selectedImages.length < 2) - InkWell( - onTap: _showImageSourceModal, - child: Container( - width: 110, - height: 80, - decoration: BoxDecoration( - color: Colors.grey.shade200, - borderRadius: BorderRadius.circular(8), - border: Border.all( - color: Colors.grey.shade400, - style: BorderStyle.solid), - ), - child: const Column( - mainAxisAlignment: MainAxisAlignment.center, - children: [ - Icon(Icons.add_a_photo, color: Colors.grey), - SizedBox(height: 4), - Text('Foto hinzufügen', - style: TextStyle( - fontSize: 11, color: Colors.black54)), - ], - ), ), - ), - ], + ], + ), ), const SizedBox(height: 32), SizedBox( @@ -346,9 +515,13 @@ class _AddIssueScreenState extends State { child: CircularProgressIndicator( strokeWidth: 2, color: Colors.white), ) - : const Icon(Icons.check_circle_outline), + : Icon(isEditing ? Icons.save : Icons.check_circle_outline), label: Text( - _isSaving ? 'Wird gespeichert...' : 'Mangel fertigstellen', + _isSaving + ? 'Wird gespeichert...' + : (isEditing + ? 'Änderungen speichern' + : 'Mangel fertigstellen'), style: const TextStyle(fontSize: 16), ), ), diff --git a/lib/screens/add_post_screen.dart b/lib/screens/add_post_screen.dart index 3c80fe1..b4a286c 100644 --- a/lib/screens/add_post_screen.dart +++ b/lib/screens/add_post_screen.dart @@ -1,4 +1,5 @@ import 'dart:io'; +import 'package:cached_network_image/cached_network_image.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:image_picker/image_picker.dart'; @@ -9,11 +10,13 @@ import '../services/storage_service.dart'; class AddPostScreen extends StatefulWidget { final String collectionName; final String screenTitle; + final PostItem? postToEdit; const AddPostScreen({ super.key, required this.collectionName, required this.screenTitle, + this.postToEdit, }); @override @@ -29,8 +32,25 @@ class _AddPostScreenState extends State { final StorageService _storageService = StorageService(); File? _selectedImage; + String? _existingImageUrl; bool _isSaving = false; + bool get isEditing => widget.postToEdit != null; + + @override + void initState() { + super.initState(); + if (widget.postToEdit != null) { + _titleController.text = widget.postToEdit!.title; + _descriptionController.text = widget.postToEdit!.description; + if (widget.postToEdit!.imageUrls.isNotEmpty) { + _existingImageUrl = widget.postToEdit!.imageUrls.first; + } else if (widget.postToEdit!.imageUrl.isNotEmpty) { + _existingImageUrl = widget.postToEdit!.imageUrl; + } + } + } + @override void dispose() { _titleController.dispose(); @@ -100,38 +120,85 @@ class _AddPostScreenState extends State { }); try { - final currentUserId = FirebaseAuth.instance.currentUser?.uid; - String imageUrl = ''; + if (isEditing) { + String imageUrl = _existingImageUrl ?? ''; - if (_selectedImage != null) { - imageUrl = await _storageService.uploadFile( - file: _selectedImage!, - collectionName: widget.collectionName, - optimize: true, + if (_selectedImage != null) { + // If a new image was chosen, remove the old one from storage if it existed + if (widget.postToEdit!.imageUrls.isNotEmpty) { + for (final oldUrl in widget.postToEdit!.imageUrls) { + try { + await _storageService.deleteFileByUrl(oldUrl); + } catch (_) {} + } + } + imageUrl = await _storageService.uploadFile( + file: _selectedImage!, + collectionName: widget.collectionName, + optimize: true, + ); + } else if (_existingImageUrl == null && + widget.postToEdit!.imageUrls.isNotEmpty) { + // Existing image was deleted by the user + for (final oldUrl in widget.postToEdit!.imageUrls) { + try { + await _storageService.deleteFileByUrl(oldUrl); + } catch (_) {} + } + } + + final updatedPost = widget.postToEdit!.copyWith( + title: _titleController.text.trim(), + description: _descriptionController.text.trim(), + imageUrl: imageUrl, + imageUrls: imageUrl.isNotEmpty ? [imageUrl] : [], ); + + await _firestoreService.updatePost(widget.collectionName, updatedPost); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Eintrag erfolgreich aktualisiert!'), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context, updatedPost); + } else { + final currentUserId = FirebaseAuth.instance.currentUser?.uid; + String imageUrl = ''; + + if (_selectedImage != null) { + imageUrl = await _storageService.uploadFile( + file: _selectedImage!, + collectionName: widget.collectionName, + optimize: true, + ); + } + + final newPost = PostItem( + id: '', + title: _titleController.text.trim(), + description: _descriptionController.text.trim(), + imageUrl: imageUrl, + imageUrls: imageUrl.isNotEmpty ? [imageUrl] : [], + createdDate: DateTime.now(), + authorUid: currentUserId, + ); + + await _firestoreService.addPost(widget.collectionName, newPost); + + if (!mounted) return; + + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar( + content: Text('Eintrag erfolgreich veröffentlicht!'), + backgroundColor: Colors.green, + ), + ); + Navigator.pop(context, newPost); } - - final newPost = PostItem( - id: '', - title: _titleController.text.trim(), - description: _descriptionController.text.trim(), - imageUrl: imageUrl, - imageUrls: imageUrl.isNotEmpty ? [imageUrl] : [], - createdDate: DateTime.now(), - authorUid: currentUserId, - ); - - await _firestoreService.addPost(widget.collectionName, newPost); - - if (!mounted) return; - - ScaffoldMessenger.of(context).showSnackBar( - const SnackBar( - content: Text('Eintrag erfolgreich veröffentlicht!'), - backgroundColor: Colors.green, - ), - ); - Navigator.pop(context); } catch (e) { if (!mounted) return; ScaffoldMessenger.of(context).showSnackBar( @@ -153,7 +220,7 @@ class _AddPostScreenState extends State { Widget build(BuildContext context) { return Scaffold( appBar: AppBar( - title: Text(widget.screenTitle), + title: Text(isEditing ? 'Beitrag bearbeiten' : widget.screenTitle), ), body: SingleChildScrollView( padding: EdgeInsets.only( @@ -218,12 +285,68 @@ class _AddPostScreenState extends State { backgroundColor: Colors.black54, child: IconButton( icon: const Icon(Icons.close, color: Colors.white), - onPressed: () => setState(() => _selectedImage = null), + onPressed: () => + setState(() => _selectedImage = null), ), ), ), ], ) + else if (_existingImageUrl != null && + _existingImageUrl!.isNotEmpty) + Stack( + children: [ + Container( + height: 180, + width: double.infinity, + decoration: BoxDecoration( + borderRadius: BorderRadius.circular(10), + border: Border.all(color: Colors.grey.shade400), + ), + clipBehavior: Clip.antiAlias, + child: CachedNetworkImage( + imageUrl: _existingImageUrl!, + fit: BoxFit.cover, + placeholder: (ctx, url) => const Center( + child: CircularProgressIndicator(), + ), + errorWidget: (ctx, url, err) => Container( + color: Colors.grey.shade200, + child: const Icon(Icons.broken_image, size: 40), + ), + ), + ), + Positioned( + top: 8, + right: 8, + child: CircleAvatar( + backgroundColor: Colors.black54, + child: IconButton( + icon: const Icon(Icons.close, color: Colors.white), + tooltip: 'Bild entfernen', + onPressed: () => + setState(() => _existingImageUrl = null), + ), + ), + ), + Positioned( + bottom: 8, + right: 8, + child: ElevatedButton.icon( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.black54, + foregroundColor: Colors.white, + padding: const EdgeInsets.symmetric( + horizontal: 10, vertical: 6), + ), + onPressed: _showImageSourceModal, + icon: const Icon(Icons.camera_alt, size: 16), + label: const Text('Ersetzen', + style: TextStyle(fontSize: 12)), + ), + ), + ], + ) else InkWell( onTap: _showImageSourceModal, @@ -238,9 +361,11 @@ class _AddPostScreenState extends State { child: const Column( mainAxisAlignment: MainAxisAlignment.center, children: [ - Icon(Icons.add_photo_alternate, size: 36, color: Colors.grey), + Icon(Icons.add_photo_alternate, + size: 36, color: Colors.grey), SizedBox(height: 6), - Text('Foto hinzufügen', style: TextStyle(color: Colors.black54)), + Text('Foto hinzufügen', + style: TextStyle(color: Colors.black54)), ], ), ), @@ -258,9 +383,13 @@ class _AddPostScreenState extends State { child: CircularProgressIndicator( strokeWidth: 2, color: Colors.white), ) - : const Icon(Icons.send), + : Icon(isEditing ? Icons.save : Icons.send), label: Text( - _isSaving ? 'Wird gespeichert...' : 'Veröffentlichen', + _isSaving + ? 'Wird gespeichert...' + : (isEditing + ? 'Änderungen speichern' + : 'Veröffentlichen'), style: const TextStyle(fontSize: 16), ), ), diff --git a/lib/screens/detail_screen.dart b/lib/screens/detail_screen.dart index fb886b8..aef4498 100644 --- a/lib/screens/detail_screen.dart +++ b/lib/screens/detail_screen.dart @@ -1,28 +1,147 @@ import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; +import 'package:provider/provider.dart'; import '../models/post_item.dart'; +import '../services/auth_service.dart'; +import '../services/firestore_service.dart'; import '../services/pdf_service.dart'; +import '../services/storage_service.dart'; +import 'add_issue_screen.dart'; +import 'add_post_screen.dart'; import 'pdf_viewer_screen.dart'; -class DetailScreen extends StatelessWidget { +class DetailScreen extends StatefulWidget { final PostItem item; + final String? collectionName; - const DetailScreen({super.key, required this.item}); + const DetailScreen({ + super.key, + required this.item, + this.collectionName, + }); + + @override + State createState() => _DetailScreenState(); +} + +class _DetailScreenState extends State { + late PostItem _item; + + @override + void initState() { + super.initState(); + _item = widget.item; + } + + Future _editItem() async { + final collection = widget.collectionName ?? + (_item.street != null ? 'Issues' : 'CitizensForum'); + PostItem? updated; + if (collection == 'Issues' || _item.street != null) { + updated = await Navigator.push( + context, + MaterialPageRoute( + builder: (ctx) => AddIssueScreen(issueToEdit: _item), + ), + ); + } else { + updated = await Navigator.push( + context, + MaterialPageRoute( + builder: (ctx) => AddPostScreen( + collectionName: collection, + screenTitle: 'Beitrag bearbeiten', + postToEdit: _item, + ), + ), + ); + } + if (updated != null && mounted) { + setState(() { + _item = updated!; + }); + } + } + + Future _deleteItem() async { + final confirmed = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: const Text('Eintrag löschen?'), + content: const Text( + 'Möchten Sie diesen Eintrag wirklich unwiderruflich löschen?'), + actions: [ + TextButton( + onPressed: () => Navigator.pop(dialogCtx, false), + child: const Text('Abbrechen'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom(backgroundColor: Colors.red), + onPressed: () => Navigator.pop(dialogCtx, true), + child: const Text('Löschen'), + ), + ], + ), + ); + + if (confirmed != true || !mounted) return; + + final collection = widget.collectionName ?? + (_item.street != null ? 'Issues' : 'News'); + try { + final storage = StorageService(); + final firestore = FirestoreService(); + for (final url in _item.imageUrls) { + try { + await storage.deleteFileByUrl(url); + } catch (_) {} + } + await firestore.deletePost(collection, _item.id); + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + const SnackBar(content: Text('Eintrag gelöscht.')), + ); + Navigator.pop(context); + } catch (e) { + if (!mounted) return; + ScaffoldMessenger.of(context).showSnackBar( + SnackBar(content: Text('Fehler beim Löschen: $e')), + ); + } + } @override Widget build(BuildContext context) { + final auth = Provider.of(context); + final currentUser = auth.user; + final isAuthor = currentUser != null && _item.authorUid == currentUser.uid; + final canEdit = !_item.isAussendung && (isAuthor || auth.isAdmin); + final canDelete = !_item.isAussendung && (isAuthor || auth.isAdmin); + final formattedDate = - DateFormat('dd.MM.yyyy HH:mm').format(item.createdDate); + DateFormat('dd.MM.yyyy HH:mm').format(_item.createdDate); return Scaffold( appBar: AppBar( - title: Text(item.title, overflow: TextOverflow.ellipsis), + title: Text(_item.title, overflow: TextOverflow.ellipsis), actions: [ + if (canEdit) + IconButton( + icon: const Icon(Icons.edit), + tooltip: 'Beitrag bearbeiten', + onPressed: _editItem, + ), + if (canDelete) + IconButton( + icon: const Icon(Icons.delete_outline), + tooltip: 'Beitrag löschen', + onPressed: _deleteItem, + ), IconButton( icon: const Icon(Icons.picture_as_pdf), tooltip: 'Als PDF drucken / teilen', - onPressed: () => PdfService.printSinglePost(item), + onPressed: () => PdfService.printSinglePost(_item), ), ], ), @@ -36,11 +155,11 @@ class DetailScreen extends StatelessWidget { child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ - if (item.imageUrls.isNotEmpty) + if (_item.imageUrls.isNotEmpty) ClipRRect( borderRadius: BorderRadius.circular(12), child: CachedNetworkImage( - imageUrl: item.imageUrls.first, + imageUrl: _item.imageUrls.first, width: double.infinity, fit: BoxFit.cover, placeholder: (context, url) => const Center( @@ -58,7 +177,7 @@ class DetailScreen extends StatelessWidget { ), const SizedBox(height: 16), Text( - item.title, + _item.title, style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold), ), const SizedBox(height: 8), @@ -70,7 +189,7 @@ class DetailScreen extends StatelessWidget { formattedDate, style: TextStyle(fontSize: 13, color: Colors.grey.shade700), ), - if (item.status != null) ...[ + if (_item.status != null) ...[ const Spacer(), Container( padding: @@ -81,7 +200,7 @@ class DetailScreen extends StatelessWidget { border: Border.all(color: Colors.blue.shade200), ), child: Text( - item.status!, + _item.status!, style: TextStyle( fontSize: 12, fontWeight: FontWeight.bold, @@ -91,27 +210,27 @@ class DetailScreen extends StatelessWidget { ], ], ), - if (item.street != null && item.street!.isNotEmpty) ...[ + if (_item.street != null && _item.street!.isNotEmpty) ...[ const SizedBox(height: 10), Row( children: [ const Icon(Icons.location_on, size: 16, color: Colors.redAccent), const SizedBox(width: 6), Text( - 'Örtlichkeit: ${item.street}', + 'Örtlichkeit: ${_item.street}', style: const TextStyle(fontWeight: FontWeight.w600), ), ], ), ], - if (item.category != null && item.category!.isNotEmpty) ...[ + if (_item.category != null && _item.category!.isNotEmpty) ...[ const SizedBox(height: 6), Row( children: [ const Icon(Icons.category, size: 16, color: Colors.orange), const SizedBox(width: 6), Text( - 'Kategorie: ${item.category}', + 'Kategorie: ${_item.category}', style: TextStyle(color: Colors.grey.shade800), ), ], @@ -126,10 +245,10 @@ class DetailScreen extends StatelessWidget { ), const SizedBox(height: 8), Text( - item.description, + _item.description, style: const TextStyle(fontSize: 15, height: 1.5), ), - if (item.pdfUrl != null && item.pdfUrl!.isNotEmpty) ...[ + if (_item.pdfUrl != null && _item.pdfUrl!.isNotEmpty) ...[ const SizedBox(height: 16), Card( color: Colors.red.shade50, @@ -155,8 +274,8 @@ class DetailScreen extends StatelessWidget { context, MaterialPageRoute( builder: (ctx) => PdfViewerScreen( - title: item.title, - pdfUrl: item.pdfUrl!, + title: _item.title, + pdfUrl: _item.pdfUrl!, ), ), ); @@ -166,7 +285,7 @@ class DetailScreen extends StatelessWidget { ], const SizedBox(height: 24), // Additional images gallery if there are multiple images - if (item.imageUrls.length > 1) ...[ + if (_item.imageUrls.length > 1) ...[ const Text( 'Weitere Fotos', style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), @@ -176,10 +295,10 @@ class DetailScreen extends StatelessWidget { height: 120, child: ListView.separated( scrollDirection: Axis.horizontal, - itemCount: item.imageUrls.length - 1, + itemCount: _item.imageUrls.length - 1, separatorBuilder: (ctx, i) => const SizedBox(width: 8), itemBuilder: (ctx, index) { - final url = item.imageUrls[index + 1]; + final url = _item.imageUrls[index + 1]; return ClipRRect( borderRadius: BorderRadius.circular(8), child: CachedNetworkImage( diff --git a/lib/screens/pdf_viewer_screen.dart b/lib/screens/pdf_viewer_screen.dart index 7838bcc..b3c8f15 100644 --- a/lib/screens/pdf_viewer_screen.dart +++ b/lib/screens/pdf_viewer_screen.dart @@ -191,61 +191,69 @@ class _PdfViewerScreenState extends State ), ), pagesBuilder: (context, pages) { - return GestureDetector( - behavior: HitTestBehavior.translucent, - onDoubleTapDown: (details) => _doubleTapDetails = details, - onDoubleTap: _handleDoubleTap, - child: InteractiveViewer( - transformationController: _transformationController, - minScale: 1.0, - maxScale: 5.0, - panEnabled: true, - scaleEnabled: true, - child: SingleChildScrollView( - physics: const BouncingScrollPhysics(), - padding: const EdgeInsets.symmetric( - horizontal: 8.0, vertical: 16.0), - child: Center( - child: Column( - mainAxisSize: MainAxisSize.min, - children: [ - for (int i = 0; i < pages.length; i++) ...[ - Container( - margin: const EdgeInsets.only(bottom: 16), - decoration: BoxDecoration( - color: Colors.white, - borderRadius: BorderRadius.circular(4), - boxShadow: [ - BoxShadow( - color: Colors.black.withValues(alpha: 0.15), - blurRadius: 10, - offset: const Offset(0, 3), + return LayoutBuilder( + builder: (context, constraints) { + final viewportWidth = constraints.maxWidth; + return GestureDetector( + behavior: HitTestBehavior.translucent, + onDoubleTapDown: (details) => _doubleTapDetails = details, + onDoubleTap: _handleDoubleTap, + child: InteractiveViewer( + transformationController: _transformationController, + minScale: 1.0, + maxScale: 5.0, + panEnabled: true, + scaleEnabled: true, + constrained: false, + alignment: Alignment.topCenter, + child: SizedBox( + width: viewportWidth, + child: Padding( + padding: const EdgeInsets.symmetric( + horizontal: 8.0, vertical: 16.0), + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + for (int i = 0; i < pages.length; i++) ...[ + Container( + margin: const EdgeInsets.only(bottom: 16), + decoration: BoxDecoration( + color: Colors.white, + borderRadius: BorderRadius.circular(4), + boxShadow: [ + BoxShadow( + color: + Colors.black.withValues(alpha: 0.15), + blurRadius: 10, + offset: const Offset(0, 3), + ), + ], ), - ], - ), - child: Image( - image: pages[i].image, - fit: BoxFit.contain, - ), - ), - if (pages.length > 1) - Padding( - padding: const EdgeInsets.only(bottom: 12.0), - child: Text( - 'Seite ${i + 1} von ${pages.length}', - style: TextStyle( - fontSize: 12, - fontWeight: FontWeight.w500, - color: Colors.grey.shade700, + child: Image( + image: pages[i].image, + fit: BoxFit.contain, ), ), - ), - ], - ], + if (pages.length > 1) + Padding( + padding: const EdgeInsets.only(bottom: 12.0), + child: Text( + 'Seite ${i + 1} von ${pages.length}', + style: TextStyle( + fontSize: 12, + fontWeight: FontWeight.w500, + color: Colors.grey.shade700, + ), + ), + ), + ], + ], + ), + ), ), ), - ), - ), + ); + }, ); }, ), diff --git a/lib/screens/post_list_screen.dart b/lib/screens/post_list_screen.dart index 184119b..cd4144f 100644 --- a/lib/screens/post_list_screen.dart +++ b/lib/screens/post_list_screen.dart @@ -129,6 +129,30 @@ class _PostListScreenState extends State { } } + void _editPost(PostItem item) { + if (widget.collectionName == 'Issues') { + Navigator.push( + context, + MaterialPageRoute( + builder: (ctx) => AddIssueScreen(issueToEdit: item), + ), + ); + } else { + Navigator.push( + context, + MaterialPageRoute( + builder: (ctx) => AddPostScreen( + collectionName: widget.collectionName, + screenTitle: widget.collectionName == 'News' + ? 'Nachricht bearbeiten' + : 'Idee bearbeiten', + postToEdit: item, + ), + ), + ); + } + } + Future _onAddNewPressed() async { final auth = Provider.of(context, listen: false); @@ -402,6 +426,7 @@ class _PostListScreenState extends State { final isAuthor = currentUser != null && item.authorUid == currentUser.uid; final canDelete = !item.isAussendung && (isAuthor || auth.isAdmin); + final canEdit = !item.isAussendung && (isAuthor || auth.isAdmin); final formattedDate = DateFormat('dd.MM.yyyy').format(item.createdDate); @@ -525,7 +550,10 @@ class _PostListScreenState extends State { Navigator.push( context, MaterialPageRoute( - builder: (ctx) => DetailScreen(item: item), + builder: (ctx) => DetailScreen( + item: item, + collectionName: widget.collectionName, + ), ), ); } @@ -535,7 +563,73 @@ class _PostListScreenState extends State { trailing: item.isAussendung ? Icon(Icons.arrow_forward_ios, size: 14, color: Colors.grey.shade400) - : null, + : (_selectedItems.isNotEmpty + ? null + : ((canEdit || canDelete) + ? PopupMenuButton( + icon: const Icon(Icons.more_vert, + size: 20, color: Colors.black54), + tooltip: 'Optionen', + onSelected: (value) async { + if (value == 'edit') { + _editPost(item); + } else if (value == 'delete') { + final confirmed = await showDialog( + context: context, + builder: (dialogCtx) => AlertDialog( + title: const Text('Eintrag löschen?'), + content: const Text( + 'Möchten Sie diesen Eintrag wirklich unwiderruflich löschen?'), + actions: [ + TextButton( + onPressed: () => + Navigator.pop(dialogCtx, false), + child: const Text('Abbrechen'), + ), + ElevatedButton( + style: ElevatedButton.styleFrom( + backgroundColor: Colors.red), + onPressed: () => + Navigator.pop(dialogCtx, true), + child: const Text('Löschen'), + ), + ], + ), + ); + if (confirmed == true) { + _deletePost(item); + } + } + }, + itemBuilder: (ctx) => [ + if (canEdit) + const PopupMenuItem( + value: 'edit', + child: Row( + children: [ + Icon(Icons.edit_outlined, size: 20), + SizedBox(width: 8), + Text('Bearbeiten'), + ], + ), + ), + if (canDelete) + const PopupMenuItem( + value: 'delete', + child: Row( + children: [ + Icon(Icons.delete_outline, + size: 20, color: Colors.red), + SizedBox(width: 8), + Text('Löschen', + style: + TextStyle(color: Colors.red)), + ], + ), + ), + ], + ) + : null)), title: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ diff --git a/lib/services/firestore_service.dart b/lib/services/firestore_service.dart index defd9ec..8d65bbb 100644 --- a/lib/services/firestore_service.dart +++ b/lib/services/firestore_service.dart @@ -43,6 +43,14 @@ class FirestoreService { await _firestore.collection(collectionName).doc(documentId).delete(); } + /// Update an existing post by ID + Future updatePost(String collectionName, PostItem item) async { + await _firestore + .collection(collectionName) + .doc(item.id) + .update(item.toFirestore()); + } + /// Send a contact form submission to Firestore Future submitContactMessage({ required String firstName, diff --git a/test/widget_test.dart b/test/widget_test.dart index 0dadaf4..b01654c 100644 --- a/test/widget_test.dart +++ b/test/widget_test.dart @@ -219,4 +219,121 @@ void main() { expect(totalBottomPadding > systemNavBarHeight, isTrue); }); }); + + group('Post Edit & Permissions Tests', () { + test('PostItem.copyWith updates fields while preserving existing values', () { + final original = PostItem( + id: 'post-1', + title: 'Original Title', + description: 'Original Desc', + createdDate: DateTime(2026, 1, 1), + authorUid: 'user-123', + imageUrl: 'https://example.com/img1.jpg', + street: 'Hauptstraße', + category: 'Sonstiges', + status: 'Gemeldet', + ); + + final edited = original.copyWith( + title: 'Updated Title', + description: 'Updated Desc', + imageUrl: 'https://example.com/img2.jpg', + imageUrls: ['https://example.com/img2.jpg'], + status: 'In Bearbeitung', + ); + + expect(edited.id, 'post-1'); + expect(edited.authorUid, 'user-123'); + expect(edited.createdDate, DateTime(2026, 1, 1)); + expect(edited.street, 'Hauptstraße'); + expect(edited.category, 'Sonstiges'); + expect(edited.title, 'Updated Title'); + expect(edited.description, 'Updated Desc'); + expect(edited.imageUrl, 'https://example.com/img2.jpg'); + expect(edited.imageUrls, ['https://example.com/img2.jpg']); + expect(edited.status, 'In Bearbeitung'); + }); + + test('verifies post edit permissions: admins can edit all, users can edit only their own, Aussendungen cannot be edited', () { + bool canEditPost({ + required PostItem post, + required String? currentUserId, + required bool isAdmin, + }) { + if (post.isAussendung) return false; + final isAuthor = currentUserId != null && post.authorUid == currentUserId; + return isAuthor || isAdmin; + } + + final userPost = PostItem( + id: 'user_post_1', + title: 'Schlagloch', + description: 'Großes Schlagloch', + createdDate: DateTime.now(), + authorUid: 'author_1', + ); + + final aussendung = PostItem( + id: 'wp_123', + title: 'Aussendung', + description: 'PDF', + createdDate: DateTime.now(), + isAussendung: true, + ); + + // 1. Author user can edit their own post + expect( + canEditPost(post: userPost, currentUserId: 'author_1', isAdmin: false), + isTrue, + ); + + // 2. Different user cannot edit other user's post + expect( + canEditPost(post: userPost, currentUserId: 'other_user', isAdmin: false), + isFalse, + ); + + // 3. Admin can edit any post (even if not author) + expect( + canEditPost(post: userPost, currentUserId: 'other_user', isAdmin: true), + isTrue, + ); + + // 4. Admin cannot edit external WordPress Aussendungen + expect( + canEditPost(post: aussendung, currentUserId: 'author_1', isAdmin: true), + isFalse, + ); + + // 5. Unauthenticated user cannot edit + expect( + canEditPost(post: userPost, currentUserId: null, isAdmin: false), + isFalse, + ); + }); + + test('validates issue status editing for admins', () { + const allowedStatuses = ['Gemeldet', 'In Bearbeitung', 'Erledigt']; + + final issue = PostItem( + id: 'issue_1', + title: 'Straßenlaterne', + description: 'Laterne dunkel', + createdDate: DateTime.now(), + authorUid: 'user_1', + status: 'Gemeldet', + ); + + expect(issue.status, 'Gemeldet'); + + // Admin transitions status + final inProgress = issue.copyWith(status: 'In Bearbeitung'); + expect(inProgress.status, 'In Bearbeitung'); + expect(allowedStatuses.contains(inProgress.status), isTrue); + + final done = inProgress.copyWith(status: 'Erledigt'); + expect(done.status, 'Erledigt'); + expect(allowedStatuses.contains(done.status), isTrue); + }); + }); }