feat: complete CalDAV (RFC 4791) and CardDAV (RFC 6352) implementation

- CalDAV: MKCALENDAR, PROPFIND, PUT/GET/DELETE events, REPORT calendar-query
- CardDAV: MKCOL, PROPFIND, PUT/GET/DELETE vCards, REPORT addressbook-query
- Fix routing: move CalDAV/CardDAV to top-level merge() with explicit routes
- Fix DB schema: VARCHAR(36) -> UUID for entity IDs, vcard_data -> vcard
- Fix 15 repository stub methods that returned empty results
- Fix vCard parser in ContactStorageAdapter (was hardcoded stub)
- All operations tested end-to-end in Docker (201/207/200/204 as expected)
This commit is contained in:
Dionisio
2026-02-10 18:46:59 +01:00
parent 5bd505ccd7
commit ef9ed2cc31
22 changed files with 3479 additions and 1125 deletions
@@ -344,25 +344,90 @@ impl ContactUseCase for ContactStorageAdapter {
// Check write access
self.check_write_access(&address_book_id, &dto.user_id).await?;
// Parse vCard - for now, create a basic contact with the raw vCard
// Parse vCard fields
let now = chrono::Utc::now();
let vcard_data = &dto.vcard;
let mut uid: Option<String> = None;
let mut full_name: Option<String> = None;
let mut first_name: Option<String> = None;
let mut last_name: Option<String> = None;
let mut nickname: Option<String> = None;
let mut organization: Option<String> = None;
let mut title: Option<String> = None;
let mut notes: Option<String> = None;
let mut emails: Vec<Email> = Vec::new();
let mut phones: Vec<Phone> = Vec::new();
for line in vcard_data.lines() {
let trimmed = line.trim();
if trimmed.starts_with("UID:") {
uid = Some(trimmed[4..].trim().to_string());
} else if trimmed.starts_with("FN:") {
full_name = Some(trimmed[3..].trim().to_string());
} else if trimmed.starts_with("N:") {
let parts: Vec<&str> = trimmed[2..].split(';').collect();
if parts.len() >= 2 {
last_name = Some(parts[0].trim().to_string()).filter(|s| !s.is_empty());
first_name = Some(parts[1].trim().to_string()).filter(|s| !s.is_empty());
}
} else if trimmed.starts_with("NICKNAME:") {
nickname = Some(trimmed[9..].trim().to_string());
} else if trimmed.starts_with("ORG:") {
organization = Some(trimmed[4..].trim().to_string());
} else if trimmed.starts_with("TITLE:") {
title = Some(trimmed[6..].trim().to_string());
} else if trimmed.starts_with("NOTE:") {
notes = Some(trimmed[5..].trim().to_string());
} else if trimmed.starts_with("EMAIL") {
if let Some(value) = trimmed.split(':').nth(1) {
if !value.is_empty() {
let email_type = if trimmed.contains("TYPE=HOME") { "home" }
else if trimmed.contains("TYPE=WORK") { "work" }
else { "other" };
emails.push(Email {
email: value.trim().to_string(),
r#type: email_type.to_string(),
is_primary: emails.is_empty(),
});
}
}
} else if trimmed.starts_with("TEL") {
if let Some(value) = trimmed.split(':').nth(1) {
if !value.is_empty() {
let phone_type = if trimmed.contains("TYPE=CELL") || trimmed.contains("TYPE=MOBILE") { "mobile" }
else if trimmed.contains("TYPE=HOME") { "home" }
else if trimmed.contains("TYPE=WORK") { "work" }
else { "other" };
phones.push(Phone {
number: value.trim().to_string(),
r#type: phone_type.to_string(),
is_primary: phones.is_empty(),
});
}
}
}
}
let contact_uid = uid.unwrap_or_else(|| format!("{}@oxicloud", Uuid::new_v4()));
let contact = Contact::from_raw(
Uuid::new_v4(),
address_book_id,
format!("{}@oxicloud", Uuid::new_v4()),
Some("Imported Contact".to_string()),
None,
None,
None,
Vec::new(),
Vec::new(),
Vec::new(),
None,
None,
None,
None,
None,
None,
contact_uid,
full_name,
first_name,
last_name,
nickname,
emails,
phones,
Vec::new(), // addresses — simplified for now
organization,
title,
notes,
None, // photo_url
None, // birthday
None, // anniversary
dto.vcard,
Uuid::new_v4().to_string(),
now,
@@ -112,10 +112,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
start: &DateTime<Utc>,
end: &DateTime<Utc>
) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
// Para una implementación real, necesitaríamos construir objetos CalendarEvent con un constructor adecuado
// Esta es una implementación simplificada para mostrar cómo evitar las macros query_as!
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -139,15 +136,25 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get events in time range: {}", e)))?;
// En un escenario real, construiríamos objetos CalendarEvent para cada fila
// Aquí solo devolvemos un vector vacío como ejemplo
let events = Vec::new();
// Código para construir eventos desde rows iría aquí
// Por ejemplo:
// for row in rows {
// events.push(CalendarEvent::new(...))
// }
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
events.push(event);
}
Ok(events)
}
@@ -193,8 +200,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
}
async fn list_events_by_calendar(&self, calendar_id: &Uuid) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
// Usamos sqlx::query en lugar de query_as para evitar la necesidad de verificar la base de datos en tiempo de compilación
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -210,20 +216,25 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get events by calendar: {}", e)))?;
// En una implementación real, mapearíamos cada fila a un objeto CalendarEvent
// Este es un ejemplo simplificado que devuelve una lista vacía
let events = Vec::new();
// Ejemplo de cómo sería el mapeo real:
// for row in rows {
// let event = CalendarEvent::new(
// row.get("id"),
// row.get("calendar_id"),
// row.get("summary"),
// // ... otros campos
// );
// events.push(event);
// }
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
events.push(event);
}
Ok(events)
}
@@ -231,7 +242,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
async fn find_events_by_summary(&self, calendar_id: &Uuid, summary: &str) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
let search_pattern = format!("%{}%", summary);
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -248,20 +259,31 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to find events by summary: {}", e)))?;
// En una implementación real, mapearíamos cada fila a un objeto CalendarEvent
// Este es un ejemplo simplificado que devuelve una lista vacía
let events = Vec::new();
// Aquí iría el código para construir eventos desde rows
// for row in rows {
// events.push(CalendarEvent::new(...));
// }
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
events.push(event);
}
Ok(events)
}
async fn find_event_by_ical_uid(&self, calendar_id: &Uuid, ical_uid: &str) -> CalendarEventRepositoryResult<Option<CalendarEvent>> {
let _row_opt = sqlx::query(
let row_opt = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -277,9 +299,27 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get calendar event by UID: {}", e)))?;
// En una implementación real, crearíamos un objeto CalendarEvent a partir de row_opt
// Por simplicidad, devolvemos None como ejemplo
Ok(None)
match row_opt {
Some(row) => {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
Ok(Some(event))
}
None => Ok(None),
}
}
async fn count_events_in_calendar(&self, calendar_id: &Uuid) -> CalendarEventRepositoryResult<i64> {
@@ -319,8 +359,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
limit: i64,
offset: i64
) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
// Usamos sqlx::query en lugar de query_as para evitar la necesidad de verificar la base de datos en tiempo de compilación
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -339,20 +378,25 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get paginated events by calendar: {}", e)))?;
// En una implementación real, mapearíamos cada fila a un objeto CalendarEvent
// Este es un ejemplo simplificado que devuelve una lista vacía
let events = Vec::new();
// Ejemplo de cómo sería el mapeo real:
// for row in rows {
// let event = CalendarEvent::new(
// row.get("id"),
// row.get("calendar_id"),
// row.get("summary"),
// // ... otros campos
// );
// events.push(event);
// }
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
events.push(event);
}
Ok(events)
}
@@ -363,7 +407,7 @@ impl CalendarEventRepository for CalendarEventPgRepository {
start: &DateTime<Utc>,
end: &DateTime<Utc>
) -> CalendarEventRepositoryResult<Vec<CalendarEvent>> {
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, calendar_id, summary, description, location,
@@ -384,28 +428,25 @@ impl CalendarEventRepository for CalendarEventPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to find recurring events in range: {}", e)))?;
// En una implementación real, mapearíamos cada fila a un objeto CalendarEvent
// Por simplicidad, devolvemos una lista vacía de eventos
let events = Vec::new();
// Aquí iría el código para construir los objetos CalendarEvent
// for row in rows {
// events.push(CalendarEvent::with_id(
// row.get("id"),
// row.get("calendar_id"),
// row.get("summary"),
// row.get::<Option<String>, _>("description"),
// row.get::<Option<String>, _>("location"),
// row.get("start_time"),
// row.get("end_time"),
// row.get("all_day"),
// row.get::<Option<String>, _>("rrule"),
// row.get("ical_uid"),
// row.get("ical_data"),
// row.get("created_at"),
// row.get("updated_at")
// ).unwrap());
// }
let mut events = Vec::new();
for row in rows {
let event = CalendarEvent::with_id(
row.get("id"),
row.get("calendar_id"),
row.get("summary"),
row.get::<Option<String>, _>("description"),
row.get::<Option<String>, _>("location"),
row.get("start_time"),
row.get("end_time"),
row.get("all_day"),
row.get::<Option<String>, _>("rrule"),
row.get("ical_uid"),
row.get("ical_data"),
row.get("created_at"),
row.get("updated_at"),
).map_err(|e| DomainError::database_error(format!("Error creating calendar event: {}", e)))?;
events.push(event);
}
Ok(events)
}
@@ -0,0 +1,223 @@
use async_trait::async_trait;
use sqlx::{PgPool, Row, types::Uuid};
use std::sync::Arc;
use chrono::Utc;
use serde_json::Value as JsonValue;
use crate::domain::entities::contact::{Contact, ContactGroup};
use crate::domain::repositories::contact_repository::{ContactGroupRepository, ContactRepositoryResult};
use crate::common::errors::{DomainError, ErrorKind};
use super::contact_persistence_dto::{
emails_from_persistence, phones_from_persistence, addresses_from_persistence,
EmailPersistenceDto, PhonePersistenceDto, AddressPersistenceDto,
};
pub struct ContactGroupPgRepository {
pool: Arc<PgPool>,
}
impl ContactGroupPgRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
}
#[async_trait]
impl ContactGroupRepository for ContactGroupPgRepository {
async fn create_group(&self, group: ContactGroup) -> ContactRepositoryResult<ContactGroup> {
sqlx::query(
"INSERT INTO carddav.contact_groups (id, address_book_id, name, created_at, updated_at) VALUES ($1, $2, $3, $4, $5)"
)
.bind(group.id())
.bind(group.address_book_id())
.bind(group.name())
.bind(group.created_at())
.bind(group.updated_at())
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to create group: {}", e)))?;
Ok(group)
}
async fn update_group(&self, group: ContactGroup) -> ContactRepositoryResult<ContactGroup> {
sqlx::query(
"UPDATE carddav.contact_groups SET name = $1, updated_at = $2 WHERE id = $3"
)
.bind(group.name())
.bind(Utc::now())
.bind(group.id())
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to update group: {}", e)))?;
Ok(group)
}
async fn delete_group(&self, id: &Uuid) -> ContactRepositoryResult<()> {
// Delete memberships first
sqlx::query("DELETE FROM carddav.group_memberships WHERE group_id = $1")
.bind(id)
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to delete group memberships: {}", e)))?;
sqlx::query("DELETE FROM carddav.contact_groups WHERE id = $1")
.bind(id)
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to delete group: {}", e)))?;
Ok(())
}
async fn get_group_by_id(&self, id: &Uuid) -> ContactRepositoryResult<Option<ContactGroup>> {
let row = sqlx::query(
"SELECT id, address_book_id, name, created_at, updated_at FROM carddav.contact_groups WHERE id = $1"
)
.bind(id)
.fetch_optional(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to get group: {}", e)))?;
match row {
Some(row) => {
let group = ContactGroup::from_raw(
row.get::<Uuid, _>("id"),
row.get::<Uuid, _>("address_book_id"),
row.get::<String, _>("name"),
row.get("created_at"),
row.get("updated_at"),
);
Ok(Some(group))
},
None => Ok(None),
}
}
async fn get_groups_by_address_book(&self, address_book_id: &Uuid) -> ContactRepositoryResult<Vec<ContactGroup>> {
let rows = sqlx::query(
"SELECT id, address_book_id, name, created_at, updated_at FROM carddav.contact_groups WHERE address_book_id = $1 ORDER BY name"
)
.bind(address_book_id)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to list groups: {}", e)))?;
Ok(rows.into_iter().map(|row| {
ContactGroup::from_raw(
row.get::<Uuid, _>("id"),
row.get::<Uuid, _>("address_book_id"),
row.get::<String, _>("name"),
row.get("created_at"),
row.get("updated_at"),
)
}).collect())
}
async fn add_contact_to_group(&self, group_id: &Uuid, contact_id: &Uuid) -> ContactRepositoryResult<()> {
sqlx::query(
"INSERT INTO carddav.group_memberships (group_id, contact_id) VALUES ($1, $2) ON CONFLICT DO NOTHING"
)
.bind(group_id)
.bind(contact_id)
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to add contact to group: {}", e)))?;
Ok(())
}
async fn remove_contact_from_group(&self, group_id: &Uuid, contact_id: &Uuid) -> ContactRepositoryResult<()> {
sqlx::query(
"DELETE FROM carddav.group_memberships WHERE group_id = $1 AND contact_id = $2"
)
.bind(group_id)
.bind(contact_id)
.execute(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to remove contact from group: {}", e)))?;
Ok(())
}
async fn get_contacts_in_group(&self, group_id: &Uuid) -> ContactRepositoryResult<Vec<Contact>> {
let rows = sqlx::query(
r#"
SELECT
c.id, c.address_book_id, c.uid, c.full_name, c.first_name, c.last_name, c.nickname,
c.email, c.phone, c.address, c.organization, c.title, c.notes, c.photo_url,
c.birthday, c.anniversary, c.vcard, c.etag, c.created_at, c.updated_at
FROM carddav.contacts c
INNER JOIN carddav.group_memberships gm ON c.id = gm.contact_id
WHERE gm.group_id = $1
ORDER BY c.full_name, c.first_name, c.last_name
"#
)
.bind(group_id)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to get contacts in group: {}", e)))?;
let mut contacts = Vec::new();
for row in &rows {
let email_json: JsonValue = row.get("email");
let phone_json: JsonValue = row.get("phone");
let address_json: JsonValue = row.get("address");
let emails = serde_json::from_value::<Vec<EmailPersistenceDto>>(email_json)
.map(emails_from_persistence)
.unwrap_or_default();
let phones = serde_json::from_value::<Vec<PhonePersistenceDto>>(phone_json)
.map(phones_from_persistence)
.unwrap_or_default();
let addresses = serde_json::from_value::<Vec<AddressPersistenceDto>>(address_json)
.map(addresses_from_persistence)
.unwrap_or_default();
contacts.push(Contact::from_raw(
row.get("id"),
row.get("address_book_id"),
row.get("uid"),
row.get::<Option<String>, _>("full_name"),
row.get::<Option<String>, _>("first_name"),
row.get::<Option<String>, _>("last_name"),
row.get::<Option<String>, _>("nickname"),
emails,
phones,
addresses,
row.get::<Option<String>, _>("organization"),
row.get::<Option<String>, _>("title"),
row.get::<Option<String>, _>("notes"),
row.get::<Option<String>, _>("photo_url"),
row.get("birthday"),
row.get("anniversary"),
row.get("vcard"),
row.get("etag"),
row.get("created_at"),
row.get("updated_at"),
));
}
Ok(contacts)
}
async fn get_groups_for_contact(&self, contact_id: &Uuid) -> ContactRepositoryResult<Vec<ContactGroup>> {
let rows = sqlx::query(
"SELECT g.id, g.address_book_id, g.name, g.created_at, g.updated_at FROM carddav.contact_groups g INNER JOIN carddav.group_memberships gm ON g.id = gm.group_id WHERE gm.contact_id = $1 ORDER BY g.name"
)
.bind(contact_id)
.fetch_all(self.pool.as_ref())
.await
.map_err(|e| DomainError::new(ErrorKind::InternalError, "ContactGroup", format!("Failed to get groups for contact: {}", e)))?;
Ok(rows.into_iter().map(|row| {
ContactGroup::from_raw(
row.get::<Uuid, _>("id"),
row.get::<Uuid, _>("address_book_id"),
row.get::<String, _>("name"),
row.get("created_at"),
row.get("updated_at"),
)
}).collect())
}
}
@@ -1,13 +1,17 @@
use async_trait::async_trait;
use chrono::Utc;
use sqlx::{PgPool, types::Uuid};
use sqlx::{PgPool, Row, types::Uuid};
use std::sync::Arc;
use serde_json::Value as JsonValue;
use crate::domain::entities::contact::Contact;
use crate::domain::repositories::contact_repository::{ContactRepository, ContactRepositoryResult};
use crate::common::errors::DomainError;
use super::contact_persistence_dto::{emails_to_persistence, phones_to_persistence, addresses_to_persistence};
use super::contact_persistence_dto::{
emails_to_persistence, phones_to_persistence, addresses_to_persistence,
emails_from_persistence, phones_from_persistence, addresses_from_persistence,
EmailPersistenceDto, PhonePersistenceDto, AddressPersistenceDto,
};
pub struct ContactPgRepository {
pool: Arc<PgPool>,
@@ -17,6 +21,46 @@ impl ContactPgRepository {
pub fn new(pool: Arc<PgPool>) -> Self {
Self { pool }
}
/// Maps a database row to a Contact domain entity
fn row_to_contact(row: &sqlx::postgres::PgRow) -> Result<Contact, DomainError> {
let email_json: JsonValue = row.get("email");
let phone_json: JsonValue = row.get("phone");
let address_json: JsonValue = row.get("address");
let emails = serde_json::from_value::<Vec<EmailPersistenceDto>>(email_json)
.map(emails_from_persistence)
.unwrap_or_default();
let phones = serde_json::from_value::<Vec<PhonePersistenceDto>>(phone_json)
.map(phones_from_persistence)
.unwrap_or_default();
let addresses = serde_json::from_value::<Vec<AddressPersistenceDto>>(address_json)
.map(addresses_from_persistence)
.unwrap_or_default();
Ok(Contact::from_raw(
row.get("id"),
row.get("address_book_id"),
row.get("uid"),
row.get::<Option<String>, _>("full_name"),
row.get::<Option<String>, _>("first_name"),
row.get::<Option<String>, _>("last_name"),
row.get::<Option<String>, _>("nickname"),
emails,
phones,
addresses,
row.get::<Option<String>, _>("organization"),
row.get::<Option<String>, _>("title"),
row.get::<Option<String>, _>("notes"),
row.get::<Option<String>, _>("photo_url"),
row.get("birthday"),
row.get("anniversary"),
row.get("vcard"),
row.get("etag"),
row.get("created_at"),
row.get("updated_at"),
))
}
}
#[async_trait]
@@ -31,7 +75,7 @@ impl ContactRepository for ContactPgRepository {
let phone_json = serde_json::to_value(&phone_dtos).unwrap_or(JsonValue::Null);
let address_json = serde_json::to_value(&address_dtos).unwrap_or(JsonValue::Null);
let _row = sqlx::query(
let row = sqlx::query(
r#"
INSERT INTO carddav.contacts (
id, address_book_id, uid, full_name, first_name, last_name, nickname,
@@ -72,9 +116,7 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to create contact: {}", e)))?;
// En una implementación real, construiríamos un objeto Contact completo
// Por simplicidad, devolvemos el contacto original
Ok(contact)
Self::row_to_contact(&row)
}
async fn update_contact(&self, contact: Contact) -> ContactRepositoryResult<Contact> {
@@ -92,7 +134,7 @@ impl ContactRepository for ContactPgRepository {
let mut updated_contact = contact.clone();
updated_contact.set_updated_at(now);
let _row = sqlx::query(
let row = sqlx::query(
r#"
UPDATE carddav.contacts
SET
@@ -140,9 +182,7 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to update contact: {}", e)))?;
// En una implementación real, construiríamos un objeto Contact a partir de la fila resultante
// Por simplicidad, devolvemos el contacto con el timestamp actualizado
Ok(updated_contact)
Self::row_to_contact(&row)
}
async fn delete_contact(&self, id: &Uuid) -> ContactRepositoryResult<()> {
@@ -176,13 +216,10 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contact by id: {}", e)))?;
if let Some(_row) = row_opt {
// En una implementación real, construiríamos un objeto Contact a partir de la fila
// Por simplicidad y demostración, devolvemos una instancia predeterminada
return Ok(Some(Contact::default()));
match row_opt {
Some(row) => Ok(Some(Self::row_to_contact(&row)?)),
None => Ok(None),
}
Ok(None)
}
async fn get_contact_by_uid(&self, address_book_id: &Uuid, uid: &str) -> ContactRepositoryResult<Option<Contact>> {
@@ -202,17 +239,14 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contact by uid: {}", e)))?;
if let Some(_row) = row_opt {
// En una implementación real, construiríamos un objeto Contact a partir de la fila
// Por simplicidad y demostración, devolvemos una instancia predeterminada
return Ok(Some(Contact::default()));
match row_opt {
Some(row) => Ok(Some(Self::row_to_contact(&row)?)),
None => Ok(None),
}
Ok(None)
}
async fn get_contacts_by_address_book(&self, address_book_id: &Uuid) -> ContactRepositoryResult<Vec<Contact>> {
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
@@ -228,17 +262,17 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contacts by address book: {}", e)))?;
// En una implementación real, construiríamos objetos Contact a partir de las filas
// Por simplicidad y demostración, devolvemos una lista vacía
let contacts = Vec::new();
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
async fn get_contacts_by_email(&self, email: &str) -> ContactRepositoryResult<Vec<Contact>> {
let search_pattern = format!("%{}%", email);
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
@@ -254,15 +288,15 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contacts by email: {}", e)))?;
// En una implementación real, construiríamos objetos Contact a partir de las filas
// Por simplicidad y demostración, devolvemos una lista vacía
let contacts = Vec::new();
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
async fn get_contacts_by_group(&self, group_id: &Uuid) -> ContactRepositoryResult<Vec<Contact>> {
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
c.id, c.address_book_id, c.uid, c.full_name, c.first_name, c.last_name, c.nickname,
@@ -279,17 +313,17 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to get contacts by group: {}", e)))?;
// En una implementación real, construiríamos objetos Contact a partir de las filas
// Por simplicidad y demostración, devolvemos una lista vacía
let contacts = Vec::new();
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
async fn search_contacts(&self, address_book_id: &Uuid, query: &str) -> ContactRepositoryResult<Vec<Contact>> {
let search_pattern = format!("%{}%", query);
let _rows = sqlx::query(
let rows = sqlx::query(
r#"
SELECT
id, address_book_id, uid, full_name, first_name, last_name, nickname,
@@ -315,10 +349,10 @@ impl ContactRepository for ContactPgRepository {
.await
.map_err(|e| DomainError::database_error(format!("Failed to search contacts: {}", e)))?;
// En una implementación real, construiríamos objetos Contact a partir de las filas
// Por simplicidad y demostración, devolvemos una lista vacía
let contacts = Vec::new();
let mut contacts = Vec::new();
for row in &rows {
contacts.push(Self::row_to_contact(row)?);
}
Ok(contacts)
}
}
@@ -2,6 +2,7 @@ mod address_book_pg_repository;
mod calendar_pg_repository;
mod calendar_event_pg_repository;
mod contact_pg_repository;
mod contact_group_pg_repository;
mod contact_persistence_dto;
mod favorites_pg_repository;
mod recent_items_pg_repository;
@@ -13,6 +14,7 @@ pub use address_book_pg_repository::AddressBookPgRepository;
pub use calendar_pg_repository::CalendarPgRepository;
pub use calendar_event_pg_repository::CalendarEventPgRepository;
pub use contact_pg_repository::ContactPgRepository;
pub use contact_group_pg_repository::ContactGroupPgRepository;
pub use contact_persistence_dto::*;
pub use favorites_pg_repository::FavoritesPgRepository;
pub use recent_items_pg_repository::RecentItemsPgRepository;