use std::collections::HashMap;
use std::sync::Arc;
use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};
use backbone_core::http::{ApiResponse, BackboneCrudHandler};
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;
use crate::domain::entity::*;
use crate::application::service::{ConversionJobService, ServiceError};
use crate::presentation::dto::{CreateConversionJobDto, UpdateConversionJobDto, PatchConversionJobDto, ConversionJobResponseDto};
use crate::domain::state_machine::{ConversionJobState, ConversionJobStateMachine, ConversionJobTransition};
#[derive(Debug, thiserror::Error)]
pub enum ConversionJobError {
#[error("Not found: {0}")]
NotFound(String),
#[error("Validation error: {0}")]
Validation(String),
#[error("Database error: {0}")]
Database(String),
#[error("Internal error: {0}")]
Internal(String),
#[error("Source file must exist: {0}")]
SourceFileNotFound(String),
#[error("Source file must be accessible: {0}")]
FileNotAccessible(String),
#[error("Target format must be supported: {0}")]
ConversionNotSupported(String),
#[error("Insufficient storage quota for conversion result: {0}")]
InsufficientQuota(String),
#[error("A pending conversion with same params already exists: {0}")]
DuplicateConversion(String),
#[error("Progress cannot decrease: {0}")]
InvalidProgress(String),
}
impl From<ServiceError> for ConversionJobError {
fn from(err: ServiceError) -> Self {
match err {
ServiceError::NotFound => Self::NotFound(err.to_string()),
ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
ServiceError::Repository(ref e) => Self::Database(e.to_string()),
ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
ServiceError::Violations(_) => Self::Validation(err.to_string()),
}
}
}
impl axum::response::IntoResponse for ConversionJobError {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
use axum::Json;
let (status, code) = match &self {
Self::NotFound(_) => (StatusCode::NOT_FOUND, "CONVERSIONJOB_NOT_FOUND"),
Self::Validation(_) => (StatusCode::BAD_REQUEST, "CONVERSIONJOB_VALIDATION_ERROR"),
Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "CONVERSIONJOB_DATABASE_ERROR"),
Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "CONVERSIONJOB_INTERNAL_ERROR"),
Self::SourceFileNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_SOURCE_FILE_NOT_FOUND"),
Self::FileNotAccessible(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_FILE_NOT_ACCESSIBLE"),
Self::ConversionNotSupported(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_CONVERSION_NOT_SUPPORTED"),
Self::InsufficientQuota(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_INSUFFICIENT_QUOTA"),
Self::DuplicateConversion(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_DUPLICATE_CONVERSION"),
Self::InvalidProgress(_) => (StatusCode::UNPROCESSABLE_ENTITY, "CONVERSIONJOB_INVALID_PROGRESS"),
};
let body = serde_json::json!({
"success": false,
"error": code,
"message": self.to_string(),
});
(status, Json(body)).into_response()
}
}
pub mod conversion_job_errors {
pub const SOURCE_FILE_NOT_FOUND: &str = "CONVERSIONJOB_SOURCE_FILE_NOT_FOUND";
pub const FILE_NOT_ACCESSIBLE: &str = "CONVERSIONJOB_FILE_NOT_ACCESSIBLE";
pub const CONVERSION_NOT_SUPPORTED: &str = "CONVERSIONJOB_CONVERSION_NOT_SUPPORTED";
pub const INSUFFICIENT_QUOTA: &str = "CONVERSIONJOB_INSUFFICIENT_QUOTA";
pub const DUPLICATE_CONVERSION: &str = "CONVERSIONJOB_DUPLICATE_CONVERSION";
pub const INVALID_PROGRESS: &str = "CONVERSIONJOB_INVALID_PROGRESS";
}
pub fn create_conversion_job_routes(service: Arc<ConversionJobService>) -> Router {
BackboneCrudHandler::<ConversionJobService, ConversionJob, CreateConversionJobDto, UpdateConversionJobDto, ConversionJobResponseDto>::routes(
service,
"/conversion_jobs",
)
}
pub fn create_conversion_job_read_routes(service: Arc<ConversionJobService>) -> Router {
BackboneCrudHandler::<ConversionJobService, ConversionJob, CreateConversionJobDto, UpdateConversionJobDto, ConversionJobResponseDto>::read_routes(
service,
"/conversion_jobs",
)
}
pub fn create_conversion_job_write_routes(service: Arc<ConversionJobService>) -> Router {
BackboneCrudHandler::<ConversionJobService, ConversionJob, CreateConversionJobDto, UpdateConversionJobDto, ConversionJobResponseDto>::write_routes(
service,
"/conversion_jobs",
)
}
#[cfg(feature = "auth")]
pub fn create_protected_conversion_job_routes<A: AuthMiddleware + Send + Sync + 'static>(
service: Arc<ConversionJobService>,
auth: Arc<A>,
) -> Router {
use axum::middleware;
use axum::response::IntoResponse;
let auth_layer = auth.clone();
create_conversion_job_routes(service)
.layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
let auth = auth_layer.clone();
async move {
let token = req.headers()
.get(axum::http::header::AUTHORIZATION)
.and_then(|h| h.to_str().ok())
.and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
.unwrap_or("");
match auth.authenticate(token).await {
Ok(ctx) => {
req.extensions_mut().insert(ctx);
next.run(req).await
}
Err(_) => {
(axum::http::StatusCode::UNAUTHORIZED,
axum::Json(serde_json::json!({
"success": false,
"error": "unauthorized",
"message": "Authentication required"
}))
).into_response()
}
}
}
}))
}
pub async fn start_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::Start.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:start");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for start transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::Start) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Processing".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn update_progress_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::UpdateProgress.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:update_progress");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for update_progress transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::UpdateProgress) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Processing".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn complete_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::Complete.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:complete");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for complete transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::Complete) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Completed".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn fail_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::Fail.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:fail");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for fail transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::Fail) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Failed".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn cancel_pending_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::CancelPending.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:cancel_pending");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for cancel_pending transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::CancelPending) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Cancelled".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn cancel_running_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::CancelRunning.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:cancel_running");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for cancel_running transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::CancelRunning) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Cancelled".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn retry_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::Retry.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:retry");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for retry transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::Retry) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Pending".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub async fn reconvert_transition(
axum::extract::State(service): axum::extract::State<Arc<ConversionJobService>>,
axum::extract::Path(id): axum::extract::Path<String>,
#[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
) -> impl axum::response::IntoResponse {
use axum::{http::StatusCode, Json};
let entity = match service.get_by_id(&id).await {
Ok(Some(e)) => e,
Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
};
#[cfg(feature = "auth")]
{
let allowed_roles = ConversionJobTransition::Reconvert.allowed_roles();
let has_specific_perm = auth.permissions.iter().any(|p| p == "conversion_job:transition:reconvert");
let has_update_perm = auth.permissions.iter().any(|p| p == "conversion_job:update");
let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
if !has_specific_perm && !has_update_perm && !has_role {
return (StatusCode::FORBIDDEN, Json(ApiResponse::<ConversionJobResponseDto>::error("Insufficient permissions for reconvert transition")));
}
}
let current_state: ConversionJobState = entity.status.to_string().parse()
.unwrap_or(ConversionJobState::default());
let sm = ConversionJobStateMachine::from_state(current_state);
if !sm.can_transition(ConversionJobTransition::Reconvert) {
return (StatusCode::BAD_REQUEST, Json(ApiResponse::<ConversionJobResponseDto>::error("Transition not allowed from current state")));
}
let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
fields.insert("status".to_string(), serde_json::Value::String("Pending".to_string()));
match service.partial_update(&id, fields).await {
Ok(Some(updated)) => {
let response: ConversionJobResponseDto = updated.into();
(StatusCode::OK, Json(ApiResponse::ok(response)))
}
Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<ConversionJobResponseDto>::not_found("ConversionJob", &id))),
Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<ConversionJobResponseDto>::error(e.to_string()))),
}
}
pub fn create_conversion_job_transition_routes(service: Arc<ConversionJobService>) -> Router {
use axum::routing::post;
Router::new()
.route("/conversion_jobs/:id/transitions/start", post(start_transition))
.route("/conversion_jobs/:id/transitions/update_progress", post(update_progress_transition))
.route("/conversion_jobs/:id/transitions/complete", post(complete_transition))
.route("/conversion_jobs/:id/transitions/fail", post(fail_transition))
.route("/conversion_jobs/:id/transitions/cancel_pending", post(cancel_pending_transition))
.route("/conversion_jobs/:id/transitions/cancel_running", post(cancel_running_transition))
.route("/conversion_jobs/:id/transitions/retry", post(retry_transition))
.route("/conversion_jobs/:id/transitions/reconvert", post(reconvert_transition))
.with_state(service)
}