306886a42b
Auth (Test-Mode):
- middleware.AuthMiddleware now takes a devMode flag. In dev,
requests without Authorization fall back to a deterministic dev
UUID (00000000-...-001) and role=teacher. ENVIRONMENT=production
re-enables the strict 401 path.
- main.go wires devMode = cfg.Environment != "production".
- page.tsx replaces the red 'Anmeldung noch nicht integriert' banner
with a softer Testumgebung notice; the manual-token form moves
behind a nested details block.
Export endpoints (school-service):
- LoadExportLessons joins tt_lesson with tt_period for wall-clock
times; one query feeds both CSV and ICS.
- WriteCSV streams 10 columns including pinned flag.
- WriteICS emits one VEVENT per lesson anchored to a Monday — caller
overridable via ?start=YYYY-MM-DD. RFC 5545 escapes for ',', ';',
'\n' in icsEscape().
- NextMonday helper for the default anchor.
- GET /timetable/solutions/:id/export.{csv,ics} handlers attach
Content-Disposition: attachment so browsers download instead of
rendering.
Frontend:
- lib/stundenplan/api.ts downloadSolutionExport() fetches as blob,
triggers a synthetic <a download> click, and forwards the JWT when
present.
- PlanView gains CSV / ICS / Drucken buttons next to the perspective
selector. The toolbar carries class 'no-print' so window.print()
yields only the grid.
- globals.css @media print rule hides chrome, forces white
background, gives the table proper borders for A4.
Docs:
- docs-src/services/stundenplan/{index,architecture,constraints,
solver-tuning,export}.md with nav entry in mkdocs.yml under
Services → Stundenplaner.
- sbom/stundenplan/README.md lists manually-verified key dependencies
and the policy reference. scripts/stundenplan-sbom.sh generates
full machine-readable inventories via go-licenses + pip-licenses
+ license-checker when those tools are available.
Tests:
- internal/services/timetable_exports_test.go: 4 unit tests covering
CSV column layout + quoting, ICS structure + DTSTART formatting,
icsEscape special chars, NextMonday weekday math.
- studio-v2/e2e/stundenplan-export.spec.ts split out of the main spec
file (LOC budget) — 3 tests for button render, CSV download,
ICS download.
- mockSchoolApi extended with export.csv + export.ics routes.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
190 lines
9.1 KiB
TypeScript
190 lines
9.1 KiB
TypeScript
/**
|
|
* Stundenplan API client. All requests go through /api/school/* which proxies
|
|
* to the school-service Gin server (port 8084). Auth token, if available, is
|
|
* passed via Authorization: Bearer; for now no token = upstream 401.
|
|
*/
|
|
|
|
import type {
|
|
TimetableClass, TimetablePeriod, TimetableRoom, TimetableSubject,
|
|
TimetableTeacher, TimetableCurriculum, TimetableAssignment,
|
|
CreateTimetableClass, CreateTimetablePeriod, CreateTimetableRoom,
|
|
CreateTimetableSubject, CreateTimetableTeacher,
|
|
CreateTimetableCurriculum, CreateTimetableAssignment,
|
|
TeacherUnavailableDay, TeacherUnavailableWindow, TeacherMaxHoursDay,
|
|
TeacherMaxHoursWeek, TeacherExcludedSubject, TeacherExcludedRoom,
|
|
SubjectMinDayGap, SubjectMaxConsecutive, SubjectContiguousWhenRepeated,
|
|
SubjectPreferredPeriod, SubjectDoubleLesson,
|
|
ClassMaxHoursDay, ClassNoGaps,
|
|
RoomRequiresType, RoomUnavailable,
|
|
TimetableSolution, TimetableLesson, CreateTimetableSolution,
|
|
} from '@/app/stundenplan/types'
|
|
|
|
const TOKEN_KEY = 'bp_stundenplan_jwt'
|
|
|
|
export function setStundenplanToken(token: string): void {
|
|
if (typeof window !== 'undefined') localStorage.setItem(TOKEN_KEY, token)
|
|
}
|
|
|
|
export function getStundenplanToken(): string {
|
|
if (typeof window === 'undefined') return ''
|
|
return localStorage.getItem(TOKEN_KEY) || ''
|
|
}
|
|
|
|
async function apiFetch<T>(endpoint: string, options: RequestInit = {}): Promise<T> {
|
|
const headers: Record<string, string> = {
|
|
'Content-Type': 'application/json',
|
|
...(options.headers as Record<string, string> | undefined),
|
|
}
|
|
const token = getStundenplanToken()
|
|
if (token) headers['Authorization'] = `Bearer ${token}`
|
|
|
|
const res = await fetch(`/api/school${endpoint}`, { ...options, headers })
|
|
if (!res.ok) {
|
|
const errData = await res.json().catch(() => ({ error: 'Unknown error' }))
|
|
throw new Error(errData.error || errData.detail || `HTTP ${res.status}`)
|
|
}
|
|
if (res.status === 204) return undefined as T
|
|
return res.json()
|
|
}
|
|
|
|
// ---------- Stammdaten ----------
|
|
|
|
export const classesApi = {
|
|
list: () => apiFetch<TimetableClass[]>('/timetable/classes'),
|
|
create: (data: CreateTimetableClass) =>
|
|
apiFetch<TimetableClass>('/timetable/classes', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/classes/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const periodsApi = {
|
|
list: () => apiFetch<TimetablePeriod[]>('/timetable/periods'),
|
|
create: (data: CreateTimetablePeriod) =>
|
|
apiFetch<TimetablePeriod>('/timetable/periods', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/periods/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const roomsApi = {
|
|
list: () => apiFetch<TimetableRoom[]>('/timetable/rooms'),
|
|
create: (data: CreateTimetableRoom) =>
|
|
apiFetch<TimetableRoom>('/timetable/rooms', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/rooms/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const subjectsApi = {
|
|
list: () => apiFetch<TimetableSubject[]>('/timetable/subjects'),
|
|
create: (data: CreateTimetableSubject) =>
|
|
apiFetch<TimetableSubject>('/timetable/subjects', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/subjects/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const teachersApi = {
|
|
list: () => apiFetch<TimetableTeacher[]>('/timetable/teachers'),
|
|
create: (data: CreateTimetableTeacher) =>
|
|
apiFetch<TimetableTeacher>('/timetable/teachers', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/teachers/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const curriculumApi = {
|
|
list: () => apiFetch<TimetableCurriculum[]>('/timetable/curriculum'),
|
|
create: (data: CreateTimetableCurriculum) =>
|
|
apiFetch<TimetableCurriculum>('/timetable/curriculum', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/curriculum/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
export const assignmentsApi = {
|
|
list: () => apiFetch<TimetableAssignment[]>('/timetable/assignments'),
|
|
create: (data: CreateTimetableAssignment) =>
|
|
apiFetch<TimetableAssignment>('/timetable/assignments', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/assignments/${id}`, { method: 'DELETE' }),
|
|
}
|
|
|
|
// ---------- Constraints ----------
|
|
|
|
/**
|
|
* Factory that builds a list/create/remove triple for a constraint endpoint.
|
|
* The 15 constraint tables share the same CRUD shape; only TItem differs.
|
|
*/
|
|
function constraintApi<TItem, TCreate>(path: string) {
|
|
return {
|
|
list: () => apiFetch<TItem[]>(`/timetable/constraints/${path}`),
|
|
create: (data: TCreate) =>
|
|
apiFetch<TItem>(`/timetable/constraints/${path}`, { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/constraints/${path}/${id}`, { method: 'DELETE' }),
|
|
}
|
|
}
|
|
|
|
export const teacherUnavailableDayApi = constraintApi<TeacherUnavailableDay, Omit<TeacherUnavailableDay, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/unavailable-day')
|
|
export const teacherUnavailableWindowApi = constraintApi<TeacherUnavailableWindow, Omit<TeacherUnavailableWindow, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/unavailable-window')
|
|
export const teacherMaxHoursDayApi = constraintApi<TeacherMaxHoursDay, Omit<TeacherMaxHoursDay, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/max-hours-day')
|
|
export const teacherMaxHoursWeekApi = constraintApi<TeacherMaxHoursWeek, Omit<TeacherMaxHoursWeek, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/max-hours-week')
|
|
export const teacherExcludedSubjectApi = constraintApi<TeacherExcludedSubject, Omit<TeacherExcludedSubject, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/excluded-subject')
|
|
export const teacherExcludedRoomApi = constraintApi<TeacherExcludedRoom, Omit<TeacherExcludedRoom, 'id' | 'created_by_user_id' | 'created_at'>>('teacher/excluded-room')
|
|
|
|
export const subjectMinDayGapApi = constraintApi<SubjectMinDayGap, Omit<SubjectMinDayGap, 'id' | 'created_by_user_id' | 'created_at'>>('subject/min-day-gap')
|
|
export const subjectMaxConsecutiveApi = constraintApi<SubjectMaxConsecutive, Omit<SubjectMaxConsecutive, 'id' | 'created_by_user_id' | 'created_at'>>('subject/max-consecutive')
|
|
export const subjectContiguousWhenRepeatedApi = constraintApi<SubjectContiguousWhenRepeated, Omit<SubjectContiguousWhenRepeated, 'id' | 'created_by_user_id' | 'created_at'>>('subject/contiguous-when-repeated')
|
|
export const subjectPreferredPeriodApi = constraintApi<SubjectPreferredPeriod, Omit<SubjectPreferredPeriod, 'id' | 'created_by_user_id' | 'created_at'>>('subject/preferred-period')
|
|
export const subjectDoubleLessonApi = constraintApi<SubjectDoubleLesson, Omit<SubjectDoubleLesson, 'id' | 'created_by_user_id' | 'created_at'>>('subject/double-lesson')
|
|
|
|
export const classMaxHoursDayApi = constraintApi<ClassMaxHoursDay, Omit<ClassMaxHoursDay, 'id' | 'created_by_user_id' | 'created_at'>>('class/max-hours-day')
|
|
export const classNoGapsApi = constraintApi<ClassNoGaps, Omit<ClassNoGaps, 'id' | 'created_by_user_id' | 'created_at'>>('class/no-gaps')
|
|
|
|
export const roomRequiresTypeApi = constraintApi<RoomRequiresType, Omit<RoomRequiresType, 'id' | 'created_by_user_id' | 'created_at'>>('room/requires-type')
|
|
export const roomUnavailableApi = constraintApi<RoomUnavailable, Omit<RoomUnavailable, 'id' | 'created_by_user_id' | 'created_at'>>('room/unavailable')
|
|
|
|
// ---------- Solutions ----------
|
|
|
|
export const solutionsApi = {
|
|
list: () => apiFetch<TimetableSolution[]>('/timetable/solutions'),
|
|
get: (id: string) => apiFetch<TimetableSolution>(`/timetable/solutions/${id}`),
|
|
create: (data: CreateTimetableSolution) =>
|
|
apiFetch<TimetableSolution>('/timetable/solutions', { method: 'POST', body: JSON.stringify(data) }),
|
|
remove: (id: string) =>
|
|
apiFetch<void>(`/timetable/solutions/${id}`, { method: 'DELETE' }),
|
|
lessons: (id: string) =>
|
|
apiFetch<TimetableLesson[]>(`/timetable/solutions/${id}/lessons`),
|
|
}
|
|
|
|
export const lessonsApi = {
|
|
pin: (id: string, pinned: boolean) =>
|
|
apiFetch<{ message: string; pinned: boolean }>(`/timetable/lessons/${id}/pin`, {
|
|
method: 'PUT',
|
|
body: JSON.stringify({ pinned }),
|
|
}),
|
|
}
|
|
|
|
// Phase 8: exports. Fetched as blobs through the proxy so the JWT (when
|
|
// set) is forwarded; download is triggered by creating an object URL.
|
|
export async function downloadSolutionExport(
|
|
solutionId: string,
|
|
format: 'csv' | 'ics',
|
|
options: { startDate?: string } = {},
|
|
): Promise<void> {
|
|
const token = getStundenplanToken()
|
|
const headers: Record<string, string> = {}
|
|
if (token) headers['Authorization'] = `Bearer ${token}`
|
|
|
|
const qs = format === 'ics' && options.startDate ? `?start=${options.startDate}` : ''
|
|
const res = await fetch(`/api/school/timetable/solutions/${solutionId}/export.${format}${qs}`, { headers })
|
|
if (!res.ok) {
|
|
throw new Error(`Export fehlgeschlagen (HTTP ${res.status})`)
|
|
}
|
|
const blob = await res.blob()
|
|
const url = URL.createObjectURL(blob)
|
|
const a = document.createElement('a')
|
|
a.href = url
|
|
a.download = `stundenplan-${solutionId.slice(0, 8)}.${format}`
|
|
document.body.appendChild(a)
|
|
a.click()
|
|
a.remove()
|
|
URL.revokeObjectURL(url)
|
|
}
|