diff --git a/docs/backend/podcast-transcript-request.md b/docs/backend/podcast-transcript-request.md index 87e13a8..f51c562 100644 --- a/docs/backend/podcast-transcript-request.md +++ b/docs/backend/podcast-transcript-request.md @@ -1,36 +1,27 @@ # Feature request: timed transcript for podcast episodes -Status: requested by frontend · Date: 2026-09-23 -Contract checked: live OpenAPI at `https://hezarfen-backend.dizey.sh/api-docs/openapi.json` -(fetched 2026-09-23) — no transcript field or route under `/podcast/*`. - -## What the frontend already does - -The podcast player (`src/components/notes/podcast-player.tsx`) renders a -timed transcript under the audio when one is present: the line being spoken -is highlighted and kept in view, and clicking a line plays from its start -(`src/components/notes/podcast-transcript.tsx`). Until the backend sends a -transcript, the player shows no transcript control at all. - -It reads the transcript from `GET /podcast/jobs/{id}/result`, as an optional -field of `PodcastJobArtifacts` (`src/api/client/types.ts`): - -```jsonc -{ - "job_id": "…", - "audio_id": "…", - "duration_secs": 754, - "format": "ogrenci_hoca", - "transcript": [ - { "start_secs": 0.0, "end_secs": 4.2, "text": "Bugün hücreyi konuşalım.", "speaker": "Öğretmen" }, - { "start_secs": 4.2, "end_secs": 7.9, "text": "Hücre neden bu kadar önemli?", "speaker": "Öğrenci" } - ] -} -``` - -## Requested shape - -- `transcript`: array, ordered by `start_secs`, or `null`/absent when the +Status: partly shipped · Updated: 2026-09-23 +Contract checked: live OpenAPI at `https://hezarfen-backend.dizey.sh/api-docs/openapi.json`. + +## What the backend ships now + +`GET /podcast/jobs/{id}/result` carries `transcript: string | null` on +`JobArtifacts` — the episode's narration as plain text, chapters joined by +blank lines, with no timings. `null` for jobs that finished before the column +existed. + +## What the frontend does with it + +The podcast player (`src/components/notes/podcast-player.tsx`) reads the +result of whichever episode is selected and, when the transcript is present, +offers a "Transkript" toggle that shows it one paragraph per chapter +(`src/components/notes/podcast-transcript.tsx`). With no transcript there is +no toggle. Without timings the text cannot follow playback or seek, so the +request below still stands. + +## Still requested: timings + +- `transcript_segments` (new field beside the plain `transcript`): array, ordered by `start_secs`, or `null`/absent when the service produced none. Only on a `done` job. - `start_secs` / `end_secs`: offsets into the produced audio, in seconds (fractions allowed). The pipeline already knows these when it stitches the @@ -42,8 +33,8 @@ field of `PodcastJobArtifacts` (`src/api/client/types.ts`): If the backend prefers a separate door (for example `GET /podcast/jobs/{id}/transcript`, which would also let the history list and the studio inspector load it lazily), or different field names, the frontend -changes in one place: the type above and the `transcript` prop passed to -`PodcastPlayer`. +changes in one place: `PodcastJobArtifacts` in `src/api/client/types.ts` and +the fetch in `PodcastPlayer`. ## Related: the audio door cannot be seeked diff --git a/src/api/__tests__/client/client.test.ts b/src/api/__tests__/client/client.test.ts index 40ca333..d2113bf 100644 --- a/src/api/__tests__/client/client.test.ts +++ b/src/api/__tests__/client/client.test.ts @@ -377,6 +377,62 @@ describe("client", () => { ); }); + it("localizes still-linked and archived conflicts instead of quoting them", () => { + const yearLinked = new ApiError(409, "classes and terms are still linked to this academic year — unlink them first"); + expect(formatApiError(yearLinked, "tr")).toBe( + "Bu eğitim yılına bağlı şubeler ve dönemler var. Silmeden önce onları başka bir yıla taşı veya sil.", + ); + expect(formatApiError(yearLinked, "en")).toBe( + "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.", + ); + // a reworded tail or a curly apostrophe still lands on the same wording + expect(formatApiError(new ApiError(409, "Terms are still linked to this year."), "tr")).toMatch(/^Bu eğitim yılına bağlı/); + + const cases: Array<[string, RegExp]> = [ + ["this class’s academic year is archived — past years are read-only", /^Bu eğitim yılı arşivlendi\./], + ["students or instances are still on this class", /^Bu şubede hâlâ öğrenci veya ders var\./], + ["a class still teaches this course", /^Bu ders hâlâ bir şubede okutuluyor/], + ["exams or frozen karnes still belong to this term", /^Bu döneme bağlı sınavlar/], + ["exam questions or homework still reference this subject", /^Sınav soruları veya ödevler/], + ["the menu still has live bookings", /^Bu menüde hâlâ rezervasyonlar var\./], + ["the slot has a pending or approved booking", /^Bu saatte bekleyen veya onaylanmış/], + ["the plan is already assigned to a student", /^Bu ödeme planı bir öğrenciye atanmış/], + ["that account is the school's last admin", /^Bu hesap okulun son yöneticisi\./], + ["a blueprint already exists for that grade", /^Bu seviye için zaten bir şablon var\./], + ["the year changed under concurrent edits (re-read and retry)", /^Bu kayıt sen düzenlerken değişti\./], + ]; + for (const [backend, turkish] of cases) { + expect(formatApiError(new ApiError(409, backend), "tr")).toMatch(turkish); + expect(formatApiError(new ApiError(409, backend), "en")).not.toMatch(/Server said/); + } + // the exact table still wins over a looser pattern + expect(formatApiError(new ApiError(409, "bank questions still reference this subject — re-tag or delete them first"), "en")).toBe( + "Question bank templates still use this subject. Re-tag or delete them first.", + ); + }); + + it("prefers the machine code over the prose when the backend sends one", () => { + expect(formatApiError(new ApiError(409, "class is at its course ceiling (12)", null, null, "class_at_course_ceiling"), "tr")).toBe( + "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.", + ); + expect(formatApiError(new ApiError(409, "some reworded text", null, null, "student_number_taken"), "en")).toBe( + "Another student already has this student number. Enter a different number.", + ); + expect(formatApiError(new ApiError(409, "whatever", null, null, "academic_year_archived"), "tr")).toMatch(/^Bu eğitim yılı arşivlendi\./); + // an unknown code falls through to the prose and then the quoted fallback + expect(formatApiError(new ApiError(409, "slot taken by a later edit", null, null, "brand_new_code"), "tr")).toBe( + "İşlem kaydın şu anki durumuyla çakışıyor. Sunucu yanıtı: “slot taken by a later edit”.", + ); + }); + + it("carries the payload code onto the ApiError", async () => { + mockFetchError(409, { error: "already attached", code: "class_at_course_ceiling" }); + const err = await client("/classes/1/instances", { method: "POST", body: {} }).catch((e: unknown) => e); + expect(err).toBeInstanceOf(ApiError); + expect((err as ApiError).code).toBe("class_at_course_ceiling"); + expect(formatApiError(err, "en")).toMatch(/^This class already has the maximum number of courses\./); + }); + it("formats 500+", () => { expect(formatApiError(new ApiError(500, ""), "en")).toBe("Server error. Please try again."); expect(formatApiError(new ApiError(503, ""), "tr")).toBe("Sunucuda bir sorun oluştu. Lütfen tekrar dene."); diff --git a/src/api/client/client.ts b/src/api/client/client.ts index 566560a..c8e7abb 100644 --- a/src/api/client/client.ts +++ b/src/api/client/client.ts @@ -5,13 +5,22 @@ export class ApiError extends Error { readonly retryAfter: number | null; /** Set when the school has this route's module switched off (`403 {error, module}`). */ readonly module: string | null; - - constructor(status: number, message: string, retryAfter: number | null = null, module: string | null = null) { + /** Machine refusal code (`{error, code}`), sent only where a route documents one. */ + readonly code: string | null; + + constructor( + status: number, + message: string, + retryAfter: number | null = null, + module: string | null = null, + code: string | null = null, + ) { super(message); this.name = "ApiError"; this.status = status; this.retryAfter = retryAfter; this.module = module; + this.code = code; } } @@ -300,6 +309,252 @@ const API_ERROR_MESSAGES: Record> = { }, }; +type LocalizedMessage = Record; + +const ARCHIVED_YEAR: LocalizedMessage = { + en: "This academic year is archived. Past years are read-only, so records in it can no longer change.", + 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.", +}; + +const STUDENT_NUMBER_TAKEN: LocalizedMessage = { + en: "Another student already has this student number. Enter a different number.", + tr: "Bu öğrenci numarası başka bir öğrencide kayıtlı. Farklı bir numara gir.", +}; + +const STALE_RECORD: LocalizedMessage = { + en: "This record changed while you were editing it. Reload the page and try again.", + tr: "Bu kayıt sen düzenlerken değişti. Sayfayı yenileyip tekrar dene.", +}; + +/** + * Machine refusal codes (`{error, code}`). The backend sends one only where a + * route documents its vocabulary (class attach/add-member, podcast, insight + * report, student numbers), so these win over the prose whenever present. + * `duplicate` is left out on purpose: it means a course on one route and a + * student on another, so the prose patterns below tell them apart. + */ +const API_ERROR_CODE_MESSAGES: Record = { + academic_year_archived: ARCHIVED_YEAR, + class_at_course_ceiling: { + en: "This class already has the maximum number of courses. Remove a course from it before adding another.", + tr: "Bu şube en fazla ders sayısına ulaştı. Yeni ders eklemeden önce şubeden bir ders çıkar.", + }, + class_roster_too_large: { + en: "This class has too many students to enroll in a course in one step. Contact your system administrator.", + tr: "Bu şubede bir derse tek seferde kaydedilemeyecek kadar çok öğrenci var. Sistem yöneticine başvur.", + }, + class_at_roster_ceiling: { + en: "This class is full. Remove a student from it before adding another.", + tr: "Bu şube dolu. Yeni öğrenci eklemeden önce şubeden bir öğrenci çıkar.", + }, + class_course_list_too_large: { + en: "This class has too many courses to enroll a student in one step. Contact your system administrator.", + tr: "Bu şubede bir öğrenciyi tek seferde kaydetmek için çok fazla ders var. Sistem yöneticine başvur.", + }, + linked_course_missing: { + en: "One of this class's courses was removed while the student was being added. Reload the page and try again.", + tr: "Öğrenci eklenirken şubenin derslerinden biri kaldırıldı. Sayfayı yenileyip tekrar dene.", + }, + student_number_taken: STUDENT_NUMBER_TAKEN, + not_ready: { + en: "This audio is not ready yet. Wait for it to finish and try again.", + tr: "Bu ses kaydı henüz hazır değil. Tamamlanmasını bekleyip tekrar dene.", + }, + audio_missing: { + en: "This audio file could not be found on the server. Generate the episode again.", + tr: "Bu ses dosyası sunucuda bulunamadı. Bölümü yeniden oluştur.", + }, + source_missing: { + en: "This note has no PDF to narrate. Attach a PDF to the note and try again.", + tr: "Bu notta seslendirilecek bir PDF yok. Nota bir PDF ekleyip tekrar dene.", + }, + report_missing: { + en: "No report has been generated for this day yet.", + tr: "Bu gün için henüz rapor oluşturulmadı.", + }, + report_empty: { + en: "There is no data for this day to build a report from.", + tr: "Bu gün için rapor oluşturacak veri yok.", + }, + report_refused: { + en: "The AI service declined to write this report. Try again later.", + tr: "Yapay zekâ servisi bu raporu hazırlamayı reddetti. Daha sonra tekrar dene.", + }, +}; + +/** + * Backend refusals that carry no code, matched on the stable part of their + * prose (the nouns and the "still linked / in use / already" verb) rather than + * byte-exact, so a reworded tail or a different em dash still lands. Checked + * in order after the exact table; keep each pattern specific enough that it + * cannot swallow an unrelated reason. + */ +const API_ERROR_PATTERNS: ReadonlyArray = [ + [ + /\b(classes|terms)\b.*\bstill linked to this (academic )?year\b/, + { + en: "Classes and terms are still linked to this academic year. Move them to another year or delete them before deleting this one.", + 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.", + }, + ], + [/\bacademic year is archived\b|\bin an archived academic year\b/, ARCHIVED_YEAR], + [ + /\btarget year already (holds|has) classes\b/, + { + en: "The target year already has classes. Choose an empty year to carry the classes into.", + tr: "Hedef eğitim yılında zaten şubeler var. Şubeleri aktarmak için boş bir yıl seç.", + }, + ], + [ + /\b(academic )?year (with|named) (that|this) name already exists\b|\bacademic year .*already exists\b/, + { + en: "An academic year with this name already exists. Choose a different name.", + tr: "Bu adla bir eğitim yılı zaten var. Farklı bir ad seç.", + }, + ], + [ + /\b(students|instances|courses)\b.*\bstill (on|in|attached to) this class\b/, + { + en: "This class still has students or courses. Remove its students and detach its courses before deleting it.", + tr: "Bu şubede hâlâ öğrenci veya ders var. Silmeden önce öğrencileri şubeden çıkar ve dersleri şubeden kaldır.", + }, + ], + [ + /\bclass(es)? still teach(es)? this course\b|\bstudents still hold an individual membership\b/, + { + 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.", + 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.", + }, + ], + [ + /\b(exams|karnes?)\b.*\bstill belong to this term\b/, + { + en: "Exams or finalized report cards still belong to this term, so it cannot be deleted. Archive it instead.", + 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.", + }, + ], + [ + /\b(exam questions|questions|homework)\b.*\bstill reference this subject\b/, + { + en: "Exam questions or homework still use this subject. Move them to another subject or delete them first.", + tr: "Sınav soruları veya ödevler hâlâ bu konuyu kullanıyor. Önce onları başka bir konuya taşı veya sil.", + }, + ], + [ + /\bmenu still has (live |active )?bookings\b/, + { + en: "This menu still has bookings. Cancel them before deleting the menu.", + tr: "Bu menüde hâlâ rezervasyonlar var. Menüyü silmeden önce rezervasyonları iptal et.", + }, + ], + [ + /\b(slot|occurrence) has an? (pending or approved )?(booking|appointment)\b/, + { + en: "This time already has a pending or approved appointment. Cancel or decline it before removing the time.", + tr: "Bu saatte bekleyen veya onaylanmış bir randevu var. Saati kaldırmadan önce randevuyu iptal et ya da reddet.", + }, + ], + [ + /\bplan is already assigned\b/, + { + en: "This payment plan is already assigned to a student, so it can no longer be changed or deleted.", + tr: "Bu ödeme planı bir öğrenciye atanmış, bu yüzden artık değiştirilemez veya silinemez.", + }, + ], + [ + /\bschool's last admin\b|\blast admin (of|in) (this|the) school\b/, + { + en: "This account is the school's last admin. Make someone else an admin before changing its role.", + tr: "Bu hesap okulun son yöneticisi. Rolünü değiştirmeden önce başka birini yönetici yap.", + }, + ], + [ + /\bblueprint already exists\b/, + { + en: "A template already exists for this grade. Edit the existing template instead.", + tr: "Bu seviye için zaten bir şablon var. Bunun yerine mevcut şablonu düzenle.", + }, + ], + [ + /\bmenu already exists\b/, + { + en: "A menu already exists for this date and meal. Edit the existing menu instead.", + tr: "Bu tarih ve öğün için zaten bir menü var. Bunun yerine mevcut menüyü düzenle.", + }, + ], + [/\bstudent number is already taken\b|\bstudent number already (exists|taken|in use)\b/, STUDENT_NUMBER_TAKEN], + [ + /\balready attached\b/, + { + en: "This course is already attached to this class.", + tr: "Bu ders bu şubeye zaten eklenmiş.", + }, + ], + [ + /\balready in this class\b/, + { + en: "This student is already in this class.", + tr: "Bu öğrenci zaten bu şubede.", + }, + ], + [ + /\bhomework (has been|is) graded\b/, + { + en: "This homework has been graded, so the submission is locked until the grade is removed.", + tr: "Bu ödev notlandırıldı. Not kaldırılana kadar teslim değiştirilemez.", + }, + ], + [ + /\bquestion is approved\b/, + { + en: "This question is approved, so its content can no longer change.", + tr: "Bu soru onaylandığı için içeriği artık değiştirilemez.", + }, + ], + [ + /\battempts have started\b/, + { + en: "Students have already started this exam, so its questions can no longer change.", + tr: "Öğrenciler bu sınava başladığı için soruları artık değiştirilemez.", + }, + ], + [ + /\bremoved exam kind still has\b/, + { + en: "An exam kind you removed still has graded exams. Keep it in the list, or move those exams to another kind first.", + 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şı.", + }, + ], + [ + /\bremoved meal slot still has\b/, + { + en: "A meal you removed still has published menus. Keep it in the list, or delete those menus first.", + tr: "Kaldırdığın öğüne ait yayınlanmış menüler var. Öğünü listede bırak ya da önce bu menüleri sil.", + }, + ], + [ + /\bmaximum number of boards\b/, + { + en: "You already have the maximum number of boards. Delete one before creating another.", + tr: "En fazla tahta sayısına ulaştın. Yenisini oluşturmadan önce birini sil.", + }, + ], + [/\bre-read (it )?and retry\b|\bunder concurrent edits\b|\bkept changing\b/, STALE_RECORD], +]; + +/** A specific wording for this backend refusal, or null when only the generic fallback fits. */ +function knownApiErrorMessage(message: string, code: string | null, locale: Locale): string | null { + const normalized = normalizeApiMessage(message); + const exact = API_ERROR_MESSAGES[normalized]?.[locale]; + if (exact) return exact; + const byCode = code ? API_ERROR_CODE_MESSAGES[code]?.[locale] : undefined; + if (byCode) return byCode; + for (const [pattern, messages] of API_ERROR_PATTERNS) { + if (pattern.test(normalized)) return messages[locale]; + } + return null; +} + const FIELD_LABELS: Record> = { content: { en: "Content", tr: "İçerik" }, description: { en: "Description", tr: "Açıklama" }, @@ -375,6 +630,12 @@ function formatValidationMessage(message: string, locale: Locale): string | null return `${label} must be at most ${max} characters. Currently ${got} characters.`; } +function errorCodeFromPayload(data: unknown): string | null { + if (!data || typeof data !== "object") return null; + const code = (data as { code?: unknown }).code; + return typeof code === "string" && code ? code : null; +} + function errorMessageFromPayload(data: unknown, fallback: string): string { if (!data || typeof data !== "object") return fallback; const record = data as Record; @@ -465,7 +726,7 @@ async function request(path: string, options: RequestOptions = {}): Promise(path: string, body: FormData, signal?: Abort if (!res.ok) { const message = errorMessageFromPayload(data, res.statusText || "Request failed"); - throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data)); + throw new ApiError(res.status, message, null, disabledModuleOf(res.status, data), errorCodeFromPayload(data)); } return data as T; @@ -533,7 +794,7 @@ export async function blobClient(path: string, signal?: AbortSignal): Promise