backbone-bucket 0.4.0

Bucket Bounded Context: File Storage Module for Backbone Framework
Documentation
//! UserQuota 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::{UserQuotaService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateUserQuotaDto, UpdateUserQuotaDto, PatchUserQuotaDto, UserQuotaResponseDto};

use crate::domain::state_machine::{UserQuotaState, UserQuotaStateMachine, UserQuotaTransition};

/// Application error type
#[derive(Debug, thiserror::Error)]
pub enum UserQuotaError {
    #[error("Not found: {0}")]
    NotFound(String),
    #[error("Validation error: {0}")]
    Validation(String),
    #[error("Database error: {0}")]
    Database(String),
    #[error("Internal error: {0}")]
    Internal(String),
    // Domain-specific errors from hook rules
    #[error("User does not exist: {0}")]
    UserNotFound(String),
    #[error("User already has a quota record: {0}")]
    QuotaExists(String),
    #[error("Invalid tier. Must be free, pro, or enterprise: {0}")]
    InvalidTier(String),
    #[error("Max storage must be positive: {0}")]
    InvalidMaxStorage(String),
    #[error("Max file size must be positive: {0}")]
    InvalidMaxFileSize(String),
    #[error("Max file size cannot exceed max storage: {0}")]
    FileSizeExceedsStorage(String),
    #[error("Cannot downgrade tier: current usage exceeds new quota limits: {0}")]
    DowngradeNotAllowed(String),
    #[error("Warning threshold must be between 50 and 99 percent: {0}")]
    InvalidWarningThreshold(String),
}

impl From<ServiceError> for UserQuotaError {
    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 UserQuotaError {
    fn into_response(self) -> axum::response::Response {
        use axum::http::StatusCode;
        use axum::Json;

        let (status, code) = match &self {
            Self::NotFound(_) => (StatusCode::NOT_FOUND, "USERQUOTA_NOT_FOUND"),
            Self::Validation(_) => (StatusCode::BAD_REQUEST, "USERQUOTA_VALIDATION_ERROR"),
            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_DATABASE_ERROR"),
            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_INTERNAL_ERROR"),
            Self::UserNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_USER_NOT_FOUND"),
            Self::QuotaExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_QUOTA_EXISTS"),
            Self::InvalidTier(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_TIER"),
            Self::InvalidMaxStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_STORAGE"),
            Self::InvalidMaxFileSize(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_FILE_SIZE"),
            Self::FileSizeExceedsStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE"),
            Self::DowngradeNotAllowed(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_DOWNGRADE_NOT_ALLOWED"),
            Self::InvalidWarningThreshold(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_WARNING_THRESHOLD"),
        };

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

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

/// Domain-specific error codes for UserQuota
pub mod user_quota_errors {
    pub const USER_NOT_FOUND: &str = "USERQUOTA_USER_NOT_FOUND";
    pub const QUOTA_EXISTS: &str = "USERQUOTA_QUOTA_EXISTS";
    pub const INVALID_TIER: &str = "USERQUOTA_INVALID_TIER";
    pub const INVALID_MAX_STORAGE: &str = "USERQUOTA_INVALID_MAX_STORAGE";
    pub const INVALID_MAX_FILE_SIZE: &str = "USERQUOTA_INVALID_MAX_FILE_SIZE";
    pub const FILE_SIZE_EXCEEDS_STORAGE: &str = "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE";
    pub const DOWNGRADE_NOT_ALLOWED: &str = "USERQUOTA_DOWNGRADE_NOT_ALLOWED";
    pub const INVALID_WARNING_THRESHOLD: &str = "USERQUOTA_INVALID_WARNING_THRESHOLD";
}

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

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

/// Create Axum router with only the read (GET) endpoints for UserQuota.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_user_quota_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_user_quota_read_routes(service: Arc<UserQuotaService>) -> Router {
    BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::read_routes(
        service,
        "/user_quotas",
    )
}

/// Create Axum router with only the write (mutation) endpoints for UserQuota.
///
/// 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_user_quota_write_routes(service: Arc<UserQuotaService>) -> Router {
    BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::write_routes(
        service,
        "/user_quotas",
    )
}

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

    let auth_layer = auth.clone();
    create_user_quota_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 exceed transition on a UserQuota.
///
/// POST /user_quotas/:id/transitions/exceed
pub async fn exceed_transition(
    axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
    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::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = UserQuotaTransition::Exceed.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:exceed");
        let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota: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::<UserQuotaResponseDto>::error("Insufficient permissions for exceed transition")));
        }
    }

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

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

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

/// Execute restore transition on a UserQuota.
///
/// POST /user_quotas/:id/transitions/restore
pub async fn restore_transition(
    axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
    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::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
    };

    // Check permission (if auth enabled)
    #[cfg(feature = "auth")]
    {
        let allowed_roles = UserQuotaTransition::Restore.allowed_roles();
        let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:restore");
        let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota: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::<UserQuotaResponseDto>::error("Insufficient permissions for restore transition")));
        }
    }

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

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

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

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

    Router::new()
        .route("/user_quotas/:id/transitions/exceed", post(exceed_transition))
        .route("/user_quotas/:id/transitions/restore", post(restore_transition))
        .with_state(service)
}