Phase 9a: Schulkalender — Bundesland-Auswahl + Monatsansicht mit Ferien
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 29s
CI / test-go-edu-search (push) Successful in 27s
CI / test-python-klausur (push) Failing after 2m50s
CI / test-python-agent-core (push) Successful in 18s
CI / test-nodejs-website (push) Successful in 21s
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 29s
CI / test-go-edu-search (push) Successful in 27s
CI / test-python-klausur (push) Failing after 2m50s
CI / test-python-agent-core (push) Successful in 18s
CI / test-nodejs-website (push) Successful in 21s
Backend (school-service):
- cal_public_event (region, event_type, name_de, name_en, start/end,
UNIQUE(region, event_type, name_de, start_date)) — global snapshot.
- cal_school_config (user_id PRIMARY KEY, bundesland, school year dates).
- cal_school_event — Schul-eigene Termine; CRUD folgt in 9b.
- GET /calendar/holidays?region=&from=&to= — Range-Query against
cal_public_event, ordered by start_date.
- GET / PUT /calendar/config — upsert Bundesland per User.
- SeedFromSnapshot reads internal/seed/calendar_holidays.json on every
boot; idempotent via the unique constraint. Async goroutine so the
HTTP server starts immediately even if the seed file is large.
Data source:
- scripts/calendar-snapshot.sh ruft openholidaysapi.org fuer alle 16
Bundeslaender x 3 Schuljahre und schreibt
school-service/internal/seed/calendar_holidays.json (854 Events,
Stand Schuljahre 2026-2028).
- Dockerfile kopiert das seed/-Verzeichnis ins Image, damit die
Container-Datenbank beim ersten Start gefuellt wird.
Frontend (studio-v2):
- /schulkalender Page mit Gradient + Blobs wie /stundenplan und
/korrektur — gleicher Visual-Style.
- BundeslandWizard: zeigt alle 16 Laender als Dropdown, speichert
bei Klick die Config und switcht zur Monatsansicht.
- MonthView: 6-Wochen-Grid Mo-So, Feiertage rose-toned, Schulferien
amber-toned, heutiges Datum mit Indigo-Ring. Prev/Next/Heute
Navigation.
- lib/schulkalender/api.ts re-uses the stundenplan JWT helper so
auth-mode wechselt nicht.
- Sidebar bekommt einen Schulkalender-Eintrag (Icon mit Datum-Dots,
Pfad /schulkalender) in allen 26 Sprachen.
Tests:
- Go: 3 neue Validator-Tests (Bundesland len=5, EventType oneof,
Pflichtfelder). 77 Tests gesamt, alle gruen.
- Playwright: e2e/schulkalender.spec.ts mit Wizard, Save-Flow,
MonthView-Render, Heute-Button, Sidebar-Link. Hermetisch via
mockCalendarApi.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -40,6 +40,9 @@ COPY --from=builder /app/school-service .
|
||||
# Copy templates directory
|
||||
COPY --from=builder /app/templates ./templates
|
||||
|
||||
# Copy calendar seed snapshot (Phase 9a — OpenHolidaysAPI data)
|
||||
COPY --from=builder /app/internal/seed ./internal/seed
|
||||
|
||||
# Use non-root user
|
||||
USER appuser
|
||||
|
||||
|
||||
@@ -1,7 +1,9 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/config"
|
||||
"github.com/breakpilot/school-service/internal/database"
|
||||
@@ -37,6 +39,19 @@ func main() {
|
||||
// Create handler
|
||||
handler := handlers.NewHandler(db.Pool, cfg.LLMGatewayURL, cfg.SolverServiceURL)
|
||||
|
||||
// Calendar seed — idempotent, runs every boot. Snapshot path is bundled
|
||||
// in the Docker image at /app/internal/seed/calendar_holidays.json. Failures
|
||||
// don't block startup; the holiday table is filled lazily next boot.
|
||||
go func() {
|
||||
seedPath := "internal/seed/calendar_holidays.json"
|
||||
if _, err := os.Stat(seedPath); err != nil {
|
||||
seedPath = "/app/internal/seed/calendar_holidays.json"
|
||||
}
|
||||
if err := handler.CalendarService().SeedFromSnapshot(context.Background(), seedPath); err != nil {
|
||||
log.Printf("calendar seed failed: %v", err)
|
||||
}
|
||||
}()
|
||||
|
||||
// Create router
|
||||
router := gin.New()
|
||||
router.Use(gin.Recovery())
|
||||
@@ -232,6 +247,11 @@ func main() {
|
||||
// Phase 8: exports.
|
||||
api.GET("/timetable/solutions/:id/export.csv", handler.ExportTimetableSolutionCSV)
|
||||
api.GET("/timetable/solutions/:id/export.ics", handler.ExportTimetableSolutionICS)
|
||||
|
||||
// Phase 9a: Schulkalender (holidays + per-user Bundesland config).
|
||||
api.GET("/calendar/holidays", handler.ListCalendarHolidays)
|
||||
api.GET("/calendar/config", handler.GetCalendarConfig)
|
||||
api.PUT("/calendar/config", handler.UpsertCalendarConfig)
|
||||
}
|
||||
|
||||
// Start server
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
package database
|
||||
|
||||
// CalendarMigrations creates the three calendar tables for Phase 9a:
|
||||
//
|
||||
// cal_public_event — read-only snapshot of school holidays + public
|
||||
// holidays from OpenHolidaysAPI. Imported on first
|
||||
// boot via seed/calendar_holidays.json.
|
||||
// cal_school_config — per-Rektor bundesland selection (1 row per user).
|
||||
// cal_school_event — user-managed school events (Fortbildung,
|
||||
// Schulfeier, Klassenfahrt etc.).
|
||||
//
|
||||
// cal_public_event is global (no created_by_user_id) because the data is the
|
||||
// same for every school in a given bundesland. School-events are
|
||||
// per-tenant.
|
||||
func CalendarMigrations() []string {
|
||||
return []string{
|
||||
`CREATE TABLE IF NOT EXISTS cal_public_event (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
region VARCHAR(8) NOT NULL,
|
||||
event_type VARCHAR(20) NOT NULL CHECK (event_type IN ('public_holiday', 'school_holiday')),
|
||||
name_de VARCHAR(255) NOT NULL,
|
||||
name_en VARCHAR(255),
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
source VARCHAR(50) DEFAULT 'OpenHolidaysAPI',
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
UNIQUE(region, event_type, name_de, start_date),
|
||||
CHECK (end_date >= start_date)
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS cal_school_config (
|
||||
user_id UUID PRIMARY KEY,
|
||||
bundesland VARCHAR(8) NOT NULL,
|
||||
school_year_start DATE,
|
||||
school_year_end DATE,
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW()
|
||||
)`,
|
||||
|
||||
`CREATE TABLE IF NOT EXISTS cal_school_event (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
created_by_user_id UUID NOT NULL,
|
||||
title VARCHAR(255) NOT NULL,
|
||||
description TEXT,
|
||||
event_type VARCHAR(30) NOT NULL
|
||||
CHECK (event_type IN ('fortbildung','schulfeier','klassenfahrt','projekttag','eltern_info','andere')),
|
||||
is_school_free BOOLEAN DEFAULT false,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
start_time TIME,
|
||||
end_time TIME,
|
||||
affected_class_ids UUID[] DEFAULT '{}',
|
||||
visible_to_parents BOOLEAN DEFAULT true,
|
||||
notify_parents BOOLEAN DEFAULT false,
|
||||
notify_students BOOLEAN DEFAULT false,
|
||||
notification_lead_days INT[] DEFAULT '{7,1}',
|
||||
created_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ DEFAULT NOW(),
|
||||
CHECK (end_date >= start_date)
|
||||
)`,
|
||||
|
||||
// Indexes — public events are queried by region + date range. School
|
||||
// events are queried by owner + date range.
|
||||
`CREATE INDEX IF NOT EXISTS idx_cal_public_event_region_date
|
||||
ON cal_public_event(region, start_date, end_date)`,
|
||||
`CREATE INDEX IF NOT EXISTS idx_cal_school_event_user_date
|
||||
ON cal_school_event(created_by_user_id, start_date, end_date)`,
|
||||
}
|
||||
}
|
||||
@@ -221,6 +221,9 @@ func Migrate(db *DB) error {
|
||||
// Append timetable solution migrations (see timetable_solution_migrations.go)
|
||||
migrations = append(migrations, TimetableSolutionMigrations()...)
|
||||
|
||||
// Append calendar migrations (see calendar_migrations.go).
|
||||
migrations = append(migrations, CalendarMigrations()...)
|
||||
|
||||
for _, migration := range migrations {
|
||||
_, err := db.Pool.Exec(ctx, migration)
|
||||
if err != nil {
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
// ListCalendarHolidays returns OpenHolidaysAPI events for a region + range.
|
||||
// Query params: ?region=DE-NI&from=2026-08-01&to=2027-07-31. If omitted,
|
||||
// region falls back to the caller's saved config and the range to the
|
||||
// current calendar year.
|
||||
func (h *Handler) ListCalendarHolidays(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
region := c.Query("region")
|
||||
if region == "" {
|
||||
cfg, err := h.calendarService.GetConfig(c.Request.Context(), uid)
|
||||
if err != nil || cfg == nil {
|
||||
respondError(c, http.StatusBadRequest, "region query param required (no saved config)")
|
||||
return
|
||||
}
|
||||
region = cfg.Bundesland
|
||||
}
|
||||
from := c.DefaultQuery("from", time.Now().Format("2006-01-02"))
|
||||
to := c.DefaultQuery("to", time.Now().AddDate(1, 0, 0).Format("2006-01-02"))
|
||||
|
||||
events, err := h.calendarService.ListHolidays(c.Request.Context(), region, from, to)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "Failed to load holidays: "+err.Error())
|
||||
return
|
||||
}
|
||||
if events == nil {
|
||||
events = []models.PublicEvent{}
|
||||
}
|
||||
respondSuccess(c, events)
|
||||
}
|
||||
|
||||
func (h *Handler) GetCalendarConfig(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
cfg, err := h.calendarService.GetConfig(c.Request.Context(), uid)
|
||||
if err != nil {
|
||||
// No row → 200 with null so the wizard knows to prompt.
|
||||
respondSuccess(c, nil)
|
||||
return
|
||||
}
|
||||
respondSuccess(c, cfg)
|
||||
}
|
||||
|
||||
func (h *Handler) UpsertCalendarConfig(c *gin.Context) {
|
||||
uid := getUserID(c)
|
||||
if uid == "" {
|
||||
respondError(c, http.StatusUnauthorized, "User not authenticated")
|
||||
return
|
||||
}
|
||||
var req models.UpsertSchoolCalendarConfigRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
respondError(c, http.StatusBadRequest, "Invalid request: "+err.Error())
|
||||
return
|
||||
}
|
||||
cfg, err := h.calendarService.UpsertConfig(c.Request.Context(), uid, &req)
|
||||
if err != nil {
|
||||
respondError(c, http.StatusInternalServerError, "Failed to save config: "+err.Error())
|
||||
return
|
||||
}
|
||||
respondCreated(c, cfg)
|
||||
}
|
||||
@@ -17,6 +17,7 @@ type Handler struct {
|
||||
certificateService *services.CertificateService
|
||||
aiService *services.AIService
|
||||
timetableService *services.TimetableService
|
||||
calendarService *services.CalendarService
|
||||
solverServiceURL string
|
||||
}
|
||||
|
||||
@@ -29,6 +30,7 @@ func NewHandler(db *pgxpool.Pool, llmGatewayURL, solverServiceURL string) *Handl
|
||||
certificateService := services.NewCertificateService(db, gradeService, gradebookService)
|
||||
aiService := services.NewAIService(llmGatewayURL)
|
||||
timetableService := services.NewTimetableService(db)
|
||||
calendarService := services.NewCalendarService(db)
|
||||
|
||||
return &Handler{
|
||||
classService: classService,
|
||||
@@ -38,10 +40,17 @@ func NewHandler(db *pgxpool.Pool, llmGatewayURL, solverServiceURL string) *Handl
|
||||
certificateService: certificateService,
|
||||
aiService: aiService,
|
||||
timetableService: timetableService,
|
||||
calendarService: calendarService,
|
||||
solverServiceURL: solverServiceURL,
|
||||
}
|
||||
}
|
||||
|
||||
// CalendarService exposes the underlying service so main.go can run the
|
||||
// one-off seed import after migrations.
|
||||
func (h *Handler) CalendarService() *services.CalendarService {
|
||||
return h.calendarService
|
||||
}
|
||||
|
||||
// Health returns the service health status
|
||||
func (h *Handler) Health(c *gin.Context) {
|
||||
c.JSON(http.StatusOK, gin.H{
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// PublicEvent is a holiday or school-vacation row imported from
|
||||
// OpenHolidaysAPI. Global (no owner) — same for every school per region.
|
||||
type PublicEvent struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
Region string `json:"region" db:"region"` // e.g. "DE-NI"
|
||||
EventType string `json:"event_type" db:"event_type"` // public_holiday | school_holiday
|
||||
NameDe string `json:"name_de" db:"name_de"`
|
||||
NameEn string `json:"name_en,omitempty" db:"name_en"`
|
||||
StartDate string `json:"start_date" db:"start_date"` // YYYY-MM-DD
|
||||
EndDate string `json:"end_date" db:"end_date"`
|
||||
Source string `json:"source,omitempty" db:"source"`
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
}
|
||||
|
||||
// SchoolCalendarConfig stores the Bundesland selection for one school
|
||||
// (= one Rektor account). One row per user.
|
||||
type SchoolCalendarConfig struct {
|
||||
UserID uuid.UUID `json:"user_id" db:"user_id"`
|
||||
Bundesland string `json:"bundesland" db:"bundesland"` // DE-NI ...
|
||||
SchoolYearStart *string `json:"school_year_start,omitempty" db:"school_year_start"`
|
||||
SchoolYearEnd *string `json:"school_year_end,omitempty" db:"school_year_end"`
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// SchoolEvent is a user-managed event (Fortbildung, Schulfeier, …).
|
||||
type SchoolEvent struct {
|
||||
ID uuid.UUID `json:"id" db:"id"`
|
||||
CreatedByUserID uuid.UUID `json:"created_by_user_id" db:"created_by_user_id"`
|
||||
Title string `json:"title" db:"title"`
|
||||
Description string `json:"description,omitempty" db:"description"`
|
||||
EventType string `json:"event_type" db:"event_type"`
|
||||
IsSchoolFree bool `json:"is_school_free" db:"is_school_free"`
|
||||
StartDate string `json:"start_date" db:"start_date"`
|
||||
EndDate string `json:"end_date" db:"end_date"`
|
||||
StartTime *string `json:"start_time,omitempty" db:"start_time"`
|
||||
EndTime *string `json:"end_time,omitempty" db:"end_time"`
|
||||
AffectedClassIDs []uuid.UUID `json:"affected_class_ids" db:"affected_class_ids"`
|
||||
VisibleToParents bool `json:"visible_to_parents" db:"visible_to_parents"`
|
||||
NotifyParents bool `json:"notify_parents" db:"notify_parents"`
|
||||
NotifyStudents bool `json:"notify_students" db:"notify_students"`
|
||||
NotificationLeadDays []int `json:"notification_lead_days" db:"notification_lead_days"`
|
||||
CreatedAt time.Time `json:"created_at" db:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
|
||||
}
|
||||
|
||||
// Request DTOs
|
||||
|
||||
// UpsertSchoolCalendarConfigRequest sets or updates the Bundesland for the
|
||||
// authenticated user. Both school-year dates are optional (defaults to the
|
||||
// running year based on today's date).
|
||||
type UpsertSchoolCalendarConfigRequest struct {
|
||||
Bundesland string `json:"bundesland" binding:"required,len=5"`
|
||||
SchoolYearStart *string `json:"school_year_start,omitempty"`
|
||||
SchoolYearEnd *string `json:"school_year_end,omitempty"`
|
||||
}
|
||||
|
||||
type CreateSchoolEventRequest struct {
|
||||
Title string `json:"title" binding:"required"`
|
||||
Description string `json:"description"`
|
||||
EventType string `json:"event_type" binding:"required,oneof=fortbildung schulfeier klassenfahrt projekttag eltern_info andere"`
|
||||
IsSchoolFree bool `json:"is_school_free"`
|
||||
StartDate string `json:"start_date" binding:"required"`
|
||||
EndDate string `json:"end_date" binding:"required"`
|
||||
StartTime *string `json:"start_time,omitempty"`
|
||||
EndTime *string `json:"end_time,omitempty"`
|
||||
AffectedClassIDs []string `json:"affected_class_ids"`
|
||||
VisibleToParents bool `json:"visible_to_parents"`
|
||||
NotifyParents bool `json:"notify_parents"`
|
||||
NotifyStudents bool `json:"notify_students"`
|
||||
NotificationLeadDays []int `json:"notification_lead_days"`
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,134 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// CalendarService owns the cal_* tables and the read of the seed snapshot
|
||||
// on first boot. Holidays are global (no owner) — same data for every
|
||||
// school in a given Bundesland.
|
||||
type CalendarService struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewCalendarService(db *pgxpool.Pool) *CalendarService {
|
||||
return &CalendarService{db: db}
|
||||
}
|
||||
|
||||
// SeedFromSnapshot reads internal/seed/calendar_holidays.json and bulk-inserts
|
||||
// every row that doesn't already exist (idempotent via the unique constraint
|
||||
// on region+event_type+name_de+start_date). Called once at server start.
|
||||
func (s *CalendarService) SeedFromSnapshot(ctx context.Context, path string) error {
|
||||
raw, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
log.Printf("calendar seed file not found at %s — skipping", path)
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("read snapshot: %w", err)
|
||||
}
|
||||
|
||||
var events []models.PublicEvent
|
||||
if err := json.Unmarshal(raw, &events); err != nil {
|
||||
return fmt.Errorf("parse snapshot: %w", err)
|
||||
}
|
||||
|
||||
tx, err := s.db.Begin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
|
||||
inserted := 0
|
||||
for _, e := range events {
|
||||
ct, err := tx.Exec(ctx, `
|
||||
INSERT INTO cal_public_event (region, event_type, name_de, name_en, start_date, end_date, source)
|
||||
VALUES ($1, $2, $3, NULLIF($4, ''), $5::date, $6::date, 'OpenHolidaysAPI')
|
||||
ON CONFLICT (region, event_type, name_de, start_date) DO NOTHING
|
||||
`, e.Region, e.EventType, e.NameDe, e.NameEn, e.StartDate, e.EndDate)
|
||||
if err != nil {
|
||||
return fmt.Errorf("insert event: %w", err)
|
||||
}
|
||||
inserted += int(ct.RowsAffected())
|
||||
}
|
||||
|
||||
if err := tx.Commit(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
log.Printf("calendar seed: %d new events inserted (of %d in snapshot)", inserted, len(events))
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListHolidays returns all public + school holidays for the given region
|
||||
// between from..to (YYYY-MM-DD inclusive).
|
||||
func (s *CalendarService) ListHolidays(ctx context.Context, region, from, to string) ([]models.PublicEvent, error) {
|
||||
rows, err := s.db.Query(ctx, `
|
||||
SELECT id, region, event_type, name_de, COALESCE(name_en, ''),
|
||||
start_date::text, end_date::text, COALESCE(source, ''), created_at
|
||||
FROM cal_public_event
|
||||
WHERE region = $1
|
||||
AND end_date >= $2::date
|
||||
AND start_date <= $3::date
|
||||
ORDER BY start_date, event_type, name_de
|
||||
`, region, from, to)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []models.PublicEvent
|
||||
for rows.Next() {
|
||||
var e models.PublicEvent
|
||||
if err := rows.Scan(&e.ID, &e.Region, &e.EventType, &e.NameDe, &e.NameEn,
|
||||
&e.StartDate, &e.EndDate, &e.Source, &e.CreatedAt); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, e)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetConfig returns the per-user calendar config (Bundesland etc.) or nil
|
||||
// if the user has not configured one yet.
|
||||
func (s *CalendarService) GetConfig(ctx context.Context, userID string) (*models.SchoolCalendarConfig, error) {
|
||||
var c models.SchoolCalendarConfig
|
||||
err := s.db.QueryRow(ctx, `
|
||||
SELECT user_id, bundesland, school_year_start::text, school_year_end::text, created_at, updated_at
|
||||
FROM cal_school_config WHERE user_id = $1
|
||||
`, userID).Scan(&c.UserID, &c.Bundesland, &c.SchoolYearStart, &c.SchoolYearEnd, &c.CreatedAt, &c.UpdatedAt)
|
||||
if err != nil {
|
||||
// pgx returns no-rows error; caller maps to 404.
|
||||
return nil, err
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
// UpsertConfig inserts or updates the Bundesland selection.
|
||||
func (s *CalendarService) UpsertConfig(ctx context.Context, userID string, req *models.UpsertSchoolCalendarConfigRequest) (*models.SchoolCalendarConfig, error) {
|
||||
var c models.SchoolCalendarConfig
|
||||
err := s.db.QueryRow(ctx, `
|
||||
INSERT INTO cal_school_config (user_id, bundesland, school_year_start, school_year_end)
|
||||
VALUES ($1, $2, NULLIF($3, '')::date, NULLIF($4, '')::date)
|
||||
ON CONFLICT (user_id) DO UPDATE
|
||||
SET bundesland = EXCLUDED.bundesland,
|
||||
school_year_start = EXCLUDED.school_year_start,
|
||||
school_year_end = EXCLUDED.school_year_end,
|
||||
updated_at = NOW()
|
||||
RETURNING user_id, bundesland, school_year_start::text, school_year_end::text, created_at, updated_at
|
||||
`, userID, req.Bundesland, strOrEmpty(req.SchoolYearStart), strOrEmpty(req.SchoolYearEnd)).
|
||||
Scan(&c.UserID, &c.Bundesland, &c.SchoolYearStart, &c.SchoolYearEnd, &c.CreatedAt, &c.UpdatedAt)
|
||||
return &c, err
|
||||
}
|
||||
|
||||
func strOrEmpty(s *string) string {
|
||||
if s == nil {
|
||||
return ""
|
||||
}
|
||||
return *s
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"github.com/breakpilot/school-service/internal/models"
|
||||
)
|
||||
|
||||
func TestUpsertSchoolCalendarConfigRequest_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req models.UpsertSchoolCalendarConfigRequest
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid NI", models.UpsertSchoolCalendarConfigRequest{Bundesland: "DE-NI"}, false},
|
||||
{"empty bundesland", models.UpsertSchoolCalendarConfigRequest{Bundesland: ""}, true},
|
||||
{"too long", models.UpsertSchoolCalendarConfigRequest{Bundesland: "DE-NIE"}, true},
|
||||
{"too short", models.UpsertSchoolCalendarConfigRequest{Bundesland: "DE"}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if (validate.Struct(tt.req) != nil) != tt.wantErr {
|
||||
t.Errorf("unexpected validation outcome for %s", tt.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreateSchoolEventRequest_Validation(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
req models.CreateSchoolEventRequest
|
||||
wantErr bool
|
||||
}{
|
||||
{"valid fortbildung", models.CreateSchoolEventRequest{
|
||||
Title: "SCHILF", EventType: "fortbildung",
|
||||
StartDate: "2026-10-01", EndDate: "2026-10-01",
|
||||
}, false},
|
||||
{"missing title", models.CreateSchoolEventRequest{
|
||||
EventType: "fortbildung", StartDate: "2026-10-01", EndDate: "2026-10-01",
|
||||
}, true},
|
||||
{"invalid event type", models.CreateSchoolEventRequest{
|
||||
Title: "X", EventType: "wedding",
|
||||
StartDate: "2026-10-01", EndDate: "2026-10-01",
|
||||
}, true},
|
||||
{"missing dates", models.CreateSchoolEventRequest{
|
||||
Title: "X", EventType: "schulfeier",
|
||||
}, true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if (validate.Struct(tt.req) != nil) != tt.wantErr {
|
||||
t.Errorf("unexpected validation outcome for %s", tt.name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewCalendarService_Constructs(t *testing.T) {
|
||||
s := NewCalendarService(nil)
|
||||
if s == nil {
|
||||
t.Fatal("expected non-nil service")
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user