Equipe sur event details OK

Modif evenement OK
This commit is contained in:
2025-06-03 19:59:40 +02:00
parent acab16e101
commit 57c59c911a
6 changed files with 299 additions and 111 deletions

View File

@ -23,14 +23,15 @@ import 'package:em2rp/views/widgets/inputs/option_selector_widget.dart';
// ignore: avoid_web_libraries_in_flutter
import 'dart:html' as html;
class EventAddPage extends StatefulWidget {
const EventAddPage({super.key});
class EventAddEditPage extends StatefulWidget {
final EventModel? event;
const EventAddEditPage({super.key, this.event});
@override
State<EventAddPage> createState() => _EventAddPageState();
State<EventAddEditPage> createState() => _EventAddEditPageState();
}
class _EventAddPageState extends State<EventAddPage> {
class _EventAddEditPageState extends State<EventAddEditPage> {
final _formKey = GlobalKey<FormState>();
final TextEditingController _nameController = TextEditingController();
final TextEditingController _descriptionController = TextEditingController();
@ -61,6 +62,8 @@ class _EventAddPageState extends State<EventAddPage> {
bool _formChanged = false;
EventStatus _selectedStatus = EventStatus.waitingForApproval;
bool get isEditMode => widget.event != null;
@override
void initState() {
super.initState();
@ -73,7 +76,24 @@ class _EventAddPageState extends State<EventAddPage> {
_addressController.addListener(_onAnyFieldChanged);
_descriptionController.addListener(_onAnyFieldChanged);
_addBeforeUnloadListener();
_selectedStatus = EventStatus.waitingForApproval;
if (isEditMode) {
final e = widget.event!;
_nameController.text = e.name;
_descriptionController.text = e.description;
_basePriceController.text = e.basePrice.toStringAsFixed(2);
_installationController.text = e.installationTime.toString();
_disassemblyController.text = e.disassemblyTime.toString();
_addressController.text = e.address;
_startDateTime = e.startDateTime;
_endDateTime = e.endDateTime;
_selectedEventType = e.eventTypeId.isNotEmpty ? e.eventTypeId : null;
_selectedUserIds = e.workforce.map((ref) => ref.id).toList();
_uploadedFiles = List<Map<String, String>>.from(e.documents);
_selectedOptions = List<Map<String, dynamic>>.from(e.options);
_selectedStatus = e.status;
} else {
_selectedStatus = EventStatus.waitingForApproval;
}
}
void _handleDescriptionChange() {
@ -284,78 +304,121 @@ class _EventAddPageState extends State<EventAddPage> {
});
try {
final eventProvider = Provider.of<EventProvider>(context, listen: false);
final newEvent = EventModel(
id: '',
name: _nameController.text.trim(),
description: _descriptionController.text.trim(),
startDateTime: _startDateTime!,
endDateTime: _endDateTime!,
basePrice: double.tryParse(_basePriceController.text) ?? 0.0,
installationTime: int.tryParse(_installationController.text) ?? 0,
disassemblyTime: int.tryParse(_disassemblyController.text) ?? 0,
eventTypeId: _selectedEventType!,
customerId: '',
address: _addressController.text.trim(),
workforce: _selectedUserIds
.map((id) => FirebaseFirestore.instance.collection('users').doc(id))
.toList(),
latitude: 0.0,
longitude: 0.0,
documents: _uploadedFiles,
options: _selectedOptions
.map((opt) => {
'name': opt['name'],
'price': opt['price'],
})
.toList(),
status: _selectedStatus,
);
final docRef = await FirebaseFirestore.instance
.collection('events')
.add(newEvent.toMap());
final eventId = docRef.id;
List<Map<String, String>> newFiles = [];
for (final file in _uploadedFiles) {
final fileName = file['name']!;
final oldUrl = file['url']!;
String sourcePath;
final tempPattern = RegExp(r'events/temp/[^?]+');
final match = tempPattern.firstMatch(oldUrl);
if (match != null) {
sourcePath = match.group(0)!;
} else {
final tempFileName =
Uri.decodeComponent(oldUrl.split('/').last.split('?').first);
sourcePath = tempFileName;
}
final destinationPath = 'events/$eventId/$fileName';
final newUrl = await moveEventFileHttp(
sourcePath: sourcePath,
destinationPath: destinationPath,
if (isEditMode) {
// Edition : on met à jour l'événement existant
final updatedEvent = EventModel(
id: widget.event!.id,
name: _nameController.text.trim(),
description: _descriptionController.text.trim(),
startDateTime: _startDateTime!,
endDateTime: _endDateTime!,
basePrice: double.tryParse(_basePriceController.text) ?? 0.0,
installationTime: int.tryParse(_installationController.text) ?? 0,
disassemblyTime: int.tryParse(_disassemblyController.text) ?? 0,
eventTypeId: _selectedEventType!,
customerId: '',
address: _addressController.text.trim(),
workforce: _selectedUserIds
.map((id) =>
FirebaseFirestore.instance.collection('users').doc(id))
.toList(),
latitude: 0.0,
longitude: 0.0,
documents: _uploadedFiles,
options: _selectedOptions
.map((opt) => {
'name': opt['name'],
'price': opt['price'],
})
.toList(),
status: _selectedStatus,
);
if (newUrl != null) {
newFiles.add({'name': fileName, 'url': newUrl});
} else {
newFiles.add({'name': fileName, 'url': oldUrl});
final docRef = FirebaseFirestore.instance
.collection('events')
.doc(widget.event!.id);
await docRef.update(updatedEvent.toMap());
// Gestion des fichiers (si besoin, à adapter selon ta logique)
// ...
setState(() {
_success = "Événement modifié avec succès !";
});
if (context.mounted) Navigator.of(context).pop();
} else {
// Création : logique existante
final newEvent = EventModel(
id: '',
name: _nameController.text.trim(),
description: _descriptionController.text.trim(),
startDateTime: _startDateTime!,
endDateTime: _endDateTime!,
basePrice: double.tryParse(_basePriceController.text) ?? 0.0,
installationTime: int.tryParse(_installationController.text) ?? 0,
disassemblyTime: int.tryParse(_disassemblyController.text) ?? 0,
eventTypeId: _selectedEventType!,
customerId: '',
address: _addressController.text.trim(),
workforce: _selectedUserIds
.map((id) =>
FirebaseFirestore.instance.collection('users').doc(id))
.toList(),
latitude: 0.0,
longitude: 0.0,
documents: _uploadedFiles,
options: _selectedOptions
.map((opt) => {
'name': opt['name'],
'price': opt['price'],
})
.toList(),
status: _selectedStatus,
);
final docRef = await FirebaseFirestore.instance
.collection('events')
.add(newEvent.toMap());
final eventId = docRef.id;
List<Map<String, String>> newFiles = [];
for (final file in _uploadedFiles) {
final fileName = file['name']!;
final oldUrl = file['url']!;
String sourcePath;
final tempPattern = RegExp(r'events/temp/[^?]+');
final match = tempPattern.firstMatch(oldUrl);
if (match != null) {
sourcePath = match.group(0)!;
} else {
final tempFileName =
Uri.decodeComponent(oldUrl.split('/').last.split('?').first);
sourcePath = tempFileName;
}
final destinationPath = 'events/$eventId/$fileName';
final newUrl = await moveEventFileHttp(
sourcePath: sourcePath,
destinationPath: destinationPath,
);
if (newUrl != null) {
newFiles.add({'name': fileName, 'url': newUrl});
} else {
newFiles.add({'name': fileName, 'url': oldUrl});
}
}
await docRef.update({'documents': newFiles});
final localUserProvider =
Provider.of<LocalUserProvider>(context, listen: false);
final userId = localUserProvider.uid;
final canViewAllEvents =
localUserProvider.hasPermission('view_all_events');
if (userId != null) {
await eventProvider.loadUserEvents(userId,
canViewAllEvents: canViewAllEvents);
}
setState(() {
_success = "Événement créé avec succès !";
});
if (context.mounted) Navigator.of(context).pop();
}
await docRef.update({'documents': newFiles});
final localUserProvider =
Provider.of<LocalUserProvider>(context, listen: false);
final userId = localUserProvider.uid;
final canViewAllEvents =
localUserProvider.hasPermission('view_all_events');
if (userId != null) {
await eventProvider.loadUserEvents(userId,
canViewAllEvents: canViewAllEvents);
}
setState(() {
_success = "Événement créé avec succès !";
});
if (context.mounted) Navigator.of(context).pop();
} catch (e) {
setState(() {
_error = "Erreur lors de la création : $e";
_error = "Erreur lors de la sauvegarde : $e";
});
} finally {
setState(() {
@ -385,7 +448,8 @@ class _EventAddPageState extends State<EventAddPage> {
onWillPop: _onWillPop,
child: Scaffold(
appBar: AppBar(
title: const Text('Créer un événement'),
title:
Text(isEditMode ? 'Modifier un événement' : 'Créer un événement'),
),
body: Center(
child: SingleChildScrollView(
@ -393,10 +457,7 @@ class _EventAddPageState extends State<EventAddPage> {
? Padding(
padding: const EdgeInsets.symmetric(
horizontal: 16, vertical: 12),
child: Container(
// Pas de Card sur mobile, juste un conteneur
child: _buildFormContent(isMobile),
),
child: _buildFormContent(isMobile),
)
: Card(
elevation: 6,
@ -764,23 +825,23 @@ class _EventAddPageState extends State<EventAddPage> {
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
)
: const Text('Créer'),
: Text(isEditMode ? 'Enregistrer' : 'Créer'),
),
],
),
const SizedBox(height: 16),
Center(
child: ElevatedButton.icon(
icon: const Icon(Icons.check_circle, color: Colors.white),
label: const Text('Définir cet événement comme confirmé'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
textStyle: const TextStyle(fontWeight: FontWeight.bold),
if (!isEditMode)
Center(
child: ElevatedButton.icon(
icon: const Icon(Icons.check_circle, color: Colors.white),
label: const Text('Définir cet événement comme confirmé'),
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
foregroundColor: Colors.white,
textStyle: const TextStyle(fontWeight: FontWeight.bold),
),
onPressed: null,
),
onPressed: null,
),
),
],
),
);