| 1 | |
| 2 | |
| 3 | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| 8 | |
| 9 | |
| 10 | |
| 11 | use sqlx::types::Json; |
| 12 | |
| 13 | use crate::database::{Database, tx_with_retry}; |
| 14 | use crate::domain::settings::{ExamKindDef, GradeBand, MealSlotDef, Settings}; |
| 15 | use crate::error::AppError; |
| 16 | |
| 17 | |
| 18 | |
| 19 | fn sorted(values: &[String]) -> Vec<String> { |
| 20 | let mut sorted = values.to_vec(); |
| 21 | sorted.sort(); |
| 22 | sorted |
| 23 | } |
| 24 | |
| 25 | |
| 26 | |
| 27 | fn encode_optional( |
| 28 | values: &Option<Json<Vec<String>>>, |
| 29 | ) -> Result<Option<serde_json::Value>, AppError> { |
| 30 | values |
| 31 | .as_ref() |
| 32 | .map(|list| serde_json::to_value(&list.0)) |
| 33 | .transpose() |
| 34 | .map_err(|e| AppError::Internal(format!("settings encode: {e}"))) |
| 35 | } |
| 36 | |
| 37 | |
| 38 | |
| 39 | |
| 40 | async fn load_row<'e, E>(db: E) -> Result<Option<Settings>, AppError> |
| 41 | where |
| 42 | E: sqlx::PgExecutor<'e>, |
| 43 | { |
| 44 | let settings = sqlx::query_as!( |
| 45 | Settings, |
| 46 | r#"SELECT s.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>", |
| 47 | COALESCE((SELECT array_agg(t.status ORDER BY t.status) |
| 48 | FROM settings_attendance_status t |
| 49 | WHERE t.settings = s.id), '{}') AS "attendance_statuses!: Vec<String>", |
| 50 | s.grade_bands AS "grade_bands: Json<Vec<GradeBand>>", |
| 51 | s.max_file_bytes, |
| 52 | s.chatbot_history_turns, |
| 53 | s.max_chatbot_message_len, |
| 54 | s.max_chatbot_threads, |
| 55 | s.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", |
| 56 | (SELECT array_agg(t.tag ORDER BY t.tag) |
| 57 | FROM settings_dietary_tag t |
| 58 | WHERE t.settings = s.id) AS dietary_tags, |
| 59 | s.meal_cancel_cutoff_minutes, |
| 60 | s.branches AS "branches: Json<Vec<String>>", |
| 61 | s.excuse_kinds AS "excuse_kinds: Json<Vec<String>>", |
| 62 | s.max_excused_absent_days, |
| 63 | s.max_unexcused_absent_days, |
| 64 | s.timezone |
| 65 | FROM settings s WHERE s.id = 'school'"# |
| 66 | ) |
| 67 | .fetch_optional(db) |
| 68 | .await?; |
| 69 | Ok(settings) |
| 70 | } |
| 71 | |
| 72 | pub async fn load(db: &Database) -> Result<Settings, AppError> { |
| 73 | let settings = load_row(db).await?; |
| 74 | Ok(settings.unwrap_or_else(Settings::defaults)) |
| 75 | } |
| 76 | |
| 77 | |
| 78 | |
| 79 | |
| 80 | async fn replace_statuses( |
| 81 | conn: &mut sqlx::PgConnection, |
| 82 | statuses: &[String], |
| 83 | ) -> Result<(), AppError> { |
| 84 | sqlx::query!("DELETE FROM settings_attendance_status WHERE settings = 'school'") |
| 85 | .execute(&mut *conn) |
| 86 | .await?; |
| 87 | sqlx::query!( |
| 88 | "INSERT INTO settings_attendance_status (settings, status) |
| 89 | SELECT 'school', t.status FROM unnest($1::text[]) AS t(status)", |
| 90 | statuses, |
| 91 | ) |
| 92 | .execute(&mut *conn) |
| 93 | .await?; |
| 94 | Ok(()) |
| 95 | } |
| 96 | |
| 97 | |
| 98 | |
| 99 | |
| 100 | async fn replace_tags( |
| 101 | conn: &mut sqlx::PgConnection, |
| 102 | tags: Option<&[String]>, |
| 103 | ) -> Result<(), AppError> { |
| 104 | sqlx::query!("DELETE FROM settings_dietary_tag WHERE settings = 'school'") |
| 105 | .execute(&mut *conn) |
| 106 | .await?; |
| 107 | sqlx::query!( |
| 108 | "INSERT INTO settings_dietary_tag (settings, tag) |
| 109 | SELECT 'school', t.tag FROM unnest($1::text[]) AS t(tag)", |
| 110 | tags, |
| 111 | ) |
| 112 | .execute(&mut *conn) |
| 113 | .await?; |
| 114 | Ok(()) |
| 115 | } |
| 116 | |
| 117 | |
| 118 | |
| 119 | |
| 120 | |
| 121 | pub async fn save(db: &Database, settings: Settings) -> Result<Settings, AppError> { |
| 122 | |
| 123 | let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) |
| 124 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 125 | let grade_bands = serde_json::to_value(&settings.grade_bands.0) |
| 126 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 127 | let meal_slots = settings |
| 128 | .meal_slots |
| 129 | .as_ref() |
| 130 | .map(|slots| serde_json::to_value(&slots.0)) |
| 131 | .transpose() |
| 132 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 133 | |
| 134 | |
| 135 | |
| 136 | |
| 137 | let branches = encode_optional(&settings.branches)?; |
| 138 | let excuse_kinds = encode_optional(&settings.excuse_kinds)?; |
| 139 | let attendance = sorted(&settings.attendance_statuses); |
| 140 | let dietary = settings.dietary_tags.clone(); |
| 141 | tx_with_retry(db, true, async move |tx| { |
| 142 | sqlx::query!( |
| 143 | r#"INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes, |
| 144 | chatbot_history_turns, max_chatbot_message_len, |
| 145 | max_chatbot_threads, meal_slots, |
| 146 | meal_cancel_cutoff_minutes, branches, excuse_kinds, |
| 147 | max_excused_absent_days, max_unexcused_absent_days, |
| 148 | timezone) |
| 149 | VALUES ('school', $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13) |
| 150 | ON CONFLICT (id) DO UPDATE SET |
| 151 | exam_kinds = EXCLUDED.exam_kinds, |
| 152 | grade_bands = EXCLUDED.grade_bands, |
| 153 | max_file_bytes = EXCLUDED.max_file_bytes, |
| 154 | chatbot_history_turns = EXCLUDED.chatbot_history_turns, |
| 155 | max_chatbot_message_len = EXCLUDED.max_chatbot_message_len, |
| 156 | max_chatbot_threads = EXCLUDED.max_chatbot_threads, |
| 157 | meal_slots = EXCLUDED.meal_slots, |
| 158 | meal_cancel_cutoff_minutes = EXCLUDED.meal_cancel_cutoff_minutes, |
| 159 | branches = EXCLUDED.branches, |
| 160 | excuse_kinds = EXCLUDED.excuse_kinds, |
| 161 | max_excused_absent_days = EXCLUDED.max_excused_absent_days, |
| 162 | max_unexcused_absent_days = EXCLUDED.max_unexcused_absent_days, |
| 163 | timezone = EXCLUDED.timezone"#, |
| 164 | exam_kinds, |
| 165 | grade_bands, |
| 166 | settings.max_file_bytes, |
| 167 | settings.chatbot_history_turns, |
| 168 | settings.max_chatbot_message_len, |
| 169 | settings.max_chatbot_threads, |
| 170 | meal_slots, |
| 171 | settings.meal_cancel_cutoff_minutes, |
| 172 | branches, |
| 173 | excuse_kinds, |
| 174 | settings.max_excused_absent_days, |
| 175 | settings.max_unexcused_absent_days, |
| 176 | settings.timezone, |
| 177 | ) |
| 178 | .execute(&mut *tx) |
| 179 | .await?; |
| 180 | replace_statuses(&mut *tx, &attendance).await?; |
| 181 | replace_tags(&mut *tx, dietary.as_deref()).await?; |
| 182 | load_row(&mut *tx).await?.ok_or(AppError::NotFound) |
| 183 | }) |
| 184 | .await |
| 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 | pub async fn save_if_unchanged<'e, E>( |
| 216 | db: E, |
| 217 | settings: Settings, |
| 218 | expected: &Settings, |
| 219 | ) -> Result<Option<Settings>, AppError> |
| 220 | where |
| 221 | E: sqlx::PgExecutor<'e>, |
| 222 | { |
| 223 | let exam_kinds = serde_json::to_value(&settings.exam_kinds.0) |
| 224 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 225 | let grade_bands = serde_json::to_value(&settings.grade_bands.0) |
| 226 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 227 | let meal_slots = settings |
| 228 | .meal_slots |
| 229 | .as_ref() |
| 230 | .map(|slots| serde_json::to_value(&slots.0)) |
| 231 | .transpose() |
| 232 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 233 | let expected_exam_kinds = serde_json::to_value(&expected.exam_kinds.0) |
| 234 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 235 | let expected_grade_bands = serde_json::to_value(&expected.grade_bands.0) |
| 236 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 237 | let expected_meal_slots = expected |
| 238 | .meal_slots |
| 239 | .as_ref() |
| 240 | .map(|slots| serde_json::to_value(&slots.0)) |
| 241 | .transpose() |
| 242 | .map_err(|e| AppError::Internal(format!("settings encode: {e}")))?; |
| 243 | let branches = encode_optional(&settings.branches)?; |
| 244 | let excuse_kinds = encode_optional(&settings.excuse_kinds)?; |
| 245 | let expected_branches = encode_optional(&expected.branches)?; |
| 246 | let expected_excuse_kinds = encode_optional(&expected.excuse_kinds)?; |
| 247 | let attendance = sorted(&settings.attendance_statuses); |
| 248 | let expected_attendance = sorted(&expected.attendance_statuses); |
| 249 | |
| 250 | |
| 251 | let expected_dietary = expected |
| 252 | .dietary_tags |
| 253 | .as_ref() |
| 254 | .filter(|tags| !tags.is_empty()) |
| 255 | .map(|tags| tags.as_slice()); |
| 256 | let saved = sqlx::query_as!( |
| 257 | Settings, |
| 258 | r#"WITH new_row AS ( |
| 259 | INSERT INTO settings (id, exam_kinds, grade_bands, max_file_bytes, |
| 260 | chatbot_history_turns, max_chatbot_message_len, |
| 261 | max_chatbot_threads, meal_slots, |
| 262 | meal_cancel_cutoff_minutes, branches, excuse_kinds, |
| 263 | max_excused_absent_days, max_unexcused_absent_days, |
| 264 | timezone) |
| 265 | VALUES ('school', $1, $3, $4, $5, $6, $7, $8, $10, $21, $22, $23, $24, $25) |
| 266 | ON CONFLICT (id) DO UPDATE SET |
| 267 | exam_kinds = $1, |
| 268 | grade_bands = $3, |
| 269 | max_file_bytes = $4, |
| 270 | chatbot_history_turns = $5, |
| 271 | max_chatbot_message_len = $6, |
| 272 | max_chatbot_threads = $7, |
| 273 | meal_slots = $8, |
| 274 | meal_cancel_cutoff_minutes = $10, |
| 275 | branches = $21, |
| 276 | excuse_kinds = $22, |
| 277 | max_excused_absent_days = $23, |
| 278 | max_unexcused_absent_days = $24, |
| 279 | timezone = $25 |
| 280 | WHERE settings.exam_kinds IS NOT DISTINCT FROM $13 |
| 281 | AND settings.grade_bands IS NOT DISTINCT FROM $14 |
| 282 | AND settings.max_file_bytes IS NOT DISTINCT FROM $15 |
| 283 | AND settings.chatbot_history_turns IS NOT DISTINCT FROM $16 |
| 284 | AND settings.max_chatbot_message_len IS NOT DISTINCT FROM $17 |
| 285 | AND settings.max_chatbot_threads IS NOT DISTINCT FROM $18 |
| 286 | AND settings.meal_slots IS NOT DISTINCT FROM $19 |
| 287 | AND settings.meal_cancel_cutoff_minutes IS NOT DISTINCT FROM $20 |
| 288 | AND settings.branches IS NOT DISTINCT FROM $26 |
| 289 | AND settings.excuse_kinds IS NOT DISTINCT FROM $27 |
| 290 | AND settings.max_excused_absent_days IS NOT DISTINCT FROM $28 |
| 291 | AND settings.max_unexcused_absent_days IS NOT DISTINCT FROM $29 |
| 292 | AND settings.timezone IS NOT DISTINCT FROM $30 |
| 293 | AND COALESCE((SELECT array_agg(s.status ORDER BY s.status) |
| 294 | FROM settings_attendance_status s |
| 295 | WHERE s.settings = settings.id), '{}') |
| 296 | IS NOT DISTINCT FROM $11::text[] |
| 297 | AND (SELECT array_agg(t.tag ORDER BY t.tag) |
| 298 | FROM settings_dietary_tag t |
| 299 | WHERE t.settings = settings.id) |
| 300 | IS NOT DISTINCT FROM $12::text[] |
| 301 | RETURNING exam_kinds, grade_bands, max_file_bytes, |
| 302 | chatbot_history_turns, max_chatbot_message_len, |
| 303 | max_chatbot_threads, meal_slots, meal_cancel_cutoff_minutes, |
| 304 | branches, excuse_kinds, max_excused_absent_days, |
| 305 | max_unexcused_absent_days, timezone), |
| 306 | status_del AS ( |
| 307 | DELETE FROM settings_attendance_status |
| 308 | WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row) |
| 309 | RETURNING 1), |
| 310 | status_ins AS ( |
| 311 | INSERT INTO settings_attendance_status (settings, status) |
| 312 | SELECT 'school', t.status FROM unnest($2::text[]) AS t(status) |
| 313 | CROSS JOIN (SELECT count(*) AS deleted FROM status_del) d |
| 314 | WHERE EXISTS (SELECT 1 FROM new_row) |
| 315 | RETURNING status), |
| 316 | tag_del AS ( |
| 317 | DELETE FROM settings_dietary_tag |
| 318 | WHERE settings = 'school' AND EXISTS (SELECT 1 FROM new_row) |
| 319 | RETURNING 1), |
| 320 | tag_ins AS ( |
| 321 | INSERT INTO settings_dietary_tag (settings, tag) |
| 322 | SELECT 'school', t.tag FROM unnest($9::text[]) AS t(tag) |
| 323 | CROSS JOIN (SELECT count(*) AS deleted FROM tag_del) d |
| 324 | WHERE EXISTS (SELECT 1 FROM new_row) |
| 325 | RETURNING tag) |
| 326 | SELECT r.exam_kinds AS "exam_kinds: Json<Vec<ExamKindDef>>", |
| 327 | COALESCE((SELECT array_agg(status ORDER BY status) |
| 328 | FROM status_ins), '{}') AS "attendance_statuses!: Vec<String>", |
| 329 | r.grade_bands AS "grade_bands: Json<Vec<GradeBand>>", |
| 330 | r.max_file_bytes, |
| 331 | r.chatbot_history_turns, |
| 332 | r.max_chatbot_message_len, |
| 333 | r.max_chatbot_threads, |
| 334 | r.meal_slots AS "meal_slots: Json<Vec<MealSlotDef>>", |
| 335 | (SELECT array_agg(tag ORDER BY tag) FROM tag_ins) AS dietary_tags, |
| 336 | r.meal_cancel_cutoff_minutes, |
| 337 | r.branches AS "branches: Json<Vec<String>>", |
| 338 | r.excuse_kinds AS "excuse_kinds: Json<Vec<String>>", |
| 339 | r.max_excused_absent_days, |
| 340 | r.max_unexcused_absent_days, |
| 341 | r.timezone |
| 342 | FROM new_row r"#, |
| 343 | exam_kinds, |
| 344 | &attendance, |
| 345 | grade_bands, |
| 346 | settings.max_file_bytes, |
| 347 | settings.chatbot_history_turns, |
| 348 | settings.max_chatbot_message_len, |
| 349 | settings.max_chatbot_threads, |
| 350 | meal_slots, |
| 351 | settings.dietary_tags.as_deref(), |
| 352 | settings.meal_cancel_cutoff_minutes, |
| 353 | &expected_attendance, |
| 354 | expected_dietary, |
| 355 | expected_exam_kinds, |
| 356 | expected_grade_bands, |
| 357 | expected.max_file_bytes, |
| 358 | expected.chatbot_history_turns, |
| 359 | expected.max_chatbot_message_len, |
| 360 | expected.max_chatbot_threads, |
| 361 | expected_meal_slots, |
| 362 | expected.meal_cancel_cutoff_minutes, |
| 363 | branches, |
| 364 | excuse_kinds, |
| 365 | settings.max_excused_absent_days, |
| 366 | settings.max_unexcused_absent_days, |
| 367 | settings.timezone, |
| 368 | expected_branches, |
| 369 | expected_excuse_kinds, |
| 370 | expected.max_excused_absent_days, |
| 371 | expected.max_unexcused_absent_days, |
| 372 | expected.timezone, |
| 373 | ) |
| 374 | .fetch_optional(db) |
| 375 | .await?; |
| 376 | |
| 377 | Ok(saved) |
| 378 | } |
| 379 | |
| 380 | #[cfg(test)] |
| 381 | mod tests { |
| 382 | |
| 383 | } |