hezarfen_frontend
Clone
https://git.tahinli.com/Hezarfen/hezarfen_frontend.git
0 watching0 forksTypeScript5.5 MiB5fcd955Burak Boduroğlu2 months ago730 commits
| 1 | import type { Locale } from "@/i18n/messages"; |
| 2 | |
| 3 | export class ApiError extends Error { |
| 4 | readonly status: number; |
| 5 | readonly retryAfter: number | null; |
| 6 | /** Set when the school has this route's module switched off (`403 {error, module}`). */ |
| 7 | readonly module: string | null; |
| 8 | /** Machine refusal code (`{error, code}`), sent only where a route documents one. */ |
| 9 | readonly code: string | null; |
| 10 | |
| 11 | constructor( |
| 12 | status: number, |
| 13 | message: string, |
| 14 | retryAfter: number | null = null, |
| 15 | module: string | null = null, |
| 16 | code: string | null = null, |
| 17 | ) { |
| 18 | super(message); |
| 19 | this.name = "ApiError"; |
| 20 | this.status = status; |
| 21 | this.retryAfter = retryAfter; |
| 22 | this.module = module; |
| 23 | this.code = code; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | /** True for a refusal because the school's module is off, not a role or record problem. */ |
| 28 | export function isModuleDisabledError(err: unknown): err is ApiError & { module: string } { |
| 29 | return err instanceof ApiError && err.status === 403 && err.module != null; |
| 30 | } |
| 31 | |
| 32 | // A builder can switch a module off mid-session; the backend then answers |
| 33 | // `403 {error, module}` on every route of it. Listeners (the modules context) |
| 34 | // hear about it on the first such refusal and refetch the enabled set, so the |
| 35 | // nav and route gate catch up without a reload. |
| 36 | const moduleDisabledListeners = new Set<(module: string) => void>(); |
| 37 | |
| 38 | export function onModuleDisabled(listener: (module: string) => void): () => void { |
| 39 | moduleDisabledListeners.add(listener); |
| 40 | return () => moduleDisabledListeners.delete(listener); |
| 41 | } |
| 42 | |
| 43 | function disabledModuleOf(status: number, data: unknown): string | null { |
| 44 | if (status !== 403 || !data || typeof data !== "object") return null; |
| 45 | const module = (data as { module?: unknown }).module; |
| 46 | if (typeof module !== "string" || !module) return null; |
| 47 | for (const listener of moduleDisabledListeners) listener(module); |
| 48 | return module; |
| 49 | } |
| 50 | |
| 51 | type RequestOptions = { |
| 52 | method?: "GET" | "POST" | "PATCH" | "DELETE"; |
| 53 | body?: unknown; |
| 54 | signal?: AbortSignal; |
| 55 | cache?: RequestCache; |
| 56 | }; |
| 57 | |
| 58 | const API_PREFIX = "/api"; |
| 59 | |
| 60 | // Deadline for a JSON request. Generous enough for the slowest real call |
| 61 | // (login's Argon2 hash under load), short enough that a hung socket surfaces |
| 62 | // as an error instead of a permanently disabled button. |
| 63 | const REQUEST_TIMEOUT_MS = 20_000; |
| 64 | |
| 65 | const API_ERROR_MESSAGES: Record<string, Record<Locale, string>> = { |
| 66 | // Settings lists reject two entries that fold to the same word — İZİN/izin, |
| 67 | // ÖDEV/odev. Keyed on the whole normalized string, so both fields are listed. |
| 68 | "exam_kinds: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": { |
| 69 | en: "Two exam kinds are the same word apart from upper/lower case or Turkish letters. Keep only one of them.", |
| 70 | tr: "İki sınav türü, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.", |
| 71 | }, |
| 72 | "attendance_statuses: two entries are the same word apart from upper/lower case or turkish letters — keep only one of them": { |
| 73 | en: "Two attendance statuses are the same word apart from upper/lower case or Turkish letters. Keep only one of them.", |
| 74 | tr: "İki yoklama durumu, büyük/küçük harf veya Türkçe harf farkı dışında aynı. Sadece birini bırak.", |
| 75 | }, |
| 76 | "request failed": { |
| 77 | en: "Request failed.", |
| 78 | tr: "İşlem tamamlanamadı.", |
| 79 | }, |
| 80 | "unauthorized": { |
| 81 | en: "Sign in to continue.", |
| 82 | tr: "Devam etmek için giriş yap.", |
| 83 | }, |
| 84 | "forbidden": { |
| 85 | en: "You do not have permission for this action.", |
| 86 | tr: "Bu işlem için yetkin yok.", |
| 87 | }, |
| 88 | "not found": { |
| 89 | en: "The requested record was not found.", |
| 90 | tr: "İstenen kayıt bulunamadı.", |
| 91 | }, |
| 92 | "invalid credentials": { |
| 93 | en: "Username or password is incorrect.", |
| 94 | tr: "Kullanıcı adı veya şifre hatalı.", |
| 95 | }, |
| 96 | "username already exists": { |
| 97 | en: "This username is already in use.", |
| 98 | tr: "Bu kullanıcı adı zaten kullanılıyor.", |
| 99 | }, |
| 100 | "file too large": { |
| 101 | en: "This file is larger than the allowed upload limit.", |
| 102 | tr: "Bu dosya izin verilen yükleme sınırından büyük.", |
| 103 | }, |
| 104 | "payload too large": { |
| 105 | en: "This upload is too large. Choose a smaller file and try again.", |
| 106 | tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", |
| 107 | }, |
| 108 | "request entity too large": { |
| 109 | en: "This upload is too large. Choose a smaller file and try again.", |
| 110 | tr: "Bu yükleme çok büyük. Daha küçük bir dosya seçip tekrar dene.", |
| 111 | }, |
| 112 | "unsupported file type": { |
| 113 | en: "This file type is not supported.", |
| 114 | tr: "Bu dosya türü desteklenmiyor.", |
| 115 | }, |
| 116 | "unsupported image type": { |
| 117 | en: "This image type is not supported. Use PNG, JPEG, WebP, or GIF.", |
| 118 | tr: "Bu görsel türü desteklenmiyor. PNG, JPEG, WebP veya GIF kullan.", |
| 119 | }, |
| 120 | "invalid image": { |
| 121 | en: "The image could not be read. Choose another image and try again.", |
| 122 | tr: "Görsel okunamadı. Başka bir görsel seçip tekrar dene.", |
| 123 | }, |
| 124 | "too many files": { |
| 125 | en: "This note already has the maximum number of files.", |
| 126 | tr: "Bu notta en fazla dosya sayısına ulaşılmış.", |
| 127 | }, |
| 128 | "note file limit reached": { |
| 129 | en: "This note already has the maximum number of files.", |
| 130 | tr: "Bu notta en fazla dosya sayısına ulaşılmış.", |
| 131 | }, |
| 132 | "this time overlaps a slot you have already published": { |
| 133 | en: "This time overlaps a slot you already published.", |
| 134 | tr: "Bu zaman aralığı, daha önce yayınladığın bir müsaitlikle çakışıyor.", |
| 135 | }, |
| 136 | "a repeated slot overlaps one you have already published": { |
| 137 | en: "One of the repeated slots overlaps a slot you already published.", |
| 138 | tr: "Tekrarlanan müsaitliklerden biri, daha önce yayınladığın bir müsaitlikle çakışıyor.", |
| 139 | }, |
| 140 | "the repeated slots overlap each other": { |
| 141 | en: "The repeated slots overlap each other.", |
| 142 | tr: "Tekrarlanan müsaitlikler birbiriyle çakışıyor.", |
| 143 | }, |
| 144 | // Builder surface (web/builder.rs, tenant.rs) — byte-exact. |
| 145 | "that account is not an admin of this school": { |
| 146 | en: "That account exists but is not an admin of this school.", |
| 147 | tr: "Bu hesap var ama bu okulun yöneticisi değil.", |
| 148 | }, |
| 149 | "school is suspended": { |
| 150 | en: "This school is suspended.", |
| 151 | tr: "Bu okul askıya alınmış.", |
| 152 | }, |
| 153 | // Booking/decision conflicts from domain/appointment.rs — byte-exact. |
| 154 | "the slot is already booked": { |
| 155 | en: "Someone else booked this time first.", |
| 156 | tr: "Bu saati senden önce başkası aldı.", |
| 157 | }, |
| 158 | "the slot has already started": { |
| 159 | en: "This time has already started, so it can no longer be booked.", |
| 160 | tr: "Bu saat başladığı için artık randevu alınamaz.", |
| 161 | }, |
| 162 | "you already have an appointment at that time": { |
| 163 | en: "You already have an appointment at that time.", |
| 164 | tr: "O saatte zaten bir randevun var.", |
| 165 | }, |
| 166 | "the appointment is already settled": { |
| 167 | en: "This appointment is already settled.", |
| 168 | tr: "Bu randevu zaten sonuçlanmış.", |
| 169 | }, |
| 170 | "the appointment has already started": { |
| 171 | en: "This appointment has already started.", |
| 172 | tr: "Bu randevu çoktan başladı.", |
| 173 | }, |
| 174 | "that time has already started": { |
| 175 | en: "That time has already started. Pick a later one.", |
| 176 | tr: "O saat çoktan başladı. Daha ileri bir saat seç.", |
| 177 | }, |
| 178 | "no time has been proposed": { |
| 179 | en: "No time has been proposed for this appointment yet.", |
| 180 | tr: "Bu randevu için henüz bir saat önerilmedi.", |
| 181 | }, |
| 182 | "the appointment is no longer pending": { |
| 183 | en: "This appointment is no longer waiting for an answer.", |
| 184 | tr: "Bu randevu artık yanıt bekliyor değil.", |
| 185 | }, |
| 186 | "question: this question did not come from a bank template": { |
| 187 | en: "This question was not copied from a bank template, so there is nothing to refresh it from.", |
| 188 | tr: "Bu soru bir banka şablonundan kopyalanmadığı için yenilenecek bir kaynağı yok.", |
| 189 | }, |
| 190 | "request timed out": { |
| 191 | en: "The server did not respond in time. Check your connection and try again.", |
| 192 | tr: "Sunucu zamanında yanıt vermedi. Bağlantını kontrol edip tekrar dene.", |
| 193 | }, |
| 194 | "only the template's owner or an admin can change it": { |
| 195 | en: "Only the teacher who created this template (or an admin) can change it.", |
| 196 | tr: "Bu şablonu yalnızca onu oluşturan öğretmen (veya bir yönetici) değiştirebilir.", |
| 197 | }, |
| 198 | "only the course creator, an assigned teacher, or a manager/admin can author questions": { |
| 199 | en: "Only this course's teachers or a manager can add questions to this exam.", |
| 200 | tr: "Bu sınava yalnızca dersin öğretmenleri veya bir müdür soru ekleyebilir.", |
| 201 | }, |
| 202 | "only the course creator, an assigned teacher, or a manager/admin can save questions to the bank": { |
| 203 | en: "Only this course's teachers or a manager can save this question to the bank.", |
| 204 | tr: "Bu soruyu bankaya yalnızca dersin öğretmenleri veya bir müdür kaydedebilir.", |
| 205 | }, |
| 206 | "cannot change questions after attempts have started": { |
| 207 | en: "Students have already started this exam, so its questions can no longer change.", |
| 208 | tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", |
| 209 | }, |
| 210 | "bank questions still reference this subject — re-tag or delete them first": { |
| 211 | en: "Question bank templates still use this subject. Re-tag or delete them first.", |
| 212 | tr: "Soru bankasındaki şablonlar hâlâ bu konuyu kullanıyor. Önce onları başka konuya taşı veya sil.", |
| 213 | }, |
| 214 | "the term is archived — past years are read-only": { |
| 215 | en: "This term is archived. Past years are read-only.", |
| 216 | tr: "Bu dönem arşivli. Geçmiş dönemler salt okunur.", |
| 217 | }, |
| 218 | "this course's term is archived — past years are read-only": { |
| 219 | en: "This course's term is archived. Past years are read-only.", |
| 220 | tr: "Bu dersin dönemi arşivli. Geçmiş dönemler salt okunur.", |
| 221 | }, |
| 222 | "module disabled": { |
| 223 | en: "This feature is not enabled for your school.", |
| 224 | tr: "Bu özellik okulunuz için etkin değil.", |
| 225 | }, |
| 226 | "course not found": { |
| 227 | en: "Course not found.", |
| 228 | tr: "Ders bulunamadı.", |
| 229 | }, |
| 230 | "exam not found": { |
| 231 | en: "Exam not found.", |
| 232 | tr: "Sınav bulunamadı.", |
| 233 | }, |
| 234 | "not enrolled in this exam's course": { |
| 235 | en: "You are not enrolled in this exam's course.", |
| 236 | tr: "Bu sınavın dersine kayıtlı değilsin.", |
| 237 | }, |
| 238 | "you are not enrolled in this exam's course": { |
| 239 | en: "You are not enrolled in this exam's course.", |
| 240 | tr: "Bu sınavın dersine kayıtlı değilsin.", |
| 241 | }, |
| 242 | "exam is not scheduled": { |
| 243 | en: "This exam is not scheduled for online sitting.", |
| 244 | tr: "Bu sınav çevrim içi oturum için zamanlanmamış.", |
| 245 | }, |
| 246 | "attempt not found": { |
| 247 | en: "Start the exam before opening the exam room.", |
| 248 | tr: "Sınav odasını açmadan önce sınavı başlat.", |
| 249 | }, |
| 250 | "attempt is closed": { |
| 251 | en: "This attempt is closed. Answers are read-only.", |
| 252 | tr: "Bu oturum kapalı. Cevaplar salt okunur.", |
| 253 | }, |
| 254 | "exam has not started": { |
| 255 | en: "This exam has not started yet.", |
| 256 | tr: "Bu sınav henüz başlamadı.", |
| 257 | }, |
| 258 | "exam has ended": { |
| 259 | en: "This exam has ended.", |
| 260 | tr: "Bu sınav sona erdi.", |
| 261 | }, |
| 262 | "no attempts left": { |
| 263 | en: "No attempts left for this exam.", |
| 264 | tr: "Bu sınav için deneme hakkı kalmadı.", |
| 265 | }, |
| 266 | "answer is required": { |
| 267 | en: "Enter an answer before saving.", |
| 268 | tr: "Kaydetmeden önce cevap gir.", |
| 269 | }, |
| 270 | "only students can sit exams": { |
| 271 | en: "Only students can take exams.", |
| 272 | tr: "Sınava yalnızca öğrenciler girebilir.", |
| 273 | }, |
| 274 | "user_id: only students can be enrolled in a course": { |
| 275 | en: "Only students can be enrolled in a course.", |
| 276 | tr: "Derse yalnızca öğrenciler kaydedilebilir.", |
| 277 | }, |
| 278 | "user_id: only students can be graded": { |
| 279 | en: "Only students can be graded.", |
| 280 | tr: "Yalnızca öğrencilere not verilebilir.", |
| 281 | }, |
| 282 | "user_id: only students can be marked present in a lesson": { |
| 283 | en: "Only students can be marked on a lesson roll call.", |
| 284 | tr: "Ders yoklamasında yalnızca öğrenciler işaretlenebilir.", |
| 285 | }, |
| 286 | "event is full": { |
| 287 | en: "This event is full.", |
| 288 | tr: "Bu etkinlik dolu.", |
| 289 | }, |
| 290 | "registration is closed": { |
| 291 | en: "Registration is closed for this event.", |
| 292 | tr: "Bu etkinlik için kayıt kapalı.", |
| 293 | }, |
| 294 | "already registered": { |
| 295 | en: "This student is already registered.", |
| 296 | tr: "Bu öğrenci zaten kayıtlı.", |
| 297 | }, |
| 298 | "already enrolled": { |
| 299 | en: "This student is already enrolled.", |
| 300 | tr: "Bu öğrenci zaten kayıtlı.", |
| 301 | }, |
| 302 | "active pomodoro session already exists": { |
| 303 | en: "You already have a focus session running.", |
| 304 | tr: "Zaten devam eden bir odak oturumun var.", |
| 305 | }, |
| 306 | "no active pomodoro session": { |
| 307 | en: "There is no active focus session to finish.", |
| 308 | tr: "Bitirilecek aktif odak oturumu yok.", |
| 309 | }, |
| 310 | }; |
| 311 | |
| 312 | type LocalizedMessage = Record<Locale, string>; |
| 313 | |
| 314 | const ARCHIVED_YEAR: LocalizedMessage = { |
| 315 | en: "This academic year is archived. Past years are read-only, so records in it can no longer change.", |
| 316 | tr: "Bu eğitim yılı arşivlendi. Geçmiş yıllar salt okunur, bu yüzden içindeki kayıtlar artık değiştirilemez.", |
| 317 | }; |
| 318 | |
| 319 | const STUDENT_NUMBER_TAKEN: LocalizedMessage = { |
| 320 | en: "Another student already has this student number. Enter a different number.", |
| 321 | tr: "Bu öğrenci numarası başka bir öğrencide kayıtlı. Farklı bir numara gir.", |
| 322 | }; |
| 323 | |
| 324 | const STALE_RECORD: LocalizedMessage = { |
| 325 | en: "This record changed while you were editing it. Reload the page and try again.", |
| 326 | tr: "Bu kayıt sen düzenlerken değişti. Sayfayı yenileyip tekrar dene.", |
| 327 | }; |
| 328 | |
| 329 | /** |
| 330 | * Machine refusal codes (`{error, code}`). The backend sends one only where a |
| 331 | * route documents its vocabulary (class attach/add-member, podcast, insight |
| 332 | * report, student numbers), so these win over the prose whenever present. |
| 333 | * `duplicate` is left out on purpose: it means a course on one route and a |
| 334 | * student on another, so the prose patterns below tell them apart. |
| 335 | */ |
| 336 | const API_ERROR_CODE_MESSAGES: Record<string, LocalizedMessage> = { |
| 337 | academic_year_archived: ARCHIVED_YEAR, |
| 338 | class_at_course_ceiling: { |
| 339 | en: "This class already has the maximum number of courses. Remove a course from it before adding another.", |
| 340 | tr: "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.", |
| 341 | }, |
| 342 | class_roster_too_large: { |
| 343 | en: "This class has too many students to enroll in a course in one step. Contact your system administrator.", |
| 344 | tr: "Bu şubede bir derse tek seferde kaydedilemeyecek kadar çok öğrenci var. Sistem yöneticine başvur.", |
| 345 | }, |
| 346 | class_at_roster_ceiling: { |
| 347 | en: "This class is full. Remove a student from it before adding another.", |
| 348 | tr: "Bu şube dolu. Yeni öğrenci eklemeden önce şubeden bir öğrenci çıkar.", |
| 349 | }, |
| 350 | class_course_list_too_large: { |
| 351 | en: "This class has too many courses to enroll a student in one step. Contact your system administrator.", |
| 352 | tr: "Bu şubede bir öğrenciyi tek seferde kaydetmek için çok fazla ders var. Sistem yöneticine başvur.", |
| 353 | }, |
| 354 | linked_course_missing: { |
| 355 | en: "One of this class's courses was removed while the student was being added. Reload the page and try again.", |
| 356 | tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.", |
| 357 | }, |
| 358 | student_number_taken: STUDENT_NUMBER_TAKEN, |
| 359 | session_time_taken: { |
| 360 | en: "Another lesson of this section already starts at this time. Pick a different start time.", |
| 361 | tr: "Bu şubenin başka bir dersi zaten bu saatte başlıyor. Farklı bir başlangıç saati seç.", |
| 362 | }, |
| 363 | offering_exists: { |
| 364 | en: "This course already has a template for this grade. Edit the existing template instead.", |
| 365 | tr: "Bu dersin bu seviye için zaten bir şablonu var. Bunun yerine mevcut şablonu düzenle.", |
| 366 | }, |
| 367 | offering_in_use: { |
| 368 | en: "Classes still teach from this template. Detach the course from those classes first.", |
| 369 | tr: "Bu şablondan hâlâ ders işleyen şubeler var. Önce dersi o şubelerden çıkar.", |
| 370 | }, |
| 371 | slot_overlap: { |
| 372 | en: "Another slot on this day overlaps this time window. Pick a different time.", |
| 373 | tr: "Bu gündeki başka bir ders saati bu zaman aralığıyla çakışıyor. Farklı bir saat seç.", |
| 374 | }, |
| 375 | slot_cap: { |
| 376 | en: "This weekly plan already holds the maximum number of slots. Remove one before adding another.", |
| 377 | tr: "Bu haftalık plan en fazla ders saati sayısına ulaştı. Yenisini eklemeden önce birini kaldır.", |
| 378 | }, |
| 379 | unknown_exam_kind: { |
| 380 | en: "This exam kind is not one the school uses. Pick a kind from the school settings.", |
| 381 | tr: "Bu sınav türü okulun kullandığı türlerden biri değil. Okul ayarlarındaki türlerden birini seç.", |
| 382 | }, |
| 383 | instance_has_no_weekly_plan: { |
| 384 | en: "This section has no weekly plan yet. Add slots before generating lessons.", |
| 385 | tr: "Bu şubenin henüz haftalık planı yok. Ders üretmeden önce ders saati ekle.", |
| 386 | }, |
| 387 | instance_has_no_teacher: { |
| 388 | en: "No teacher is assigned to this section. Assign a teacher before generating lessons.", |
| 389 | tr: "Bu şubeye atanmış öğretmen yok. Ders üretmeden önce bir öğretmen ata.", |
| 390 | }, |
| 391 | not_ready: { |
| 392 | en: "This audio is not ready yet. Wait for it to finish and try again.", |
| 393 | tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.", |
| 394 | }, |
| 395 | audio_missing: { |
| 396 | en: "This audio file could not be found on the server. Generate the episode again.", |
| 397 | tr: "Bu ses dosyası sunucuda bulunamadı. Bölümü yeniden oluştur.", |
| 398 | }, |
| 399 | source_missing: { |
| 400 | en: "This note has no PDF to narrate. Attach a PDF to the note and try again.", |
| 401 | tr: "Bu notta seslendirilecek bir PDF yok. Nota bir PDF ekleyip tekrar dene.", |
| 402 | }, |
| 403 | report_missing: { |
| 404 | en: "No report has been generated for this day yet.", |
| 405 | tr: "Bu gün için henüz rapor oluşturulmadı.", |
| 406 | }, |
| 407 | report_empty: { |
| 408 | en: "There is no data for this day to build a report from.", |
| 409 | tr: "Bu gün için rapor oluşturacak veri yok.", |
| 410 | }, |
| 411 | report_refused: { |
| 412 | en: "The AI service declined to write this report. Try again later.", |
| 413 | tr: "Yapay zekâ servisi bu raporu hazırlamayı reddetti. Daha sonra tekrar dene.", |
| 414 | }, |
| 415 | }; |
| 416 | |
| 417 | /** |
| 418 | * Backend refusals that carry no code, matched on the stable part of their |
| 419 | * prose (the nouns and the "still linked / in use / already" verb) rather than |
| 420 | * byte-exact, so a reworded tail or a different em dash still lands. Checked |
| 421 | * in order after the exact table; keep each pattern specific enough that it |
| 422 | * cannot swallow an unrelated reason. |
| 423 | */ |
| 424 | const API_ERROR_PATTERNS: ReadonlyArray<readonly [RegExp, LocalizedMessage]> = [ |
| 425 | [ |
| 426 | /\b(classes|terms)\b.*\bstill linked to this (academic )?year\b/, |
| 427 | { |
| 428 | en: "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.", |
| 429 | tr: "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.", |
| 430 | }, |
| 431 | ], |
| 432 | [/\bacademic year is archived\b|\bin an archived academic year\b/, ARCHIVED_YEAR], |
| 433 | [ |
| 434 | /\btarget year already (holds|has) classes\b/, |
| 435 | { |
| 436 | en: "The target year already has classes. Choose an empty year to carry the classes into.", |
| 437 | tr: "Hedef eğitim yılında zaten şubeler var. Şubeleri aktarmak için boş bir yıl seç.", |
| 438 | }, |
| 439 | ], |
| 440 | [ |
| 441 | /\b(academic )?year (with|named) (that|this) name already exists\b|\bacademic year .*already exists\b/, |
| 442 | { |
| 443 | en: "An academic year with this name already exists. Choose a different name.", |
| 444 | tr: "Bu adla bir eğitim yılı zaten var. Farklı bir ad seç.", |
| 445 | }, |
| 446 | ], |
| 447 | [ |
| 448 | /\b(students|instances|courses)\b.*\bstill (on|in|attached to) this class\b/, |
| 449 | { |
| 450 | en: "This class still has students or courses. Remove its students and detach its courses before deleting it.", |
| 451 | tr: "Bu şubede hâlâ öğrenci veya ders var. Silmeden önce öğrencileri şubeden çıkar ve dersleri şubeden kaldır.", |
| 452 | }, |
| 453 | ], |
| 454 | [ |
| 455 | /\bclass(es)? still teach(es)? this course\b|\bstudents still hold an individual membership\b/, |
| 456 | { |
| 457 | en: "A class still teaches this course, or students are still enrolled in it directly. Detach it from its classes and remove those students before deleting it.", |
| 458 | tr: "Bu ders hâlâ bir şubede okutuluyor ya da derse doğrudan kayıtlı öğrenciler var. Silmeden önce dersi şubelerden çıkar ve bu öğrencileri dersten kaldır.", |
| 459 | }, |
| 460 | ], |
| 461 | [ |
| 462 | /\b(exams|karnes?)\b.*\bstill belong to this term\b/, |
| 463 | { |
| 464 | en: "Exams or finalized report cards still belong to this term, so it cannot be deleted. Archive it instead.", |
| 465 | tr: "Bu döneme bağlı sınavlar veya kesinleşmiş karneler var, bu yüzden dönem silinemez. Bunun yerine dönemi arşivle.", |
| 466 | }, |
| 467 | ], |
| 468 | [ |
| 469 | /\b(exam questions|questions|homework)\b.*\bstill reference this subject\b/, |
| 470 | { |
| 471 | en: "Exam questions or homework still use this subject. Move them to another subject or delete them first.", |
| 472 | tr: "Sınav soruları veya ödevler hâlâ bu konuyu kullanıyor. Önce onları başka bir konuya taşı veya sil.", |
| 473 | }, |
| 474 | ], |
| 475 | [ |
| 476 | /\bmenu still has (live |active )?bookings\b/, |
| 477 | { |
| 478 | en: "This menu still has bookings. Cancel them before deleting the menu.", |
| 479 | tr: "Bu menüde hâlâ rezervasyonlar var. Menüyü silmeden önce rezervasyonları iptal et.", |
| 480 | }, |
| 481 | ], |
| 482 | [ |
| 483 | /\b(slot|occurrence) has an? (pending or approved )?(booking|appointment)\b/, |
| 484 | { |
| 485 | en: "This time already has a pending or approved appointment. Cancel or decline it before removing the time.", |
| 486 | tr: "Bu saatte bekleyen veya onaylanmış bir randevu var. Saati kaldırmadan önce randevuyu iptal et ya da reddet.", |
| 487 | }, |
| 488 | ], |
| 489 | [ |
| 490 | /\bplan is already assigned\b/, |
| 491 | { |
| 492 | en: "This payment plan is already assigned to a student, so it can no longer be changed or deleted.", |
| 493 | tr: "Bu ödeme planı bir öğrenciye atanmış, bu yüzden artık değiştirilemez veya silinemez.", |
| 494 | }, |
| 495 | ], |
| 496 | [ |
| 497 | /\bschool's last admin\b|\blast admin (of|in) (this|the) school\b/, |
| 498 | { |
| 499 | en: "This account is the school's last admin. Make someone else an admin before changing its role.", |
| 500 | tr: "Bu hesap okulun son yöneticisi. Rolünü değiştirmeden önce başka birini yönetici yap.", |
| 501 | }, |
| 502 | ], |
| 503 | [ |
| 504 | /\bblueprint already exists\b/, |
| 505 | { |
| 506 | en: "A template already exists for this grade. Edit the existing template instead.", |
| 507 | tr: "Bu seviye için zaten bir şablon var. Bunun yerine mevcut şablonu düzenle.", |
| 508 | }, |
| 509 | ], |
| 510 | [ |
| 511 | /\bmenu already exists\b/, |
| 512 | { |
| 513 | en: "A menu already exists for this date and meal. Edit the existing menu instead.", |
| 514 | tr: "Bu tarih ve öğün için zaten bir menü var. Bunun yerine mevcut menüyü düzenle.", |
| 515 | }, |
| 516 | ], |
| 517 | [/\bstudent number is already taken\b|\bstudent number already (exists|taken|in use)\b/, STUDENT_NUMBER_TAKEN], |
| 518 | [ |
| 519 | /\balready attached\b/, |
| 520 | { |
| 521 | en: "This course is already attached to this class.", |
| 522 | tr: "Bu ders bu şubeye zaten eklenmiş.", |
| 523 | }, |
| 524 | ], |
| 525 | [ |
| 526 | /\balready in this class\b/, |
| 527 | { |
| 528 | en: "This student is already in this class.", |
| 529 | tr: "Bu öğrenci zaten bu şubede.", |
| 530 | }, |
| 531 | ], |
| 532 | [ |
| 533 | /\bhomework (has been|is) graded\b/, |
| 534 | { |
| 535 | en: "This homework has been graded, so the submission is locked until the grade is removed.", |
| 536 | tr: "Bu ödev notlandırıldı. Not kaldırılana kadar teslim değiştirilemez.", |
| 537 | }, |
| 538 | ], |
| 539 | [ |
| 540 | /\bquestion is approved\b/, |
| 541 | { |
| 542 | en: "This question is approved, so its content can no longer change.", |
| 543 | tr: "Bu soru onaylandığı için içeriği artık değiştirilemez.", |
| 544 | }, |
| 545 | ], |
| 546 | [ |
| 547 | /\battempts have started\b/, |
| 548 | { |
| 549 | en: "Students have already started this exam, so its questions can no longer change.", |
| 550 | tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", |
| 551 | }, |
| 552 | ], |
| 553 | [ |
| 554 | /\bremoved exam kind still has\b/, |
| 555 | { |
| 556 | en: "An exam kind you removed still has graded exams. Keep it in the list, or move those exams to another kind first.", |
| 557 | tr: "Kaldırdığın sınav türüne ait notlandırılmış sınavlar var. Türü listede bırak ya da önce bu sınavları başka bir türe taşı.", |
| 558 | }, |
| 559 | ], |
| 560 | [ |
| 561 | /\bremoved meal slot still has\b/, |
| 562 | { |
| 563 | en: "A meal you removed still has published menus. Keep it in the list, or delete those menus first.", |
| 564 | tr: "Kaldırdığın öğüne ait yayınlanmış menüler var. Öğünü listede bırak ya da önce bu menüleri sil.", |
| 565 | }, |
| 566 | ], |
| 567 | [ |
| 568 | /\bmaximum number of boards\b/, |
| 569 | { |
| 570 | en: "You already have the maximum number of boards. Delete one before creating another.", |
| 571 | tr: "En fazla tahta sayısına ulaştın. Yenisini oluşturmadan önce birini sil.", |
| 572 | }, |
| 573 | ], |
| 574 | [/\bre-read (it )?and retry\b|\bunder concurrent edits\b|\bkept changing\b/, STALE_RECORD], |
| 575 | ]; |
| 576 | |
| 577 | /** A specific wording for this backend refusal, or null when only the generic fallback fits. */ |
| 578 | function knownApiErrorMessage(message: string, code: string | null, locale: Locale): string | null { |
| 579 | const normalized = normalizeApiMessage(message); |
| 580 | const exact = API_ERROR_MESSAGES[normalized]?.[locale]; |
| 581 | if (exact) return exact; |
| 582 | const byCode = code ? API_ERROR_CODE_MESSAGES[code]?.[locale] : undefined; |
| 583 | if (byCode) return byCode; |
| 584 | for (const [pattern, messages] of API_ERROR_PATTERNS) { |
| 585 | if (pattern.test(normalized)) return messages[locale]; |
| 586 | } |
| 587 | return null; |
| 588 | } |
| 589 | |
| 590 | const FIELD_LABELS: Record<string, Record<Locale, string>> = { |
| 591 | content: { en: "Content", tr: "İçerik" }, |
| 592 | description: { en: "Description", tr: "Açıklama" }, |
| 593 | password: { en: "Password", tr: "Şifre" }, |
| 594 | title: { en: "Title", tr: "Başlık" }, |
| 595 | username: { en: "Username", tr: "Kullanıcı adı" }, |
| 596 | }; |
| 597 | |
| 598 | export function currentLocale(): Locale { |
| 599 | if (typeof window === "undefined") return "en"; |
| 600 | try { |
| 601 | const saved = window.localStorage.getItem("hezarfen.locale"); |
| 602 | if (saved === "en" || saved === "tr") return saved; |
| 603 | return window.navigator.language.toLowerCase().startsWith("tr") ? "tr" : "en"; |
| 604 | } catch { |
| 605 | return "en"; |
| 606 | } |
| 607 | } |
| 608 | |
| 609 | function normalizeApiMessage(message: string): string { |
| 610 | return message |
| 611 | .trim() |
| 612 | .replace(/[’‘]/g, "'") |
| 613 | .replace(/\s+/g, " ") |
| 614 | .replace(/[.!?]+$/, "") |
| 615 | .toLowerCase(); |
| 616 | } |
| 617 | |
| 618 | function sentenceCase(message: string): string { |
| 619 | const trimmed = message.trim(); |
| 620 | if (!trimmed) return trimmed; |
| 621 | return trimmed[0].toLocaleUpperCase("en-US") + trimmed.slice(1); |
| 622 | } |
| 623 | |
| 624 | function formatRuntimeErrorMessage(message: string, locale: Locale): string | null { |
| 625 | const normalized = normalizeApiMessage(message); |
| 626 | if (/^(failed to fetch|load failed|networkerror|network request failed)/.test(normalized)) { |
| 627 | return locale === "tr" |
| 628 | ? "Sunucuya ulaşılamadı. Bağlantını kontrol edip tekrar dene." |
| 629 | : "Could not reach the server. Check your connection and try again."; |
| 630 | } |
| 631 | if ( |
| 632 | /^(typeerror:\s*)?cannot (read|set) propert(y|ies) of (null|undefined)/.test(normalized) || |
| 633 | /^use\w+ must be used within \w+provider/.test(normalized) |
| 634 | ) { |
| 635 | return locale === "tr" |
| 636 | ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." |
| 637 | : "Something went wrong while loading the page. Reload the page and try again."; |
| 638 | } |
| 639 | return null; |
| 640 | } |
| 641 | |
| 642 | function formatNumber(value: string, locale: Locale): string { |
| 643 | return new Intl.NumberFormat(locale === "tr" ? "tr-TR" : "en-US").format(Number(value)); |
| 644 | } |
| 645 | |
| 646 | function fieldLabel(field: string, locale: Locale): string { |
| 647 | const normalized = field.trim().toLowerCase().replace(/[_.-]+/g, " "); |
| 648 | const known = FIELD_LABELS[normalized]?.[locale]; |
| 649 | if (known) return known; |
| 650 | return sentenceCase(normalized); |
| 651 | } |
| 652 | |
| 653 | function formatValidationMessage(message: string, locale: Locale): string | null { |
| 654 | const lengthMatch = message.match(/^([\w .-]+) must be at most (\d+) characters \(got (\d+)\)$/i); |
| 655 | if (!lengthMatch) return null; |
| 656 | |
| 657 | const label = fieldLabel(lengthMatch[1], locale); |
| 658 | const max = formatNumber(lengthMatch[2], locale); |
| 659 | const got = formatNumber(lengthMatch[3], locale); |
| 660 | |
| 661 | if (locale === "tr") return `${label} en fazla ${max} karakter olmalı. Şu an ${got} karakter.`; |
| 662 | return `${label} must be at most ${max} characters. Currently ${got} characters.`; |
| 663 | } |
| 664 | |
| 665 | function errorCodeFromPayload(data: unknown): string | null { |
| 666 | if (!data || typeof data !== "object") return null; |
| 667 | const code = (data as { code?: unknown }).code; |
| 668 | return typeof code === "string" && code ? code : null; |
| 669 | } |
| 670 | |
| 671 | function errorMessageFromPayload(data: unknown, fallback: string): string { |
| 672 | if (!data || typeof data !== "object") return fallback; |
| 673 | const record = data as Record<string, unknown>; |
| 674 | if (typeof record.error === "string") return record.error; |
| 675 | if (typeof record.message === "string") return record.message; |
| 676 | const detail = record.detail; |
| 677 | if (typeof detail === "string") return detail; |
| 678 | if (Array.isArray(detail)) { |
| 679 | return detail |
| 680 | .map((item) => { |
| 681 | if (!item || typeof item !== "object") return ""; |
| 682 | const row = item as Record<string, unknown>; |
| 683 | const loc = Array.isArray(row.loc) ? row.loc.map(String).join(".") : ""; |
| 684 | const msg = typeof row.msg === "string" ? row.msg : ""; |
| 685 | return loc && msg ? `${loc}: ${msg}` : msg; |
| 686 | }) |
| 687 | .filter(Boolean) |
| 688 | .join("; ") || fallback; |
| 689 | } |
| 690 | return fallback; |
| 691 | } |
| 692 | |
| 693 | const pendingGets = new Map<string, Promise<unknown>>(); |
| 694 | |
| 695 | async function request<T>(path: string, options: RequestOptions = {}): Promise<T> { |
| 696 | const headers: Record<string, string> = {}; |
| 697 | let body: string | undefined; |
| 698 | |
| 699 | if (options.body !== undefined) { |
| 700 | headers["Content-Type"] = "application/json"; |
| 701 | body = JSON.stringify(options.body); |
| 702 | } |
| 703 | |
| 704 | // JSON calls only — uploads (formClient) and downloads (blobClient) stay |
| 705 | // untimed. Without this a dead connection leaves callers (exam-room REST |
| 706 | // autosave) stuck on "saving…" until the browser gives up. |
| 707 | const timeout = AbortSignal.timeout(REQUEST_TIMEOUT_MS); |
| 708 | // Caller-initiated aborts keep their original AbortError so cancellation |
| 709 | // handling upstream is untouched; only our own deadline becomes an ApiError. |
| 710 | const asDeadlineError = (err: unknown) => |
| 711 | timeout.aborted && !options.signal?.aborted ? new ApiError(408, "request timed out") : err; |
| 712 | |
| 713 | let res: Response; |
| 714 | try { |
| 715 | res = await fetch(`${API_PREFIX}${path}`, { |
| 716 | method: options.method ?? "GET", |
| 717 | headers, |
| 718 | body, |
| 719 | credentials: "same-origin", |
| 720 | signal: options.signal ? AbortSignal.any([options.signal, timeout]) : timeout, |
| 721 | cache: options.cache, |
| 722 | }); |
| 723 | } catch (err) { |
| 724 | throw asDeadlineError(err); |
| 725 | } |
| 726 | |
| 727 | if (res.status === 204) { |
| 728 | return undefined as T; |
| 729 | } |
| 730 | |
| 731 | // The deadline aborts the body stream too, so headers can arrive in time and |
| 732 | // res.text() still blow up mid-download on a multi-MB response. |
| 733 | let text: string; |
| 734 | try { |
| 735 | text = await res.text(); |
| 736 | } catch (err) { |
| 737 | throw asDeadlineError(err); |
| 738 | } |
| 739 | |
| 740 | let data: unknown = null; |
| 741 | if (text) { |
| 742 | try { |
| 743 | data = JSON.parse(text); |
| 744 | } catch { |
| 745 | data = { error: text }; |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | if (!res.ok) { |
| 750 | const message = errorMessageFromPayload(data, res.statusText || "Request failed"); |
| 751 | |
| 752 | let retryAfter: number | null = null; |
| 753 | if (res.status === 429 || res.status === 503) { |
| 754 | const raw = res.headers.get("Retry-After"); |
| 755 | if (raw) { |
| 756 | const n = Number(raw); |
| 757 | retryAfter = Number.isFinite(n) ? n : null; |
| 758 | } |
| 759 | } |
| 760 | |
| 761 | throw new ApiError(res.status, message, retryAfter, disabledModuleOf(res.status, data), errorCodeFromPayload(data)); |
| 762 | } |
| 763 | |
| 764 | return data as T; |
| 765 | } |
| 766 | |
| 767 | /** |
| 768 | * Coalesce only overlapping, non-cancellable GETs. This is deliberately not a |
| 769 | * cache: once settled the entry disappears, so every later resource refetch |
| 770 | * still reaches the backend and mutation consistency stays unchanged. |
| 771 | */ |
| 772 | export function client<T>(path: string, options: RequestOptions = {}): Promise<T> { |
| 773 | const method = options.method ?? "GET"; |
| 774 | if (method !== "GET" || options.body !== undefined || options.signal || options.cache === "no-store") { |
| 775 | return request<T>(path, options); |
| 776 | } |
| 777 | const key = `${path}\u0000${options.cache ?? "default"}`; |
| 778 | const pending = pendingGets.get(key); |
| 779 | if (pending) return pending as Promise<T>; |
| 780 | const next = request<T>(path, options).finally(() => pendingGets.delete(key)); |
| 781 | pendingGets.set(key, next); |
| 782 | return next; |
| 783 | } |
| 784 | |
| 785 | export async function formClient<T>(path: string, body: FormData, signal?: AbortSignal): Promise<T> { |
| 786 | const res = await fetch(`${API_PREFIX}${path}`, { |
| 787 | method: "POST", |
| 788 | body, |
| 789 | credentials: "same-origin", |
| 790 | signal, |
| 791 | }); |
| 792 | |
| 793 | const text = await res.text(); |
| 794 | let data: unknown = null; |
| 795 | if (text) { |
| 796 | try { |
| 797 | data = JSON.parse(text); |
| 798 | } catch { |
| 799 | data = { error: text }; |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | if (!res.ok) { |
| 804 | const message = errorMessageFromPayload(data, res.statusText || "Request failed"); |
| 805 | throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data), errorCodeFromPayload(data)); |
| 806 | } |
| 807 | |
| 808 | return data as T; |
| 809 | } |
| 810 | |
| 811 | export async function blobClient(path: string, signal?: AbortSignal): Promise<Blob> { |
| 812 | const res = await fetch(`${API_PREFIX}${path}`, { |
| 813 | credentials: "same-origin", |
| 814 | signal, |
| 815 | }); |
| 816 | |
| 817 | if (!res.ok) { |
| 818 | const text = await res.text(); |
| 819 | let message = res.statusText || "Request failed"; |
| 820 | let payload: unknown = null; |
| 821 | if (text) { |
| 822 | try { |
| 823 | payload = JSON.parse(text); |
| 824 | message = errorMessageFromPayload(payload, message); |
| 825 | } catch { |
| 826 | message = text; |
| 827 | } |
| 828 | } |
| 829 | throw new ApiError(res.status, message, null, disabledModuleOf(res.status, payload), errorCodeFromPayload(payload)); |
| 830 | } |
| 831 | |
| 832 | return res.blob(); |
| 833 | } |
| 834 | |
| 835 | /** |
| 836 | * A request body the backend could not read (its JSON extractor, serde). The |
| 837 | * text names the field and what was wrong with it, which is exactly what a |
| 838 | * reader needs to fix the form — so it is translated instead of hidden. |
| 839 | */ |
| 840 | function formatDecodeMessage(message: string, locale: Locale): string | null { |
| 841 | const tr = locale === "tr"; |
| 842 | const missing = message.match(/missing field `([^`]+)`/i); |
| 843 | if (missing) { |
| 844 | const label = fieldLabel(missing[1], locale); |
| 845 | return tr ? `“${label}” alanı eksik. Doldurup tekrar dene.` : `The “${label}” field is missing. Fill it in and try again.`; |
| 846 | } |
| 847 | const variant = message.match(/unknown variant `([^`]*)`, expected (.+?)(?: at line \d+.*)?$/i); |
| 848 | if (variant) { |
| 849 | return tr |
| 850 | ? `“${variant[1]}” geçerli bir seçenek değil. Geçerli değerler: ${variant[2].replace(/`/g, "")}.` |
| 851 | : `“${variant[1]}” is not a valid option. Valid values: ${variant[2].replace(/`/g, "")}.`; |
| 852 | } |
| 853 | const field = message.match(/([\w.[\]]+): invalid (?:type|value|length)/i)?.[1]; |
| 854 | const typed = message.match(/invalid (?:type|value): (.+?), expected (.+?)(?: at line \d+.*)?$/i); |
| 855 | if (typed) { |
| 856 | const where = field ? (tr ? `“${fieldLabel(field, locale)}” alanının` : `The “${fieldLabel(field, locale)}” field has the`) : tr ? "Bir alanın" : "A field has the"; |
| 857 | return tr |
| 858 | ? `${where} biçimi hatalı: ${typed[2]} bekleniyordu, ${typed[1]} geldi.` |
| 859 | : `${where} wrong format: expected ${typed[2]}, got ${typed[1]}.`; |
| 860 | } |
| 861 | if (/failed to (parse|deserialize) the (request )?(json )?body|expected value at line|eof while parsing/i.test(message)) { |
| 862 | return tr ? "Gönderilen veri okunamadı (biçim hatası). Alanları kontrol edip tekrar dene." : "The data sent could not be read (format error). Check the fields and try again."; |
| 863 | } |
| 864 | return null; |
| 865 | } |
| 866 | |
| 867 | /** What kind of failure a status is, for when the backend's words are not mapped. */ |
| 868 | function statusLead(status: number | null, locale: Locale): string { |
| 869 | const tr = locale === "tr"; |
| 870 | if (status === 400) return tr ? "Sunucu isteği geçersiz buldu." : "The server rejected the request as invalid."; |
| 871 | if (status === 408) return tr ? "Sunucu zamanında yanıt vermedi." : "The server did not answer in time."; |
| 872 | if (status === 409) return tr ? "İşlem kaydın şu anki durumuyla çakışıyor." : "The action conflicts with the record's current state."; |
| 873 | if (status === 422) return tr ? "Gönderilen bilgilerde eksik ya da hatalı bir alan var." : "A field is missing or has the wrong format."; |
| 874 | return tr ? "İşlem tamamlanamadı." : "The action could not be completed."; |
| 875 | } |
| 876 | |
| 877 | /** |
| 878 | * The last resort: say what kind of failure it was and quote the backend's |
| 879 | * own reason, so the reader (and whoever they ask) can tell a format problem |
| 880 | * from a conflict. Raw text is labelled as the server's, not passed off as ours. |
| 881 | */ |
| 882 | function formatFallbackMessage(message: string, status: number | null, locale: Locale): string { |
| 883 | const lead = statusLead(status, locale); |
| 884 | const detail = message.trim().replace(/[.\s]+$/, ""); |
| 885 | const generic = !detail || /^(request failed|bad request|unprocessable entity|conflict|error)$/i.test(detail); |
| 886 | if (generic) return `${lead} ${locale === "tr" ? "Bilgileri kontrol edip tekrar dene." : "Check your input and try again."}`; |
| 887 | return `${lead} ${locale === "tr" ? "Sunucu yanıtı" : "Server said"}: “${detail}”.`; |
| 888 | } |
| 889 | |
| 890 | export function formatApiErrorMessage(message: string, locale: Locale = currentLocale(), status: number | null = null): string { |
| 891 | const known = knownApiErrorMessage(message, null, locale); |
| 892 | if (known) return known; |
| 893 | const runtime = formatRuntimeErrorMessage(message, locale); |
| 894 | if (runtime) return runtime; |
| 895 | const validation = formatValidationMessage(message, locale); |
| 896 | if (validation) return validation; |
| 897 | const decode = formatDecodeMessage(message, locale); |
| 898 | if (decode) return decode; |
| 899 | // Unmapped backend text: name the kind of failure and quote the server's |
| 900 | // reason instead of a bare "something went wrong" that hides it. Add a |
| 901 | // mapping in API_ERROR_MESSAGES (exact), API_ERROR_CODE_MESSAGES or |
| 902 | // API_ERROR_PATTERNS when a message deserves its own wording. |
| 903 | return formatFallbackMessage(message, status, locale); |
| 904 | } |
| 905 | |
| 906 | export function formatApiError(err: unknown, locale: Locale = currentLocale()): string { |
| 907 | if (err instanceof ApiError) { |
| 908 | if ((err.status === 429 || err.status === 503) && err.retryAfter != null) { |
| 909 | return locale === "tr" ? `${err.retryAfter} sn sonra tekrar dene.` : `Try again in ${err.retryAfter}s.`; |
| 910 | } |
| 911 | // The specific backend message wins over the per-status generic one — |
| 912 | // otherwise every 401/403/404/413/5xx entry in the table is dead code. |
| 913 | // Ahead of the message table: the backend's text for a switched-off |
| 914 | // module may be a generic "forbidden", which reads as a permissions fault. |
| 915 | if (err.module != null && err.status === 403) { |
| 916 | return locale === "tr" ? "Bu özellik okulunuzda şu an kapalı." : "This feature is currently switched off for your school."; |
| 917 | } |
| 918 | const known = knownApiErrorMessage(err.message, err.code, locale); |
| 919 | if (known) return known; |
| 920 | if (err.status === 401) return API_ERROR_MESSAGES.unauthorized[locale]; |
| 921 | if (err.status === 403) return API_ERROR_MESSAGES.forbidden[locale]; |
| 922 | if (err.status === 404) return API_ERROR_MESSAGES["not found"][locale]; |
| 923 | if (err.status === 413) return API_ERROR_MESSAGES["payload too large"][locale]; |
| 924 | if (err.status >= 500) return locale === "tr" ? "Sunucuda bir sorun oluştu. Lütfen tekrar dene." : "Server error. Please try again."; |
| 925 | return formatApiErrorMessage(err.message, locale, err.status); |
| 926 | } |
| 927 | if (err instanceof TypeError) { |
| 928 | return formatRuntimeErrorMessage(err.message, locale) ?? |
| 929 | (locale === "tr" |
| 930 | ? "Sayfa yüklenirken bir sorun oluştu. Sayfayı yeniden yükleyip tekrar dene." |
| 931 | : "Something went wrong while loading the page. Reload the page and try again."); |
| 932 | } |
| 933 | if (err instanceof Error) return formatApiErrorMessage(err.message, locale); |
| 934 | return locale === "tr" ? "Bir şeyler ters gitti." : "Something went wrong."; |
| 935 | } |