Skip to main content

backbone_bucket/presentation/http/
user_quota_handler.rs

1//! UserQuota REST handlers
2//!
3//! Generated by metaphor-schema. Do not edit manually.
4//!
5//! Uses Axum and backbone-core's BackboneCrudHandler for all 12 CRUD endpoints.
6
7use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use chrono::{DateTime, Utc};
14
15// Backbone framework imports
16use backbone_core::http::{ApiResponse, BackboneCrudHandler};
17
18// Auth integration (optional)
19#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24// Domain imports
25use crate::domain::entity::*;
26use crate::application::service::{UserQuotaService, ServiceError};
27
28// DTO imports
29use crate::presentation::dto::{CreateUserQuotaDto, UpdateUserQuotaDto, PatchUserQuotaDto, UserQuotaResponseDto};
30
31use crate::domain::state_machine::{UserQuotaState, UserQuotaStateMachine, UserQuotaTransition};
32
33/// Application error type
34#[derive(Debug, thiserror::Error)]
35pub enum UserQuotaError {
36    #[error("Not found: {0}")]
37    NotFound(String),
38    #[error("Validation error: {0}")]
39    Validation(String),
40    #[error("Database error: {0}")]
41    Database(String),
42    #[error("Internal error: {0}")]
43    Internal(String),
44    // Domain-specific errors from hook rules
45    #[error("User does not exist: {0}")]
46    UserNotFound(String),
47    #[error("User already has a quota record: {0}")]
48    QuotaExists(String),
49    #[error("Invalid tier. Must be free, pro, or enterprise: {0}")]
50    InvalidTier(String),
51    #[error("Max storage must be positive: {0}")]
52    InvalidMaxStorage(String),
53    #[error("Max file size must be positive: {0}")]
54    InvalidMaxFileSize(String),
55    #[error("Max file size cannot exceed max storage: {0}")]
56    FileSizeExceedsStorage(String),
57    #[error("Cannot downgrade tier: current usage exceeds new quota limits: {0}")]
58    DowngradeNotAllowed(String),
59    #[error("Warning threshold must be between 50 and 99 percent: {0}")]
60    InvalidWarningThreshold(String),
61}
62
63impl From<ServiceError> for UserQuotaError {
64    fn from(err: ServiceError) -> Self {
65        match err {
66            ServiceError::NotFound => Self::NotFound(err.to_string()),
67            ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
68            ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
69            ServiceError::Repository(ref e) => Self::Database(e.to_string()),
70            ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
71            ServiceError::Violations(_) => Self::Validation(err.to_string()),
72        }
73    }
74}
75
76impl axum::response::IntoResponse for UserQuotaError {
77    fn into_response(self) -> axum::response::Response {
78        use axum::http::StatusCode;
79        use axum::Json;
80
81        let (status, code) = match &self {
82            Self::NotFound(_) => (StatusCode::NOT_FOUND, "USERQUOTA_NOT_FOUND"),
83            Self::Validation(_) => (StatusCode::BAD_REQUEST, "USERQUOTA_VALIDATION_ERROR"),
84            Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_DATABASE_ERROR"),
85            Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "USERQUOTA_INTERNAL_ERROR"),
86            Self::UserNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_USER_NOT_FOUND"),
87            Self::QuotaExists(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_QUOTA_EXISTS"),
88            Self::InvalidTier(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_TIER"),
89            Self::InvalidMaxStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_STORAGE"),
90            Self::InvalidMaxFileSize(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_MAX_FILE_SIZE"),
91            Self::FileSizeExceedsStorage(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE"),
92            Self::DowngradeNotAllowed(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_DOWNGRADE_NOT_ALLOWED"),
93            Self::InvalidWarningThreshold(_) => (StatusCode::UNPROCESSABLE_ENTITY, "USERQUOTA_INVALID_WARNING_THRESHOLD"),
94        };
95
96        let body = serde_json::json!({
97            "success": false,
98            "error": code,
99            "message": self.to_string(),
100        });
101
102        (status, Json(body)).into_response()
103    }
104}
105
106/// Domain-specific error codes for UserQuota
107pub mod user_quota_errors {
108    pub const USER_NOT_FOUND: &str = "USERQUOTA_USER_NOT_FOUND";
109    pub const QUOTA_EXISTS: &str = "USERQUOTA_QUOTA_EXISTS";
110    pub const INVALID_TIER: &str = "USERQUOTA_INVALID_TIER";
111    pub const INVALID_MAX_STORAGE: &str = "USERQUOTA_INVALID_MAX_STORAGE";
112    pub const INVALID_MAX_FILE_SIZE: &str = "USERQUOTA_INVALID_MAX_FILE_SIZE";
113    pub const FILE_SIZE_EXCEEDS_STORAGE: &str = "USERQUOTA_FILE_SIZE_EXCEEDS_STORAGE";
114    pub const DOWNGRADE_NOT_ALLOWED: &str = "USERQUOTA_DOWNGRADE_NOT_ALLOWED";
115    pub const INVALID_WARNING_THRESHOLD: &str = "USERQUOTA_INVALID_WARNING_THRESHOLD";
116}
117
118// =============================================================================
119// Route Configuration
120// =============================================================================
121
122/// Create Axum router with all 16 Backbone endpoints for UserQuota.
123///
124/// # Routes
125///
126/// | Method | Path | Description |
127/// |--------|------|-------------|
128/// | GET | /user_quotas | List with pagination |
129/// | POST | /user_quotas | Create new |
130/// | GET | /user_quotas/:id | Get by ID |
131/// | PUT | /user_quotas/:id | Full update |
132/// | PATCH | /user_quotas/:id | Partial update |
133/// | DELETE | /user_quotas/:id | Soft delete |
134/// | POST | /user_quotas/bulk | Bulk create |
135/// | POST | /user_quotas/upsert | Upsert |
136/// | GET | /user_quotas/trash | List deleted |
137/// | POST | /user_quotas/:id/restore | Restore |
138/// | DELETE | /user_quotas/empty | Empty trash |
139/// | GET | /user_quotas/:id/deleted | Get deleted by ID |
140/// | DELETE | /user_quotas/trash/:id | Permanent delete from trash |
141/// | GET | /user_quotas/count | Count active entities |
142/// | GET | /user_quotas/trash/count | Count deleted entities |
143///
144/// # Example
145///
146/// ```text
147/// let service = Arc::new(UserQuotaService::with_repository(repository));
148/// let router = create_user_quota_routes(service);
149/// ```
150pub fn create_user_quota_routes(service: Arc<UserQuotaService>) -> Router {
151    BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::routes(
152        service,
153        "/user_quotas",
154    )
155}
156
157/// Create Axum router with only the read (GET) endpoints for UserQuota.
158///
159/// Safe for public, unauthenticated exposure (e.g., reference data).
160/// Mutations must be served separately via `create_user_quota_write_routes`,
161/// typically wrapped in an auth middleware layer.
162pub fn create_user_quota_read_routes(service: Arc<UserQuotaService>) -> Router {
163    BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::read_routes(
164        service,
165        "/user_quotas",
166    )
167}
168
169/// Create Axum router with only the write (mutation) endpoints for UserQuota.
170///
171/// These routes must NOT be publicly exposed. Wrap them with an auth
172/// middleware before nesting into the application router.
173///
174/// # This is unguarded generic CRUD, not a validated write path
175///
176/// These are plain create/update/patch/delete mutations over the entity row —
177/// they bypass all business invariants. If the module exposes a validated write
178/// service (e.g. a command router over its domain engine), serve THAT instead
179/// for any mutation that must respect domain rules.
180pub fn create_user_quota_write_routes(service: Arc<UserQuotaService>) -> Router {
181    BackboneCrudHandler::<UserQuotaService, UserQuota, CreateUserQuotaDto, UpdateUserQuotaDto, UserQuotaResponseDto>::write_routes(
182        service,
183        "/user_quotas",
184    )
185}
186
187/// Create authenticated routes with auth middleware.
188///
189/// Requires the `auth` feature flag. The `AuthMiddleware` implementation
190/// is responsible for extracting and validating tokens, then providing
191/// an `AuthContext` via request extensions.
192#[cfg(feature = "auth")]
193pub fn create_protected_user_quota_routes<A: AuthMiddleware + Send + Sync + 'static>(
194    service: Arc<UserQuotaService>,
195    auth: Arc<A>,
196) -> Router {
197    use axum::middleware;
198    use axum::response::IntoResponse;
199
200    let auth_layer = auth.clone();
201    create_user_quota_routes(service)
202        .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
203            let auth = auth_layer.clone();
204            async move {
205                let token = req.headers()
206                    .get(axum::http::header::AUTHORIZATION)
207                    .and_then(|h| h.to_str().ok())
208                    .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
209                    .unwrap_or("");
210                match auth.authenticate(token).await {
211                    Ok(ctx) => {
212                        req.extensions_mut().insert(ctx);
213                        next.run(req).await
214                    }
215                    Err(_) => {
216                        (axum::http::StatusCode::UNAUTHORIZED,
217                         axum::Json(serde_json::json!({
218                             "success": false,
219                             "error": "unauthorized",
220                             "message": "Authentication required"
221                         }))
222                        ).into_response()
223                    }
224                }
225            }
226        }))
227}
228
229// =============================================================================
230// State Transition Handlers
231// =============================================================================
232
233/// Execute exceed transition on a UserQuota.
234///
235/// POST /user_quotas/:id/transitions/exceed
236pub async fn exceed_transition(
237    axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
238    axum::extract::Path(id): axum::extract::Path<String>,
239    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
240) -> impl axum::response::IntoResponse {
241    use axum::{http::StatusCode, Json};
242
243    // Get current entity
244    let entity = match service.get_by_id(&id).await {
245        Ok(Some(e)) => e,
246        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
247        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
248    };
249
250    // Check permission (if auth enabled)
251    #[cfg(feature = "auth")]
252    {
253        let allowed_roles = UserQuotaTransition::Exceed.allowed_roles();
254        let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:exceed");
255        let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota:update");
256        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
257        if !has_specific_perm && !has_role {
258            if !has_update_perm {
259                return (StatusCode::FORBIDDEN, Json(ApiResponse::<UserQuotaResponseDto>::error("Insufficient permissions for exceed transition")));
260            }
261            tracing::warn!(target: "backbone::write_guard", entity = "UserQuota", verb = "exceed", code = "transition_by_update_permission", "a transition granted only by user_quota:update, running in shadow; it needs user_quota:transition:exceed or a role of ["system"]");
262        }
263    }
264
265    // Create state machine from entity's actual status and validate transition
266    let current_state: UserQuotaState = match entity.quota_status.to_string().parse() {
267        Ok(s) => s,
268        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<UserQuotaResponseDto>::error("The stored state is not a state of this machine"))),
269    };
270    let sm = UserQuotaStateMachine::from_state(current_state);
271    if !sm.can_transition(UserQuotaTransition::Exceed) {
272        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<UserQuotaResponseDto>::error("Transition not allowed from current state")));
273    }
274
275    // Guard `used_storage_bytes >= max_storage_bytes` not compiled (`used_storage_bytes` is not a field of UserQuota); the transition is not checked against it.
276    // Apply transition via partial update
277    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
278    fields.insert("quota_status".to_string(), serde_json::Value::String("exceeded".to_string()));
279
280    match backbone_core::write_guard::as_transition("exceed", service.partial_update(&id, fields)).await {
281        Ok(Some(updated)) => {
282            let response: UserQuotaResponseDto = updated.into();
283            (StatusCode::OK, Json(ApiResponse::ok(response)))
284        }
285        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
286        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
287    }
288}
289
290/// Execute restore transition on a UserQuota.
291///
292/// POST /user_quotas/:id/transitions/restore
293pub async fn restore_transition(
294    axum::extract::State(service): axum::extract::State<Arc<UserQuotaService>>,
295    axum::extract::Path(id): axum::extract::Path<String>,
296    #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
297) -> impl axum::response::IntoResponse {
298    use axum::{http::StatusCode, Json};
299
300    // Get current entity
301    let entity = match service.get_by_id(&id).await {
302        Ok(Some(e)) => e,
303        Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
304        Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
305    };
306
307    // Check permission (if auth enabled)
308    #[cfg(feature = "auth")]
309    {
310        let allowed_roles = UserQuotaTransition::Restore.allowed_roles();
311        let has_specific_perm = auth.permissions.iter().any(|p| p == "user_quota:transition:restore");
312        let has_update_perm = auth.permissions.iter().any(|p| p == "user_quota:update");
313        let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
314        if !has_specific_perm && !has_role {
315            if !has_update_perm {
316                return (StatusCode::FORBIDDEN, Json(ApiResponse::<UserQuotaResponseDto>::error("Insufficient permissions for restore transition")));
317            }
318            tracing::warn!(target: "backbone::write_guard", entity = "UserQuota", verb = "restore", code = "transition_by_update_permission", "a transition granted only by user_quota:update, running in shadow; it needs user_quota:transition:restore or a role of ["system"]");
319        }
320    }
321
322    // Create state machine from entity's actual status and validate transition
323    let current_state: UserQuotaState = match entity.quota_status.to_string().parse() {
324        Ok(s) => s,
325        Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<UserQuotaResponseDto>::error("The stored state is not a state of this machine"))),
326    };
327    let sm = UserQuotaStateMachine::from_state(current_state);
328    if !sm.can_transition(UserQuotaTransition::Restore) {
329        return (StatusCode::BAD_REQUEST, Json(ApiResponse::<UserQuotaResponseDto>::error("Transition not allowed from current state")));
330    }
331
332    // Guard `used_storage_bytes < max_storage_bytes` not compiled (`used_storage_bytes` is not a field of UserQuota); the transition is not checked against it.
333    // Apply transition via partial update
334    let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
335    fields.insert("quota_status".to_string(), serde_json::Value::String("normal".to_string()));
336
337    match backbone_core::write_guard::as_transition("restore", service.partial_update(&id, fields)).await {
338        Ok(Some(updated)) => {
339            let response: UserQuotaResponseDto = updated.into();
340            (StatusCode::OK, Json(ApiResponse::ok(response)))
341        }
342        Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<UserQuotaResponseDto>::not_found("UserQuota", &id))),
343        Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<UserQuotaResponseDto>::error(e.to_string()))),
344    }
345}
346
347/// Create routes for state transitions.
348pub fn create_user_quota_transition_routes(service: Arc<UserQuotaService>) -> Router {
349    use axum::routing::post;
350
351    Router::new()
352        .route("/user_quotas/:id/transitions/exceed", post(exceed_transition))
353        .route("/user_quotas/:id/transitions/restore", post(restore_transition))
354        .with_state(service)
355}
356