1use std::collections::HashMap;
8use std::sync::Arc;
9
10use axum::Router;
11use serde::{Deserialize, Serialize};
12use uuid::Uuid;
13use chrono::{DateTime, Utc};
14
15use backbone_core::http::{ApiResponse, BackboneCrudHandler};
17
18#[cfg(feature = "auth")]
20use backbone_auth::middleware::AuthContext;
21#[cfg(feature = "auth")]
22use backbone_auth::AuthMiddleware;
23
24use crate::domain::entity::*;
26use crate::application::service::{FileCommentService, ServiceError};
27
28use crate::presentation::dto::{CreateFileCommentDto, UpdateFileCommentDto, PatchFileCommentDto, FileCommentResponseDto};
30
31use crate::domain::state_machine::{FileCommentState, FileCommentStateMachine, FileCommentTransition};
32
33#[derive(Debug, thiserror::Error)]
35pub enum FileCommentError {
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 #[error("File must exist: {0}")]
46 FileNotFound(String),
47 #[error("File must be accessible: {0}")]
48 FileNotAccessible(String),
49 #[error("Comment content is required: {0}")]
50 EmptyComment(String),
51 #[error("Comment content max 10000 characters: {0}")]
52 CommentTooLong(String),
53 #[error("Parent comment must exist if provided: {0}")]
54 InvalidParentComment(String),
55 #[error("All mentioned users must exist: {0}")]
56 InvalidMention(String),
57 #[error("Annotation region must be valid JSON: {0}")]
58 InvalidAnnotation(String),
59 #[error("Only comment owner can edit: {0}")]
60 NotCommentOwner(String),
61 #[error("Cannot edit deleted comment: {0}")]
62 CommentDeleted(String),
63 #[error("Cannot edit resolved comment after 5 minutes: {0}")]
64 EditTimeout(String),
65 #[error("Maximum thread depth exceeded: {0}")]
66 MaxThreadDepthExceeded(String),
67}
68
69impl From<ServiceError> for FileCommentError {
70 fn from(err: ServiceError) -> Self {
71 match err {
72 ServiceError::NotFound => Self::NotFound(err.to_string()),
73 ServiceError::Validation(ref msg) => Self::Validation(msg.clone()),
74 ServiceError::AlreadyExists(ref msg) => Self::Validation(msg.clone()),
75 ServiceError::Repository(ref e) => Self::Database(e.to_string()),
76 ServiceError::Internal(ref msg) => Self::Internal(msg.clone()),
77 ServiceError::Violations(_) => Self::Validation(err.to_string()),
78 }
79 }
80}
81
82impl axum::response::IntoResponse for FileCommentError {
83 fn into_response(self) -> axum::response::Response {
84 use axum::http::StatusCode;
85 use axum::Json;
86
87 let (status, code) = match &self {
88 Self::NotFound(_) => (StatusCode::NOT_FOUND, "FILECOMMENT_NOT_FOUND"),
89 Self::Validation(_) => (StatusCode::BAD_REQUEST, "FILECOMMENT_VALIDATION_ERROR"),
90 Self::Database(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_DATABASE_ERROR"),
91 Self::Internal(_) => (StatusCode::INTERNAL_SERVER_ERROR, "FILECOMMENT_INTERNAL_ERROR"),
92 Self::FileNotFound(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_FOUND"),
93 Self::FileNotAccessible(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_FILE_NOT_ACCESSIBLE"),
94 Self::EmptyComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EMPTY_COMMENT"),
95 Self::CommentTooLong(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_TOO_LONG"),
96 Self::InvalidParentComment(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_PARENT_COMMENT"),
97 Self::InvalidMention(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_MENTION"),
98 Self::InvalidAnnotation(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_INVALID_ANNOTATION"),
99 Self::NotCommentOwner(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_NOT_COMMENT_OWNER"),
100 Self::CommentDeleted(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_COMMENT_DELETED"),
101 Self::EditTimeout(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_EDIT_TIMEOUT"),
102 Self::MaxThreadDepthExceeded(_) => (StatusCode::UNPROCESSABLE_ENTITY, "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED"),
103 };
104
105 let body = serde_json::json!({
106 "success": false,
107 "error": code,
108 "message": self.to_string(),
109 });
110
111 (status, Json(body)).into_response()
112 }
113}
114
115pub mod file_comment_errors {
117 pub const FILE_NOT_FOUND: &str = "FILECOMMENT_FILE_NOT_FOUND";
118 pub const FILE_NOT_ACCESSIBLE: &str = "FILECOMMENT_FILE_NOT_ACCESSIBLE";
119 pub const EMPTY_COMMENT: &str = "FILECOMMENT_EMPTY_COMMENT";
120 pub const COMMENT_TOO_LONG: &str = "FILECOMMENT_COMMENT_TOO_LONG";
121 pub const INVALID_PARENT_COMMENT: &str = "FILECOMMENT_INVALID_PARENT_COMMENT";
122 pub const INVALID_MENTION: &str = "FILECOMMENT_INVALID_MENTION";
123 pub const INVALID_ANNOTATION: &str = "FILECOMMENT_INVALID_ANNOTATION";
124 pub const NOT_COMMENT_OWNER: &str = "FILECOMMENT_NOT_COMMENT_OWNER";
125 pub const COMMENT_DELETED: &str = "FILECOMMENT_COMMENT_DELETED";
126 pub const EDIT_TIMEOUT: &str = "FILECOMMENT_EDIT_TIMEOUT";
127 pub const MAX_THREAD_DEPTH_EXCEEDED: &str = "FILECOMMENT_MAX_THREAD_DEPTH_EXCEEDED";
128}
129
130pub fn create_file_comment_routes(service: Arc<FileCommentService>) -> Router {
163 BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::routes(
164 service,
165 "/file_comments",
166 )
167}
168
169pub fn create_file_comment_read_routes(service: Arc<FileCommentService>) -> Router {
175 BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::read_routes(
176 service,
177 "/file_comments",
178 )
179}
180
181pub fn create_file_comment_write_routes(service: Arc<FileCommentService>) -> Router {
193 BackboneCrudHandler::<FileCommentService, FileComment, CreateFileCommentDto, UpdateFileCommentDto, FileCommentResponseDto>::write_routes(
194 service,
195 "/file_comments",
196 )
197}
198
199#[cfg(feature = "auth")]
205pub fn create_protected_file_comment_routes<A: AuthMiddleware + Send + Sync + 'static>(
206 service: Arc<FileCommentService>,
207 auth: Arc<A>,
208) -> Router {
209 use axum::middleware;
210 use axum::response::IntoResponse;
211
212 let auth_layer = auth.clone();
213 create_file_comment_routes(service)
214 .layer(middleware::from_fn(move |mut req: axum::extract::Request, next: axum::middleware::Next| {
215 let auth = auth_layer.clone();
216 async move {
217 let token = req.headers()
218 .get(axum::http::header::AUTHORIZATION)
219 .and_then(|h| h.to_str().ok())
220 .and_then(|raw| raw.strip_prefix("Bearer ").or_else(|| raw.strip_prefix("bearer ")))
221 .unwrap_or("");
222 match auth.authenticate(token).await {
223 Ok(ctx) => {
224 req.extensions_mut().insert(ctx);
225 next.run(req).await
226 }
227 Err(_) => {
228 (axum::http::StatusCode::UNAUTHORIZED,
229 axum::Json(serde_json::json!({
230 "success": false,
231 "error": "unauthorized",
232 "message": "Authentication required"
233 }))
234 ).into_response()
235 }
236 }
237 }
238 }))
239}
240
241pub async fn resolve_transition(
249 axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
250 axum::extract::Path(id): axum::extract::Path<String>,
251 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
252) -> impl axum::response::IntoResponse {
253 use axum::{http::StatusCode, Json};
254
255 let entity = match service.get_by_id(&id).await {
257 Ok(Some(e)) => e,
258 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
259 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
260 };
261
262 #[cfg(feature = "auth")]
264 {
265 let allowed_roles = FileCommentTransition::Resolve.allowed_roles();
266 let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:resolve");
267 let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
268 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
269 if !has_specific_perm && !has_role {
270 if !has_update_perm {
271 return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for resolve transition")));
272 }
273 tracing::warn!(target: "backbone::write_guard", entity = "FileComment", verb = "resolve", code = "transition_by_update_permission", "a transition granted only by file_comment:update, running in shadow; it needs file_comment:transition:resolve or a role of ["owner", "file_owner"]");
274 }
275 }
276
277 let current_state: FileCommentState = match entity.status.to_string().parse() {
279 Ok(s) => s,
280 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileCommentResponseDto>::error("The stored state is not a state of this machine"))),
281 };
282 let sm = FileCommentStateMachine::from_state(current_state);
283 if !sm.can_transition(FileCommentTransition::Resolve) {
284 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
285 }
286
287 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
290 fields.insert("status".to_string(), serde_json::Value::String("resolved".to_string()));
291
292 match backbone_core::write_guard::as_transition("resolve", service.partial_update(&id, fields)).await {
293 Ok(Some(updated)) => {
294 let response: FileCommentResponseDto = updated.into();
295 (StatusCode::OK, Json(ApiResponse::ok(response)))
296 }
297 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
298 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
299 }
300}
301
302pub async fn edit_transition(
306 axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
307 axum::extract::Path(id): axum::extract::Path<String>,
308 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
309) -> impl axum::response::IntoResponse {
310 use axum::{http::StatusCode, Json};
311
312 let entity = match service.get_by_id(&id).await {
314 Ok(Some(e)) => e,
315 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
316 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
317 };
318
319 #[cfg(feature = "auth")]
321 {
322 let allowed_roles = FileCommentTransition::Edit.allowed_roles();
323 let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:edit");
324 let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
325 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
326 if !has_specific_perm && !has_role {
327 if !has_update_perm {
328 return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for edit transition")));
329 }
330 tracing::warn!(target: "backbone::write_guard", entity = "FileComment", verb = "edit", code = "transition_by_update_permission", "a transition granted only by file_comment:update, running in shadow; it needs file_comment:transition:edit or a role of ["owner"]");
331 }
332 }
333
334 let current_state: FileCommentState = match entity.status.to_string().parse() {
336 Ok(s) => s,
337 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileCommentResponseDto>::error("The stored state is not a state of this machine"))),
338 };
339 let sm = FileCommentStateMachine::from_state(current_state);
340 if !sm.can_transition(FileCommentTransition::Edit) {
341 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
342 }
343
344 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
347 fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
348
349 match backbone_core::write_guard::as_transition("edit", service.partial_update(&id, fields)).await {
350 Ok(Some(updated)) => {
351 let response: FileCommentResponseDto = updated.into();
352 (StatusCode::OK, Json(ApiResponse::ok(response)))
353 }
354 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
355 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
356 }
357}
358
359pub async fn delete_active_transition(
363 axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
364 axum::extract::Path(id): axum::extract::Path<String>,
365 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
366) -> impl axum::response::IntoResponse {
367 use axum::{http::StatusCode, Json};
368
369 let entity = match service.get_by_id(&id).await {
371 Ok(Some(e)) => e,
372 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
373 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
374 };
375
376 #[cfg(feature = "auth")]
378 {
379 let allowed_roles = FileCommentTransition::DeleteActive.allowed_roles();
380 let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_active");
381 let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
382 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
383 if !has_specific_perm && !has_role {
384 if !has_update_perm {
385 return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for delete_active transition")));
386 }
387 tracing::warn!(target: "backbone::write_guard", entity = "FileComment", verb = "delete_active", code = "transition_by_update_permission", "a transition granted only by file_comment:update, running in shadow; it needs file_comment:transition:delete_active or a role of ["owner", "file_owner"]");
388 }
389 }
390
391 let current_state: FileCommentState = match entity.status.to_string().parse() {
393 Ok(s) => s,
394 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileCommentResponseDto>::error("The stored state is not a state of this machine"))),
395 };
396 let sm = FileCommentStateMachine::from_state(current_state);
397 if !sm.can_transition(FileCommentTransition::DeleteActive) {
398 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
399 }
400
401 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
404 fields.insert("status".to_string(), serde_json::Value::String("deleted".to_string()));
405
406 match backbone_core::write_guard::as_transition("delete_active", service.partial_update(&id, fields)).await {
407 Ok(Some(updated)) => {
408 let response: FileCommentResponseDto = updated.into();
409 (StatusCode::OK, Json(ApiResponse::ok(response)))
410 }
411 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
412 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
413 }
414}
415
416pub async fn reopen_transition(
420 axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
421 axum::extract::Path(id): axum::extract::Path<String>,
422 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
423) -> impl axum::response::IntoResponse {
424 use axum::{http::StatusCode, Json};
425
426 let entity = match service.get_by_id(&id).await {
428 Ok(Some(e)) => e,
429 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
430 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
431 };
432
433 #[cfg(feature = "auth")]
435 {
436 let allowed_roles = FileCommentTransition::Reopen.allowed_roles();
437 let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:reopen");
438 let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
439 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
440 if !has_specific_perm && !has_role {
441 if !has_update_perm {
442 return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for reopen transition")));
443 }
444 tracing::warn!(target: "backbone::write_guard", entity = "FileComment", verb = "reopen", code = "transition_by_update_permission", "a transition granted only by file_comment:update, running in shadow; it needs file_comment:transition:reopen or a role of ["user"]");
445 }
446 }
447
448 let current_state: FileCommentState = match entity.status.to_string().parse() {
450 Ok(s) => s,
451 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileCommentResponseDto>::error("The stored state is not a state of this machine"))),
452 };
453 let sm = FileCommentStateMachine::from_state(current_state);
454 if !sm.can_transition(FileCommentTransition::Reopen) {
455 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
456 }
457
458 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
461 fields.insert("status".to_string(), serde_json::Value::String("active".to_string()));
462
463 match backbone_core::write_guard::as_transition("reopen", service.partial_update(&id, fields)).await {
464 Ok(Some(updated)) => {
465 let response: FileCommentResponseDto = updated.into();
466 (StatusCode::OK, Json(ApiResponse::ok(response)))
467 }
468 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
469 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
470 }
471}
472
473pub async fn delete_resolved_transition(
477 axum::extract::State(service): axum::extract::State<Arc<FileCommentService>>,
478 axum::extract::Path(id): axum::extract::Path<String>,
479 #[cfg(feature = "auth")] axum::Extension(auth): axum::Extension<AuthContext>,
480) -> impl axum::response::IntoResponse {
481 use axum::{http::StatusCode, Json};
482
483 let entity = match service.get_by_id(&id).await {
485 Ok(Some(e)) => e,
486 Ok(None) => return (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
487 Err(e) => return (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
488 };
489
490 #[cfg(feature = "auth")]
492 {
493 let allowed_roles = FileCommentTransition::DeleteResolved.allowed_roles();
494 let has_specific_perm = auth.permissions.iter().any(|p| p == "file_comment:transition:delete_resolved");
495 let has_update_perm = auth.permissions.iter().any(|p| p == "file_comment:update");
496 let has_role = auth.roles.iter().any(|r| allowed_roles.contains(&r.as_str()));
497 if !has_specific_perm && !has_role {
498 if !has_update_perm {
499 return (StatusCode::FORBIDDEN, Json(ApiResponse::<FileCommentResponseDto>::error("Insufficient permissions for delete_resolved transition")));
500 }
501 tracing::warn!(target: "backbone::write_guard", entity = "FileComment", verb = "delete_resolved", code = "transition_by_update_permission", "a transition granted only by file_comment:update, running in shadow; it needs file_comment:transition:delete_resolved or a role of ["owner", "file_owner"]");
502 }
503 }
504
505 let current_state: FileCommentState = match entity.status.to_string().parse() {
507 Ok(s) => s,
508 Err(_) => return (StatusCode::CONFLICT, Json(ApiResponse::<FileCommentResponseDto>::error("The stored state is not a state of this machine"))),
509 };
510 let sm = FileCommentStateMachine::from_state(current_state);
511 if !sm.can_transition(FileCommentTransition::DeleteResolved) {
512 return (StatusCode::BAD_REQUEST, Json(ApiResponse::<FileCommentResponseDto>::error("Transition not allowed from current state")));
513 }
514
515 let mut fields: HashMap<String, serde_json::Value> = HashMap::new();
518 fields.insert("status".to_string(), serde_json::Value::String("deleted".to_string()));
519
520 match backbone_core::write_guard::as_transition("delete_resolved", service.partial_update(&id, fields)).await {
521 Ok(Some(updated)) => {
522 let response: FileCommentResponseDto = updated.into();
523 (StatusCode::OK, Json(ApiResponse::ok(response)))
524 }
525 Ok(None) => (StatusCode::NOT_FOUND, Json(ApiResponse::<FileCommentResponseDto>::not_found("FileComment", &id))),
526 Err(e) => (StatusCode::INTERNAL_SERVER_ERROR, Json(ApiResponse::<FileCommentResponseDto>::error(e.to_string()))),
527 }
528}
529
530pub fn create_file_comment_transition_routes(service: Arc<FileCommentService>) -> Router {
532 use axum::routing::post;
533
534 Router::new()
535 .route("/file_comments/:id/transitions/resolve", post(resolve_transition))
536 .route("/file_comments/:id/transitions/edit", post(edit_transition))
537 .route("/file_comments/:id/transitions/delete_active", post(delete_active_transition))
538 .route("/file_comments/:id/transitions/reopen", post(reopen_transition))
539 .route("/file_comments/:id/transitions/delete_resolved", post(delete_resolved_transition))
540 .with_state(service)
541}
542