diff --git a/oedb/resources/demo.py b/oedb/resources/demo.py index c67ac72..bce150a 100644 --- a/oedb/resources/demo.py +++ b/oedb/resources/demo.py @@ -52,27 +52,47 @@ class DemoResource: # Set content type to HTML resp.content_type = 'text/html' - # Fetch the event data from the API + # Fetch the event data from the OEDB API + logger.info(f"Fetching event data from API for event ID: {id}") response = requests.get(f'https://api.openeventdatabase.org/event/{id}') - + if response.status_code != 200: + logger.error(f"API returned status {response.status_code} for event {id}") resp.status = falcon.HTTP_404 - resp.text = f"Event with ID {id} not found" + resp.text = f"Event with ID {id} not found on API" return - + event_data = response.json() - + logger.info(f"Successfully retrieved event data for {id}: {type(event_data)}") + + # Validate event data structure + if not isinstance(event_data, dict): + logger.error(f"Invalid event data type: {type(event_data)}") + resp.status = falcon.HTTP_500 + resp.text = "Invalid event data format received from API" + return + + if 'properties' not in event_data: + logger.error(f"Event data missing 'properties': {event_data}") + resp.status = falcon.HTTP_500 + resp.text = "Invalid event data structure - missing properties" + return + # Render the template with the event data template = self.jinja_env.get_template('edit.html') html = template.render( id=id, - event_data=event_data + event_data=event_data # Pass Python object directly, let Jinja2 handle JSON conversion ) - + # Set the response body and status resp.text = html resp.status = falcon.HTTP_200 logger.success(f"Successfully processed GET request to /demo/edit for event ID: {id}") + except requests.RequestException as e: + logger.error(f"Error fetching event data from API: {e}") + resp.status = falcon.HTTP_500 + resp.text = f"Error fetching event data: {str(e)}" except Exception as e: logger.error(f"Error processing GET request to /demo/edit: {e}") resp.status = falcon.HTTP_500 diff --git a/oedb/resources/demo/static/edit.js b/oedb/resources/demo/static/edit.js index 22d04fa..25d314e 100644 --- a/oedb/resources/demo/static/edit.js +++ b/oedb/resources/demo/static/edit.js @@ -57,61 +57,127 @@ function populateForm() { console.log('✅ Données événement validées, remplissage du formulaire...'); + // Remplir le tableau des propriétés + populatePropertiesTable(eventData.properties); + const properties = eventData.properties; - + // Set form values document.getElementById('label').value = properties.label || ''; document.getElementById('type').value = properties.type || 'scheduled'; document.getElementById('what').value = properties.what || ''; - + // Handle optional fields if (properties['what:series']) { document.getElementById('what_series').value = properties['what:series']; } - + if (properties.where) { document.getElementById('where').value = properties.where; } - + // Format dates for datetime-local input if (properties.start) { const startDate = new Date(properties.start); document.getElementById('start').value = startDate.toISOString().slice(0, 16); } - + if (properties.stop) { const stopDate = new Date(properties.stop); document.getElementById('stop').value = stopDate.toISOString().slice(0, 16); } - + // Set marker on map if (eventData.geometry && eventData.geometry.coordinates) { const coords = eventData.geometry.coordinates; marker.setLngLat(coords).addTo(map); - + // Center map on event location map.flyTo({ center: coords, zoom: 10 }); } + + // Initialiser l'autocomplétion pour le champ "what" + const whatInput = document.getElementById('what'); + if (whatInput && window.initializeEventTypeAutocomplete) { + initializeEventTypeAutocomplete(whatInput); + } +} + +// Function to populate the properties table +function populatePropertiesTable(properties) { + const tableBody = document.getElementById('propertiesTableBody'); + if (!tableBody) return; + + // Clear existing rows + tableBody.innerHTML = ''; + + // Sort properties alphabetically + const sortedProperties = Object.keys(properties).sort(); + + sortedProperties.forEach(key => { + const value = properties[key]; + const row = document.createElement('tr'); + + // Determine value type and format + let displayValue; + let valueType; + + if (value === null) { + displayValue = 'null'; + valueType = 'null'; + } else if (typeof value === 'object') { + displayValue = `
${JSON.stringify(value, null, 2)}`; + valueType = 'object'; + } else if (typeof value === 'string' && value.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/)) { + displayValue = value + ` (${new Date(value).toLocaleString()})`; + valueType = 'datetime'; + } else if (typeof value === 'string' && value.startsWith('http')) { + displayValue = `${value}`; + valueType = 'url'; + } else { + displayValue = String(value); + valueType = typeof value; + } + + row.innerHTML = ` +
'; + + if (eventId) { + linksHtml += `Voir l'événement | `; + } + + linksHtml += 'Retour à la carte
'; + resultElement.innerHTML += linksHtml; }) .catch(error => { - showResult(`Error: ${error.message}`, 'error'); + console.error('❌ Erreur lors de la modification:', error); + showResult(`❌ Erreur lors de la modification: ${error.message}`, 'error'); }); }); diff --git a/oedb/resources/demo/static/traffic.js b/oedb/resources/demo/static/traffic.js index 2ec5432..4aa24d9 100644 --- a/oedb/resources/demo/static/traffic.js +++ b/oedb/resources/demo/static/traffic.js @@ -140,11 +140,11 @@ document.addEventListener('DOMContentLoaded', function () { } // Set up form submission after DOM is loaded - const reportForm = document.getElementById('trafficForm'); + const reportForm = document.getElementById('reportForm'); if (reportForm) { reportForm.addEventListener('submit', submitReport); } else { - console.warn('Traffic form not found in DOM'); + console.warn('Report form not found in DOM'); } } @@ -251,13 +251,26 @@ document.addEventListener('DOMContentLoaded', function () { } } - // Submit the event to the API - const response = await fetch('/event', { + // Submit the event to the OEDB API + const response = await fetch('https://api.openeventdatabase.org/event', { method: 'POST', headers: { 'Content-Type': 'application/json' }, - body: JSON.stringify(eventData) + body: JSON.stringify({ + type: 'Feature', + geometry: eventData.geometry, + properties: { + type: eventData.type, + what: eventData.what, + label: eventData.label, + description: eventData.description, + start: eventData.start, + stop: eventData.stop, + ...(eventData.source && { source: eventData.source }), + ...(eventData.media && { media: eventData.media }) + } + }) }); if (!response.ok) { @@ -267,8 +280,44 @@ document.addEventListener('DOMContentLoaded', function () { const data = await response.json(); - // Show success message - resultElement.textContent = `Report submitted successfully! Event ID: ${data.id}`; + // Extract event ID from response (handle different response structures) + let eventId = null; + if (data.properties && data.properties.id) { + eventId = data.properties.id; + } else if (data.id) { + eventId = data.id; + } else if (typeof data === 'string') { + eventId = data; + } + + console.log('📅 Réponse API complète:', data); + console.log('🆔 ID événement extrait:', eventId); + + // Show success message with links + let successHtml = ` +