Compare commits

...

6 Commits

Author SHA1 Message Date
mAi
cd5f752a0e feat(litigationplanner): scenarios — paliad.scenarios jsonb table + Catalog API + engine adapter (Slice D, t-paliad-306, m/paliad#124 §5)
Some checks failed
Paliad CI gate / build (push) Has been cancelled
Paliad CI gate / test-go (push) Has been cancelled
Paliad CI gate / deploy (push) Has been cancelled
A scenario is a named composition of existing proceedings + flags +
per-card choices + anchor dates. Users compose, they don't author —
spec references existing rules by submission_code; never creates new
rules. Per m's 2026-05-26 AskUserQuestion picks (doc commit 6e58595):
  Q1 composition: primary + spawned (v1); multi-proceeding peer
                  compose is the v2 goal (spec.proceedings[] array)
  Q2 scope:       per-project + abstract (project_id NULL = abstract)
  Q3 trigger:     per-anchor overrides over one base date
  Q4 storage:     NEW paliad.scenarios table with jsonb spec
                  (NOT a project_event_choices column extension)

Migration 145 — additive only. Pre-flight coordination check:
  - On-disk max: 138 (Berufung backfill, just merged).
  - Live DB tracker: 106 (significantly behind — many migs pending
    deploy).
  - curie's #93 B.2-B.6 migs not pushed yet — reserved 139-143 + 144
    as buffer; claimed 145 as the safe minimum that won't collide.
  - paliad.scenarios has audit_reason NOT applicable (no audit
    trigger on the table); updated_at trigger added on the table
    itself.
  - paliad.projects gains active_scenario_id uuid NULL FK with ON
    DELETE SET NULL (mig 134 lesson — no updated_at clauses on
    proceeding_types-style assumptions).

Schema:
  paliad.scenarios (
    id uuid pk,
    project_id uuid NULL FK → projects(id) ON DELETE CASCADE,
    name text NOT NULL CHECK char_length > 0,
    description text NULL,
    spec jsonb NOT NULL CHECK jsonb_typeof = 'object',
    created_by uuid NULL FK → users(id) ON DELETE SET NULL,
    created_at + updated_at timestamptz,
    UNIQUE NULLS NOT DISTINCT (project_id, created_by, name)
  );
  paliad.projects.active_scenario_id uuid NULL FK;
  RLS: project-scoped → can_see_project; abstract → created_by = auth.uid();
  Trigger: scenarios_touch_updated_at_trg.

pkg/litigationplanner additions:
  - Scenario struct (db + json tags)
  - ScenarioSpec / ScenarioProceeding / ScenarioCardChoice — parsed
    view of the jsonb (version-1 today, v2 multi-peer-ready)
  - ParseSpec(raw) + ScenarioSpec.PrimaryProceeding() + CalcOptionsFromSpec()
  - ScenarioFilter + Catalog.LoadScenarios + Catalog.MatchScenario
  - CalculateFromScenario(scenario, catalog, holidays, courts) — high-
    level engine entry: parses spec → builds CalcOptions → delegates
    to Calculate
  - Sentinel errors: ErrUnknownScenario, ErrInvalidScenario,
    ErrScenarioNoPrimary

paliadCatalog impl:
  - LoadScenarios with progressively-built WHERE clauses (project-id
    filter, abstract-for-user filter, or all)
  - MatchScenario by id — returns ErrUnknownScenario on not-found
  - Services connection bypasses RLS; ScenarioService enforces
    visibility at the application layer (mirrors EventChoiceService
    pattern from t-paliad-265)

SnapshotCatalog impl (embedded/upc):
  - LoadScenarios returns empty slice (no scenarios in the snapshot)
  - MatchScenario returns ErrUnknownScenario

internal/services/scenario_service.go:
  - Create / Get / ListForProject / ListAbstractForUser / Patch /
    SetActive / Delete with visibility checks
  - validateSpec checks version, base_trigger_date format, every
    proceedings[*].code resolves to an active paliad.proceeding_types
    row, every appeal_target is valid, every anchor_overrides date
    parses, every role ∈ {primary, peer}
  - SetActive validates the scenario belongs to the requested project
    (a scenario from a different project can't be active here)
  - Returns ErrScenarioNotVisible for failed visibility checks

REST endpoints (registered in handlers.go):
  GET    /api/scenarios?project=<id>             — list project's
  GET    /api/scenarios?abstract=true            — list user's abstract
  GET    /api/scenarios/{id}                     — one
  POST   /api/scenarios                          — create
  PATCH  /api/scenarios/{id}                     — partial update
  DELETE /api/scenarios/{id}                     — remove
  PUT    /api/projects/{id}/active-scenario      — set / clear active

Handler error mapping:
  - ErrUnknownScenario / ErrScenarioNotVisible → 404
  - ErrInvalidInput / ErrInvalidScenario / ErrScenarioNoPrimary → 400
  - everything else → 500

Tests:
  - pkg/litigationplanner/scenarios_test.go: ParseSpec roundtrip
    (well-formed + unknown version + malformed json),
    PrimaryProceeding zero/multi/single, CalcOptionsFromSpec full
    unpack, trigger_date_override path, no-base-trigger safety check.
    8 cases total, all DB-free.

Wired in cmd/server/main.go alongside EventChoice — same pattern,
nil-safe when DATABASE_URL is unset (handlers 503 in that mode).

Acceptance:
  - go build ./... clean
  - go test ./... all green (incl. new scenarios tests)
  - Pre-flight audit confirmed mig 145 number is safe vs curie's
    pending B.2-B.6 range
2026-05-26 17:48:56 +02:00
mAi
2377f08bd7 Merge: t-paliad-304 — R.109 anchor + columns-view duplicate fix (topo walk + 'both'→ours collapse) (m/paliad#135)
Some checks failed
Paliad CI gate / build (push) Has been cancelled
Paliad CI gate / test-go (push) Has been cancelled
Paliad CI gate / deploy (push) Has been cancelled
2026-05-26 15:54:39 +02:00
mAi
1d704f6e04 fix(litigationplanner): R.109.1/R.109.4 mis-anchor + duplicate 'both' row in columns view (t-paliad-304, m/paliad#135)
Two bugs surfaced on /tools/verfahrensablauf?side=defendant for upc.inf.cfi:

1. Anchor regression for timing='before' children of court-set parents.
   Rules R.109.1 (translation_request) and R.109.4 (interpreter_cost)
   anchor on the oral hearing (parent_id=upc.inf.cfi.oral, IsCourtSet)
   but were computing dates BEFORE the Statement of Claim — 1 month
   resp. 2 weeks before the SoC instead of before the oral hearing.

   Root cause: engine walked rules in sequence_order, and the two
   "before"-timed children carry sequence_order 45/46 (their chronological
   position, before the oral hearing at 50). Their parent had therefore
   not been processed yet when the children were, so courtSet[oral.ID]
   was still empty → parentIsCourtSet=false → the engine fell back to
   the trigger date as the base.

   Fix: walk rules in topological order (parent-first) during the
   compute pass, then restore sequence_order on the output slice so
   the wire shape and the linear timeline view's render order stay
   identical to the legacy behaviour modulo the bug fix.

2. Duplicate "Antrag auf Simultanübersetzung" row in columns view.
   With primary_party='both' and an explicit side pick (?side=defendant),
   the bucketing mirrored the card into both 'Unsere Seite' and
   'Gegnerseite' — the same card on the same row, visible as a
   duplicate.

   Fix: when the user has committed to a perspective (side picked)
   but no appellant axis applies, collapse 'both' rows into ours.
   The '↔ beide Seiten' indicator is suppressed in that path to match
   the existing appellant-collapse semantics (no sibling row to mirror
   to). Legacy mirror behaviour is preserved when side is null.

DB audit ruled out a data-level duplicate: exactly one published+active
row per submission_code in paliad.deadline_rules.

Tests:
  - pkg/litigationplanner/before_court_set_anchor_test.go: synthetic
    rules pinning the conditional-on-court-set-parent contract plus
    the override path (1mo before user-pinned oral).
  - frontend/src/client/views/verfahrensablauf-core.test.ts: two new
    cases pinning the side-collapse routing for party='both'.
2026-05-26 15:54:02 +02:00
mAi
a75731a902 Merge: t-paliad-302 — Verfahrensablauf duration indicator (hover + toggle, +3 lp.TimelineEntry fields) (m/paliad#133)
Some checks failed
Paliad CI gate / build (push) Has been cancelled
Paliad CI gate / test-go (push) Has been cancelled
Paliad CI gate / deploy (push) Has been cancelled
2026-05-26 15:45:15 +02:00
mAi
727e01c6c9 Merge: t-paliad-303 — backfill applies_to_target: Schadensbemessung (merits) + Bucheinsicht (order) (mig 138) (m/paliad#134)
Some checks failed
Paliad CI gate / build (push) Has been cancelled
Paliad CI gate / test-go (push) Has been cancelled
Paliad CI gate / deploy (push) Has been cancelled
2026-05-26 15:44:19 +02:00
mAi
3097df3918 mAi: #133 — Verfahrensablauf duration affordance (hover + toggle)
Some checks failed
Paliad CI gate / build (push) Has been cancelled
Paliad CI gate / test-go (push) Has been cancelled
Paliad CI gate / deploy (push) Has been cancelled
t-paliad-302 / m/paliad#133. Surface each event card's rule duration
("2 Mo. nach") on /tools/verfahrensablauf — by default as a hover
tooltip on the date span, and optionally inline via a new
"Dauern anzeigen" header toggle (localStorage key
paliad.verfahrensablauf.durations-show).

The issue scoped this as pure-frontend on the assumption that the
duration fields were already on the /api/tools/fristenrechner payload.
They were not: lp.TimelineEntry exposed only the computed dueDate, not
the rule's (duration_value, duration_unit, timing) tuple. Added these
as three additive optional fields and populated them in both engine
emission sites (Calculate + CalculateByTriggerEvent) from the rule
row directly. Source values are the base rule fields, not the
post-alt-swap arithmetic — the tooltip reads as a property of the
rule rather than a recap of which branch fired.

Frontend wiring:
- formatDurationLabel() in verfahrensablauf-core builds the
  "<value> <unit> <timing>" string from the existing
  deadlines.event.unit.<unit>.{one,many} + deadlines.event.timing.*
  i18n keys, reused from /tools/fristenrechner's event-mode renderer.
- deadlineCardHtml attaches the label as title= on the date span
  (hover, default) and, when CardOpts.showDurations is on, emits an
  inline <span class="timeline-duration"> in the meta row.
- Court-set / zero-duration rules (trigger event, hearings) skip the
  affordance — durationValue <= 0 short-circuits in
  formatDurationLabel.
- Toggle persisted in localStorage under
  paliad.verfahrensablauf.durations-show, default off; sits next to
  the existing "Hinweise anzeigen" toggle.

bun run build clean, go test ./pkg/litigationplanner/... and
./internal/... clean, bun test src/client/views clean (89/89).
2026-05-26 15:43:30 +02:00
22 changed files with 1885 additions and 13 deletions

View File

@@ -221,6 +221,8 @@ func main() {
Export: services.NewExportService(pool, branding.Name),
// t-paliad-265 / m/paliad#96 — per-event-card optional choices.
EventChoice: services.NewEventChoiceService(pool, projectSvc, users),
// Slice D (m/paliad#124 §5, mig 145) — named scenario compositions.
Scenario: services.NewScenarioService(pool, projectSvc, rules),
}
// t-paliad-246 Slice A — Backup Mode runner. Wired only when

View File

@@ -312,6 +312,7 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.view.timeline": "Zeitstrahl",
"deadlines.view.columns": "Spalten",
"deadlines.notes.show": "Hinweise anzeigen",
"deadlines.durations.show": "Dauern anzeigen",
"deadlines.col.ours": "Unsere Seite",
"deadlines.col.court": "Gericht",
"deadlines.col.opponent": "Gegnerseite",
@@ -3406,6 +3407,7 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.view.timeline": "Timeline",
"deadlines.view.columns": "Columns",
"deadlines.notes.show": "Show details",
"deadlines.durations.show": "Show durations",
"deadlines.col.ours": "Client Side",
"deadlines.col.court": "Court",
"deadlines.col.opponent": "Opponent Side",

View File

@@ -276,6 +276,21 @@ function writeNotesPref(on: boolean): void {
}
let showNotes = readNotesPref();
// Durations toggle (m/paliad#133, t-paliad-302) — when off (default),
// the per-rule duration label ("2 Mo. nach") only shows on hover via
// the date span's `title` attribute. When on, the label renders inline
// in the timeline meta row of every event card. Persisted in
// localStorage under its own key so the preference is independent of
// "Hinweise anzeigen".
const DURATIONS_PREF_KEY = "paliad.verfahrensablauf.durations-show";
function readDurationsPref(): boolean {
try { return localStorage.getItem(DURATIONS_PREF_KEY) === "1"; } catch { return false; }
}
function writeDurationsPref(on: boolean): void {
try { localStorage.setItem(DURATIONS_PREF_KEY, on ? "1" : "0"); } catch { /* no-op */ }
}
let showDurations = readDurationsPref();
// Jurisdiction display prefix for the proceeding-summary chip + the
// trigger-event placeholder. Same forum slugs the .proceeding-group
// `data-forum` attribute carries in verfahrensablauf.tsx /
@@ -482,6 +497,7 @@ function renderResults(data: DeadlineResponse) {
? renderColumnsBody(data, {
editable: true,
showNotes,
showDurations,
side: currentSide,
// t-paliad-301: the appellant axis collapses into the single
// side picker. For role-swap proceedings, currentSide IS the
@@ -490,7 +506,7 @@ function renderResults(data: DeadlineResponse) {
// the appellant axis is irrelevant — pass null.
appellant: hasAppellantAxis(selectedType) ? currentSide : null,
})
: renderTimelineBody(data, { showParty: true, editable: true, showNotes });
: renderTimelineBody(data, { showParty: true, editable: true, showNotes, showDurations });
container.innerHTML = headerHtml + noteHtml + bodyHtml;
if (printBtn) printBtn.style.display = "block";
@@ -868,6 +884,19 @@ document.addEventListener("DOMContentLoaded", () => {
});
}
// Durations toggle (m/paliad#133, t-paliad-302) — sibling of the
// notes toggle. Hover-only labels (default) become inline labels when
// the user opts in.
const durationsShowCb = document.getElementById("verfahrensablauf-durations-show") as HTMLInputElement | null;
if (durationsShowCb) {
durationsShowCb.checked = showDurations;
durationsShowCb.addEventListener("change", () => {
showDurations = durationsShowCb.checked;
writeDurationsPref(showDurations);
if (lastResponse) renderResults(lastResponse);
});
}
// t-paliad-290 — show-hidden toggle. Hydrate from URL, wire change
// to URL + recalc (the backend reshapes the response — we can't just
// re-render lastResponse since the hidden rows aren't in it when the

View File

@@ -327,6 +327,29 @@ describe("bucketDeadlinesIntoColumns — side+appellant column routing (m/paliad
expect(rows[0].ours).toHaveLength(0);
});
test("side=defendant collapses 'both' rules into ours (no mirror) — m/paliad#135", () => {
// When the user has committed to a perspective via `?side=`, the
// mirror is visual noise: the same card renders twice on one row,
// once in 'Unsere Seite' and once in 'Gegnerseite'. The card's
// '↔ beide Seiten' indicator already conveys the both-parties
// semantic, so collapsing into ours is sufficient.
const rows = bucketDeadlinesIntoColumns(
[both("Antrag auf Simultanübersetzung", "2026-04-27")],
{ side: "defendant" },
);
expect(rows[0].ours.map((d) => d.name)).toEqual(["Antrag auf Simultanübersetzung"]);
expect(rows[0].opponent).toHaveLength(0);
});
test("side=claimant collapses 'both' rules into ours (no mirror) — m/paliad#135", () => {
const rows = bucketDeadlinesIntoColumns(
[both("Antrag auf Simultanübersetzung", "2026-04-27")],
{ side: "claimant" },
);
expect(rows[0].ours.map((d) => d.name)).toEqual(["Antrag auf Simultanübersetzung"]);
expect(rows[0].opponent).toHaveLength(0);
});
test("rows align across columns by dueDate so same-day events stay on one grid row", () => {
const sameDate = "2026-07-23";
const rows = bucketDeadlinesIntoColumns([

View File

@@ -95,6 +95,36 @@ export interface CalculatedDeadline {
parentRuleCode?: string;
parentRuleName?: string;
parentRuleNameEN?: string;
// durationValue / durationUnit / timing surface the rule's arithmetic
// so the timeline card can show "2 Mo. nach" on hover (and inline when
// the "Dauern anzeigen" toggle is on). Zero-duration rules (root
// event, court-set) carry durationValue=0 and the renderer suppresses
// the affordance — those don't have an explainable interval.
// (m/paliad#133, t-paliad-302)
durationValue?: number;
durationUnit?: string;
timing?: string;
}
// formatDurationLabel renders the per-rule duration ("2 Mo. nach") for
// the Verfahrensablauf card affordance (m/paliad#133, t-paliad-302).
// Returns empty string for rules without a usable duration so the
// caller can skip the tooltip / inline span entirely.
//
// Pluralisation key naming mirrors the Fristenrechner event-mode
// renderer (deadlines.event.unit.<unit>.{one,many}) — the unit and
// timing translations already exist for /tools/fristenrechner's
// "Was kommt nach…" mode and are reused here as the single
// source of truth.
export function formatDurationLabel(dl: CalculatedDeadline): string {
const value = dl.durationValue ?? 0;
const unit = dl.durationUnit || "";
if (value <= 0 || !unit) return "";
const unitKey = `deadlines.event.unit.${unit}` + (value === 1 ? ".one" : ".many");
const unitStr = tDyn(unitKey);
const timing = dl.timing || "";
const timingStr = timing ? tDyn(`deadlines.event.timing.${timing}`) : "";
return timingStr ? `${value} ${unitStr} ${timingStr}` : `${value} ${unitStr}`;
}
// priorityRendering returns the per-priority UX hints the save-modal
@@ -321,15 +351,38 @@ export interface CardOpts {
// Page shells expose a toggle ("Hinweise anzeigen") that flips this and
// re-renders. Default false — notes are noisy on long timelines.
showNotes?: boolean;
// showDurations controls per-rule duration rendering on event cards
// (m/paliad#133, t-paliad-302):
// true → inline `<span class="timeline-duration">2 Mo. nach</span>`
// next to the date.
// false → hover-only tooltip on the date span (browser-native
// `title` attribute). Cards without a usable
// `durationValue > 0` get neither — court-set and trigger-
// event cards have no explainable interval.
// /tools/verfahrensablauf exposes a toggle ("Dauern anzeigen") that
// flips this and re-renders; persisted via the localStorage key
// `paliad.verfahrensablauf.durations-show`. Default false.
showDurations?: boolean;
}
export function deadlineCardHtml(dl: CalculatedDeadline, opts: CardOpts): string {
const wantsEditable = !!opts.editable;
const editable = wantsEditable && !dl.isRootEvent && dl.code !== "";
const overriddenClass = dl.isOverridden ? " timeline-date--overridden" : "";
// Duration affordance (m/paliad#133, t-paliad-302). Computed once so
// both the date-span tooltip and the inline meta-row span pull from
// the same string. Empty for rules without a usable duration.
const durationLabel = formatDurationLabel(dl);
// Hover affordance on the date span: prefer the duration tooltip when
// we have one, else fall back to the edit-hint when the cell is
// click-to-edit. The edit affordance still works either way — the
// title is purely advisory.
const dateTitle = durationLabel
? durationLabel
: (editable ? t("deadlines.date.edit.hint") : "");
const editAttrs = editable
? ` data-rule-code="${escAttr(dl.code)}" data-current-date="${escAttr(dl.dueDate)}" role="button" tabindex="0" title="${escAttr(t("deadlines.date.edit.hint"))}"`
: "";
? ` data-rule-code="${escAttr(dl.code)}" data-current-date="${escAttr(dl.dueDate)}" role="button" tabindex="0"${dateTitle ? ` title="${escAttr(dateTitle)}"` : ""}`
: (dateTitle ? ` title="${escAttr(dateTitle)}"` : "");
// Conditional rows (t-paliad-289) replace the date column with an
// "abhängig von <parent>" chip. The chip remains click-to-edit so
// the user can pin a real date once known (e.g. once the oral
@@ -434,9 +487,19 @@ export function deadlineCardHtml(dl: CalculatedDeadline, opts: CardOpts): string
? `<span class="timeline-note-hint" tabindex="0" role="note" aria-label="${escAttr(noteText)}" title="${escAttr(noteText)}">ⓘ</span>`
: "";
const meta = (opts.showParty || ruleRef || noteHint)
// Inline duration affordance (m/paliad#133, t-paliad-302). Only
// emitted when the "Dauern anzeigen" toggle is on AND the rule has a
// usable duration; the default-off hover-tooltip path is wired
// separately on the date span itself.
const showDurations = opts.showDurations === true;
const durationInline = showDurations && durationLabel
? `<span class="timeline-duration">${escHtml(durationLabel)}</span>`
: "";
const meta = (opts.showParty || ruleRef || noteHint || durationInline)
? `<div class="timeline-meta">
${opts.showParty ? partyBadge(dl.party) : ""}
${durationInline}
${ruleRef}
${noteHint}
</div>`
@@ -614,6 +677,9 @@ type ColumnPosition = "ours" | "opponent";
export interface ColumnsBodyOpts {
editable?: boolean;
showNotes?: boolean;
// Forwarded to deadlineCardHtml — see CardOpts.showDurations.
// (m/paliad#133, t-paliad-302)
showDurations?: boolean;
// side: which side the user is on. Drives column placement;
// does NOT filter rows. Default null = claimant-on-the-left
// (i.e. "ours = claimant", legacy default).
@@ -698,7 +764,18 @@ export function bucketDeadlinesIntoColumns(
// Role-swap collapse: appellant initiated → both → one row
// in appellant's column. Mirror suppressed.
row[appellantColumn].push(dl);
} else if (userSide !== null) {
// Side picked but no appellant axis (first-instance Inf, Rev,
// …): the user has committed to a perspective, so the mirror
// is visual noise — the same card appears twice on the same
// row, once in "Unsere Seite" and once in "Gegnerseite".
// Collapse into ours; the "↔ beide Seiten" indicator on the
// card already conveys that the rule applies to both parties.
// (m/paliad#135 / t-paliad-304)
row.ours.push(dl);
} else {
// No perspective picked → keep the legacy mirror so neither
// axis is privileged. Pinned by the "default (no opts)" test.
row.ours.push(dl);
row.opponent.push(dl);
}
@@ -724,12 +801,23 @@ export function renderColumnsBody(data: DeadlineResponse, opts: ColumnsBodyOpts
const rows = bucketDeadlinesIntoColumns(data.deadlines, { side: userSide, appellant: opts.appellant });
const appellantPinned = opts.appellant === "claimant" || opts.appellant === "defendant";
const cardOpts: CardOpts = { showParty: false, editable: opts.editable, showNotes: opts.showNotes };
const cardOpts: CardOpts = {
showParty: false,
editable: opts.editable,
showNotes: opts.showNotes,
showDurations: opts.showDurations,
};
// Collapsed "both" rows lose their mirror tag — there's no longer
// a sibling row to mirror to, so the "↔ beide Seiten" hint would
// be misleading. Keep it for the legacy mirror path.
const showMirrorTag = !appellantPinned;
// be misleading. Both collapse paths suppress it:
// - appellantPinned: role-swap collapse into appellant's column
// - userSide !== null without appellantPinned: perspective-locked
// collapse into ours (m/paliad#135 / t-paliad-304).
// Legacy mirror path (no side, no appellant) keeps the tag — both
// sibling rows still render so the tag has a visual referent.
const sideCollapse = userSide !== null;
const showMirrorTag = !appellantPinned && !sideCollapse;
const renderCell = (items: CalculatedDeadline[]): string => {
if (items.length === 0) {

View File

@@ -1264,6 +1264,7 @@ export type I18nKey =
| "deadlines.dpma.appeal.bgh"
| "deadlines.dpma.appeal.bpatg"
| "deadlines.dpma.opp.dpma"
| "deadlines.durations.show"
| "deadlines.empty.filtered"
| "deadlines.empty.hint"
| "deadlines.empty.title"

View File

@@ -3750,6 +3750,16 @@ input[type="range"]::-moz-range-thumb {
color: var(--color-text-muted);
}
/* Per-rule duration label rendered inline in the meta row when
"Dauern anzeigen" is on (m/paliad#133, t-paliad-302). Matches the
sibling .timeline-rule weight so the meta line reads as one band of
secondary metadata; non-mono so the value reads as prose ("2 Mo. nach")
rather than a code reference. */
.timeline-duration {
font-size: 0.72rem;
color: var(--color-text-muted);
}
.timeline-adjusted {
font-size: 0.78rem;
color: var(--status-amber-fg-2);

View File

@@ -341,6 +341,13 @@ export function renderVerfahrensablauf(): string {
<input type="checkbox" id="fristen-notes-show" />
<span data-i18n="deadlines.notes.show">Hinweise anzeigen</span>
</label>
{/* Durations toggle (m/paliad#133, t-paliad-302).
Default off — hover-tooltips on date spans are
the always-on path. */}
<label className="fristen-notes-option">
<input type="checkbox" id="verfahrensablauf-durations-show" />
<span data-i18n="deadlines.durations.show">Dauern anzeigen</span>
</label>
</div>
<div id="timeline-container">

View File

@@ -0,0 +1,13 @@
-- 145_scenarios — DOWN
--
-- Reverses mig 145. Drops the FK on paliad.projects, the table, the
-- trigger function, and the RLS policies (CASCADE on table drop kills
-- policies). Any data in paliad.scenarios is lost on down.
ALTER TABLE paliad.projects
DROP COLUMN IF EXISTS active_scenario_id;
DROP TRIGGER IF EXISTS scenarios_touch_updated_at_trg ON paliad.scenarios;
DROP FUNCTION IF EXISTS paliad.scenarios_touch_updated_at();
DROP TABLE IF EXISTS paliad.scenarios CASCADE;

View File

@@ -0,0 +1,170 @@
-- 145_scenarios — Slice D, m/paliad#124 §5 (revised)
--
-- Creates paliad.scenarios + paliad.projects.active_scenario_id FK.
-- A scenario is a named composition of existing proceedings + flags
-- + per-card choices + anchor dates the user can switch between for
-- a project (project_id NOT NULL) OR save as an abstract template on
-- /tools/verfahrensablauf (project_id IS NULL).
--
-- m's 2026-05-26 picks (AskUserQuestion round, doc commit 6e58595):
-- Q1: composition shape → primary+spawned (v1); multi-proceeding
-- peer compose is the v2 goal. spec.jsonb
-- architected for N entries from day 1.
-- Q2: scope → per-project + abstract.
-- Q3: trigger dates → per-anchor overrides over one base date.
-- Q4: storage → NEW paliad.scenarios table with jsonb
-- spec (NOT a project_event_choices column
-- extension).
--
-- "users should not add their own rules" (m, t-paliad-301) — scenarios
-- compose existing rules, never author new ones. spec.proceedings[*].code
-- must resolve to an existing active paliad.proceeding_types row;
-- spec.proceedings[*].anchor_overrides keys must resolve to existing
-- submission_codes. Validation happens at the application layer
-- (ScenarioService.validateSpec) — not in DB CHECK constraints (too
-- expensive to express in pure SQL).
--
-- Migration number: 145. Coordination check 2026-05-26 17:38: curie's
-- B.2-B.6 migrations land in the 139-143 range. 144 reserved as buffer.
-- 145 is the next safe claim.
--
-- ADDITIVE ONLY: CREATE TABLE, ALTER ADD COLUMN, indexes, RLS policies.
-- Down drops everything. No backfill (zero existing scenarios on day 1).
--
-- See docs/design-litigation-planner-2026-05-26.md §5 + §18.4 for the
-- design.
-- ---------------------------------------------------------------
-- 1. The scenarios table
-- ---------------------------------------------------------------
CREATE TABLE paliad.scenarios (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
-- project_id NULL = abstract scenario (saved Verfahrensablauf
-- template, no Akte). project_id NOT NULL = scenario attached to
-- a real Akte.
project_id uuid NULL REFERENCES paliad.projects(id) ON DELETE CASCADE,
name text NOT NULL,
description text NULL,
-- spec carries the full composition. Shape documented in the
-- design doc §5; the application validates structure before write.
spec jsonb NOT NULL,
created_by uuid NULL REFERENCES paliad.users(id) ON DELETE SET NULL,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
-- Within a single project, scenario names are unique. Abstract
-- scenarios are unique per (created_by, name) so two users can
-- each keep a "with_ccr" template without colliding. NULLS NOT
-- DISTINCT means a single user can have one "name" per
-- (project_id, created_by) tuple, where NULL project_id +
-- NULL created_by is a single global namespace (used only by
-- seed / system scenarios — none today).
CONSTRAINT scenarios_unique_per_scope
UNIQUE NULLS NOT DISTINCT (project_id, created_by, name),
-- Non-empty name.
CONSTRAINT scenarios_name_nonempty CHECK (char_length(name) > 0),
-- Non-empty spec — at least an object. The application checks
-- structure (version, proceedings[], base_trigger_date format).
CONSTRAINT scenarios_spec_object CHECK (jsonb_typeof(spec) = 'object')
);
CREATE INDEX scenarios_project_id_idx
ON paliad.scenarios(project_id) WHERE project_id IS NOT NULL;
CREATE INDEX scenarios_abstract_user_idx
ON paliad.scenarios(created_by) WHERE project_id IS NULL;
COMMENT ON TABLE paliad.scenarios IS
'Named compositions of existing proceedings + flags + per-card '
'choices + anchor dates. project_id NULL = abstract template; '
'project_id NOT NULL = attached to an Akte. Design: '
'docs/design-litigation-planner-2026-05-26.md §5. (Slice D)';
COMMENT ON COLUMN paliad.scenarios.spec IS
'jsonb composition spec. Shape: {version: int, base_trigger_date: '
'ISO date, proceedings: [{code, role, flags[], per_card_choices, '
'anchor_overrides, skip_rules[]}, ...]}. Validated at write-time '
'by ScenarioService.validateSpec.';
-- ---------------------------------------------------------------
-- 2. paliad.projects.active_scenario_id FK
--
-- NULL = use today's ad-hoc per-card choice state from
-- paliad.project_event_choices (pre-scenario behaviour preserved).
-- Non-NULL = the project's current SmartTimeline / Akte-Fristenrechner
-- render reads from this scenario's spec instead.
-- ---------------------------------------------------------------
ALTER TABLE paliad.projects
ADD COLUMN active_scenario_id uuid NULL
REFERENCES paliad.scenarios(id) ON DELETE SET NULL;
COMMENT ON COLUMN paliad.projects.active_scenario_id IS
'FK to paliad.scenarios. NULL = read choices from '
'paliad.project_event_choices (legacy). Non-NULL = read from the '
'pointed scenario.spec.';
-- ---------------------------------------------------------------
-- 3. RLS — mirror paliad.project_event_choices's pattern (mig 129).
--
-- Project-scoped scenarios (project_id NOT NULL) inherit team visibility
-- via paliad.can_see_project. Abstract scenarios (project_id IS NULL)
-- are private to created_by — only the author can read / write them.
-- ---------------------------------------------------------------
ALTER TABLE paliad.scenarios ENABLE ROW LEVEL SECURITY;
-- Project-scoped: team visibility.
DROP POLICY IF EXISTS scenarios_project_select ON paliad.scenarios;
CREATE POLICY scenarios_project_select ON paliad.scenarios
FOR SELECT
USING (project_id IS NOT NULL AND paliad.can_see_project(project_id));
DROP POLICY IF EXISTS scenarios_project_mutate ON paliad.scenarios;
CREATE POLICY scenarios_project_mutate ON paliad.scenarios
FOR ALL
USING (project_id IS NOT NULL AND paliad.can_see_project(project_id))
WITH CHECK (project_id IS NOT NULL AND paliad.can_see_project(project_id));
-- Abstract: owner-only.
DROP POLICY IF EXISTS scenarios_abstract_select ON paliad.scenarios;
CREATE POLICY scenarios_abstract_select ON paliad.scenarios
FOR SELECT
USING (project_id IS NULL AND created_by = auth.uid());
DROP POLICY IF EXISTS scenarios_abstract_mutate ON paliad.scenarios;
CREATE POLICY scenarios_abstract_mutate ON paliad.scenarios
FOR ALL
USING (project_id IS NULL AND created_by = auth.uid())
WITH CHECK (project_id IS NULL AND created_by = auth.uid());
-- ---------------------------------------------------------------
-- 4. updated_at trigger (mirrors other paliad tables that carry
-- updated_at — keep it in lockstep with row mutations).
-- ---------------------------------------------------------------
CREATE OR REPLACE FUNCTION paliad.scenarios_touch_updated_at()
RETURNS trigger AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$ LANGUAGE plpgsql;
CREATE TRIGGER scenarios_touch_updated_at_trg
BEFORE UPDATE ON paliad.scenarios
FOR EACH ROW
EXECUTE FUNCTION paliad.scenarios_touch_updated_at();
-- ---------------------------------------------------------------
-- 5. Informational NOTICE — schema-only migration, zero rows added.
-- ---------------------------------------------------------------
DO $$
BEGIN
RAISE NOTICE '[mig 145] paliad.scenarios created (0 rows; awaits API usage)';
RAISE NOTICE '[mig 145] paliad.projects.active_scenario_id added (all rows NULL initially)';
END $$;

View File

@@ -120,6 +120,11 @@ type Services struct {
// the Verfahrensablauf timeline.
EventChoice *services.EventChoiceService
// Slice D (m/paliad#124 §5, mig 145) — named scenario compositions
// per project or as abstract templates. Nil when DATABASE_URL is
// unset; the /api/scenarios routes return 503 in that case.
Scenario *services.ScenarioService
// Paliadin is wired when DATABASE_URL is set. The concrete backend
// is picked in cmd/server/main.go based on PALIADIN_REMOTE_HOST
// (remote → mRiver via SSH) or local tmux availability. Stays nil
@@ -184,6 +189,7 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
backup: svc.Backup,
submissionDraft: svc.SubmissionDraft,
eventChoice: svc.EventChoice,
scenario: svc.Scenario,
}
}
@@ -446,6 +452,15 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("PUT /api/projects/{id}/event-choices", handlePutProjectEventChoice)
protected.HandleFunc("DELETE /api/projects/{id}/event-choices/{submission_code}/{choice_kind}", handleDeleteProjectEventChoice)
// Slice D (m/paliad#124 §5, mig 145) — named scenario compositions
// per project or as abstract templates on /tools/verfahrensablauf.
protected.HandleFunc("GET /api/scenarios", handleScenariosList)
protected.HandleFunc("GET /api/scenarios/{id}", handleScenarioGet)
protected.HandleFunc("POST /api/scenarios", handleScenarioCreate)
protected.HandleFunc("PATCH /api/scenarios/{id}", handleScenarioPatch)
protected.HandleFunc("DELETE /api/scenarios/{id}", handleScenarioDelete)
protected.HandleFunc("PUT /api/projects/{id}/active-scenario", handleSetActiveScenario)
// Partner units (structural partner-led units; legacy "Dezernate").
protected.HandleFunc("GET /api/partner-units", handleListPartnerUnits)
protected.HandleFunc("POST /api/partner-units", handleCreatePartnerUnit)

View File

@@ -71,6 +71,9 @@ type dbServices struct {
// t-paliad-265 — per-event-card optional choices.
eventChoice *services.EventChoiceService
// Slice D — named scenario compositions (m/paliad#124 §5).
scenario *services.ScenarioService
}
var dbSvc *dbServices

View File

@@ -0,0 +1,216 @@
package handlers
import (
"encoding/json"
"errors"
"net/http"
"github.com/google/uuid"
"mgit.msbls.de/m/paliad/internal/services"
lp "mgit.msbls.de/m/paliad/pkg/litigationplanner"
)
// Slice D (m/paliad#124 §5, mig 145) — REST endpoints for paliad.scenarios.
//
// Routes (registered in handlers.go):
//
// GET /api/scenarios?project=<id> — list project's scenarios
// GET /api/scenarios?abstract=true — list caller's abstract scenarios
// GET /api/scenarios/{id} — fetch one
// POST /api/scenarios — create
// PATCH /api/scenarios/{id} — partial update
// PUT /api/projects/{id}/active-scenario — set/clear active scenario
// DELETE /api/scenarios/{id} — remove
//
// All endpoints require auth; visibility is enforced by
// ScenarioService.requireProjectVisible / requireVisible.
func requireScenarioService(w http.ResponseWriter) bool {
if dbSvc == nil || dbSvc.scenario == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "Szenarien sind vorübergehend nicht verfügbar (keine Datenbank).",
})
return false
}
return true
}
// scenarioErrorToStatus maps service errors to HTTP statuses. Mirrors
// the patterns in projects.go and event_choices.go.
func scenarioErrorToStatus(err error) (int, string) {
switch {
case errors.Is(err, lp.ErrUnknownScenario), errors.Is(err, services.ErrScenarioNotVisible):
return http.StatusNotFound, "Szenario nicht gefunden"
case errors.Is(err, services.ErrInvalidInput), errors.Is(err, lp.ErrInvalidScenario), errors.Is(err, lp.ErrScenarioNoPrimary):
return http.StatusBadRequest, err.Error()
}
return http.StatusInternalServerError, err.Error()
}
// handleScenariosList — GET /api/scenarios?project=<uuid> OR ?abstract=true.
func handleScenariosList(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
abstract := r.URL.Query().Get("abstract") == "true"
projectStr := r.URL.Query().Get("project")
switch {
case abstract:
out, err := dbSvc.scenario.ListAbstractForUser(r.Context(), uid)
if err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
writeJSON(w, http.StatusOK, out)
case projectStr != "":
pid, err := uuid.Parse(projectStr)
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige project ID"})
return
}
out, err := dbSvc.scenario.ListForProject(r.Context(), uid, pid)
if err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
writeJSON(w, http.StatusOK, out)
default:
writeJSON(w, http.StatusBadRequest, map[string]string{
"error": "?project=<uuid> oder ?abstract=true erforderlich",
})
}
}
// handleScenarioGet — GET /api/scenarios/{id}.
func handleScenarioGet(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige ID"})
return
}
out, err := dbSvc.scenario.Get(r.Context(), uid, id)
if err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
writeJSON(w, http.StatusOK, out)
}
// handleScenarioCreate — POST /api/scenarios.
func handleScenarioCreate(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
var input services.CreateScenarioInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige Anfrage"})
return
}
out, err := dbSvc.scenario.Create(r.Context(), uid, input)
if err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
writeJSON(w, http.StatusCreated, out)
}
// handleScenarioPatch — PATCH /api/scenarios/{id}.
func handleScenarioPatch(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige ID"})
return
}
var input services.PatchScenarioInput
if err := json.NewDecoder(r.Body).Decode(&input); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige Anfrage"})
return
}
out, err := dbSvc.scenario.Patch(r.Context(), uid, id, input)
if err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
writeJSON(w, http.StatusOK, out)
}
// handleScenarioDelete — DELETE /api/scenarios/{id}.
func handleScenarioDelete(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
id, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige ID"})
return
}
if err := dbSvc.scenario.Delete(r.Context(), uid, id); err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
w.WriteHeader(http.StatusNoContent)
}
// handleSetActiveScenario — PUT /api/projects/{id}/active-scenario.
// Body: {"scenario_id": "<uuid>"} or {"scenario_id": null} to clear.
func handleSetActiveScenario(w http.ResponseWriter, r *http.Request) {
if !requireScenarioService(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
pid, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige project ID"})
return
}
var body struct {
ScenarioID *uuid.UUID `json:"scenario_id"`
}
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "ungültige Anfrage"})
return
}
if err := dbSvc.scenario.SetActive(r.Context(), uid, pid, body.ScenarioID); err != nil {
status, msg := scenarioErrorToStatus(err)
writeJSON(w, status, map[string]string{"error": msg})
return
}
w.WriteHeader(http.StatusNoContent)
}

View File

@@ -516,6 +516,61 @@ func computeDepths(
return depths
}
// LoadScenarios lists scenarios visible to the caller (Slice D,
// m/paliad#124 §5, mig 145). RLS on paliad.scenarios enforces:
// project-scoped rows require paliad.can_see_project(project_id);
// abstract rows require created_by = auth.uid(). The filter narrows
// the SELECT (project_id-bound, abstract-for-user, or all).
func (c *paliadCatalog) LoadScenarios(ctx context.Context, filter lp.ScenarioFilter) ([]lp.Scenario, error) {
where := []string{}
args := []any{}
add := func(clause string, val any) {
args = append(args, val)
where = append(where, fmt.Sprintf(clause, len(args)))
}
if filter.ProjectID != nil {
add("project_id = $%d", *filter.ProjectID)
}
if filter.AbstractForUser != nil {
where = append(where, "project_id IS NULL")
add("created_by = $%d", *filter.AbstractForUser)
}
query := `SELECT id, project_id, name, description, spec,
created_by, created_at, updated_at
FROM paliad.scenarios`
if len(where) > 0 {
query += " WHERE " + strings.Join(where, " AND ")
}
query += " ORDER BY created_at DESC"
var rows []lp.Scenario
if err := c.rules.db.SelectContext(ctx, &rows, query, args...); err != nil {
return nil, fmt.Errorf("load scenarios: %w", err)
}
return rows, nil
}
// MatchScenario returns the scenario with the given id, or
// lp.ErrUnknownScenario if not visible / not found. RLS gates
// visibility; a not-found result could mean "doesn't exist" OR
// "exists but you can't see it" — either way the caller treats it
// as unknown.
func (c *paliadCatalog) MatchScenario(ctx context.Context, id uuid.UUID) (*lp.Scenario, error) {
var s lp.Scenario
err := c.rules.db.GetContext(ctx, &s,
`SELECT id, project_id, name, description, spec,
created_by, created_at, updated_at
FROM paliad.scenarios
WHERE id = $1`, id)
if errors.Is(err, sql.ErrNoRows) {
return nil, lp.ErrUnknownScenario
}
if err != nil {
return nil, fmt.Errorf("match scenario %q: %w", id, err)
}
return &s, nil
}
// _ proves paliadCatalog satisfies lp.Catalog at compile time.
var _ lp.Catalog = (*paliadCatalog)(nil)

View File

@@ -0,0 +1,347 @@
package services
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"mgit.msbls.de/m/paliad/internal/models"
lp "mgit.msbls.de/m/paliad/pkg/litigationplanner"
)
// ScenarioService reads + writes paliad.scenarios — named compositions
// of existing proceedings + flags + per-card choices + anchor dates,
// switchable per project or saved as abstract templates on
// /tools/verfahrensablauf. Slice D, m/paliad#124 §5, mig 145.
//
// Visibility:
// - Project-scoped scenarios (project_id NOT NULL): require
// can_see_project on the bound project (mirrors
// EventChoiceService.requireProjectVisible).
// - Abstract scenarios (project_id IS NULL): owner-only. Only
// created_by can read / mutate.
//
// The service applies these checks in application code; paliad.scenarios
// also has RLS policies (mig 145) as defense-in-depth for callers that
// connect through Supabase Auth's auth.uid() session.
type ScenarioService struct {
db *sqlx.DB
projects *ProjectService
rules *DeadlineRuleService
}
// NewScenarioService wires the service to its dependencies.
func NewScenarioService(db *sqlx.DB, projects *ProjectService, rules *DeadlineRuleService) *ScenarioService {
return &ScenarioService{db: db, projects: projects, rules: rules}
}
// Sentinel errors. Mirrors EventChoiceService + the lp package errors
// so handlers can map cleanly to HTTP statuses.
var (
ErrScenarioNotVisible = errors.New("scenario not visible to caller")
)
// CreateScenarioInput is the payload for POST /api/scenarios. project_id
// nil = abstract scenario (saved Verfahrensablauf template).
type CreateScenarioInput struct {
ProjectID *uuid.UUID `json:"project_id,omitempty"`
Name string `json:"name"`
Description *string `json:"description,omitempty"`
Spec json.RawMessage `json:"spec"`
}
// Create inserts a new scenario after validating the spec.
func (s *ScenarioService) Create(ctx context.Context, userID uuid.UUID, input CreateScenarioInput) (*lp.Scenario, error) {
if input.Name == "" {
return nil, fmt.Errorf("%w: name required", ErrInvalidInput)
}
if err := s.validateSpec(ctx, input.Spec); err != nil {
return nil, err
}
if input.ProjectID != nil {
if err := s.requireProjectVisible(ctx, userID, *input.ProjectID); err != nil {
return nil, err
}
}
var out lp.Scenario
err := s.db.GetContext(ctx, &out,
`INSERT INTO paliad.scenarios (project_id, name, description, spec, created_by)
VALUES ($1, $2, $3, $4, $5)
RETURNING id, project_id, name, description, spec, created_by,
created_at, updated_at`,
input.ProjectID, input.Name, input.Description,
[]byte(input.Spec), userID)
if err != nil {
return nil, fmt.Errorf("create scenario: %w", err)
}
return &out, nil
}
// Get returns one scenario by id after a visibility check.
func (s *ScenarioService) Get(ctx context.Context, userID, scenarioID uuid.UUID) (*lp.Scenario, error) {
var sc lp.Scenario
err := s.db.GetContext(ctx, &sc,
`SELECT id, project_id, name, description, spec, created_by,
created_at, updated_at
FROM paliad.scenarios
WHERE id = $1`, scenarioID)
if errors.Is(err, sql.ErrNoRows) {
return nil, lp.ErrUnknownScenario
}
if err != nil {
return nil, fmt.Errorf("get scenario: %w", err)
}
if err := s.requireVisible(ctx, userID, &sc); err != nil {
return nil, err
}
return &sc, nil
}
// ListForProject returns scenarios attached to one project, ordered by
// created_at desc.
func (s *ScenarioService) ListForProject(ctx context.Context, userID, projectID uuid.UUID) ([]lp.Scenario, error) {
if err := s.requireProjectVisible(ctx, userID, projectID); err != nil {
return nil, err
}
out := []lp.Scenario{}
err := s.db.SelectContext(ctx, &out,
`SELECT id, project_id, name, description, spec, created_by,
created_at, updated_at
FROM paliad.scenarios
WHERE project_id = $1
ORDER BY created_at DESC`, projectID)
if err != nil {
return nil, fmt.Errorf("list scenarios for project: %w", err)
}
return out, nil
}
// ListAbstractForUser returns the calling user's abstract scenarios.
func (s *ScenarioService) ListAbstractForUser(ctx context.Context, userID uuid.UUID) ([]lp.Scenario, error) {
out := []lp.Scenario{}
err := s.db.SelectContext(ctx, &out,
`SELECT id, project_id, name, description, spec, created_by,
created_at, updated_at
FROM paliad.scenarios
WHERE project_id IS NULL AND created_by = $1
ORDER BY created_at DESC`, userID)
if err != nil {
return nil, fmt.Errorf("list abstract scenarios: %w", err)
}
return out, nil
}
// PatchScenarioInput is the payload for PATCH /api/scenarios/{id}. Any
// field nil means "don't change". Spec replacement re-runs validation.
type PatchScenarioInput struct {
Name *string `json:"name,omitempty"`
Description *string `json:"description,omitempty"`
Spec json.RawMessage `json:"spec,omitempty"`
}
// Patch updates one or more scenario fields. Visibility check fires
// first (the caller must already see the scenario to mutate it).
func (s *ScenarioService) Patch(ctx context.Context, userID, scenarioID uuid.UUID, input PatchScenarioInput) (*lp.Scenario, error) {
current, err := s.Get(ctx, userID, scenarioID)
if err != nil {
return nil, err
}
if len(input.Spec) > 0 {
if err := s.validateSpec(ctx, input.Spec); err != nil {
return nil, err
}
}
sets := []string{}
args := []any{}
add := func(clause string, val any) {
args = append(args, val)
sets = append(sets, fmt.Sprintf(clause, len(args)))
}
if input.Name != nil {
add("name = $%d", *input.Name)
}
if input.Description != nil {
add("description = $%d", *input.Description)
}
if len(input.Spec) > 0 {
add("spec = $%d", []byte(input.Spec))
}
if len(sets) == 0 {
return current, nil
}
args = append(args, scenarioID)
query := fmt.Sprintf(`UPDATE paliad.scenarios SET %s
WHERE id = $%d
RETURNING id, project_id, name, description, spec, created_by,
created_at, updated_at`, joinSets(sets), len(args))
var out lp.Scenario
if err := s.db.GetContext(ctx, &out, query, args...); err != nil {
return nil, fmt.Errorf("patch scenario: %w", err)
}
return &out, nil
}
// SetActive points a project at one of its scenarios. Pass nil to
// clear (revert to ad-hoc per-card choice state).
func (s *ScenarioService) SetActive(ctx context.Context, userID, projectID uuid.UUID, scenarioID *uuid.UUID) error {
if err := s.requireProjectVisible(ctx, userID, projectID); err != nil {
return err
}
if scenarioID != nil {
// Ensure scenario exists + belongs to this project. A scenario
// from a different project (or an abstract one) can't be the
// active scenario on this project.
sc, err := s.Get(ctx, userID, *scenarioID)
if err != nil {
return err
}
if sc.ProjectID == nil || *sc.ProjectID != projectID {
return fmt.Errorf("%w: scenario %s is not attached to project %s",
ErrInvalidInput, *scenarioID, projectID)
}
}
_, err := s.db.ExecContext(ctx,
`UPDATE paliad.projects SET active_scenario_id = $1 WHERE id = $2`,
scenarioID, projectID)
if err != nil {
return fmt.Errorf("set active scenario: %w", err)
}
return nil
}
// Delete removes a scenario. Project's active_scenario_id is cleared
// automatically via the FK's ON DELETE SET NULL.
func (s *ScenarioService) Delete(ctx context.Context, userID, scenarioID uuid.UUID) error {
// Visibility check via Get — also resolves the existence question.
if _, err := s.Get(ctx, userID, scenarioID); err != nil {
return err
}
if _, err := s.db.ExecContext(ctx,
`DELETE FROM paliad.scenarios WHERE id = $1`, scenarioID); err != nil {
return fmt.Errorf("delete scenario: %w", err)
}
return nil
}
// requireVisible enforces the per-row visibility rule:
// - project_id NOT NULL → caller must see the project
// - project_id IS NULL → caller must be the row's created_by
func (s *ScenarioService) requireVisible(ctx context.Context, userID uuid.UUID, sc *lp.Scenario) error {
if sc.ProjectID != nil {
return s.requireProjectVisible(ctx, userID, *sc.ProjectID)
}
if sc.CreatedBy == nil || *sc.CreatedBy != userID {
return ErrScenarioNotVisible
}
return nil
}
// requireProjectVisible mirrors EventChoiceService.requireProjectVisible
// (visibility via can_see_project). Cheap re-implementation — keeps the
// call-graph small + avoids a cross-service dep.
func (s *ScenarioService) requireProjectVisible(ctx context.Context, userID, projectID uuid.UUID) error {
var visible bool
err := s.db.GetContext(ctx, &visible,
`SELECT EXISTS (
SELECT 1 FROM paliad.users u
WHERE u.id = $1 AND u.global_role = 'global_admin'
) OR EXISTS (
SELECT 1 FROM paliad.projects p
JOIN paliad.project_teams pt ON pt.project_id = ANY(
string_to_array(p.path, '.')::uuid[]
)
WHERE p.id = $2 AND pt.user_id = $1
)`, userID, projectID)
if err != nil {
return fmt.Errorf("check project visibility: %w", err)
}
if !visible {
return ErrScenarioNotVisible
}
return nil
}
// validateSpec checks the jsonb spec is well-formed, has the right
// version, and that every referenced proceeding code + submission code
// resolves to an active row in the live catalog. Surfaces friendly
// errors wrapping ErrInvalidInput so the handler can map to a 400.
func (s *ScenarioService) validateSpec(ctx context.Context, raw json.RawMessage) error {
if len(raw) == 0 {
return fmt.Errorf("%w: spec is required", ErrInvalidInput)
}
parsed, err := lp.ParseSpec(lp.NullableJSON(raw))
if err != nil {
return fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if _, err := parsed.PrimaryProceeding(); err != nil {
return fmt.Errorf("%w: %v", ErrInvalidInput, err)
}
if parsed.BaseTriggerDate != "" {
if _, err := time.Parse("2006-01-02", parsed.BaseTriggerDate); err != nil {
return fmt.Errorf("%w: base_trigger_date %q is not YYYY-MM-DD", ErrInvalidInput, parsed.BaseTriggerDate)
}
}
for i, p := range parsed.Proceedings {
if p.Code == "" {
return fmt.Errorf("%w: proceedings[%d].code is empty", ErrInvalidInput, i)
}
if p.Role != lp.ScenarioRolePrimary && p.Role != lp.ScenarioRolePeer {
return fmt.Errorf("%w: proceedings[%d].role=%q must be 'primary' or 'peer'",
ErrInvalidInput, i, p.Role)
}
if p.AppealTarget != "" && !lp.IsValidAppealTarget(p.AppealTarget) {
return fmt.Errorf("%w: proceedings[%d].appeal_target=%q not in %v",
ErrInvalidInput, i, p.AppealTarget, lp.AppealTargets)
}
if p.TriggerDateOverride != "" {
if _, err := time.Parse("2006-01-02", p.TriggerDateOverride); err != nil {
return fmt.Errorf("%w: proceedings[%d].trigger_date_override %q is not YYYY-MM-DD",
ErrInvalidInput, i, p.TriggerDateOverride)
}
}
for code, dateStr := range p.AnchorOverrides {
if _, err := time.Parse("2006-01-02", dateStr); err != nil {
return fmt.Errorf("%w: proceedings[%d].anchor_overrides[%q]=%q is not YYYY-MM-DD",
ErrInvalidInput, i, code, dateStr)
}
}
// Resolve code against active proceedings.
var exists bool
if err := s.db.GetContext(ctx, &exists,
`SELECT EXISTS(SELECT 1 FROM paliad.proceeding_types
WHERE code = $1 AND is_active = true)`,
p.Code); err != nil {
return fmt.Errorf("validate spec proceedings[%d]: %w", i, err)
}
if !exists {
return fmt.Errorf("%w: proceedings[%d].code=%q is not an active proceeding_type",
ErrInvalidInput, i, p.Code)
}
}
return nil
}
// joinSets joins SET clauses with ", ". Tiny utility, kept here to
// avoid cross-package strings.Join indirection.
func joinSets(sets []string) string {
out := ""
for i, s := range sets {
if i > 0 {
out += ", "
}
out += s
}
return out
}
// Suppress unused-import diagnostic when models isn't referenced
// (kept for future shape-evolution; canonical scenario row lives in lp).
var _ = models.NullableJSON(nil)

View File

@@ -0,0 +1,328 @@
package litigationplanner
import (
"context"
"errors"
"testing"
"time"
"github.com/google/uuid"
)
// Regression test for t-paliad-304 / m/paliad#135.
//
// Reproduces the R.109.1 / R.109.4 anchor bug on upc.inf.cfi:
// - Trigger (Klageerhebung): parent_id=nil, duration=0, !IsCourtSet, sequence_order=0
// - Translation request: parent_id=oral, duration=1mo before, sequence_order=45
// - Interpreter cost: parent_id=oral, duration=2w before, sequence_order=46
// - Oral hearing: parent_id=nil, duration=0, IsCourtSet, sequence_order=50
//
// The "before" children are listed BEFORE the oral hearing in sequence
// order (because chronologically they happen before it). The engine walks
// rules in sequence_order, so when it processes the translation/
// interpreter rows, the oral hearing has not yet been processed →
// courtSet[oral.ID] is not yet set → parentIsCourtSet is false → the
// engine falls back to the trigger date as the base. Result: the timing=
// 'before' arithmetic produces 27.04.2026 (1mo before SoC) instead of
// the conditional-no-date treatment that a court-set parent should
// trigger.
//
// Expected post-fix: translation_request + interpreter_cost render as
// IsConditional (no concrete date) because their parent's date is
// court-set and the proceeding does not yet have an explicit override.
// stubCatalog implements lp.Catalog backed by an in-memory rule slice.
// Only LoadProceeding is needed for the engine path under test; the
// other interface methods return errors so an unintended call surfaces
// immediately.
type stubCatalog struct {
pt ProceedingType
rules []Rule
}
func (s *stubCatalog) LoadProceeding(_ context.Context, code string, _ ProjectHint) (*ProceedingType, []Rule, error) {
if code != s.pt.Code {
return nil, nil, ErrUnknownProceedingType
}
rules := make([]Rule, len(s.rules))
copy(rules, s.rules)
pt := s.pt
return &pt, rules, nil
}
func (s *stubCatalog) LoadProceedingByID(_ context.Context, _ int) (*ProceedingType, error) {
return nil, errors.New("stubCatalog.LoadProceedingByID: not implemented")
}
func (s *stubCatalog) LoadRuleByID(_ context.Context, _ string) (*Rule, error) {
return nil, errors.New("stubCatalog.LoadRuleByID: not implemented")
}
func (s *stubCatalog) LoadRuleByCode(_ context.Context, _, _ string) (*Rule, *ProceedingType, error) {
return nil, nil, errors.New("stubCatalog.LoadRuleByCode: not implemented")
}
func (s *stubCatalog) LoadRulesByTriggerEvent(_ context.Context, _ int64) ([]Rule, error) {
return nil, nil
}
func (s *stubCatalog) LoadTriggerEventsByIDs(_ context.Context, _ []int64) (map[int64]TriggerEvent, error) {
return map[int64]TriggerEvent{}, nil
}
func (s *stubCatalog) LookupEvents(_ context.Context, _ EventLookupAxes, _ EventLookupDepth) ([]EventMatch, error) {
return nil, nil
}
func (s *stubCatalog) LoadScenarios(_ context.Context, _ ScenarioFilter) ([]Scenario, error) {
return nil, nil
}
func (s *stubCatalog) MatchScenario(_ context.Context, _ uuid.UUID) (*Scenario, error) {
return nil, ErrUnknownScenario
}
// noOpHolidays never adjusts dates — the test fixture doesn't care about
// weekends or holidays, only about which base date the engine resolves.
type noOpHolidays struct{}
func (noOpHolidays) IsNonWorkingDay(_ time.Time, _, _ string) bool { return false }
func (noOpHolidays) AdjustForNonWorkingDays(d time.Time, _, _ string) (time.Time, time.Time, bool) {
return d, d, false
}
func (noOpHolidays) AdjustForNonWorkingDaysBackward(d time.Time, _, _ string) (time.Time, time.Time, bool) {
return d, d, false
}
func (noOpHolidays) AdjustForNonWorkingDaysWithReason(d time.Time, _, _ string) (time.Time, time.Time, bool, *AdjustmentReason) {
return d, d, false, nil
}
type fixedCourts struct{}
func (fixedCourts) CountryRegime(_, _, _ string) (string, string, error) {
return CountryDE, RegimeUPC, nil
}
func TestCalculate_BeforeChildOfCourtSetParent_OutOfOrderSequence(t *testing.T) {
ctx := context.Background()
// proceeding metadata
jurisdiction := "UPC"
procID := 1
pt := ProceedingType{
ID: procID,
Code: "upc.inf.cfi",
Name: "Verletzungsverfahren",
NameEN: "Infringement",
Jurisdiction: &jurisdiction,
IsActive: true,
}
mkID := func() uuid.UUID {
id, _ := uuid.NewRandom()
return id
}
str := func(s string) *string { return &s }
procIDPtr := &procID
socID := mkID()
oralID := mkID()
transID := mkID()
interpID := mkID()
socCode := "upc.inf.cfi.soc"
oralCode := "upc.inf.cfi.oral"
transCode := "upc.inf.cfi.translation_request"
interpCode := "upc.inf.cfi.interpreter_cost"
rules := []Rule{
{
ID: socID,
ProceedingTypeID: procIDPtr,
ParentID: nil,
SubmissionCode: &socCode,
Name: "Klageerhebung",
NameEN: "Statement of Claim",
PrimaryParty: str("claimant"),
DurationValue: 0,
DurationUnit: "months",
Timing: str("after"),
SequenceOrder: 0,
IsCourtSet: false,
IsActive: true,
LifecycleState: "published",
Priority: "mandatory",
},
// Translation request: sequence_order BEFORE the oral hearing.
// Reproduces the real corpus ordering (DB rows 45 < 50).
{
ID: transID,
ProceedingTypeID: procIDPtr,
ParentID: &oralID,
SubmissionCode: &transCode,
Name: "Antrag auf Simultanübersetzung",
NameEN: "Translation request",
PrimaryParty: str("both"),
DurationValue: 1,
DurationUnit: "months",
Timing: str("before"),
SequenceOrder: 45,
IsCourtSet: false,
IsActive: true,
LifecycleState: "published",
Priority: "optional",
},
// Interpreter cost notice: sequence_order BEFORE the oral hearing.
{
ID: interpID,
ProceedingTypeID: procIDPtr,
ParentID: &oralID,
SubmissionCode: &interpCode,
Name: "Mitteilung Dolmetscherkosten",
NameEN: "Interpreter cost notice",
PrimaryParty: str("court"),
DurationValue: 2,
DurationUnit: "weeks",
Timing: str("before"),
SequenceOrder: 46,
IsCourtSet: false,
IsActive: true,
LifecycleState: "published",
Priority: "mandatory",
},
// Oral hearing: court-set, no calculable date. Listed AFTER its
// "before"-timed children in sequence_order.
{
ID: oralID,
ProceedingTypeID: procIDPtr,
ParentID: nil,
SubmissionCode: &oralCode,
Name: "Mündliche Verhandlung",
NameEN: "Oral hearing",
PrimaryParty: str("court"),
DurationValue: 0,
DurationUnit: "months",
Timing: str("after"),
SequenceOrder: 50,
IsCourtSet: true,
IsActive: true,
LifecycleState: "published",
Priority: "mandatory",
},
}
cat := &stubCatalog{pt: pt, rules: rules}
timeline, err := Calculate(ctx, "upc.inf.cfi", "2026-05-26", CalcOptions{}, cat, noOpHolidays{}, fixedCourts{})
if err != nil {
t.Fatalf("Calculate: %v", err)
}
byCode := make(map[string]TimelineEntry, len(timeline.Deadlines))
for _, d := range timeline.Deadlines {
byCode[d.Code] = d
}
// The trigger event itself is unambiguous.
if got := byCode[socCode]; got.DueDate != "2026-05-26" || !got.IsRootEvent {
t.Errorf("SoC: DueDate=%q IsRootEvent=%v, want 2026-05-26 + IsRootEvent=true", got.DueDate, got.IsRootEvent)
}
// Oral hearing must surface as IsCourtSet (no date).
oral := byCode[oralCode]
if oral.DueDate != "" || !oral.IsCourtSet {
t.Errorf("oral: DueDate=%q IsCourtSet=%v, want empty + IsCourtSet=true", oral.DueDate, oral.IsCourtSet)
}
// The two "before" children of the court-set oral hearing MUST surface
// as conditional rows (no date, no fabricated arithmetic off the
// trigger date). The buggy behaviour produces 2026-04-27 and 2026-05-12.
trans := byCode[transCode]
if trans.DueDate != "" {
t.Errorf("translation_request: DueDate=%q, want empty (parent oral is court-set, no anchor known yet)", trans.DueDate)
}
if !trans.IsConditional && !trans.IsCourtSet {
t.Errorf("translation_request: IsConditional=%v IsCourtSet=%v, want at least one true", trans.IsConditional, trans.IsCourtSet)
}
interp := byCode[interpCode]
if interp.DueDate != "" {
t.Errorf("interpreter_cost: DueDate=%q, want empty (parent oral is court-set, no anchor known yet)", interp.DueDate)
}
if !interp.IsConditional && !interp.IsCourtSet {
t.Errorf("interpreter_cost: IsConditional=%v IsCourtSet=%v, want at least one true", interp.IsConditional, interp.IsCourtSet)
}
}
// TestCalculate_BeforeChildOfCourtSetParent_WithOverride pins the
// override semantics: when the user supplies an anchor override for
// the court-set parent, the "before" children should compute against
// that override date instead of remaining conditional.
func TestCalculate_BeforeChildOfCourtSetParent_WithOverride(t *testing.T) {
ctx := context.Background()
jurisdiction := "UPC"
procID := 1
pt := ProceedingType{
ID: procID,
Code: "upc.inf.cfi",
Name: "Verletzungsverfahren",
Jurisdiction: &jurisdiction,
IsActive: true,
}
mkID := func() uuid.UUID {
id, _ := uuid.NewRandom()
return id
}
str := func(s string) *string { return &s }
procIDPtr := &procID
socID := mkID()
oralID := mkID()
transID := mkID()
socCode := "upc.inf.cfi.soc"
oralCode := "upc.inf.cfi.oral"
transCode := "upc.inf.cfi.translation_request"
rules := []Rule{
{
ID: socID, ProceedingTypeID: procIDPtr, ParentID: nil,
SubmissionCode: &socCode, Name: "Klageerhebung", NameEN: "SoC",
PrimaryParty: str("claimant"), DurationValue: 0, DurationUnit: "months", Timing: str("after"),
SequenceOrder: 0, IsActive: true, LifecycleState: "published", Priority: "mandatory",
},
{
ID: transID, ProceedingTypeID: procIDPtr, ParentID: &oralID,
SubmissionCode: &transCode, Name: "Antrag auf Simultanübersetzung", NameEN: "Translation request",
PrimaryParty: str("both"), DurationValue: 1, DurationUnit: "months", Timing: str("before"),
SequenceOrder: 45, IsActive: true, LifecycleState: "published", Priority: "optional",
},
{
ID: oralID, ProceedingTypeID: procIDPtr, ParentID: nil,
SubmissionCode: &oralCode, Name: "Mündliche Verhandlung", NameEN: "Oral hearing",
PrimaryParty: str("court"), DurationValue: 0, DurationUnit: "months", Timing: str("after"),
SequenceOrder: 50, IsCourtSet: true, IsActive: true, LifecycleState: "published", Priority: "mandatory",
},
}
cat := &stubCatalog{pt: pt, rules: rules}
// User pins the oral hearing to 2026-10-15.
opts := CalcOptions{
AnchorOverrides: map[string]string{
oralCode: "2026-10-15",
},
}
timeline, err := Calculate(ctx, "upc.inf.cfi", "2026-05-26", opts, cat, noOpHolidays{}, fixedCourts{})
if err != nil {
t.Fatalf("Calculate: %v", err)
}
byCode := make(map[string]TimelineEntry, len(timeline.Deadlines))
for _, d := range timeline.Deadlines {
byCode[d.Code] = d
}
if got := byCode[oralCode].DueDate; got != "2026-10-15" {
t.Errorf("oral: DueDate=%q, want 2026-10-15 (user override)", got)
}
// 1 month before 2026-10-15 = 2026-09-15
if got := byCode[transCode].DueDate; got != "2026-09-15" {
t.Errorf("translation_request: DueDate=%q, want 2026-09-15 (1 month before oral override)", got)
}
}

View File

@@ -1,6 +1,10 @@
package litigationplanner
import "context"
import (
"context"
"github.com/google/uuid"
)
// Catalog supplies proceeding-type metadata + rules for the calculator.
//
@@ -59,4 +63,17 @@ type Catalog interface {
// (proceeding_type_id, sequence_order) so the frontend can render
// without re-sorting.
LookupEvents(ctx context.Context, axes EventLookupAxes, depth EventLookupDepth) ([]EventMatch, error)
// LoadScenarios lists scenarios visible to the caller, narrowed by
// the filter (Slice D, m/paliad#124 §5). Returns an empty slice
// (NOT an error) when no scenarios match. paliad-side impl applies
// RLS (paliad.can_see_project for project-scoped, created_by for
// abstract); snapshot-backed catalogs return an empty list.
LoadScenarios(ctx context.Context, filter ScenarioFilter) ([]Scenario, error)
// MatchScenario returns the scenario with the given id, or
// ErrUnknownScenario if not found / not visible. The engine adapter
// (CalculateFromScenario) calls this to fetch a scenario by id and
// then unpacks its spec via ParseSpec.
MatchScenario(ctx context.Context, id uuid.UUID) (*Scenario, error)
}

View File

@@ -292,6 +292,20 @@ func (c *SnapshotCatalog) LookupEvents(_ context.Context, axes lp.EventLookupAxe
return out, nil
}
// LoadScenarios returns an empty slice. The snapshot catalog has no
// scenarios — youpc.org (the consumer today) doesn't carry a project /
// user model. Future snapshot variants could ship demo scenarios, but
// v1 returns nothing.
func (c *SnapshotCatalog) LoadScenarios(_ context.Context, _ lp.ScenarioFilter) ([]lp.Scenario, error) {
return []lp.Scenario{}, nil
}
// MatchScenario always returns ErrUnknownScenario — the snapshot has
// no scenarios to match against.
func (c *SnapshotCatalog) MatchScenario(_ context.Context, _ uuid.UUID) (*lp.Scenario, error) {
return nil, lp.ErrUnknownScenario
}
// Compile-time assertion that SnapshotCatalog satisfies lp.Catalog.
var _ lp.Catalog = (*SnapshotCatalog)(nil)

View File

@@ -4,6 +4,7 @@ import (
"context"
"encoding/json"
"fmt"
"sort"
"time"
"github.com/google/uuid"
@@ -183,10 +184,27 @@ func Calculate(
return nil, fmt.Errorf("load trigger events for conditional labels: %w", err)
}
// Walk the rule list in sequence_order (already sorted by the
// catalog query) and compute each entry, keeping a code→date map so
// RelativeTo / parent_id references resolve to the adjusted
// predecessor date.
// Walk the rule list in TOPOLOGICAL order (parents before children),
// not the raw sequence_order order from the catalog. The catalog
// returns rules sorted by sequence_order, which is the chronological/
// display order. That order is parent-first for the common
// timing='after' case but parent-LAST for timing='before' children
// (e.g. upc.inf.cfi.translation_request at seq=45 vs its parent
// upc.inf.cfi.oral at seq=50 — m/paliad#135). Without topological
// ordering the parent-state checks below (courtSet[parent] /
// computed[parent_code]) read stale empty maps when a child appears
// before its parent, and the engine falls back to the trigger date
// → fabricates dates before the SoC.
//
// Original sequence_order is restored at the end of the walk so the
// wire shape and the timeline view's render order stay identical to
// the legacy behaviour modulo the bug fix.
sequenceIndex := make(map[uuid.UUID]int, len(rules))
for i, r := range rules {
sequenceIndex[r.ID] = i
}
walkRules := topoSortByParentDepth(rules)
computed := make(map[string]time.Time, len(rules))
courtSet := make(map[uuid.UUID]bool, len(rules))
deadlines := make([]TimelineEntry, 0, len(rules))
@@ -197,7 +215,7 @@ func Calculate(
hiddenCount := 0
appellantContext := make(map[uuid.UUID]string, len(rules))
for _, r := range rules {
for _, r := range walkRules {
// Phase-3 unified gate: evaluate condition_expr (jsonb).
// Suppression semantic preserved: when the gate fires false
// AND no alt_* values exist, the rule is dropped from the
@@ -249,6 +267,10 @@ func Calculate(
appellantContext[r.ID] = ctxVal
}
ruleTiming := ""
if r.Timing != nil {
ruleTiming = *r.Timing
}
d := TimelineEntry{
RuleID: r.ID.String(),
Name: r.Name,
@@ -258,6 +280,9 @@ func Calculate(
AppellantContext: ctxVal,
ChoicesOffered: json.RawMessage(r.ChoicesOffered),
IsHidden: isHidden,
DurationValue: r.DurationValue,
DurationUnit: r.DurationUnit,
Timing: ruleTiming,
}
if r.SubmissionCode != nil {
d.Code = *r.SubmissionCode
@@ -547,6 +572,20 @@ func Calculate(
deadlines = append(deadlines, d)
}
// Restore sequence_order on the output slice. The compute walk
// re-ordered rules topologically (parent-first) so the parent-state
// checks resolved correctly; the wire shape and the linear timeline
// view both rely on sequence_order being the surface render order.
// (m/paliad#135)
sort.SliceStable(deadlines, func(i, j int) bool {
a, errA := uuid.Parse(deadlines[i].RuleID)
b, errB := uuid.Parse(deadlines[j].RuleID)
if errA != nil || errB != nil {
return false
}
return sequenceIndex[a] < sequenceIndex[b]
})
// t-paliad-296: within consecutive runs of rules sharing the same
// trigger group (parent_id + trigger_event_id), reorder by duration
// ascending so optional events following the same anchor render in
@@ -671,6 +710,9 @@ func calculateByTriggerEvent(
OriginalDate: original.Format("2006-01-02"),
WasAdjusted: wasAdj,
AdjustmentReason: reason,
DurationValue: r.DurationValue,
DurationUnit: r.DurationUnit,
Timing: timing,
}
if r.SubmissionCode != nil {
d.Code = *r.SubmissionCode
@@ -940,3 +982,60 @@ func AllFlagsSet(required []string, set map[string]struct{}) bool {
func WireFlagsFromPriority(priority string) (isMandatory, isOptional bool) {
return wireFlagsFromPriority(priority)
}
// topoSortByParentDepth returns a copy of `rules` ordered so every rule
// appears after its parent_id ancestor. Ties (rules at the same depth)
// preserve their input order — which the catalog returns in
// sequence_order. Used by Calculate to ensure the parent-state checks
// (courtSet[parent], computed[parent_code]) see populated entries even
// when sequence_order lists a "before"-timed child BEFORE its parent
// (e.g. upc.inf.cfi.translation_request at seq=45 with parent
// upc.inf.cfi.oral at seq=50 — m/paliad#135).
//
// Rules whose parent_id is missing from the rule slice (cross-tree
// references that the per-proceeding filter dropped) are treated as
// depth 0 — they walk in their original sequence position.
//
// The algorithm is depth-via-memoised-recursion. Cycle protection: a
// rule chain that revisits a node is broken at depth 0; production
// data shouldn't contain cycles, but a corrupted catalog mustn't hang
// the calculator.
func topoSortByParentDepth(rules []Rule) []Rule {
byID := make(map[uuid.UUID]Rule, len(rules))
inSlice := make(map[uuid.UUID]bool, len(rules))
for _, r := range rules {
byID[r.ID] = r
inSlice[r.ID] = true
}
depth := make(map[uuid.UUID]int, len(rules))
var resolve func(id uuid.UUID, seen map[uuid.UUID]bool) int
resolve = func(id uuid.UUID, seen map[uuid.UUID]bool) int {
if d, ok := depth[id]; ok {
return d
}
if seen[id] {
depth[id] = 0
return 0
}
seen[id] = true
r, ok := byID[id]
if !ok || r.ParentID == nil || !inSlice[*r.ParentID] {
depth[id] = 0
return 0
}
d := resolve(*r.ParentID, seen) + 1
depth[id] = d
return d
}
for _, r := range rules {
resolve(r.ID, map[uuid.UUID]bool{})
}
out := make([]Rule, len(rules))
copy(out, rules)
sort.SliceStable(out, func(i, j int) bool {
return depth[out[i].ID] < depth[out[j].ID]
})
return out
}

View File

@@ -0,0 +1,215 @@
package litigationplanner
import (
"context"
"encoding/json"
"errors"
"fmt"
"time"
"github.com/google/uuid"
)
// Slice D scenarios — m/paliad#124 §5 (revised), mig 145.
//
// A Scenario is a named composition of existing proceedings + flags +
// per-card choices + anchor dates. v1 ships with one primary proceeding
// per scenario; the spec.proceedings[] array is architected to absorb
// multi-peer compose (v2) without a schema migration.
//
// "users should not add their own rules" (m, t-paliad-301) — the spec
// references existing rules by submission_code; it never creates new
// ones. ValidateSpec checks every code/submission resolves against the
// current catalog before a save is accepted.
// Scenario is one row of paliad.scenarios. Wire shape doubles as the
// API request/response payload for /api/scenarios.
type Scenario struct {
ID uuid.UUID `db:"id" json:"id"`
ProjectID *uuid.UUID `db:"project_id" json:"project_id,omitempty"`
Name string `db:"name" json:"name"`
Description *string `db:"description" json:"description,omitempty"`
// Spec carries the jsonb composition. Stored raw so we can ship
// shape evolutions without schema churn; ParseSpec gives the
// structured view.
Spec NullableJSON `db:"spec" json:"spec"`
CreatedBy *uuid.UUID `db:"created_by" json:"created_by,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
}
// ScenarioSpec is the parsed view of Scenario.Spec. v1 = version 1.
// Future shape changes bump the version; ParseSpec rejects unknown
// versions so an old client doesn't silently misread a future-shape
// scenario.
type ScenarioSpec struct {
Version int `json:"version"`
BaseTriggerDate string `json:"base_trigger_date"`
Proceedings []ScenarioProceeding `json:"proceedings"`
}
// ScenarioProceeding is one entry under spec.proceedings[]. v1 honours
// exactly one with role="primary" (additional entries with role="peer"
// are reserved for v2 multi-proceeding compose and silently ignored
// by the engine today).
type ScenarioProceeding struct {
Code string `json:"code"`
Role string `json:"role"` // "primary" | "peer" (v2)
TriggerDateOverride string `json:"trigger_date_override,omitempty"`
Flags []string `json:"flags,omitempty"`
PerCardChoices map[string]ScenarioCardChoice `json:"per_card_choices,omitempty"`
AnchorOverrides map[string]string `json:"anchor_overrides,omitempty"`
SkipRules []string `json:"skip_rules,omitempty"`
AppealTarget string `json:"appeal_target,omitempty"`
}
// ScenarioCardChoice is one entry under
// spec.proceedings[*].per_card_choices. Mirrors the t-paliad-265 choice
// kinds; not every kind is populated on every card.
type ScenarioCardChoice struct {
Appellant string `json:"appellant,omitempty"`
IncludeCCR *bool `json:"include_ccr,omitempty"`
Skip *bool `json:"skip,omitempty"`
}
// Spec version constant.
const ScenarioSpecVersion = 1
// Sentinel errors for scenarios.
var (
ErrUnknownScenario = errors.New("unknown scenario")
ErrInvalidScenario = errors.New("invalid scenario spec")
ErrScenarioNoPrimary = errors.New("scenario spec has no proceeding with role='primary'")
)
// ScenarioRole* are the canonical role slugs for ScenarioProceeding.Role.
const (
ScenarioRolePrimary = "primary"
ScenarioRolePeer = "peer"
)
// ParseSpec decodes Scenario.Spec into a structured ScenarioSpec. Used
// by the engine adapter + the rule-editor preview. Surfaces a friendly
// error wrapping ErrInvalidScenario on malformed JSON / unknown version
// so the handler can map to a 400.
func ParseSpec(raw NullableJSON) (*ScenarioSpec, error) {
if len(raw) == 0 {
return nil, fmt.Errorf("%w: spec is empty", ErrInvalidScenario)
}
var s ScenarioSpec
if err := json.Unmarshal([]byte(raw), &s); err != nil {
return nil, fmt.Errorf("%w: decode spec: %v", ErrInvalidScenario, err)
}
if s.Version != ScenarioSpecVersion {
return nil, fmt.Errorf("%w: spec.version=%d, want %d",
ErrInvalidScenario, s.Version, ScenarioSpecVersion)
}
return &s, nil
}
// PrimaryProceeding returns the entry from spec.proceedings[] with
// role="primary". Returns ErrScenarioNoPrimary if absent — every spec
// must carry exactly one primary entry. (Multiple primaries are also
// rejected: the engine consumes one.)
func (s *ScenarioSpec) PrimaryProceeding() (*ScenarioProceeding, error) {
var primary *ScenarioProceeding
for i := range s.Proceedings {
if s.Proceedings[i].Role == ScenarioRolePrimary {
if primary != nil {
return nil, fmt.Errorf("%w: multiple proceedings with role='primary'", ErrInvalidScenario)
}
primary = &s.Proceedings[i]
}
}
if primary == nil {
return nil, ErrScenarioNoPrimary
}
return primary, nil
}
// CalcOptionsFromSpec builds a CalcOptions from the scenario's primary
// entry. The caller still needs the proceeding code + the trigger date,
// both returned alongside.
//
// v1: only the primary entry is honoured. v2 will iterate over peer
// entries; the multi-peer merge lives in the paliad-side
// ProjectionService (one Calculate call per entry, merged + sorted by
// date).
func (s *ScenarioSpec) CalcOptionsFromSpec() (proceedingCode, triggerDate string, opts CalcOptions, err error) {
primary, err := s.PrimaryProceeding()
if err != nil {
return "", "", CalcOptions{}, err
}
td := s.BaseTriggerDate
if primary.TriggerDateOverride != "" {
td = primary.TriggerDateOverride
}
if td == "" {
return "", "", CalcOptions{}, fmt.Errorf("%w: no base_trigger_date and no per-proceeding override", ErrInvalidScenario)
}
perCardAppellant := make(map[string]string, len(primary.PerCardChoices))
skipRules := make(map[string]struct{}, len(primary.SkipRules))
includeCCRFor := make(map[string]struct{}, len(primary.PerCardChoices))
for code, choice := range primary.PerCardChoices {
if choice.Appellant != "" {
perCardAppellant[code] = choice.Appellant
}
if choice.IncludeCCR != nil && *choice.IncludeCCR {
includeCCRFor[code] = struct{}{}
}
if choice.Skip != nil && *choice.Skip {
skipRules[code] = struct{}{}
}
}
for _, code := range primary.SkipRules {
skipRules[code] = struct{}{}
}
return primary.Code, td, CalcOptions{
Flags: primary.Flags,
AnchorOverrides: primary.AnchorOverrides,
AppealTarget: primary.AppealTarget,
PerCardAppellant: perCardAppellant,
SkipRules: skipRules,
IncludeCCRFor: includeCCRFor,
}, nil
}
// ScenarioFilter narrows Catalog.LoadScenarios. All fields optional:
//
// - ProjectID non-nil: only scenarios attached to that project
// (project_id = filter.ProjectID).
// - AbstractForUser non-nil: only abstract scenarios (project_id IS
// NULL) created by that user.
// - Both nil: list every scenario the caller can see (RLS-gated).
type ScenarioFilter struct {
ProjectID *uuid.UUID
AbstractForUser *uuid.UUID
}
// CalculateFromScenario is the high-level engine entry for scenario-
// driven rendering. Unpacks the spec, builds CalcOptions, and delegates
// to Calculate.
//
// v1: surfaces only the primary proceeding's timeline. v2 multi-peer
// expansion lives on the paliad-side ProjectionService (per-entry
// Calculate + client-side merge); the package doesn't own that
// orchestration.
func CalculateFromScenario(
ctx context.Context,
scenario *Scenario,
catalog Catalog,
holidays HolidayCalendar,
courts CourtRegistry,
) (*Timeline, error) {
spec, err := ParseSpec(scenario.Spec)
if err != nil {
return nil, err
}
code, triggerDate, opts, err := spec.CalcOptionsFromSpec()
if err != nil {
return nil, err
}
return Calculate(ctx, code, triggerDate, opts, catalog, holidays, courts)
}

View File

@@ -0,0 +1,207 @@
package litigationplanner
import (
"strings"
"testing"
)
// TestParseSpec_Roundtrip pins the spec-decoder contract: well-formed
// jsonb with version=1 parses; unknown versions and malformed JSON
// surface ErrInvalidScenario.
func TestParseSpec_Roundtrip(t *testing.T) {
cases := []struct {
name string
spec string
wantErr bool
}{
{
"v1 primary-only",
`{"version":1,"base_trigger_date":"2026-05-26","proceedings":[{"code":"upc.inf.cfi","role":"primary"}]}`,
false,
},
{
"v1 with full primary entry",
`{"version":1,"base_trigger_date":"2026-05-26","proceedings":[
{"code":"upc.inf.cfi","role":"primary","flags":["with_ccr"],
"anchor_overrides":{"inf.reply":"2026-08-15"},
"skip_rules":["inf.r30_amend"]}
]}`,
false,
},
{
"v2 spec rejected — unknown version",
`{"version":2,"proceedings":[]}`,
true,
},
{
"empty spec",
``,
true,
},
{
"malformed json",
`{"version":1,"proceedings":[}`,
true,
},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
_, err := ParseSpec(NullableJSON(c.spec))
if c.wantErr && err == nil {
t.Errorf("ParseSpec(%s): want error, got nil", c.spec)
}
if !c.wantErr && err != nil {
t.Errorf("ParseSpec(%s): unexpected error %v", c.spec, err)
}
})
}
}
// TestScenarioSpec_PrimaryProceeding pins the "exactly one primary"
// invariant: zero → ErrScenarioNoPrimary; multiple → ErrInvalidScenario.
func TestScenarioSpec_PrimaryProceeding(t *testing.T) {
t.Run("zero primary → ErrScenarioNoPrimary", func(t *testing.T) {
s := &ScenarioSpec{
Version: 1,
Proceedings: []ScenarioProceeding{
{Code: "upc.inf.cfi", Role: ScenarioRolePeer},
},
}
_, err := s.PrimaryProceeding()
if err != ErrScenarioNoPrimary {
t.Errorf("want ErrScenarioNoPrimary, got %v", err)
}
})
t.Run("two primaries rejected", func(t *testing.T) {
s := &ScenarioSpec{
Version: 1,
Proceedings: []ScenarioProceeding{
{Code: "upc.inf.cfi", Role: ScenarioRolePrimary},
{Code: "upc.rev.cfi", Role: ScenarioRolePrimary},
},
}
_, err := s.PrimaryProceeding()
if err == nil || !strings.Contains(err.Error(), "multiple proceedings with role='primary'") {
t.Errorf("want multi-primary error, got %v", err)
}
})
t.Run("single primary picked", func(t *testing.T) {
s := &ScenarioSpec{
Version: 1,
Proceedings: []ScenarioProceeding{
{Code: "upc.inf.cfi", Role: ScenarioRolePeer},
{Code: "upc.rev.cfi", Role: ScenarioRolePrimary, Flags: []string{"with_amend"}},
},
}
p, err := s.PrimaryProceeding()
if err != nil {
t.Fatalf("PrimaryProceeding: %v", err)
}
if p.Code != "upc.rev.cfi" {
t.Errorf("primary code = %q, want upc.rev.cfi", p.Code)
}
if len(p.Flags) != 1 || p.Flags[0] != "with_amend" {
t.Errorf("primary.Flags = %v, want [with_amend]", p.Flags)
}
})
}
// TestScenarioSpec_CalcOptionsFromSpec covers the unpack from spec
// jsonb into the CalcOptions the engine consumes. Pins:
// - base_trigger_date used when no per-proceeding override
// - trigger_date_override wins when set
// - flags + anchor_overrides + appeal_target passed through verbatim
// - per_card_choices unpacked into PerCardAppellant / SkipRules /
// IncludeCCRFor maps
func TestScenarioSpec_CalcOptionsFromSpec(t *testing.T) {
includeTrue := true
skipTrue := true
s := &ScenarioSpec{
Version: 1,
BaseTriggerDate: "2026-05-26",
Proceedings: []ScenarioProceeding{{
Code: "upc.inf.cfi",
Role: ScenarioRolePrimary,
Flags: []string{"with_ccr"},
AnchorOverrides: map[string]string{"inf.reply": "2026-08-15"},
AppealTarget: "endentscheidung",
SkipRules: []string{"explicit_skip_code"},
PerCardChoices: map[string]ScenarioCardChoice{
"inf.r30_amend": {Appellant: "claimant"},
"inf.rejoin": {IncludeCCR: &includeTrue},
"inf.amend_other": {Skip: &skipTrue},
},
}},
}
code, td, opts, err := s.CalcOptionsFromSpec()
if err != nil {
t.Fatalf("CalcOptionsFromSpec: %v", err)
}
if code != "upc.inf.cfi" {
t.Errorf("code = %q, want upc.inf.cfi", code)
}
if td != "2026-05-26" {
t.Errorf("triggerDate = %q, want 2026-05-26", td)
}
if len(opts.Flags) != 1 || opts.Flags[0] != "with_ccr" {
t.Errorf("opts.Flags = %v, want [with_ccr]", opts.Flags)
}
if opts.AppealTarget != "endentscheidung" {
t.Errorf("opts.AppealTarget = %q, want endentscheidung", opts.AppealTarget)
}
if got := opts.AnchorOverrides["inf.reply"]; got != "2026-08-15" {
t.Errorf("opts.AnchorOverrides[inf.reply] = %q, want 2026-08-15", got)
}
if got := opts.PerCardAppellant["inf.r30_amend"]; got != "claimant" {
t.Errorf("opts.PerCardAppellant[inf.r30_amend] = %q, want claimant", got)
}
if _, ok := opts.IncludeCCRFor["inf.rejoin"]; !ok {
t.Error("opts.IncludeCCRFor missing inf.rejoin")
}
if _, ok := opts.SkipRules["inf.amend_other"]; !ok {
t.Error("opts.SkipRules missing inf.amend_other (from per_card_choices.skip)")
}
if _, ok := opts.SkipRules["explicit_skip_code"]; !ok {
t.Error("opts.SkipRules missing explicit_skip_code (from skip_rules[])")
}
}
// TestScenarioSpec_TriggerDateOverride pins the per-proceeding override
// path (v2-ready — primary entry honours trigger_date_override too).
func TestScenarioSpec_TriggerDateOverride(t *testing.T) {
s := &ScenarioSpec{
Version: 1,
BaseTriggerDate: "2026-05-26",
Proceedings: []ScenarioProceeding{{
Code: "upc.inf.cfi",
Role: ScenarioRolePrimary,
TriggerDateOverride: "2026-12-01",
}},
}
_, td, _, err := s.CalcOptionsFromSpec()
if err != nil {
t.Fatalf("CalcOptionsFromSpec: %v", err)
}
if td != "2026-12-01" {
t.Errorf("triggerDate = %q, want override 2026-12-01", td)
}
}
// TestScenarioSpec_NoBaseTrigger pins the safety check that a spec
// without base_trigger_date AND without per-proceeding override
// surfaces ErrInvalidScenario (the engine can't render without a date).
func TestScenarioSpec_NoBaseTrigger(t *testing.T) {
s := &ScenarioSpec{
Version: 1,
Proceedings: []ScenarioProceeding{{
Code: "upc.inf.cfi",
Role: ScenarioRolePrimary,
}},
}
_, _, _, err := s.CalcOptionsFromSpec()
if err == nil {
t.Fatal("want ErrInvalidScenario, got nil")
}
}

View File

@@ -430,6 +430,17 @@ type TimelineEntry struct {
ChoicesOffered json.RawMessage `json:"choicesOffered,omitempty"`
AppellantContext string `json:"appellantContext,omitempty"`
IsHidden bool `json:"isHidden,omitempty"`
// DurationValue / DurationUnit / Timing surface the rule's
// arithmetic so /tools/verfahrensablauf can show "2 Mo. nach" on
// each event card (m/paliad#133, t-paliad-302). Source values from
// the Rule row (not the post-alt-swap arithmetic) — the tooltip
// reads as a property of the rule, not a recap of which branch
// fired. Zero-duration rules (root event, court-set) emit
// DurationValue=0 and the frontend suppresses the affordance.
// Timing is "before" | "after" — empty when r.Timing is NULL.
DurationValue int `json:"durationValue,omitempty"`
DurationUnit string `json:"durationUnit,omitempty"`
Timing string `json:"timing,omitempty"`
}
// RuleCalculation is the single-rule calc response that backs the