Implement complete event editing functionality with backend update endpoint

Frontend Changes:
- Add edit context menu option to EventContextMenu with pencil icon
- Enhance CreateEventModal to support both create and edit modes
- Add event data conversion methods for pre-populating edit forms
- Implement conditional submit logic (on_create vs on_update callbacks)
- Add update_event method to CalendarService with POST /calendar/events/update

Backend Changes:
- Add UpdateEventRequest and UpdateEventResponse models
- Implement update_event handler with event search by UID across calendars
- Add POST /api/calendar/events/update route
- Full validation and parsing of all event properties for updates
- Integrate with existing CalDAV client update_event functionality

Users can now right-click events, select "Edit Event", modify properties in the modal, and successfully update existing events instead of creating duplicates.

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
Connor Johnstone
2025-08-29 09:41:16 -04:00
parent 1b57adab98
commit 2a2666e75f
7 changed files with 570 additions and 14 deletions

View File

@@ -7,7 +7,7 @@ use serde::Deserialize;
use std::sync::Arc;
use chrono::{Datelike, TimeZone};
use crate::{AppState, models::{CalDAVLoginRequest, AuthResponse, ApiError, UserInfo, CalendarInfo, CreateCalendarRequest, CreateCalendarResponse, DeleteCalendarRequest, DeleteCalendarResponse, DeleteEventRequest, DeleteEventResponse, CreateEventRequest, CreateEventResponse}};
use crate::{AppState, models::{CalDAVLoginRequest, AuthResponse, ApiError, UserInfo, CalendarInfo, CreateCalendarRequest, CreateCalendarResponse, DeleteCalendarRequest, DeleteCalendarResponse, DeleteEventRequest, DeleteEventResponse, CreateEventRequest, CreateEventResponse, UpdateEventRequest, UpdateEventResponse}};
use crate::calendar::{CalDAVClient, CalendarEvent};
#[derive(Deserialize)]
@@ -763,6 +763,239 @@ pub async fn create_event(
}))
}
pub async fn update_event(
State(state): State<Arc<AppState>>,
headers: HeaderMap,
Json(request): Json<UpdateEventRequest>,
) -> Result<Json<UpdateEventResponse>, ApiError> {
println!("📝 Update event request received: uid='{}', title='{}', calendar_path={:?}",
request.uid, request.title, request.calendar_path);
// Extract and verify token
let token = extract_bearer_token(&headers)?;
let password = extract_password_header(&headers)?;
// Validate request
if request.uid.trim().is_empty() {
return Err(ApiError::BadRequest("Event UID is required".to_string()));
}
if request.title.trim().is_empty() {
return Err(ApiError::BadRequest("Event title is required".to_string()));
}
if request.title.len() > 200 {
return Err(ApiError::BadRequest("Event title too long (max 200 characters)".to_string()));
}
// Create CalDAV config from token and password
let config = state.auth_service.caldav_config_from_token(&token, &password)?;
let client = CalDAVClient::new(config);
// Find the event across all calendars (or in the specified calendar)
let calendar_paths = if let Some(path) = &request.calendar_path {
vec![path.clone()]
} else {
client.discover_calendars()
.await
.map_err(|e| ApiError::Internal(format!("Failed to discover calendars: {}", e)))?
};
if calendar_paths.is_empty() {
return Err(ApiError::BadRequest("No calendars available for event update".to_string()));
}
// Search for the event by UID across the specified calendars
let mut found_event: Option<(CalendarEvent, String, String)> = None; // (event, calendar_path, href)
for calendar_path in &calendar_paths {
match client.fetch_event_by_uid(calendar_path, &request.uid).await {
Ok(Some(event)) => {
if let Some(href) = event.href.clone() {
found_event = Some((event, calendar_path.clone(), href));
break;
}
},
Ok(None) => continue, // Event not found in this calendar
Err(e) => {
eprintln!("Failed to fetch event from calendar {}: {}", calendar_path, e);
continue;
}
}
}
let (mut event, calendar_path, event_href) = found_event
.ok_or_else(|| ApiError::NotFound(format!("Event with UID '{}' not found", request.uid)))?;
// Parse dates and times for the updated event
let start_datetime = parse_event_datetime(&request.start_date, &request.start_time, request.all_day)
.map_err(|e| ApiError::BadRequest(format!("Invalid start date/time: {}", e)))?;
let end_datetime = parse_event_datetime(&request.end_date, &request.end_time, request.all_day)
.map_err(|e| ApiError::BadRequest(format!("Invalid end date/time: {}", e)))?;
// Validate that end is after start
if end_datetime <= start_datetime {
return Err(ApiError::BadRequest("End date/time must be after start date/time".to_string()));
}
// Parse status
let status = match request.status.to_lowercase().as_str() {
"tentative" => crate::calendar::EventStatus::Tentative,
"cancelled" => crate::calendar::EventStatus::Cancelled,
_ => crate::calendar::EventStatus::Confirmed,
};
// Parse class
let class = match request.class.to_lowercase().as_str() {
"private" => crate::calendar::EventClass::Private,
"confidential" => crate::calendar::EventClass::Confidential,
_ => crate::calendar::EventClass::Public,
};
// Parse attendees (comma-separated email list)
let attendees: Vec<String> = if request.attendees.trim().is_empty() {
Vec::new()
} else {
request.attendees
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
};
// Parse categories (comma-separated list)
let categories: Vec<String> = if request.categories.trim().is_empty() {
Vec::new()
} else {
request.categories
.split(',')
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
.collect()
};
// Parse reminders and convert to EventReminder structs
let reminders: Vec<crate::calendar::EventReminder> = match request.reminder.to_lowercase().as_str() {
"15min" => vec![crate::calendar::EventReminder {
minutes_before: 15,
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"30min" => vec![crate::calendar::EventReminder {
minutes_before: 30,
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"1hour" => vec![crate::calendar::EventReminder {
minutes_before: 60,
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"2hours" => vec![crate::calendar::EventReminder {
minutes_before: 120,
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"1day" => vec![crate::calendar::EventReminder {
minutes_before: 1440, // 24 * 60
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"2days" => vec![crate::calendar::EventReminder {
minutes_before: 2880, // 48 * 60
action: crate::calendar::ReminderAction::Display,
description: None,
}],
"1week" => vec![crate::calendar::EventReminder {
minutes_before: 10080, // 7 * 24 * 60
action: crate::calendar::ReminderAction::Display,
description: None,
}],
_ => Vec::new(),
};
// Parse recurrence with BYDAY support for weekly recurrence
let recurrence_rule = match request.recurrence.to_lowercase().as_str() {
"daily" => Some("FREQ=DAILY".to_string()),
"weekly" => {
// Handle weekly recurrence with optional BYDAY parameter
let mut rrule = "FREQ=WEEKLY".to_string();
// Check if specific days are selected (recurrence_days has 7 elements: [Sun, Mon, Tue, Wed, Thu, Fri, Sat])
if request.recurrence_days.len() == 7 {
let selected_days: Vec<&str> = request.recurrence_days
.iter()
.enumerate()
.filter_map(|(i, &selected)| {
if selected {
Some(match i {
0 => "SU", // Sunday
1 => "MO", // Monday
2 => "TU", // Tuesday
3 => "WE", // Wednesday
4 => "TH", // Thursday
5 => "FR", // Friday
6 => "SA", // Saturday
_ => return None,
})
} else {
None
}
})
.collect();
if !selected_days.is_empty() {
rrule.push_str(&format!(";BYDAY={}", selected_days.join(",")));
}
}
Some(rrule)
},
"monthly" => Some("FREQ=MONTHLY".to_string()),
"yearly" => Some("FREQ=YEARLY".to_string()),
_ => None,
};
// Update the event fields with new data
event.summary = Some(request.title.clone());
event.description = if request.description.trim().is_empty() {
None
} else {
Some(request.description.clone())
};
event.start = start_datetime;
event.end = Some(end_datetime);
event.location = if request.location.trim().is_empty() {
None
} else {
Some(request.location.clone())
};
event.status = status;
event.class = class;
event.priority = request.priority;
event.organizer = if request.organizer.trim().is_empty() {
None
} else {
Some(request.organizer.clone())
};
event.attendees = attendees;
event.categories = categories;
event.last_modified = Some(chrono::Utc::now());
event.recurrence_rule = recurrence_rule;
event.all_day = request.all_day;
event.reminders = reminders;
// Update the event on the CalDAV server
client.update_event(&calendar_path, &event, &event_href)
.await
.map_err(|e| ApiError::Internal(format!("Failed to update event: {}", e)))?;
Ok(Json(UpdateEventResponse {
success: true,
message: "Event updated successfully".to_string(),
}))
}
/// Parse date and time strings into a UTC DateTime
fn parse_event_datetime(date_str: &str, time_str: &str, all_day: bool) -> Result<chrono::DateTime<chrono::Utc>, String> {
use chrono::{NaiveDate, NaiveTime, NaiveDateTime, Utc, TimeZone};

View File

@@ -42,6 +42,7 @@ pub async fn run_server() -> Result<(), Box<dyn std::error::Error>> {
.route("/api/calendar/delete", post(handlers::delete_calendar))
.route("/api/calendar/events", get(handlers::get_calendar_events))
.route("/api/calendar/events/create", post(handlers::create_event))
.route("/api/calendar/events/update", post(handlers::update_event))
.route("/api/calendar/events/delete", post(handlers::delete_event))
.route("/api/calendar/events/:uid", get(handlers::refresh_event))
.layer(

View File

@@ -101,6 +101,35 @@ pub struct CreateEventResponse {
pub event_href: Option<String>, // The created event's href/filename
}
#[derive(Debug, Deserialize)]
pub struct UpdateEventRequest {
pub uid: String, // Event UID to identify which event to update
pub title: String,
pub description: String,
pub start_date: String, // YYYY-MM-DD format
pub start_time: String, // HH:MM format
pub end_date: String, // YYYY-MM-DD format
pub end_time: String, // HH:MM format
pub location: String,
pub all_day: bool,
pub status: String, // confirmed, tentative, cancelled
pub class: String, // public, private, confidential
pub priority: Option<u8>, // 0-9 priority level
pub organizer: String, // organizer email
pub attendees: String, // comma-separated attendee emails
pub categories: String, // comma-separated categories
pub reminder: String, // reminder type
pub recurrence: String, // recurrence type
pub recurrence_days: Vec<bool>, // [Sun, Mon, Tue, Wed, Thu, Fri, Sat] for weekly recurrence
pub calendar_path: Option<String>, // Optional - search all calendars if not specified
}
#[derive(Debug, Serialize)]
pub struct UpdateEventResponse {
pub success: bool,
pub message: String,
}
// Error handling
#[derive(Debug)]
pub enum ApiError {