backbone-mail 0.2.32

Odoo mail core port — message/notification/followers/activity/alias/sms queue (schema: messaging)
//! MailPresence REST handlers
//!
//! Generated by metaphor-schema. Do not edit manually.
//!
//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.

use std::collections::HashMap;
use std::sync::Arc;

use axum::Router;
use serde::{Deserialize, Serialize};
use uuid::Uuid;
use chrono::{DateTime, Utc};

// Backbone framework imports
use backbone_core::http::{ApiResponse, BackboneCrudHandler};

// Auth integration (optional)
#[cfg(feature = "auth")]
use backbone_auth::middleware::AuthContext;
#[cfg(feature = "auth")]
use backbone_auth::AuthMiddleware;

// Domain imports
use crate::domain::entity::*;
use crate::application::service::{MailPresenceService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateMailPresenceDto, UpdateMailPresenceDto, PatchMailPresenceDto, MailPresenceResponseDto};

use crate::domain::state_machine::{MailPresenceHooksState, MailPresenceHooksStateMachine, MailPresenceHooksTransition};

/// Application error type
#[derive(Debug, thiserror::Error)]
pub enum MailPresenceError {
    #[error("Not found: {0}")]
    NotFound(String),
    #[error("Validation error: {0}")]
    Validation(String),
    #[error("Database error: {0}")]
    Database(String),
    #[error("Internal error: {0}")]
    Internal(String),
}

impl From<ServiceError> for MailPresenceError {
    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()),
        }
    }
}

impl axum::response::IntoResponse for MailPresenceError {
    fn into_response(self) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::Json;

        let (status, code) = match &self {
            Self::NotFound(_) => (StatusCode::NOT_FOUND, "MAILPRESENCE_NOT_FOUND"),
            Self::Validation(_) => (StatusCode::BAD_REQUEST, "MAILPRESENCE_VALIDATION_ERROR"),
            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILPRESENCE_DATABASE_ERROR"),
            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "MAILPRESENCE_INTERNAL_ERROR"),
        };

        let body = serde_json::json!({
            "success": false,
            "error": code,
            "message": self.to_string(),
        });

        (status, Json(body)).into_response()
    }
}

// =============================================================================
// Route Configuration
// =============================================================================

/// Create Axum router with all 16 Backbone endpoints for MailPresence.
///
/// # Routes
///
/// | Method | Path | Description |
/// |--------|------|-------------|
/// | GET | /mail_presences | List with pagination |
/// | POST | /mail_presences | Create new |
/// | GET | /mail_presences/:id | Get by ID |
/// | PUT | /mail_presences/:id | Full update |
/// | PATCH | /mail_presences/:id | Partial update |
/// | DELETE | /mail_presences/:id | Soft delete |
/// | POST | /mail_presences/bulk | Bulk create |
/// | POST | /mail_presences/upsert | Upsert |
/// | GET | /mail_presences/trash | List deleted |
/// | POST | /mail_presences/:id/restore | Restore |
/// | DELETE | /mail_presences/empty | Empty trash |
/// | GET | /mail_presences/:id/deleted | Get deleted by ID |
/// | DELETE | /mail_presences/trash/:id | Permanent delete from trash |
/// | GET | /mail_presences/count | Count active entities |
/// | GET | /mail_presences/trash/count | Count deleted entities |
///
/// # Example
///
/// ```text
/// let service = Arc::new(MailPresenceService::with_repository(repository));
/// let router = create_mail_presence_routes(service);
/// ```
pub fn create_mail_presence_routes(service: Arc<MailPresenceService>) -> Router {
    BackboneCrudHandler::<MailPresenceService, MailPresence, CreateMailPresenceDto, UpdateMailPresenceDto, MailPresenceResponseDto>::routes(
        service,
        "/mail_presences",
    )
}

/// Create Axum router with only the read (GET) endpoints for MailPresence.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_mail_presence_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_mail_presence_read_routes(service: Arc<MailPresenceService>) -> Router {
    BackboneCrudHandler::<MailPresenceService, MailPresence, CreateMailPresenceDto, UpdateMailPresenceDto, MailPresenceResponseDto>::read_routes(
        service,
        "/mail_presences",
    )
}

/// Create Axum router with only the write (mutation) endpoints for MailPresence.
///
/// These routes must NOT be publicly exposed. Wrap them with an auth
/// middleware before nesting into the application router.
///
/// # This is unguarded generic CRUD, not a validated write path
///
/// These are plain create/update/patch/delete mutations over the entity row —
/// they bypass all business invariants. If the module exposes a validated write
/// service (e.g. a command router over its domain engine), serve THAT instead
/// for any mutation that must respect domain rules.
pub fn create_mail_presence_write_routes(service: Arc<MailPresenceService>) -> Router {
    BackboneCrudHandler::<MailPresenceService, MailPresence, CreateMailPresenceDto, UpdateMailPresenceDto, MailPresenceResponseDto>::write_routes(
        service,
        "/mail_presences",
    )
}

