backbone-events 0.3.30

Events core + the sale/booth/crm/sms/desk overlay — registrations under one authoritative seat counter, the sale seam (order-minted registrations, forward-only paid heal, SO-cancel mirror cascade), booth bookings with the DB exclusivity wall, closed-vocabulary lead rules through a host sink port, the dual-channel (mail/sms) self-arming scheduler, and the exact-match desk verb (Odoo event port, core + overlay)
//! Booth 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;

// 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::{BoothService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateBoothDto, UpdateBoothDto, PatchBoothDto, BoothResponseDto};

use crate::domain::state_machine::{booth_stateState, booth_stateStateMachine, booth_stateTransition};

/// Application error type
#[derive(Debug, thiserror::Error)]
pub enum BoothError {
    #[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 BoothError {
    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 BoothError {
    fn into_response(self) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::Json;

        let (status, code) = match &self {
            Self::NotFound(_) => (StatusCode::NOT_FOUND, "BOOTH_NOT_FOUND"),
            Self::Validation(_) => (StatusCode::BAD_REQUEST, "BOOTH_VALIDATION_ERROR"),
            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BOOTH_DATABASE_ERROR"),
            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "BOOTH_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 Booth.
///
/// # Routes
///
/// | Method | Path | Description |
/// |--------|------|-------------|
/// | GET | /booths | List with pagination |
/// | POST | /booths | Create new |
/// | GET | /booths/:id | Get by ID |
/// | PUT | /booths/:id | Full update |
/// | PATCH | /booths/:id | Partial update |
/// | DELETE | /booths/:id | Soft delete |
/// | POST | /booths/bulk | Bulk create |
/// | POST | /booths/upsert | Upsert |
/// | GET | /booths/trash | List deleted |
/// | POST | /booths/:id/restore | Restore |
/// | DELETE | /booths/empty | Empty trash |
/// | GET | /booths/:id/deleted | Get deleted by ID |
/// | DELETE | /booths/trash/:id | Permanent delete from trash |
/// | GET | /booths/count | Count active entities |
/// | GET | /booths/trash/count | Count deleted entities |
///
/// # Example
///
/// ```text
/// let service = Arc::new(BoothService::with_repository(repository));
/// let router = create_booth_routes(service);
/// ```
pub fn create_booth_routes(service: Arc<BoothService>) -> Router {
    BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::routes(
        service,
        "/booths",
    )
}

/// Create Axum router with only the read (GET) endpoints for Booth.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_booth_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_booth_read_routes(service: Arc<BoothService>) -> Router {
    BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::read_routes(
        service,
        "/booths",
    )
}

/// Create Axum router with only the write (mutation) endpoints for Booth.
///
/// 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_booth_write_routes(service: Arc<BoothService>) -> Router {
    BackboneCrudHandler::<BoothService, Booth, CreateBoothDto, UpdateBoothDto, BoothResponseDto>::write_routes(
        service,
        "/booths",
    )
}

/// 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_booth_routes<A: AuthMiddleware + Send + Sync + 'static>(
    service: Arc<BoothService>,
    auth: Arc<A>,
) -> Router {
    use axum::middleware;
    use axum::response::IntoResponse;

    let auth_layer = auth.clone();
    create_booth_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 confirm transition on a Booth.
///
/// POST /booths/:id/transitions/confirm
pub async fn confirm_transition(
    axum::extract::State(service): axum::extract::State<Arc<BoothService>>,
    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::<BoothResponseDto>::not_found("Booth", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
    };

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

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

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

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

/// Execute release transition on a Booth.
///
/// POST /booths/:id/transitions/release
pub async fn release_transition(
    axum::extract::State(service): axum::extract::State<Arc<BoothService>>,
    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::<BoothResponseDto>::not_found("Booth", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<BoothResponseDto>::error(e.to_string()))),
    };

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

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

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

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

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

    Router::new()
        .route("/booths/:id/transitions/confirm", post(confirm_transition))
        .route("/booths/:id/transitions/release", post(release_transition))
        .with_state(service)
}