refactor: group use cases into DDD bounded contexts
Flat use_cases/ (44 files) + monolithic commands.rs/queries.rs split into diary/, movies/, watchlist/, import/, auth/, users/, integrations/, search/, person/, federation/ — each with own commands.rs, queries.rs, and use case modules. Inline tests extracted to sibling tests/ dirs.
This commit is contained in:
77
crates/application/src/import/apply_mapping.rs
Normal file
77
crates/application/src/import/apply_mapping.rs
Normal file
@@ -0,0 +1,77 @@
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{AnnotatedRow, import::RowResult},
|
||||
value_objects::{ExternalMetadataId, ImportSessionId, MovieTitle, ReleaseYear, UserId},
|
||||
};
|
||||
|
||||
use crate::{context::AppContext, import::commands::ApplyImportMappingCommand};
|
||||
|
||||
pub async fn execute(
|
||||
ctx: &AppContext,
|
||||
cmd: ApplyImportMappingCommand,
|
||||
) -> Result<Vec<AnnotatedRow>, DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
let session_id = ImportSessionId::from_uuid(cmd.session_id);
|
||||
let mappings = cmd.mappings;
|
||||
let mut session = ctx
|
||||
.repos
|
||||
.import_session
|
||||
.get(&session_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import session".into()))?;
|
||||
|
||||
// clone to avoid borrow conflict when mutating session fields below
|
||||
let parsed = session
|
||||
.parsed_file
|
||||
.clone()
|
||||
.ok_or_else(|| DomainError::ValidationError("session has no parsed file".into()))?;
|
||||
|
||||
let mut annotated = ctx
|
||||
.services
|
||||
.document_parser
|
||||
.apply_mapping(&parsed, &mappings);
|
||||
|
||||
for row in annotated.iter_mut() {
|
||||
if let RowResult::Valid(ref import_row) = row.result {
|
||||
row.is_duplicate = check_duplicate(ctx, import_row).await?;
|
||||
}
|
||||
}
|
||||
|
||||
session.field_mappings = Some(mappings);
|
||||
session.row_results = Some(annotated.clone());
|
||||
|
||||
ctx.repos.import_session.update(&session).await?;
|
||||
|
||||
Ok(annotated)
|
||||
}
|
||||
|
||||
async fn check_duplicate(
|
||||
ctx: &AppContext,
|
||||
row: &domain::models::ImportRow,
|
||||
) -> Result<bool, DomainError> {
|
||||
if let Some(ext_id) = &row.external_metadata_id
|
||||
&& let Ok(eid) = ExternalMetadataId::new(ext_id.clone())
|
||||
&& ctx
|
||||
.repos
|
||||
.movie
|
||||
.get_movie_by_external_id(&eid)
|
||||
.await?
|
||||
.is_some()
|
||||
{
|
||||
return Ok(true);
|
||||
}
|
||||
if let (Some(title), Some(year_str)) = (&row.title, &row.release_year) {
|
||||
let title_vo = MovieTitle::new(title.clone());
|
||||
let year_vo = year_str
|
||||
.parse::<u16>()
|
||||
.ok()
|
||||
.and_then(|y| ReleaseYear::new(y).ok());
|
||||
if let (Ok(t), Some(y)) = (title_vo, year_vo) {
|
||||
let matches = ctx.repos.movie.get_movies_by_title_and_year(&t, &y).await?;
|
||||
if !matches.is_empty() {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(false)
|
||||
}
|
||||
29
crates/application/src/import/apply_profile.rs
Normal file
29
crates/application/src/import/apply_profile.rs
Normal file
@@ -0,0 +1,29 @@
|
||||
use crate::{context::AppContext, import::commands::ApplyImportProfileCommand};
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
value_objects::{ImportProfileId, ImportSessionId, UserId},
|
||||
};
|
||||
|
||||
/// Copies the profile's field_mappings onto the session. Caller must then invoke
|
||||
/// apply_import_mapping to regenerate row_results with the new mappings.
|
||||
pub async fn execute(ctx: &AppContext, cmd: ApplyImportProfileCommand) -> Result<(), DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
let session_id = ImportSessionId::from_uuid(cmd.session_id);
|
||||
let profile_id = ImportProfileId::from_uuid(cmd.profile_id);
|
||||
|
||||
let profile = ctx
|
||||
.repos
|
||||
.import_profile
|
||||
.get(&profile_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import profile".into()))?;
|
||||
let mut session = ctx
|
||||
.repos
|
||||
.import_session
|
||||
.get(&session_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import session".into()))?;
|
||||
session.field_mappings = Some(profile.field_mappings);
|
||||
session.row_results = None;
|
||||
ctx.repos.import_session.update(&session).await
|
||||
}
|
||||
6
crates/application/src/import/cleanup.rs
Normal file
6
crates/application/src/import/cleanup.rs
Normal file
@@ -0,0 +1,6 @@
|
||||
use crate::context::AppContext;
|
||||
use domain::errors::DomainError;
|
||||
|
||||
pub async fn execute(ctx: &AppContext) -> Result<u64, DomainError> {
|
||||
ctx.repos.import_session.delete_expired().await
|
||||
}
|
||||
37
crates/application/src/import/commands.rs
Normal file
37
crates/application/src/import/commands.rs
Normal file
@@ -0,0 +1,37 @@
|
||||
use domain::models::{FieldMapping, FileFormat};
|
||||
use uuid::Uuid;
|
||||
|
||||
pub struct CreateImportSessionCommand {
|
||||
pub user_id: Uuid,
|
||||
pub bytes: Vec<u8>,
|
||||
pub format: FileFormat,
|
||||
}
|
||||
|
||||
pub struct ApplyImportMappingCommand {
|
||||
pub user_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
pub mappings: Vec<FieldMapping>,
|
||||
}
|
||||
|
||||
pub struct ExecuteImportCommand {
|
||||
pub user_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
pub confirmed_indices: Vec<usize>,
|
||||
}
|
||||
|
||||
pub struct SaveImportProfileCommand {
|
||||
pub user_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
pub name: String,
|
||||
}
|
||||
|
||||
pub struct ApplyImportProfileCommand {
|
||||
pub user_id: Uuid,
|
||||
pub session_id: Uuid,
|
||||
pub profile_id: Uuid,
|
||||
}
|
||||
|
||||
pub struct DeleteImportProfileCommand {
|
||||
pub user_id: Uuid,
|
||||
pub profile_id: Uuid,
|
||||
}
|
||||
47
crates/application/src/import/create_session.rs
Normal file
47
crates/application/src/import/create_session.rs
Normal file
@@ -0,0 +1,47 @@
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::ImportSession,
|
||||
value_objects::{ImportSessionId, UserId},
|
||||
};
|
||||
|
||||
use crate::{context::AppContext, import::commands::CreateImportSessionCommand};
|
||||
|
||||
pub struct CreateSessionResult {
|
||||
pub session_id: ImportSessionId,
|
||||
pub columns: Vec<String>,
|
||||
pub sample_rows: Vec<Vec<String>>,
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
ctx: &AppContext,
|
||||
cmd: CreateImportSessionCommand,
|
||||
) -> Result<CreateSessionResult, DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
ctx.repos
|
||||
.import_session
|
||||
.delete_expired_for_user(&user_id)
|
||||
.await?;
|
||||
|
||||
let parsed = ctx
|
||||
.services
|
||||
.document_parser
|
||||
.parse(&cmd.bytes, cmd.format)
|
||||
.map_err(|e| DomainError::ValidationError(e.to_string()))?;
|
||||
|
||||
let sample_rows = parsed.rows.iter().take(5).cloned().collect();
|
||||
let columns = parsed.columns.clone();
|
||||
|
||||
let now = Utc::now().naive_utc();
|
||||
let mut session = ImportSession::new(ImportSessionId::generate(), user_id, now);
|
||||
let session_id = session.id.clone();
|
||||
session.parsed_file = Some(parsed);
|
||||
|
||||
ctx.repos.import_session.create(&session).await?;
|
||||
|
||||
Ok(CreateSessionResult {
|
||||
session_id,
|
||||
columns,
|
||||
sample_rows,
|
||||
})
|
||||
}
|
||||
17
crates/application/src/import/delete_profile.rs
Normal file
17
crates/application/src/import/delete_profile.rs
Normal file
@@ -0,0 +1,17 @@
|
||||
use crate::{context::AppContext, import::commands::DeleteImportProfileCommand};
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
value_objects::{ImportProfileId, UserId},
|
||||
};
|
||||
|
||||
pub async fn execute(ctx: &AppContext, cmd: DeleteImportProfileCommand) -> Result<(), DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
let profile_id = ImportProfileId::from_uuid(cmd.profile_id);
|
||||
|
||||
ctx.repos
|
||||
.import_profile
|
||||
.get(&profile_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import profile".into()))?;
|
||||
ctx.repos.import_profile.delete(&profile_id).await
|
||||
}
|
||||
99
crates/application/src/import/execute.rs
Normal file
99
crates/application/src/import/execute.rs
Normal file
@@ -0,0 +1,99 @@
|
||||
use chrono::NaiveDateTime;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::{ImportRow, import::RowResult},
|
||||
value_objects::{ImportSessionId, UserId},
|
||||
};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::{
|
||||
context::AppContext,
|
||||
diary::commands::{LogReviewCommand, MovieInput},
|
||||
diary::log_review,
|
||||
import::commands::ExecuteImportCommand,
|
||||
};
|
||||
|
||||
pub struct ImportSummary {
|
||||
pub imported: usize,
|
||||
pub skipped_duplicates: usize,
|
||||
pub failed: Vec<(usize, String)>,
|
||||
}
|
||||
|
||||
pub async fn execute(
|
||||
ctx: &AppContext,
|
||||
cmd: ExecuteImportCommand,
|
||||
) -> Result<ImportSummary, DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
let session_id = ImportSessionId::from_uuid(cmd.session_id);
|
||||
let confirmed_indices = cmd.confirmed_indices;
|
||||
let session = ctx
|
||||
.repos
|
||||
.import_session
|
||||
.get(&session_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import session".into()))?;
|
||||
|
||||
let row_results = session.row_results.unwrap_or_default();
|
||||
let confirmed_set: std::collections::HashSet<usize> = confirmed_indices.into_iter().collect();
|
||||
|
||||
let mut imported = 0;
|
||||
let mut skipped_duplicates = 0;
|
||||
let mut failed = Vec::new();
|
||||
|
||||
for (idx, annotated) in row_results.into_iter().enumerate() {
|
||||
if !confirmed_set.contains(&idx) {
|
||||
skipped_duplicates += 1;
|
||||
continue;
|
||||
}
|
||||
match annotated.result {
|
||||
RowResult::Valid(row) => match row_to_command(&row, user_id.value()) {
|
||||
Ok(cmd) => match log_review::execute(ctx, cmd).await {
|
||||
Ok(_) => imported += 1,
|
||||
Err(e) => failed.push((idx, e.to_string())),
|
||||
},
|
||||
Err(e) => failed.push((idx, e)),
|
||||
},
|
||||
RowResult::Invalid { errors, .. } => {
|
||||
failed.push((idx, errors.join("; ")));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
ctx.repos.import_session.delete(&session_id).await?;
|
||||
|
||||
Ok(ImportSummary {
|
||||
imported,
|
||||
skipped_duplicates,
|
||||
failed,
|
||||
})
|
||||
}
|
||||
|
||||
fn row_to_command(row: &ImportRow, user_id: Uuid) -> Result<LogReviewCommand, String> {
|
||||
let rating = row
|
||||
.rating
|
||||
.as_deref()
|
||||
.ok_or("missing rating")?
|
||||
.parse::<u8>()
|
||||
.map_err(|_| "rating is not a valid u8".to_string())?;
|
||||
|
||||
let watched_at_str = row.watched_at.as_deref().ok_or("missing watched_at")?;
|
||||
let watched_at =
|
||||
NaiveDateTime::parse_from_str(&format!("{} 00:00:00", watched_at_str), "%Y-%m-%d %H:%M:%S")
|
||||
.or_else(|_| NaiveDateTime::parse_from_str(watched_at_str, "%Y-%m-%d %H:%M:%S"))
|
||||
.or_else(|_| NaiveDateTime::parse_from_str(watched_at_str, "%Y-%m-%dT%H:%M:%S"))
|
||||
.map_err(|_| format!("cannot parse watched_at: '{}'", watched_at_str))?;
|
||||
|
||||
Ok(LogReviewCommand {
|
||||
user_id,
|
||||
input: MovieInput {
|
||||
movie_id: None,
|
||||
external_metadata_id: row.external_metadata_id.clone(),
|
||||
manual_title: row.title.clone(),
|
||||
manual_release_year: row.release_year.as_deref().and_then(|s| s.parse().ok()),
|
||||
manual_director: row.director.clone(),
|
||||
},
|
||||
rating,
|
||||
comment: row.comment.clone(),
|
||||
watched_at,
|
||||
})
|
||||
}
|
||||
9
crates/application/src/import/list_profiles.rs
Normal file
9
crates/application/src/import/list_profiles.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
use crate::context::AppContext;
|
||||
use domain::{errors::DomainError, models::ImportProfile, value_objects::UserId};
|
||||
|
||||
pub async fn execute(
|
||||
ctx: &AppContext,
|
||||
user_id: &UserId,
|
||||
) -> Result<Vec<ImportProfile>, DomainError> {
|
||||
ctx.repos.import_profile.list_for_user(user_id).await
|
||||
}
|
||||
9
crates/application/src/import/mod.rs
Normal file
9
crates/application/src/import/mod.rs
Normal file
@@ -0,0 +1,9 @@
|
||||
pub mod apply_mapping;
|
||||
pub mod apply_profile;
|
||||
pub mod cleanup;
|
||||
pub mod commands;
|
||||
pub mod create_session;
|
||||
pub mod delete_profile;
|
||||
pub mod execute;
|
||||
pub mod list_profiles;
|
||||
pub mod save_profile;
|
||||
35
crates/application/src/import/save_profile.rs
Normal file
35
crates/application/src/import/save_profile.rs
Normal file
@@ -0,0 +1,35 @@
|
||||
use crate::{context::AppContext, import::commands::SaveImportProfileCommand};
|
||||
use chrono::Utc;
|
||||
use domain::{
|
||||
errors::DomainError,
|
||||
models::ImportProfile,
|
||||
value_objects::{ImportProfileId, ImportSessionId, UserId},
|
||||
};
|
||||
|
||||
pub async fn execute(
|
||||
ctx: &AppContext,
|
||||
cmd: SaveImportProfileCommand,
|
||||
) -> Result<ImportProfileId, DomainError> {
|
||||
let user_id = UserId::from_uuid(cmd.user_id);
|
||||
let session_id = ImportSessionId::from_uuid(cmd.session_id);
|
||||
|
||||
let session = ctx
|
||||
.repos
|
||||
.import_session
|
||||
.get(&session_id, &user_id)
|
||||
.await?
|
||||
.ok_or_else(|| DomainError::NotFound("import session".into()))?;
|
||||
let mappings = session.field_mappings.ok_or_else(|| {
|
||||
DomainError::ValidationError("no mapping applied to this session yet".into())
|
||||
})?;
|
||||
let profile = ImportProfile::new(
|
||||
ImportProfileId::generate(),
|
||||
user_id,
|
||||
cmd.name,
|
||||
mappings,
|
||||
Utc::now().naive_utc(),
|
||||
);
|
||||
let id = profile.id.clone();
|
||||
ctx.repos.import_profile.save(&profile).await?;
|
||||
Ok(id)
|
||||
}
|
||||
Reference in New Issue
Block a user