/// Create authenticated routes with auth middleware.
///
/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
/// is responsible for extracting and validating tokens, then providing
/// an `AuthContext` via request extensions.
#[cfg(feature = "auth")]
pub fn create_protected_mail_presence_routes<A: AuthMiddleware + Send + Sync + 'static>(
    service: Arc<MailPresenceService>,
    auth: Arc<A>,
) -> Router {
    use axum::middleware;
    use axum::response::IntoResponse;

    let auth_layer = auth.clone();
    create_mail_presence_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()
                    }
                }
            }
        }))
}

// =============================================================================
// State Transition Handlers
// =============================================================================

/// Execute go_online transition on a MailPresence.
///
/// POST /mail_presences/:id/transitions/go_online
pub async fn go_online_transition(
    axum::extract::State(service): axum::extract::State<Arc<MailPresenceService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = MailPresenceHooksTransition::GoOnline.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_presence:transition:go_online");
        let has_update_perm = auth.permissions.iter().any(|p| p == "mail_presence:update");
        if !has_specific_perm && !has_update_perm {
            return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailPresenceResponseDto>::error("Insufficient permissions for go_online transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: MailPresenceHooksState = entity.status.to_string().parse()
        .unwrap_or(MailPresenceHooksState::default());
    let sm = MailPresenceHooksStateMachine::from_state(current_state);
    if !sm.can_transition(MailPresenceHooksTransition::GoOnline) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailPresenceResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("Online".to_string()));

    match service.partial_update(&id, fields).await {
        Ok(Some(updated)) => {
            let response: MailPresenceResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    }
}

/// Execute go_away transition on a MailPresence.
///
/// POST /mail_presences/:id/transitions/go_away
pub async fn go_away_transition(
    axum::extract::State(service): axum::extract::State<Arc<MailPresenceService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = MailPresenceHooksTransition::GoAway.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_presence:transition:go_away");
        let has_update_perm = auth.permissions.iter().any(|p| p == "mail_presence:update");
        if !has_specific_perm && !has_update_perm {
            return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailPresenceResponseDto>::error("Insufficient permissions for go_away transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: MailPresenceHooksState = entity.status.to_string().parse()
        .unwrap_or(MailPresenceHooksState::default());
    let sm = MailPresenceHooksStateMachine::from_state(current_state);
    if !sm.can_transition(MailPresenceHooksTransition::GoAway) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailPresenceResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("Away".to_string()));

    match service.partial_update(&id, fields).await {
        Ok(Some(updated)) => {
            let response: MailPresenceResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    }
}

/// Execute go_offline transition on a MailPresence.
///
/// POST /mail_presences/:id/transitions/go_offline
pub async fn go_offline_transition(
    axum::extract::State(service): axum::extract::State<Arc<MailPresenceService>>,
    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};

    // Get current entity
    let entity = match service.get_by_id(&id).await {
        Ok(Some(e)) => e,
        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = MailPresenceHooksTransition::GoOffline.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "mail_presence:transition:go_offline");
        let has_update_perm = auth.permissions.iter().any(|p| p == "mail_presence:update");
        if !has_specific_perm && !has_update_perm {
            return (StatusCode::FORBIDDEN, Json(ApiResponse::<MailPresenceResponseDto>::error("Insufficient permissions for go_offline transition")));
        }
    }

    // Create state machine from entity's actual status and validate transition
    let current_state: MailPresenceHooksState = entity.status.to_string().parse()
        .unwrap_or(MailPresenceHooksState::default());
    let sm = MailPresenceHooksStateMachine::from_state(current_state);
    if !sm.can_transition(MailPresenceHooksTransition::GoOffline) {
        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<MailPresenceResponseDto>::error("Transition not allowed from current state")));
    }

    // Apply transition via partial update
    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
    fields.insert("status".to_string(), serde_json::Value::String("Offline".to_string()));

    match service.partial_update(&id, fields).await {
        Ok(Some(updated)) => {
            let response: MailPresenceResponseDto = updated.into();
            (StatusCode::OK, Json(ApiResponse::ok(response)))
        }
        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<MailPresenceResponseDto>::not_found("MailPresence", &id))),
        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<MailPresenceResponseDto>::error(e.to_string()))),
    }
}

/// Create routes for state transitions.
pub fn create_mail_presence_transition_routes(service: Arc<MailPresenceService>) -> Router {
    use axum::routing::post;

    Router::new()
        .route("/mail_presences/:id/transitions/go_online", post(go_online_transition))
        .route("/mail_presences/:id/transitions/go_away", post(go_away_transition))
        .route("/mail_presences/:id/transitions/go_offline", post(go_offline_transition))
        .with_state(service)
}