feat: pinch-to-zoom gestures for PDF reader & post editing for admins and authors
Build Android APK / Build Release APKs (push) Successful in 14m41s

This commit is contained in:
2026-09-18 12:05:18 +02:00
parent a228392dc6
commit f10d5ad5ed
8 changed files with 884 additions and 203 deletions
+33
View File
@@ -236,4 +236,37 @@ class PostItem {
isAussendung: true, isAussendung: true,
); );
} }
/// Create a copy of this PostItem with updated fields
PostItem copyWith({
String? id,
String? title,
String? description,
String? imageUrl,
List<String>? 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,
);
}
} }
+268 -95
View File
@@ -1,13 +1,18 @@
import 'dart:io'; import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
import 'package:provider/provider.dart';
import '../models/post_item.dart'; import '../models/post_item.dart';
import '../services/auth_service.dart';
import '../services/firestore_service.dart'; import '../services/firestore_service.dart';
import '../services/storage_service.dart'; import '../services/storage_service.dart';
class AddIssueScreen extends StatefulWidget { class AddIssueScreen extends StatefulWidget {
const AddIssueScreen({super.key}); final PostItem? issueToEdit;
const AddIssueScreen({super.key, this.issueToEdit});
@override @override
State<AddIssueScreen> createState() => _AddIssueScreenState(); State<AddIssueScreen> createState() => _AddIssueScreenState();
@@ -22,8 +27,18 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
final StorageService _storageService = StorageService(); final StorageService _storageService = StorageService();
final List<File> _selectedImages = []; final List<File> _selectedImages = [];
List<String> _existingImageUrls = [];
String _selectedStatus = 'Gemeldet';
bool _isSaving = false; bool _isSaving = false;
bool get isEditing => widget.issueToEdit != null;
final List<String> _statuses = [
'Gemeldet',
'In Bearbeitung',
'Erledigt',
];
final List<String> _streets = [ final List<String> _streets = [
'Hauptstraße', 'Hauptstraße',
'Seestraße', 'Seestraße',
@@ -56,8 +71,31 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_selectedStreet = _streets.first; if (widget.issueToEdit != null) {
_selectedCategory = _categories.first; 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<String>.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 @override
@@ -68,9 +106,10 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
} }
Future<void> _pickImage(ImageSource source) async { Future<void> _pickImage(ImageSource source) async {
if (_selectedImages.length >= 2) { if (_existingImageUrls.length + _selectedImages.length >= 2) {
ScaffoldMessenger.of(context).showSnackBar( 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; return;
} }
@@ -136,43 +175,89 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
}); });
try { 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 // Upload newly selected images to Storage
final List<String> uploadedUrls = []; final List<String> newlyUploadedUrls = [];
for (final file in _selectedImages) { for (final file in _selectedImages) {
final url = await _storageService.uploadFile( final url = await _storageService.uploadFile(
file: file, file: file,
collectionName: 'Issues', collectionName: 'Issues',
optimize: true, 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<String> 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) { } catch (e) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -192,9 +277,13 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final auth = Provider.of<AuthService>(context, listen: false);
final isAdmin = auth.isAdmin;
final totalPhotos = _existingImageUrls.length + _selectedImages.length;
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: const Text('Mangel melden'), title: Text(isEditing ? 'Mangel bearbeiten' : 'Mangel melden'),
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: EdgeInsets.only( padding: EdgeInsets.only(
@@ -251,6 +340,26 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
.toList(), .toList(),
onChanged: (val) => setState(() => _selectedCategory = val), onChanged: (val) => setState(() => _selectedCategory = val),
), ),
if (isAdmin && isEditing) ...[
const SizedBox(height: 16),
DropdownButtonFormField<String>(
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), const SizedBox(height: 16),
TextFormField( TextFormField(
controller: _descriptionController, controller: _descriptionController,
@@ -271,67 +380,127 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14), style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Row( SingleChildScrollView(
children: [ scrollDirection: Axis.horizontal,
..._selectedImages.asMap().entries.map((entry) { child: Row(
final index = entry.key; children: [
final file = entry.value; // Existing images from Firebase Storage
return Stack( ..._existingImageUrls.asMap().entries.map((entry) {
children: [ final index = entry.key;
Container( final url = entry.value;
margin: const EdgeInsets.only(right: 12), 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, width: 110,
height: 80, height: 80,
decoration: BoxDecoration( decoration: BoxDecoration(
border: Border.all(color: Colors.grey.shade400), color: Colors.grey.shade200,
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
image: DecorationImage( border: Border.all(
image: FileImage(file), color: Colors.grey.shade400,
fit: BoxFit.cover, style: BorderStyle.solid),
),
), ),
), child: const Column(
Positioned( mainAxisAlignment: MainAxisAlignment.center,
top: -4, children: [
right: 4, Icon(Icons.add_a_photo, color: Colors.grey),
child: IconButton( SizedBox(height: 4),
icon: const Icon(Icons.cancel, color: Colors.red), Text('Foto hinzufügen',
onPressed: () { style: TextStyle(
setState(() { fontSize: 11, color: Colors.black54)),
_selectedImages.removeAt(index); ],
});
},
), ),
), ),
],
);
}),
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), const SizedBox(height: 32),
SizedBox( SizedBox(
@@ -346,9 +515,13 @@ class _AddIssueScreenState extends State<AddIssueScreen> {
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white), strokeWidth: 2, color: Colors.white),
) )
: const Icon(Icons.check_circle_outline), : Icon(isEditing ? Icons.save : Icons.check_circle_outline),
label: Text( label: Text(
_isSaving ? 'Wird gespeichert...' : 'Mangel fertigstellen', _isSaving
? 'Wird gespeichert...'
: (isEditing
? 'Änderungen speichern'
: 'Mangel fertigstellen'),
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
), ),
+164 -35
View File
@@ -1,4 +1,5 @@
import 'dart:io'; import 'dart:io';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart'; import 'package:image_picker/image_picker.dart';
@@ -9,11 +10,13 @@ import '../services/storage_service.dart';
class AddPostScreen extends StatefulWidget { class AddPostScreen extends StatefulWidget {
final String collectionName; final String collectionName;
final String screenTitle; final String screenTitle;
final PostItem? postToEdit;
const AddPostScreen({ const AddPostScreen({
super.key, super.key,
required this.collectionName, required this.collectionName,
required this.screenTitle, required this.screenTitle,
this.postToEdit,
}); });
@override @override
@@ -29,8 +32,25 @@ class _AddPostScreenState extends State<AddPostScreen> {
final StorageService _storageService = StorageService(); final StorageService _storageService = StorageService();
File? _selectedImage; File? _selectedImage;
String? _existingImageUrl;
bool _isSaving = false; 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 @override
void dispose() { void dispose() {
_titleController.dispose(); _titleController.dispose();
@@ -100,38 +120,85 @@ class _AddPostScreenState extends State<AddPostScreen> {
}); });
try { try {
final currentUserId = FirebaseAuth.instance.currentUser?.uid; if (isEditing) {
String imageUrl = ''; String imageUrl = _existingImageUrl ?? '';
if (_selectedImage != null) { if (_selectedImage != null) {
imageUrl = await _storageService.uploadFile( // If a new image was chosen, remove the old one from storage if it existed
file: _selectedImage!, if (widget.postToEdit!.imageUrls.isNotEmpty) {
collectionName: widget.collectionName, for (final oldUrl in widget.postToEdit!.imageUrls) {
optimize: true, 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) { } catch (e) {
if (!mounted) return; if (!mounted) return;
ScaffoldMessenger.of(context).showSnackBar( ScaffoldMessenger.of(context).showSnackBar(
@@ -153,7 +220,7 @@ class _AddPostScreenState extends State<AddPostScreen> {
Widget build(BuildContext context) { Widget build(BuildContext context) {
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(widget.screenTitle), title: Text(isEditing ? 'Beitrag bearbeiten' : widget.screenTitle),
), ),
body: SingleChildScrollView( body: SingleChildScrollView(
padding: EdgeInsets.only( padding: EdgeInsets.only(
@@ -218,12 +285,68 @@ class _AddPostScreenState extends State<AddPostScreen> {
backgroundColor: Colors.black54, backgroundColor: Colors.black54,
child: IconButton( child: IconButton(
icon: const Icon(Icons.close, color: Colors.white), 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 else
InkWell( InkWell(
onTap: _showImageSourceModal, onTap: _showImageSourceModal,
@@ -238,9 +361,11 @@ class _AddPostScreenState extends State<AddPostScreen> {
child: const Column( child: const Column(
mainAxisAlignment: MainAxisAlignment.center, mainAxisAlignment: MainAxisAlignment.center,
children: [ children: [
Icon(Icons.add_photo_alternate, size: 36, color: Colors.grey), Icon(Icons.add_photo_alternate,
size: 36, color: Colors.grey),
SizedBox(height: 6), 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<AddPostScreen> {
child: CircularProgressIndicator( child: CircularProgressIndicator(
strokeWidth: 2, color: Colors.white), strokeWidth: 2, color: Colors.white),
) )
: const Icon(Icons.send), : Icon(isEditing ? Icons.save : Icons.send),
label: Text( label: Text(
_isSaving ? 'Wird gespeichert...' : 'Veröffentlichen', _isSaving
? 'Wird gespeichert...'
: (isEditing
? 'Änderungen speichern'
: 'Veröffentlichen'),
style: const TextStyle(fontSize: 16), style: const TextStyle(fontSize: 16),
), ),
), ),
+140 -21
View File
@@ -1,28 +1,147 @@
import 'package:cached_network_image/cached_network_image.dart'; import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:intl/intl.dart'; import 'package:intl/intl.dart';
import 'package:provider/provider.dart';
import '../models/post_item.dart'; import '../models/post_item.dart';
import '../services/auth_service.dart';
import '../services/firestore_service.dart';
import '../services/pdf_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'; import 'pdf_viewer_screen.dart';
class DetailScreen extends StatelessWidget { class DetailScreen extends StatefulWidget {
final PostItem item; final PostItem item;
final String? collectionName;
const DetailScreen({super.key, required this.item}); const DetailScreen({
super.key,
required this.item,
this.collectionName,
});
@override
State<DetailScreen> createState() => _DetailScreenState();
}
class _DetailScreenState extends State<DetailScreen> {
late PostItem _item;
@override
void initState() {
super.initState();
_item = widget.item;
}
Future<void> _editItem() async {
final collection = widget.collectionName ??
(_item.street != null ? 'Issues' : 'CitizensForum');
PostItem? updated;
if (collection == 'Issues' || _item.street != null) {
updated = await Navigator.push<PostItem>(
context,
MaterialPageRoute(
builder: (ctx) => AddIssueScreen(issueToEdit: _item),
),
);
} else {
updated = await Navigator.push<PostItem>(
context,
MaterialPageRoute(
builder: (ctx) => AddPostScreen(
collectionName: collection,
screenTitle: 'Beitrag bearbeiten',
postToEdit: _item,
),
),
);
}
if (updated != null && mounted) {
setState(() {
_item = updated!;
});
}
}
Future<void> _deleteItem() async {
final confirmed = await showDialog<bool>(
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 @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
final auth = Provider.of<AuthService>(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 = final formattedDate =
DateFormat('dd.MM.yyyy HH:mm').format(item.createdDate); DateFormat('dd.MM.yyyy HH:mm').format(_item.createdDate);
return Scaffold( return Scaffold(
appBar: AppBar( appBar: AppBar(
title: Text(item.title, overflow: TextOverflow.ellipsis), title: Text(_item.title, overflow: TextOverflow.ellipsis),
actions: [ 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( IconButton(
icon: const Icon(Icons.picture_as_pdf), icon: const Icon(Icons.picture_as_pdf),
tooltip: 'Als PDF drucken / teilen', tooltip: 'Als PDF drucken / teilen',
onPressed: () => PdfService.printSinglePost(item), onPressed: () => PdfService.printSinglePost(_item),
), ),
], ],
), ),
@@ -36,11 +155,11 @@ class DetailScreen extends StatelessWidget {
child: Column( child: Column(
crossAxisAlignment: CrossAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start,
children: [ children: [
if (item.imageUrls.isNotEmpty) if (_item.imageUrls.isNotEmpty)
ClipRRect( ClipRRect(
borderRadius: BorderRadius.circular(12), borderRadius: BorderRadius.circular(12),
child: CachedNetworkImage( child: CachedNetworkImage(
imageUrl: item.imageUrls.first, imageUrl: _item.imageUrls.first,
width: double.infinity, width: double.infinity,
fit: BoxFit.cover, fit: BoxFit.cover,
placeholder: (context, url) => const Center( placeholder: (context, url) => const Center(
@@ -58,7 +177,7 @@ class DetailScreen extends StatelessWidget {
), ),
const SizedBox(height: 16), const SizedBox(height: 16),
Text( Text(
item.title, _item.title,
style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold), style: const TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
@@ -70,7 +189,7 @@ class DetailScreen extends StatelessWidget {
formattedDate, formattedDate,
style: TextStyle(fontSize: 13, color: Colors.grey.shade700), style: TextStyle(fontSize: 13, color: Colors.grey.shade700),
), ),
if (item.status != null) ...[ if (_item.status != null) ...[
const Spacer(), const Spacer(),
Container( Container(
padding: padding:
@@ -81,7 +200,7 @@ class DetailScreen extends StatelessWidget {
border: Border.all(color: Colors.blue.shade200), border: Border.all(color: Colors.blue.shade200),
), ),
child: Text( child: Text(
item.status!, _item.status!,
style: TextStyle( style: TextStyle(
fontSize: 12, fontSize: 12,
fontWeight: FontWeight.bold, 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), const SizedBox(height: 10),
Row( Row(
children: [ children: [
const Icon(Icons.location_on, size: 16, color: Colors.redAccent), const Icon(Icons.location_on, size: 16, color: Colors.redAccent),
const SizedBox(width: 6), const SizedBox(width: 6),
Text( Text(
'Örtlichkeit: ${item.street}', 'Örtlichkeit: ${_item.street}',
style: const TextStyle(fontWeight: FontWeight.w600), style: const TextStyle(fontWeight: FontWeight.w600),
), ),
], ],
), ),
], ],
if (item.category != null && item.category!.isNotEmpty) ...[ if (_item.category != null && _item.category!.isNotEmpty) ...[
const SizedBox(height: 6), const SizedBox(height: 6),
Row( Row(
children: [ children: [
const Icon(Icons.category, size: 16, color: Colors.orange), const Icon(Icons.category, size: 16, color: Colors.orange),
const SizedBox(width: 6), const SizedBox(width: 6),
Text( Text(
'Kategorie: ${item.category}', 'Kategorie: ${_item.category}',
style: TextStyle(color: Colors.grey.shade800), style: TextStyle(color: Colors.grey.shade800),
), ),
], ],
@@ -126,10 +245,10 @@ class DetailScreen extends StatelessWidget {
), ),
const SizedBox(height: 8), const SizedBox(height: 8),
Text( Text(
item.description, _item.description,
style: const TextStyle(fontSize: 15, height: 1.5), 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), const SizedBox(height: 16),
Card( Card(
color: Colors.red.shade50, color: Colors.red.shade50,
@@ -155,8 +274,8 @@ class DetailScreen extends StatelessWidget {
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (ctx) => PdfViewerScreen( builder: (ctx) => PdfViewerScreen(
title: item.title, title: _item.title,
pdfUrl: item.pdfUrl!, pdfUrl: _item.pdfUrl!,
), ),
), ),
); );
@@ -166,7 +285,7 @@ class DetailScreen extends StatelessWidget {
], ],
const SizedBox(height: 24), const SizedBox(height: 24),
// Additional images gallery if there are multiple images // Additional images gallery if there are multiple images
if (item.imageUrls.length > 1) ...[ if (_item.imageUrls.length > 1) ...[
const Text( const Text(
'Weitere Fotos', 'Weitere Fotos',
style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold), style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold),
@@ -176,10 +295,10 @@ class DetailScreen extends StatelessWidget {
height: 120, height: 120,
child: ListView.separated( child: ListView.separated(
scrollDirection: Axis.horizontal, scrollDirection: Axis.horizontal,
itemCount: item.imageUrls.length - 1, itemCount: _item.imageUrls.length - 1,
separatorBuilder: (ctx, i) => const SizedBox(width: 8), separatorBuilder: (ctx, i) => const SizedBox(width: 8),
itemBuilder: (ctx, index) { itemBuilder: (ctx, index) {
final url = item.imageUrls[index + 1]; final url = _item.imageUrls[index + 1];
return ClipRRect( return ClipRRect(
borderRadius: BorderRadius.circular(8), borderRadius: BorderRadius.circular(8),
child: CachedNetworkImage( child: CachedNetworkImage(
+58 -50
View File
@@ -191,61 +191,69 @@ class _PdfViewerScreenState extends State<PdfViewerScreen>
), ),
), ),
pagesBuilder: (context, pages) { pagesBuilder: (context, pages) {
return GestureDetector( return LayoutBuilder(
behavior: HitTestBehavior.translucent, builder: (context, constraints) {
onDoubleTapDown: (details) => _doubleTapDetails = details, final viewportWidth = constraints.maxWidth;
onDoubleTap: _handleDoubleTap, return GestureDetector(
child: InteractiveViewer( behavior: HitTestBehavior.translucent,
transformationController: _transformationController, onDoubleTapDown: (details) => _doubleTapDetails = details,
minScale: 1.0, onDoubleTap: _handleDoubleTap,
maxScale: 5.0, child: InteractiveViewer(
panEnabled: true, transformationController: _transformationController,
scaleEnabled: true, minScale: 1.0,
child: SingleChildScrollView( maxScale: 5.0,
physics: const BouncingScrollPhysics(), panEnabled: true,
padding: const EdgeInsets.symmetric( scaleEnabled: true,
horizontal: 8.0, vertical: 16.0), constrained: false,
child: Center( alignment: Alignment.topCenter,
child: Column( child: SizedBox(
mainAxisSize: MainAxisSize.min, width: viewportWidth,
children: [ child: Padding(
for (int i = 0; i < pages.length; i++) ...[ padding: const EdgeInsets.symmetric(
Container( horizontal: 8.0, vertical: 16.0),
margin: const EdgeInsets.only(bottom: 16), child: Column(
decoration: BoxDecoration( mainAxisSize: MainAxisSize.min,
color: Colors.white, children: [
borderRadius: BorderRadius.circular(4), for (int i = 0; i < pages.length; i++) ...[
boxShadow: [ Container(
BoxShadow( margin: const EdgeInsets.only(bottom: 16),
color: Colors.black.withValues(alpha: 0.15), decoration: BoxDecoration(
blurRadius: 10, color: Colors.white,
offset: const Offset(0, 3), 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,
child: Image( fit: BoxFit.contain,
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,
), ),
), ),
), 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,
),
),
),
],
],
),
),
), ),
), ),
), );
), },
); );
}, },
), ),
+96 -2
View File
@@ -129,6 +129,30 @@ class _PostListScreenState extends State<PostListScreen> {
} }
} }
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<void> _onAddNewPressed() async { Future<void> _onAddNewPressed() async {
final auth = Provider.of<AuthService>(context, listen: false); final auth = Provider.of<AuthService>(context, listen: false);
@@ -402,6 +426,7 @@ class _PostListScreenState extends State<PostListScreen> {
final isAuthor = final isAuthor =
currentUser != null && item.authorUid == currentUser.uid; currentUser != null && item.authorUid == currentUser.uid;
final canDelete = !item.isAussendung && (isAuthor || auth.isAdmin); final canDelete = !item.isAussendung && (isAuthor || auth.isAdmin);
final canEdit = !item.isAussendung && (isAuthor || auth.isAdmin);
final formattedDate = final formattedDate =
DateFormat('dd.MM.yyyy').format(item.createdDate); DateFormat('dd.MM.yyyy').format(item.createdDate);
@@ -525,7 +550,10 @@ class _PostListScreenState extends State<PostListScreen> {
Navigator.push( Navigator.push(
context, context,
MaterialPageRoute( MaterialPageRoute(
builder: (ctx) => DetailScreen(item: item), builder: (ctx) => DetailScreen(
item: item,
collectionName: widget.collectionName,
),
), ),
); );
} }
@@ -535,7 +563,73 @@ class _PostListScreenState extends State<PostListScreen> {
trailing: item.isAussendung trailing: item.isAussendung
? Icon(Icons.arrow_forward_ios, ? Icon(Icons.arrow_forward_ios,
size: 14, color: Colors.grey.shade400) size: 14, color: Colors.grey.shade400)
: null, : (_selectedItems.isNotEmpty
? null
: ((canEdit || canDelete)
? PopupMenuButton<String>(
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<bool>(
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<String>(
value: 'edit',
child: Row(
children: [
Icon(Icons.edit_outlined, size: 20),
SizedBox(width: 8),
Text('Bearbeiten'),
],
),
),
if (canDelete)
const PopupMenuItem<String>(
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( title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween, mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [ children: [
+8
View File
@@ -43,6 +43,14 @@ class FirestoreService {
await _firestore.collection(collectionName).doc(documentId).delete(); await _firestore.collection(collectionName).doc(documentId).delete();
} }
/// Update an existing post by ID
Future<void> updatePost(String collectionName, PostItem item) async {
await _firestore
.collection(collectionName)
.doc(item.id)
.update(item.toFirestore());
}
/// Send a contact form submission to Firestore /// Send a contact form submission to Firestore
Future<void> submitContactMessage({ Future<void> submitContactMessage({
required String firstName, required String firstName,
+117
View File
@@ -219,4 +219,121 @@ void main() {
expect(totalBottomPadding > systemNavBarHeight, isTrue); 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);
});
});
} }