Files
breakpilot-lehrer/studio-v2/lib/stundenplan/api.ts
T
Benjamin Admin bf5ea860cc
CI / go-lint (push) Has been skipped
CI / python-lint (push) Has been skipped
CI / nodejs-lint (push) Has been skipped
CI / test-go-school (push) Successful in 37s
CI / test-go-edu-search (push) Successful in 29s
CI / test-python-klausur (push) Failing after 3m56s
CI / test-python-agent-core (push) Successful in 19s
CI / test-nodejs-website (push) Successful in 23s
Phase 7: pinning, plan versions, solver budget + UX polish
Backend (school-service):
  - tt_solution gains parent_solution_id (self-FK, ON DELETE SET NULL)
    and seconds_limit columns via ALTER TABLE IF NOT EXISTS.
  - CreateTimetableSolutionRequest accepts optional parent_solution_id
    and seconds_limit (5-600s) with binding validation.
  - CreateSolution checks parent ownership before INSERT so users can't
    fork another tenant's plan.
  - New PUT /timetable/lessons/:id/pin endpoint; ownership enforced via
    the lesson's solution.created_by_user_id JOIN.

Solver:
  - Lesson.pinned now carries @PlanningPin so Timefold leaves locked
    cells untouched during the search.
  - build_problem() takes optional parent_solution_id; if set, copies
    pinned (class_id, subject_id, day, period, room) tuples onto fresh
    Lesson objects via greedy first-fit matching. Surplus pinned rows
    from curriculum changes are silently dropped.
  - _build_factory(seconds) replaces the module-level factory so each
    job honours its tt_solution.seconds_limit override.
  - persist_solution writes lesson.pinned back so subsequent re-solves
    inherit it.

Frontend (studio-v2):
  - SolutionList grows three knobs in the create-form: Basieren auf
    (parent dropdown, only completed solutions, disabled when none),
    Sekunden-Limit (5-600), and the existing Name.
  - PlanView cells get a pin/unpin button with optimistic update and
    rollback on error. Pinned cells gain an amber ring.
  - types.ts + api.ts mirror the new fields; lessonsApi.pin(id, bool).
  - HelpPanel: collapsible 6-step Bedienungsanleitung explaining the
    setup-to-plan workflow. Anchored at the top of /stundenplan above
    the dev token banner.
  - page.tsx switches to the same gradient + animated-blob background
    used on /korrektur so /stundenplan stops looking like a slate-900
    test page.
  - JWT dev banner gets a step-by-step explanation of how to grab the
    token from DevTools and a non-blocking success indicator (no more
    alert()).

Tests:
  - school-service: 6 new validator cases for parent_solution_id +
    seconds_limit boundaries. 73 subtests total, all green.
  - studio-v2: mockSchoolApi adds PUT /lessons/:id/pin route. 5 new
    Playwright tests across two suites (parent-selector visibility +
    options, seconds-limit input, pin button render, pin-icon flip).
    Existing tests adjusted to the new help panel + JWT banner wording.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-22 08:19:39 +02:00

163 lines
8.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 }),
}),
}