api/routes/modules/assignments/files/
delete.rs1use axum::{
2 extract::{State, Path},
3 http::StatusCode,
4 response::IntoResponse,
5 Json,
6};
7use sea_orm::{
8 ActiveModelTrait,
9 ColumnTrait,
10 EntityTrait,
11 QueryFilter,
12};
13use serde_json::json;
14use db::models::assignment_file;
15use util::state::AppState;
16
17pub async fn delete_files(
63 State(app_state): State<AppState>,
64 Path((_, assignment_id)): Path<(i64, i64)>,
65 Json(req): Json<serde_json::Value>,
66) -> impl IntoResponse {
67 let db = app_state.db();
68
69 let file_ids: Vec<i64> = req
70 .get("file_ids")
71 .and_then(|v| v.as_array())
72 .map(|arr| arr.iter().filter_map(|v| v.as_i64()).collect())
73 .unwrap_or_default();
74
75 if file_ids.is_empty() {
76 return (
77 StatusCode::BAD_REQUEST,
78 Json(json!({
79 "success": false,
80 "message": "Request must include a non-empty list of file_ids"
81 })),
82 );
83 }
84
85 let found_models = match assignment_file::Entity::find()
86 .filter(assignment_file::Column::AssignmentId.eq(assignment_id as i32))
87 .filter(assignment_file::Column::Id.is_in(
88 file_ids.iter().copied().map(|id| id as i32).collect::<Vec<_>>(),
89 ))
90 .all(db)
91 .await
92 {
93 Ok(models) => models,
94 Err(_) => {
95 return (
96 StatusCode::NOT_FOUND,
97 Json(json!({
98 "success": false,
99 "message": format!("File(s) not found: {:?}", file_ids)
100 })),
101 );
102 }
103 };
104
105 let found_ids: Vec<i64> = found_models.iter().map(|m| m.id as i64).collect();
106 let missing: Vec<i64> = file_ids
107 .iter()
108 .filter(|id| !found_ids.contains(id))
109 .copied()
110 .collect();
111
112 if !missing.is_empty() {
113 return (
114 StatusCode::NOT_FOUND,
115 Json(json!({
116 "success": false,
117 "message": format!("File(s) not found: {:?}", missing)
118 })),
119 );
120 }
121
122 for file in found_models {
123 let _ = file.delete_file_only();
124 let am: assignment_file::ActiveModel = file.into();
125 let _ = am.delete(db).await;
126 }
127
128 (
129 StatusCode::OK,
130 Json(json!({
131 "success": true,
132 "message": "Files removed successfully"
133 })),
134 )
135}