backbone-bucket 0.3.1

Bucket Bounded Context: File Storage Module for Backbone Framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! ConversionJob 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::{ConversionJobService, ServiceError};

// DTO imports
use crate::presentation::dto::{CreateConversionJobDto, UpdateConversionJobDto, PatchConversionJobDto, ConversionJobResponseDto};

use crate::domain::state_machine::{ConversionJobState, ConversionJobStateMachine, ConversionJobTransition};

/// Application error type
#[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),
    // Domain-specific errors from hook rules
    #[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()
    }
}

/// Domain-specific error codes for ConversionJob
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";
}

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

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

/// Create Axum router with only the read (GET) endpoints for ConversionJob.
///
/// Safe for public, unauthenticated exposure (e.g., reference data).
/// Mutations must be served separately via `create_conversion_job_write_routes`,
/// typically wrapped in an auth middleware layer.
pub fn create_conversion_job_read_routes(service: Arc<ConversionJobService>) -> Router {
    BackboneCrudHandler::<ConversionJobService, ConversionJob, CreateConversionJobDto, UpdateConversionJobDto, ConversionJobResponseDto>::read_routes(
        service,
        "/conversion_jobs",
    )
}

/// Create Axum router with only the write (mutation) endpoints for ConversionJob.
///
/// 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_conversion_job_write_routes(service: Arc<ConversionJobService>) -> Router {
    BackboneCrudHandler::<ConversionJobService, ConversionJob, CreateConversionJobDto, UpdateConversionJobDto, ConversionJobResponseDto>::write_routes(
        service,
        "/conversion_jobs",
    )
}

/// 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_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()
                    }
                }
            }
        }))
}

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

/// Execute start transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/start
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute update_progress transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/update_progress
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute complete transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/complete
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute fail transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/fail
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute cancel_pending transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/cancel_pending
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute cancel_running transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/cancel_running
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute retry transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/retry
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Execute reconvert transition on a ConversionJob.
///
/// POST /conversion_jobs/:id/transitions/reconvert
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};

    // Get current entity
    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()))),
    };

    // Check permission (if auth enabled)
    #[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")));
        }
    }

    // Create state machine from entity's actual status and validate 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")));
    }

    // Apply transition via partial update
    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()))),
    }
}

/// Create routes for state transitions.
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)
}