Closes the search half of the unified Fristenrechner. Phase D (concept-card
UI on /tools/fristenrechner) follows in a subsequent shift.
Migration 047:
- Seed the missing `wiedereinsetzung` concept and re-point the four
Wiedereinsetzung trigger_events (200..203) at it. PR-7 referenced
the slug `re-establishment-of-rights` but never seeded the concept,
so the four cross-cutting triggers were dropping out of any concept-
JOINing query. Per m's slug rule (Q1: shared cross-cutting concepts
use DE slug because German term dominates HLC vocabulary).
- Create paliad.deadline_search materialised view: UNION ALL of
(deadline_rules joined to deadline_concepts) and (trigger_events
joined to deadline_concepts via slug). Trigram GIN indexes on
legal_source / concept_name_de / concept_name_en / rule_name_de /
rule_name_en / rule_code; gin (concept_aliases) for array
containment; UNIQUE INDEX on a synthetic row_key so refresh can
run CONCURRENTLY.
Refresh strategy: data only mutates via migration files at server
startup, so no AFTER triggers and no pg_cron — main.go calls
services.RefreshSearchView right after db.ApplyMigrations. CONCURRENTLY
keeps reads online and stays well under 100 ms at < 1k rows.
Service `internal/services/deadline_search_service.go`:
- Two-query pipeline per request: (1) rank concept_ids by
GREATEST(similarity()) across name / aliases / legal_source / rule_code
plus a 0.2 alias-hit boost; (2) load all matview rows for the top-N
concepts and assemble per-pill JSON.
- normalizeQuery strips legal-prefix noise (`§`, `Art.`, `Section`,
`Rule `) so users typing `§ 82` find DE.PatG.82.1 even though the
structured legal_source column doesn't carry the prefix.
- FormatLegalSourceDisplay renders structured codes back to the
pleading form HLC users expect:
UPC.RoP.23.1 → "UPC RoP R.23(1)"
DE.PatG.82.1 → "PatG §82(1)"
EU.EPÜ.108 → "EPÜ Art.108"
EU.EPC-R.79.1 → "EPC R.79(1)"
EU.RPBA.12.1.c → "RPBA Art.12(1)(c)"
- Drill URLs route per kind: rule pills → ?proc=…&focus=…, trigger
pills → ?mode=event&triggerId=…
Handler `GET /api/tools/fristenrechner/search?q=&party=&proc=&source=&limit=`:
- Returns the JSON shape from design §6.1 (cards-with-pills).
- 503 with friendly DE message when DATABASE_URL is unset, mirroring
the other Fristenrechner endpoints.
- Empty q returns an empty cards array (browse surface is Phase D).
Tests:
- Pure-Go: TestFormatLegalSourceDisplay (12 cases across all known
prefixes) + TestNormalizeQuery (8 cases).
- Integration (skipped without TEST_DATABASE_URL): golden table
pinning the design's binding queries — Klageerwiderung returns the
statement-of-defence card with UPC.RoP.23.1, DE.ZPO.276.1,
DE.PatG.82.1, EU.EPC-R.79.1, DE.PatG.59.3 pills; "RoP 23" returns
the same card; "§ 82" → normalized "82" → BPatG hit; Wiedereinsetzung
returns one card with exactly 4 trigger pills (ids 200..203);
party / source filters narrow as expected; limit cap honoured.
- SQL semantics validated against live data via supabase MCP using a
CTE-inlined matview definition with the slug fix simulated; results
match the golden table.
Per design doc `docs/plans/unified-fristenrechner.md` §4.6 (matview
shape) + §6 (search ranking + API).
184 lines
7.0 KiB
Go
184 lines
7.0 KiB
Go
package main
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"net/http"
|
|
"os"
|
|
"os/signal"
|
|
"syscall"
|
|
|
|
// Embed Go's IANA tz database into the binary so time.LoadLocation works
|
|
// without OS tzdata. The runtime image (alpine) doesn't ship /usr/share/
|
|
// zoneinfo — without this import, every reminder timezone lookup fails
|
|
// silently and the hourly reminder slot fires in UTC instead of the
|
|
// user's chosen tz (t-paliad-064 root cause). Adds ~450KB to the binary.
|
|
_ "time/tzdata"
|
|
|
|
"mgit.msbls.de/m/paliad/internal/auth"
|
|
"mgit.msbls.de/m/paliad/internal/branding"
|
|
"mgit.msbls.de/m/paliad/internal/db"
|
|
"mgit.msbls.de/m/paliad/internal/handlers"
|
|
"mgit.msbls.de/m/paliad/internal/services"
|
|
)
|
|
|
|
func main() {
|
|
port := os.Getenv("PORT")
|
|
if port == "" {
|
|
port = "8080"
|
|
}
|
|
|
|
// Surface the firm name in the boot log so a deployer can confirm
|
|
// FIRM_NAME took effect without curl-ing a rendered page.
|
|
log.Printf("branding: firm=%q (override with FIRM_NAME)", branding.Name)
|
|
|
|
supabaseURL := os.Getenv("SUPABASE_URL")
|
|
supabaseAnonKey := os.Getenv("SUPABASE_ANON_KEY")
|
|
if supabaseURL == "" || supabaseAnonKey == "" {
|
|
log.Fatal("SUPABASE_URL and SUPABASE_ANON_KEY must be set")
|
|
}
|
|
|
|
jwtSecret := os.Getenv("SUPABASE_JWT_SECRET")
|
|
if jwtSecret == "" {
|
|
log.Fatal("SUPABASE_JWT_SECRET must be set — session cookies cannot be trusted without signature verification")
|
|
}
|
|
|
|
client := auth.NewClient(supabaseURL, supabaseAnonKey, []byte(jwtSecret))
|
|
|
|
giteaToken := os.Getenv("GITEA_TOKEN")
|
|
if giteaToken == "" {
|
|
log.Println("GITEA_TOKEN not set — file proxy will not be able to access private repos")
|
|
}
|
|
|
|
// MailService is wired regardless of DB availability — it no-ops when
|
|
// SMTP env vars are unset, so the server stays runnable for knowledge-
|
|
// platform-only deployments. Template-parse errors at boot are fatal.
|
|
mailSvc, err := services.NewMailService()
|
|
if err != nil {
|
|
log.Fatalf("mail service init: %v", err)
|
|
}
|
|
|
|
// Shared context for background goroutines (CalDAV sync + reminder job).
|
|
bgCtx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
|
defer stop()
|
|
|
|
// DATABASE_URL is optional during the Phase A → Phase D transition. The
|
|
// existing knowledge-platform features (Kostenrechner, Glossar, etc.) work
|
|
// without a DB. matter-management endpoints return 503 until DATABASE_URL is set.
|
|
dbURL := os.Getenv("DATABASE_URL")
|
|
var svcBundle *handlers.Services
|
|
var caldavSvc *services.CalDAVService
|
|
|
|
if dbURL != "" {
|
|
log.Println("applying database migrations…")
|
|
if err := db.ApplyMigrations(dbURL); err != nil {
|
|
log.Fatalf("migration failed: %v", err)
|
|
}
|
|
log.Println("database migrations applied")
|
|
|
|
pool, err := db.OpenPool(dbURL)
|
|
if err != nil {
|
|
log.Fatalf("open db pool: %v", err)
|
|
}
|
|
|
|
// Refresh paliad.deadline_search whenever migrations run, so
|
|
// search reflects any newly-seeded rule / concept / trigger.
|
|
// Migration 047 created the matview already-populated; this
|
|
// is only a no-op for the boot that introduced it. CONCURRENTLY
|
|
// keeps reads online and stays well under 100 ms at < 1k rows.
|
|
if err := services.RefreshSearchView(bgCtx, pool); err != nil {
|
|
log.Printf("refresh deadline_search: %v", err)
|
|
}
|
|
holidays := services.NewHolidayService(pool)
|
|
users := services.NewUserService(pool)
|
|
projectSvc := services.NewProjectService(pool, users)
|
|
teamSvc := services.NewTeamService(pool, projectSvc)
|
|
partnerUnitSvc := services.NewPartnerUnitService(pool, users)
|
|
rules := services.NewDeadlineRuleService(pool)
|
|
|
|
// Phase F: optional CalDAV cipher. If CALDAV_ENCRYPTION_KEY is unset
|
|
// the service exists but Enabled() reports false; handlers return 501.
|
|
// If the env var is malformed, fail fast — silently skipping would
|
|
// leave plaintext-credential bugs hidden.
|
|
cipher, err := services.LoadCalDAVCipher()
|
|
if err != nil {
|
|
log.Fatalf("CALDAV_ENCRYPTION_KEY: %v", err)
|
|
}
|
|
if cipher == nil {
|
|
log.Println("CALDAV_ENCRYPTION_KEY not set — CalDAV endpoints will return 501")
|
|
} else {
|
|
log.Println("CalDAV encryption configured (AES-256-GCM)")
|
|
}
|
|
|
|
appointmentSvc := services.NewAppointmentService(pool, projectSvc)
|
|
caldavSvc = services.NewCalDAVService(pool, cipher, appointmentSvc)
|
|
// Wire the push hook so user-driven mutations sync to the external
|
|
// calendar without waiting for the next 60-second tick.
|
|
appointmentSvc.SetCalDAVPusher(caldavSvc)
|
|
|
|
baseURL := os.Getenv("PALIAD_BASE_URL")
|
|
inviteSvc := services.NewInviteService(pool, mailSvc, handlers.AllowedEmailDomains, baseURL)
|
|
reminderSvc := services.NewReminderService(pool, mailSvc, users, baseURL)
|
|
|
|
// Wire EmailTemplateService onto the MailService so DB-backed admin
|
|
// edits propagate without a process restart. The constructor is split
|
|
// from MailService creation because the DB pool isn't available yet
|
|
// at the point we build mailSvc above.
|
|
emailTemplateSvc := services.NewEmailTemplateService(pool)
|
|
mailSvc.SetTemplateService(emailTemplateSvc)
|
|
|
|
eventTypeSvc := services.NewEventTypeService(pool, users)
|
|
deadlineSvc := services.NewDeadlineService(pool, projectSvc, eventTypeSvc)
|
|
svcBundle = &handlers.Services{
|
|
Project: projectSvc,
|
|
Team: teamSvc,
|
|
PartnerUnit: partnerUnitSvc,
|
|
Party: services.NewPartyService(pool, projectSvc),
|
|
Deadline: deadlineSvc,
|
|
Appointment: appointmentSvc,
|
|
CalDAV: caldavSvc,
|
|
Rules: rules,
|
|
Calculator: services.NewDeadlineCalculator(holidays),
|
|
Users: users,
|
|
Fristenrechner: services.NewFristenrechnerService(rules, holidays),
|
|
EventDeadline: services.NewEventDeadlineService(pool, services.NewDeadlineCalculator(holidays), holidays),
|
|
DeadlineSearch: services.NewDeadlineSearchService(pool),
|
|
EventType: eventTypeSvc,
|
|
Dashboard: services.NewDashboardService(pool, users),
|
|
Note: services.NewNoteService(pool, projectSvc, appointmentSvc),
|
|
ChecklistInst: services.NewChecklistInstanceService(pool, projectSvc),
|
|
Mail: mailSvc,
|
|
Invite: inviteSvc,
|
|
Agenda: services.NewAgendaService(pool, users, eventTypeSvc),
|
|
Audit: services.NewAuditService(pool),
|
|
EmailTemplate: emailTemplateSvc,
|
|
Link: services.NewLinkService(pool),
|
|
Event: services.NewEventService(pool, deadlineSvc, appointmentSvc),
|
|
}
|
|
log.Println("Phase B services initialised")
|
|
|
|
// Spawn background goroutines: CalDAV sync (one per enabled user)
|
|
// and the hourly reminder scanner. Both live for the process
|
|
// lifetime; the signal-scoped context cleans them up on SIGTERM.
|
|
if err := caldavSvc.Start(bgCtx); err != nil {
|
|
log.Printf("CalDAV start: %v", err)
|
|
}
|
|
reminderSvc.Start(bgCtx)
|
|
go func() {
|
|
<-bgCtx.Done()
|
|
log.Println("background services: shutdown signal received")
|
|
caldavSvc.Stop()
|
|
}()
|
|
} else {
|
|
log.Println("DATABASE_URL not set — matter-management endpoints will return 503")
|
|
}
|
|
|
|
mux := http.NewServeMux()
|
|
handlers.Register(mux, client, giteaToken, svcBundle)
|
|
|
|
log.Printf("paliad server starting on :%s", port)
|
|
if err := http.ListenAndServe(":"+port, mux); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
}
|