Compare commits

...

78 Commits

Author SHA1 Message Date
mAi
7e66da8def mAi: #92 - t-paliad-261 — submission-draft autosave focus + click-variable-in-preview jump
Two related editor polish fixes.

(A) Autosave-refresh focus preservation
  paintVariables() replaces every input via innerHTML, blowing away
  the focused-input reference and dropping the cursor mid-edit. Fix:
  capture the active variable input's data-var key + selectionStart/
  End/Direction before the repaint, restore on the new element after
  (by data-var lookup + setSelectionRange). Cursor stays put across
  autosave, rename, and reset cycles. Works for <input> and
  <textarea> via the shared selectionRange contract.

(B) Click variable in preview → jump to sidebar input
  Go renderer wraps every substituted placeholder value in the HTML
  preview with <span class="draft-var" data-var="key">…</span>.
  Implemented via a valueWrapperFn plumbed through
  substituteInDocumentXML → substituteInTextNodes /
  substituteAcrossRuns → replacePlaceholders. RenderHTML passes
  htmlPreviewWrapper which marks values with three PUA sentinels
  (U+E100/U+E101/U+E102) that emitTextWithDraftVars converts to the
  span pair inside docXMLToHTML. Missing-marker text is wrapped too
  so a clicked [KEIN WERT: foo] jumps to the empty field.

  Render() (.docx export) passes nil for wrap → output is byte-
  identical to pre-261. New test
  TestRender_DocxOutputUnchangedByPreviewWrap asserts the .docx never
  carries draft-var/data-var markup or PUA sentinels.

  Client wireDraftVars() adds .draft-var--has-input only to spans
  whose key resolves to a sidebar input — derived variables (e.g.
  today.iso) stay non-clickable. Click handler:
    scrollIntoView(smooth, center) → focus + select after 50ms →
    1.2s lime flash on the row.
  Keyboard accessible (Enter / Space) with role=button + aria-label.

CSS adds a subtle lime tint to every .draft-var so the user sees
what was substituted; --has-input layers cursor: pointer + brighter
hover background. Flash animation respects prefers-reduced-motion
via a steps(1, end) fallback.

Tests: TestRenderHTML_ExtractsParagraphsAndFormatting updated to
assert the new span wrap. New tests for missing-marker wrap +
.docx-path-untouched. Go + frontend builds clean.
2026-05-25 15:12:10 +02:00
mAi
ef21e43375 Merge: t-paliad-260 — submission-draft mobile layout (m/paliad#91) 2026-05-25 14:59:53 +02:00
mAi
4cb99fb627 mAi: #91 - t-paliad-260 — submission-draft mobile layout: drop sticky on sidebar at ≤900px
Approach A: stack vertically. At single-column widths the variable
editor was sticky + max-height: calc(100vh - 2rem), so it stayed
pinned at the top of the viewport while the user scrolled down to
read the preview, visually overlaying the preview pane.

Add a media-query override that switches the sidebar to position:
static, max-height: none, overflow-y: visible at the same ≤900px
breakpoint where the grid already collapses to one column. The
sidebar now reflows above the preview, takes its natural height,
and scrolls away as the user moves down — no overlay, no
horizontal scroll. Desktop (≥901px) layout unchanged: sidebar
keeps its sticky behavior side-by-side with the preview.

Verified at 375 / 414 / 768 / 1280 px in Playwright on the
populated editor body — same renderer serves both URL shapes
(/submissions/draft/{id} and
/projects/{id}/submissions/{code}/draft/{id}).
2026-05-25 14:58:21 +02:00
mAi
452ccdf127 Merge: t-paliad-258 — Deadline form Auto/Custom rule field + canonical rule-label display (m/paliad#89) 2026-05-25 14:56:18 +02:00
mAi
045accc6d9 mAi: #89 - deadline rule field binary Auto/Custom + canonical rule-label display
t-paliad-258. m's verdict on t-paliad-251's rule UI: "too many options"
(4 'Oral hearings' across courts, etc.). Replace the full deadline_rules
catalog dropdown + sort selector with a binary model and unify the rule
display contract across every surface that prints a rule label.

Binary Rule field on the deadline form
- Auto (default): rule_id is derived from the chosen Type. The resolved
  rule renders read-only as 'Auto | <Name · Citation>' next to the
  field. No catalog picker, no sort options.
- Custom: free-text input. Stored as deadlines.custom_rule_text (new
  nullable column, migration 122). Mutually exclusive with rule_id at
  the persistence boundary.
- Toggle link flips between modes. Re-toggling to Auto re-resolves from
  the current Type — no stale state.

Schema + service (additive)
- migration 122 adds paliad.deadlines.custom_rule_text (nullable).
  Existing rows: empty custom_rule_text + non-null rule_id = Auto-
  equivalent. Both NULL = "keine Regel" (consistent with today).
- models.Deadline.CustomRuleText + service SELECTs include the column.
- CreateDeadlineInput accepts custom_rule_text; the service drops it
  when rule_id is set (catalog wins; simple invariant at the boundary).
- UpdateDeadlineInput grows a {RuleSet, RuleID, CustomRuleText} triple.
  RuleSet=true is the discriminator so absent fields don't overwrite
  the row (PATCH semantics). RuleID and CustomRuleText are mutually
  exclusive in one request; service rejects "both set".
- EventListItem (the /api/events union) carries CustomRuleText so list
  surfaces can render it.

Frontend: deadlines-new
- Drop the rule <select>, the by_proceeding/by_court/alpha sort
  dropdown, the override-warning slot, and the collapsed-by-Regel Typ
  view. Strip the (Rule→Type) auto-fill machinery — direction is now
  one-way (Type → Auto-resolved Rule).
- Keep Type→Rule resolution: resolveAutoRuleForType picks the canonical
  rule by project's proceeding, then jurisdiction match, then first
  candidate. Same logic, just re-aimed at the read-only display.
- Standardtitel preserves the chain (event type → Auto rule label →
  Custom text → proceeding → fallback) so the recipe still produces a
  sensible title even when Custom is used.

Frontend: deadlines-detail
- Read-only display: catalog rule → Name · Citation, else
  custom_rule_text + Custom badge, else legacy rule_code, else "—".
- Edit mode: mirror the create form with the Auto/Custom toggle.
  enterEdit initialises the mode from the persisted deadline; Save
  PATCHes with rule_set:true + the chosen rule pointer.

Rule-label addendum (m's 14:31 follow-up)
- Canonical contract everywhere: Name primary, Citation muted secondary
  ("Notice of Appeal · UPC.RoP.220.1"). Custom rules render the text
  with a "Custom" pill.
- New frontend/src/client/rule-label.ts exports formatRuleLabel /
  formatRuleLabelHTML / formatCustomRuleLabelHTML — one helper per
  shape (plain text vs muted-citation HTML).
- Wired into: deadlines-new Auto display, deadlines-detail read +
  Standardtitel, events.ts ruleDisplay (REGEL column on /events),
  projects-detail.ts Fristen table, views/shape-list.ts generic
  rule column.
- Verfahrensablauf (views/verfahrensablauf-core.ts) already renders
  name + citation chip separately and matches the canonical pattern;
  no change needed. Schriftsätze table is column-shaped (name + code
  in distinct columns) and out of scope per the addendum.

CSS
- New .rule-mode-auto / .rule-mode-custom / .rule-label-* family.
- Drop the dead .rule-sort-select rule and the .event-type-collapsed*
  family (retired with the catalog dropdown).

i18n
- DE+EN. Remove 10 stale keys (rule.none, autofill, autofill_inline,
  mismatch, override, override_warn, sort.*). Add 6 (auto_no_match,
  auto_pick_type, custom_badge, custom_placeholder,
  mode.toggle_to_auto, mode.toggle_to_custom).

Build hygiene
- go build + go test ./internal/... clean.
- frontend bun build clean (2803 keys, scan clean).

Out of scope (per issue)
- Promoting Custom entries back to the catalog ("save as new rule").
- Filtering/searching custom_rule_text in deadline lists.
- Touching the event-type browse modal (Part 1 of #82 — that stays).

Files
- internal/db/migrations/122_deadlines_custom_rule_text.{up,down}.sql
- internal/models/models.go
- internal/services/deadline_service.go (Create+Update+SELECT)
- internal/services/event_service.go (union projection)
- frontend/src/client/rule-label.ts (new helper)
- frontend/src/client/deadlines-new.ts (rewrite)
- frontend/src/client/deadlines-detail.ts (Auto/Custom editor + display)
- frontend/src/client/events.ts (REGEL column)
- frontend/src/client/projects-detail.ts (Fristen table cell)
- frontend/src/client/views/shape-list.ts (generic rule column)
- frontend/src/client/i18n.ts + i18n-keys.ts (DE+EN delta)
- frontend/src/deadlines-new.tsx (strip dropdown+sort, add toggle)
- frontend/src/deadlines-detail.tsx (Auto/Custom edit slots)
- frontend/src/styles/global.css (rule-mode + rule-label families)
2026-05-25 14:54:51 +02:00
mAi
e6b61b4d2e Merge: t-paliad-259 — universal _skeleton.docx fallback for submission preview/generate (m/paliad#90) 2026-05-25 14:45:50 +02:00
mAi
940df95418 fix(submissions): t-paliad-259 — universal _skeleton.docx for fallback chain
Issue: m noticed the submission generator's preview still shows the raw
HL Patents Style .dotm letterhead for every submission_code that has no
per-firm template. Confirmed live: paliad.de's /healthz is green, the
preview path and /generate path both flow through resolveSubmissionTemplate,
and the only code wired in submissionTemplateRegistry is de.inf.lg.erwidg
(t-paliad-241). For every other code, the fallback was the bare letterhead
with zero placeholders — exactly what m observed.

Fix: slot a universal _skeleton.docx between the per-firm code-specific
template and the macro-only HL Patents Style:

  per-firm/{code}.docx → _skeleton.docx → HL Patents Style.dotm

The skeleton carries every placeholder SubmissionVarsService resolves
(all 48 keys across firm.*, today.*, user.*, project.*, parties.*, rule.*,
deadline.*) without baking in submission_code-specific prose, so any
code lands with variables substituted instead of the bare letterhead.

Changes:
- scripts/gen-skeleton-submission-template/main.go: byte-reproducible
  .docx generator mirroring gen-demo-submission-template but with a
  code-agnostic body (no Klageerwiderung "I./II./III." structure, a
  single [Schriftsatztext] block the lawyer replaces). One run per
  placeholder so the renderer's pass-1 substitution catches every token.
- internal/handlers/files.go: register slug submission/_skeleton.docx +
  fetchSubmissionSkeletonBytes helper (same stale-while-revalidate
  semantics as the existing per-code and HL-Patents-Style fetchers).
- internal/handlers/submission_drafts.go: insert the skeleton lookup
  between fetchSubmissionTemplateBytes (per-firm code) and
  fetchHLPatentsStyleBytes (bare letterhead). HL Patents Style remains
  the final fallback for resilience if mWorkRepo is unreachable.

The companion _skeleton.docx is committed to m/mWorkRepo at
6 - material/Templates/Word/Paliad/HLC/_skeleton.docx (commit f2659e4)
so the file proxy can fetch it on first request.

Build hygiene: go build ./... clean, go test ./internal/... clean,
bun run build clean.
2026-05-25 14:44:58 +02:00
mAi
538c2d2da9 Merge: t-paliad-257 — Verfahrensablauf user-perspective column axis (Unsere Seite / Gericht / Gegnerseite) (m/paliad#88) 2026-05-25 14:34:38 +02:00
mAi
a9a9adbd2a mAi: #88 - Verfahrensablauf: column axis reframed to user-perspective
Replaces the misleading Proaktiv/Reaktiv column pair with a static
"Unsere Seite" / "Gericht" / "Gegnerseite" axis ("WE always on the
left", per m's t-paliad-257 ask). The side toggle now drives row
PLACEMENT into the ours/opponent buckets — the column labels stay
truthful regardless of which physical party occupies them.

Old framing lied half the time: Klägerseite is sometimes proactive
(filing the claim) and sometimes reactive (responding to a CCR),
so "Proaktiv (Klägerseite)" was wrong whenever the user's perspective
flipped. New axis is purely positional with semantic labels.

Changes:

- frontend/src/client/views/verfahrensablauf-core.ts:
  • ColumnsRow fields proactive/reactive → ours/opponent.
  • renderColumnsBody picks static "Unsere Seite" / "Gegnerseite"
    labels — no more variant-by-side label keys.
  • bucketDeadlinesIntoColumns routes the user's party into `ours`
    when opts.side ∈ {"defendant"}; default (null) keeps the legacy
    "we are claimant" fallback so claimant-on-left layout survives.

- verfahrensablauf-core.test.ts: rewritten expectations on the new
  ours/opponent fields. Added two new tests pinning the WE-on-left
  semantics and the side+appellant interaction (side=defendant +
  appellant=claimant → "both" collapses into opponent).

- fristenrechner.ts: wires currentPerspective into renderColumnsBody
  as `side` so the columns honour the chip-strip perspective.
  Without this, a defendant-perspective user would see claimant
  filings under the "Unsere Seite" header — the old code didn't
  need the wire-up because the labels weren't perspective-aware.

- i18n.ts: replaces deadlines.col.proactive(.defendant) +
  deadlines.col.reactive(.claimant) with deadlines.col.ours +
  deadlines.col.opponent ("Unsere Seite"/"Client Side",
  "Gegnerseite"/"Opponent Side"). Court key unchanged.

- i18n-keys.ts: regenerated key union.

- global.css: .fr-col-proactive/.fr-col-reactive renamed to
  .fr-col-ours/.fr-col-opponent.

Out of scope (kept intact):
- Side and appellant URL-state plumbing.
- Appellant selector for Appeal-type proceedings (separate axis).
- Project-default side-from-our_side wiring — /tools/verfahrensablauf
  has no project context, and /tools/fristenrechner already does this
  via applyOurSidePredefine().

Build: bun run build clean (2794 keys), go build ./... clean.
Tests: 112 frontend tests pass (was 110, +2 new); all Go tests
cached green.
2026-05-25 14:32:57 +02:00
mAi
f24a90b722 Merge: t-paliad-252 — Approval withdraw warning modal + edit-instead path (m/paliad#83) 2026-05-25 14:26:20 +02:00
mAi
55bfe439f2 Merge: t-paliad-256 — test-data reset + Example Projects seed exercising chain codes (m/paliad#87) 2026-05-25 14:26:03 +02:00
mAi
0ac26fe0ee chore(seed): t-paliad-256 — wipe + seed Example Projects exercising chain code
Re-runnable Go script under scripts/seed-example-projects/ that wipes
every paliad.projects row (FK CASCADE handles dependents) and seeds 18
realistic patent-litigation projects across 3 example clients:

  SIEMENS  — UPC + LG cases incl. CCR (Widerklage) on EP3456789
  BAYER    — EPA Einspruch + BPatG Nichtigkeit on EP2222333
  BEISPL   — sparse DPMA demo on DE10987654

Every node carries the chain-code-driving fields (reference on client,
opponent_code on litigation, patent_number on patent, proceeding_type_id
on case), producing codes like SIEMENS.HUAW.789.INF.CFI and
SIEMENS.HUAW.789.CCR.CFI via services.BuildProjectCode.

One transaction wraps both wipe and seed; -dry-run rolls back so the
script can be sanity-checked before commit. Reference tables
(proceeding_types, deadline_rules, event_types, gerichte, checklists
templates, firms) are untouched.

Ran live against youpc Postgres 2026-05-25: 12 rows wiped, 18 seeded.
2026-05-25 14:25:16 +02:00
mAi
72b64140e9 mAi: #83 - approval withdraw warning modal + edit-instead path
t-paliad-252. Replace the silent confirm()-then-DELETE with a three-path
warning modal: Cancel / Edit event (primary) / Withdraw and delete
(destructive). The edit-instead path lets the requester revise the
in-flight entity without withdrawing the approval request.

Backend — new service method + endpoint
- ApprovalService.EditPendingEntity(requestID, callerID, fields):
  - validates caller == requested_by AND status = pending
  - reuses the existing wider counter-allowlist (buildCounterSetClauses
    from SuggestChanges) — every editable field on the entity, not just
    the date triggers
  - applies the field updates to the entity row via applyEntityUpdate
    (including the event_type_ids junction rewrite for deadlines)
  - merges new fields into approval_requests.payload (jsonb) so the
    approver inbox sees what was revised
  - emits a distinct *_approval_edited_by_requester project_event so the
    Verlauf surfaces the revision separately from the original *_requested
    row and any decision row
  - request stays pending; entity.approval_status stays pending
- POST /api/approval-requests/{id}/edit-entity
  - Body: {"fields": {<entity-shape>}}
  - Errors reuse the existing mapApprovalError mapping:
    400 suggestion_requires_change, 403 not_authorized,
    404, 409 request_not_pending
- Distinguishing audit event types per the spec:
  - destructive Withdraw path: existing <entity>_approval_revoked
    (no behaviour change — for CREATE deletes the entity, for UPDATE /
    COMPLETE reverts to pre_image, for DELETE cancels the delete request)
  - edit-instead path: new <entity>_approval_edited_by_requester

Frontend — shared withdraw warning modal
- frontend/src/client/components/withdraw-warning-modal.ts
  - Built on the unified openModal() primitive (t-paliad-217 Slice A)
  - Primary CTA "Termin bearbeiten" highlights the non-destructive path
  - Secondary defaults to "Abbrechen" (handled by openModal)
  - Destructive button "Endgültig zurückziehen und löschen" lives inside
    the body (red, separated by a dashed border) so the safe path stays
    visually primary in the footer
  - Copy adapts per lifecycle:
    CREATE   → "Wenn Sie zurückziehen, wird die Frist/der Termin gelöscht."
    UPDATE   → "Ihre vorgeschlagenen Änderungen werden verworfen."
    DELETE   → "Der Eintrag bleibt bestehen."

Frontend — wiring on both detail pages
- deadlines-detail.ts + appointments-detail.ts:
  - Replace confirm() in withdraw flow with openWithdrawWarningModal()
  - Edit path: set module-level pendingEditMode = true + enter edit mode
    (override existing pending-state freeze on appointments; expose
    enterEdit() via late-bound pendingEnterEdit on deadlines)
  - Save handler in pendingEditMode routes to /edit-entity instead of
    PATCH /api/<entity>/{id} (which still 409s on pending state)
  - Destructive Withdraw path: existing /revoke endpoint unchanged
  - For CREATE-lifecycle revokes the entity is gone — bounce to the
    /events list instead of trying to re-fetch (was reload() before)

i18n: +14 keys DE+EN under approvals.withdraw.* (modal title, primary,
destructive, cancel, lead.create.{deadline,appointment}, lead.update,
lead.delete, sub.create, sub.update, sub.delete)

CSS: .withdraw-warning-body + .withdraw-warning-{intro,sub,
destructive-row,destructive-btn} — lime-tint sibling palette consistent
with the existing form-hint pattern; destructive button uses .btn-danger.

Build hygiene:
- go build + go vet + go test ./internal/... clean
- frontend bun run build clean (2807 keys, +14 new, scan clean)

Files of note:
- internal/services/approval_service.go (EditPendingEntity + sortedKeys
  helper; maps.Copy for the payload merge)
- internal/handlers/approvals.go (handleEditPendingEntity)
- internal/handlers/handlers.go (route registration)
- frontend/src/client/components/withdraw-warning-modal.ts (new shared
  component)
- frontend/src/client/deadlines-detail.ts (initWithdraw rewrite + Save
  pending-edit branch)
- frontend/src/client/appointments-detail.ts (withdrawAppointmentRequest
  rewrite + Save pending-edit branch + form-freeze respects
  pendingEditMode)

Out of scope (intentionally):
- Reopening already-deleted approval requests (the destructive path
  stays final).
- Approval-request analytics / metrics.
- Notifying the original approval-requester via channel.
2026-05-25 14:24:55 +02:00
mAi
50cd80a4a6 Merge: t-paliad-255 — kill /events horizontal scroll on mobile (m/paliad#86) 2026-05-25 14:10:07 +02:00
mAi
716f6d7ece fix(events): t-paliad-255 — kill /events horizontal scroll on mobile
A native <select> sizes itself to the widest <option> text. With long
project titles in the matters filter, the select grew wider than the
viewport and the /events page scrolled horizontally on mobile.

The existing 480px media query forced .entity-select to width:100% on
phones, but the 481-1000px range (tablet portrait + landscape phones)
had no constraint at all and inherited the intrinsic select width.

Fix: cap .filter-group and .entity-select at max-width:100% with
min-width:0 so the cell can shrink to fit its flex container at every
viewport. Desktop layout is preserved — normal-length options still
sit in one row across the page; only pathological content (a single
title wider than the row) wraps onto its own line.

Approach: A — let the trigger respect its container at every width.

Verified: zero horizontal scroll at 320 / 375 / 414 / 768 px with a
realistic 130-character project title injected into the matters
selector. Desktop (1280px) keeps all four filter-groups in one row.
2026-05-25 14:08:44 +02:00
mAi
1bf62c78e3 Merge: t-paliad-251 — Deadline form overhaul (m/paliad#82) 2026-05-25 14:05:06 +02:00
mAi
9a774ba3ad Merge: t-paliad-254 — Sidebar scroll position persists across nav (m/paliad#85) 2026-05-25 14:04:39 +02:00
mAi
8caaf6a631 mAi: #82 - deadline form overhaul: type-modal filter chips, type→rule autofill, Auto mode, Standardtitel
t-paliad-251. Four bundled concerns from m's 2026-05-25 reports, one
worker, one branch.

Part 1 — Event-type browse modal (search + filters)
- Modal already had a search input; added court-type filter chips
  (UPC / EPA / DPMA / DE / Allgemein) under the search.
- Chips render only the jurisdictions actually present in the data;
  any future flavour lands at the end of the row.
- Active chip uses the lime-tint chip palette already established by
  the .event-type-collapsed* family (t-paliad-165).
- Search input keeps autofocus; chip + search filters intersect.

Part 2 — Type → Rule auto-fill + sort options
- Inverted the existing rule.concept_default_event_type_id mapping
  client-side: given a chosen event_type X, candidate rules are
  those with concept_default_event_type_id === X.
- Resolution picks (1) exact match on the project's
  proceeding_type_id, (2) jurisdiction match on the rule's
  proceeding (EPA→EPO canonicalised), (3) first candidate.
- Sort dropdown next to the Rule label: by proceeding sequence,
  by court (jurisdiction grouping with optgroup), alphabetical.
  Defaults to "by court"; localStorage-persisted per browser.
- All sorts are client-side over the existing /api/deadline-rules
  payload — no new endpoint.

Part 3 — Auto rule mode + clearer override warning
- Auto badge (.form-hint--auto, lime-tint pill + " — <rule name>")
  surfaces whenever the Rule was derived from the chosen Type.
  Disappears the moment the user manually picks a different rule.
- Override warning names BOTH sides + the actually-applied rule:
  "Typ ergibt Regel: X. Gewählte Regel: Y. Es wird Y angewendet."
- Symmetric `lastAutoFilledRuleID` sticky-replace flag mirrors the
  existing `lastAutoFilledEventTypeID` (t-paliad-165) so the auto-
  fill only replaces its own previous suggestion, never a manual
  pick.
- Collapsed Typ view (t-paliad-165) is suppressed when the rule was
  auto-derived from the type — the "vorgegeben durch Regel" copy
  reads backwards in that case; show picker + Auto badge instead.

Part 4 — Standardtitel button (create + edit)
- Button rendered next to the Title field on both /deadlines/new
  and /deadlines/{id} (edit mode only).
- Recipe (recipe-docs-here-so-future-templates-can-mirror-it):
    head =
      1. event_type label (if exactly one Typ chip is set)
      2. rule code+name (when a Rule is set — "RoP.023 — Klageerwiderung")
      3. proceeding type name from project (create form only)
      4. fallback: t("deadlines.field.title.default_fallback")
    suffix = " — <project.reference>" when ref is set and not
             already in head.
  Examples:
    Klageerwiderung — C-UPC-0042       (type known)
    RoP.023 — Klageerwiderung — REF    (rule known, no type)
    UPC — Verletzungsverfahren — REF   (only proceeding type)
    Neue Frist — REF                   (fallback)
- Click REPLACES current title; no destructive confirmation
  because the user invoked it explicitly. Focus moves into the
  title input afterwards so the user can fine-tune.

Build hygiene:
- go build + go vet + go test ./internal/... clean.
- frontend/build.ts clean (2786 keys, +10 new DE+EN, scan clean).
- All changes client-side / CSS / i18n + 2 small TSX edits; no
  schema, no service, no migration.

Files touched:
- frontend/src/client/event-types.ts (browse-modal chips)
- frontend/src/client/deadlines-new.ts (rewrite — Type→Rule, sort,
  Auto badge, override warn, Standardtitel)
- frontend/src/client/deadlines-detail.ts (edit-mode Standardtitel
  + show/hide on enter/exit edit)
- frontend/src/deadlines-new.tsx (label-row + sort dropdown + Auto
  badge slot + override-warn slot + Standardtitel button)
- frontend/src/deadlines-detail.tsx (Standardtitel button)
- frontend/src/styles/global.css (.event-type-browse-chip*,
  .form-hint--auto, .form-hint-badge, .form-field-label-row,
  .btn-link-action, .rule-sort-select)
- frontend/src/client/i18n.ts (+10 keys DE+EN)
2026-05-25 14:03:04 +02:00
mAi
228ae1b263 mAi: #85 - sidebar scroll position persists across nav
Sidebar nav clicks trigger a full page reload, which rebuilds the
sidebar from scratch and snaps .sidebar-nav back to scrollTop=0.
Persist scrollTop to sessionStorage (paliad.sidebar.scroll) on every
scroll and restore on initSidebar(). Re-apply once after
/api/user-views resolves so the async layout shift doesn't leave the
user a few rows off.

sessionStorage scopes the value to the tab: Cmd-click / right-click
"open in new tab" still produces a fresh tab that starts at the top.
2026-05-25 14:03:03 +02:00
mAi
cdd3747c2b Merge: t-paliad-250 — Browse-a-proceeding side+appellant selectors + 'appealable decision' trigger label (m/paliad#81) 2026-05-25 14:00:02 +02:00
mAi
02255c4234 mAi: #81 - verfahrensablauf side+appellant selectors + UPC Appeal trigger label
Concerns A + B + C from m/paliad#81:

A. Browse-a-proceeding (/tools/verfahrensablauf) gains a side selector
   (Kläger/Beklagter/Beide) and an appellant selector. The side selector
   swaps which column labels which user-side; the appellant selector
   collapses party='both' rules into the appellant's column (no mirror)
   so role-swap proceedings (Appeal, etc.) stop showing every row
   twice in the timeline. Both selectors are URL-driven (?side= +
   ?appellant=) and re-render without a backend round-trip.

   The appellant row hides itself for proceedings without an appellant
   axis (first-instance Inf/Rev/Opp) via a small allowlist.

B. UPC Appeal trigger-event caption now reads "Anfechtbare Entscheidung"
   / "Appealable Decision" instead of falling back to the proceeding
   name ("Berufungsverfahren" / "Appeal"). Implemented as an optional
   trigger_event_label_{de,en} column on paliad.proceeding_types (mig
   121); the frontend prefers it over the proceedingName fallback that
   fires when no rule has IsRootEvent=true. No new deadline rules, no
   slug changes (hard rule from the issue).

C. Parameter contract for the column projection is unified in
   bucketDeadlinesIntoColumns(deadlines, {side, appellant}) — a pure
   helper extracted from renderColumnsBody so the routing behaviour
   stays unit-testable without a DOM. Tests cover the default mirror,
   appellant-collapse for both sides, side-swap of column ownership,
   the combined case, and row alignment by dueDate.

Verification

- go build ./...                        clean
- go test ./...                         all green
- bun run build (frontend)              clean
- bun test (frontend/src)               110/110 pass (12 new + 98 prior)
- Migration 121 applied to paliad schema; UPC Appeal proceeding now
  carries the curated trigger label pair.

Out of scope (filed for follow-up): per-rule role tagging so
respondent-side filings (Response to Appeal, Cross-Appeal) land in
the respondent's column when an appellant is selected. The current
issue scope (one-row-per-deadline collapse) is delivered; the
realistic-per-row routing needs a deadline_rules schema bump that
the hard rules of #81 excluded.
2026-05-25 13:57:38 +02:00
mAi
206f2917ea Merge: t-paliad-253 — Submissions /generate runs the merge engine (m/paliad#84) 2026-05-25 13:55:14 +02:00
mAi
5df87f4129 fix(submissions): t-paliad-253 — /generate runs the merge engine
The "Generieren" button on the project Schriftsätze tab posts to
/api/projects/{id}/submissions/{code}/generate. Pre-fix that handler
called `fetchHLPatentsStyleBytes` unconditionally and streamed the
result after a format-only .dotm→.docx convert — it never touched
`submissionTemplateRegistry` (added in t-paliad-241 for the draft
editor) and never ran the SubmissionRenderer merge. m's report on
m/paliad#84 ("the document generator still has no variables in the
template") was the lawyer-facing manifestation: HL Patents Style has
no {{…}} placeholders, so the downloaded .docx had nothing to
substitute and looked like a generic firm-style fixture.

The "Bearbeiten" path (/projects/{id}/submissions/{code}/draft) was
unaffected — it uses `resolveSubmissionTemplate` + the renderer
already, which is why the editor preview shows the 48 placeholders
resolved correctly. Only the one-click /generate side missed the
wire-up.

Fix:

- `internal/services/submission_draft_service.go` — add
  `RenderProjectSubmission(ctx, userID, projectID, submissionCode,
  templateBytes)` that wraps `vars.Build` + `renderer.Render` for the
  no-saved-draft path. Returns the merged bytes plus the resolved
  SubmissionVarsResult (rule, project, user, lang) so the handler can
  derive filename + audit metadata without a second DB round-trip.

- `internal/handlers/submissions.go` — rewrite
  `handleGenerateProjectSubmission` to resolve the template via
  `resolveSubmissionTemplate` (per-firm slug → HL Patents Style
  fallback, same as the editor draft) and run the new service method.
  Visibility / rule-not-found semantics route through
  `SubmissionVarsService` errors so the gate behavior matches every
  other project endpoint. Removed `loadPublishedRuleByCode` and
  `errRuleNotFound` — both were only used by the old handler.

- `scripts/gen-demo-submission-template/main.go` + the regenerated
  `de.inf.lg.erwidg.docx` on mWorkRepo (HL/mWorkRepo @ 3e3e828f) now
  exercise the bare `{{today}}` alias too. The demo template covers
  every one of the 48 keys SubmissionVarsService can resolve (firm 2,
  today 4, user 3, project 18, parties 6, rule 8, deadline 7).

The renderer is a no-op on placeholder substitution when the
fallback HL Patents Style is fetched (it has none) — but it still
runs the .dotm→.docx pre-pass via `ConvertDotmToDocx`, so the
non-per-firm code path streams a byte-for-byte equivalent download.

Build + vet + tests clean (go test ./internal/...; bun run build).
2026-05-25 13:51:45 +02:00
mAi
898348a64a Merge: t-paliad-245 — Daten Exportieren demoted into Verwaltung tab (m/paliad#76) 2026-05-25 13:34:53 +02:00
mAi
1714b788d2 feat(projects-detail): t-paliad-245 — demote Daten Export into Verwaltung tab
m/paliad#76. The export button no longer pokes out of the tabs nav with a
non-tab styling — instead it lives inside a new "Verwaltung" tab (last in
the project tab list) as a normal section with heading, description, and a
plain btn-secondary trigger. Same gate as before (canExportProject).

Archive co-locates in the same tab as a pointer to the Edit-modal danger
zone: click "Bearbeiten öffnen" → modal opens scrolled to the archive
button. Single source of truth for the destructive action stays in the
modal; the Verwaltung pointer just gives it discoverability.

If neither sub-section is visible to the caller (no export entitlement,
not global_admin), the Verwaltung tab hides itself — an empty tab is
worse UX than no tab.
2026-05-25 13:33:14 +02:00
mAi
db8335253b Merge: t-paliad-244 — Team View mailto: link for non-admin members (m/paliad#75) 2026-05-25 13:31:52 +02:00
mAi
5589cbb477 mAi: #75 - team view mailto: link for non-admin members
t-paliad-244 / m/paliad#75. Both "E-Mail an Auswahl senden" actions on
/team (filter-bar + bottom selection footer) now branch on canBroadcast():
- Admin path keeps the in-app compose modal (POST /api/team/broadcast).
- Non-admin path renders a native <a href="mailto:..."> with the
  recipient list pre-filled, comma-joined and URL-encoded via
  buildMailtoHref (already exported from broadcast.ts).

Filter-bar button used to hide for non-admins; it now shows as the
mailto: anchor and its href refreshes on every filter change so the link
always matches what's visible. Empty visible set disables the affordance
visually (aria-disabled + pointer-events:none) so a click can't open an
empty composer. Bottom selection footer mirrors the same shape.

No new i18n keys, no backend changes, admin compose flow untouched.
2026-05-25 13:30:32 +02:00
mAi
0059e3f15b Merge: t-paliad-243 — project-optional Schriftsätze drafts + /submissions/new picker 2026-05-23 02:20:26 +02:00
mAi
a911a2d0ee feat(submissions): t-paliad-243 — global Schriftsätze drafts without project
Adds an end-to-end project-optional path for Schriftsatz drafts:

- Migration 120 drops NOT NULL on paliad.submission_drafts.project_id
  and rewrites the four RLS policies to gate purely on user_id when
  project_id IS NULL, otherwise on paliad.can_see_project. Down
  refuses to run if project-less rows exist (safer than silent
  data corruption).

- SubmissionDraft.ProjectID becomes *uuid.UUID end-to-end. Service
  layer skips project/parties/deadline lookups when nil and exposes
  DraftPatch.ProjectID for the "Projekt zuweisen" affordance.
  ListAllForUser LEFT JOINs paliad.projects so project-less drafts
  surface in the global index next to project-scoped ones.

- New HTTP surface:
    GET  /submissions/new                 (picker page)
    GET  /submissions/draft/{draft_id}    (editor for any draft)
    GET  /api/submissions/catalog         (catalog without project)
    POST /api/submission-drafts           (project-less or attached)
    GET/PATCH/DELETE /api/submission-drafts/{draft_id}
    POST /api/submission-drafts/{draft_id}/export
  Existing /api/projects/{id}/submissions/... routes remain bit-
  identical so the project-scoped flow keeps working unchanged.

- Frontend: /submissions/new lists the full cross-proceeding catalog
  grouped by proceeding, filterable by text + chip. Each row offers
  "Ohne Projekt" (instant draft) or "Mit Projekt…" (modal picker
  with autocomplete over visible projects). /submissions index gains
  a prominent "Neuer Entwurf" CTA and an empty-state CTA pointing at
  the picker. The editor renders a banner + "Projekt zuweisen"
  action when project_id is null; assigning persists project_id and
  redirects to the project-scoped URL.

Audit + project-event writes detect d.ProjectID == nil; the audit
row's scope flips to 'user' (scope_root = user_id) and the
project_events row is skipped entirely.
2026-05-23 02:19:55 +02:00
mAi
b26f04ffe0 Merge: t-paliad-242 — Schriftsätze tab full catalog grouped by proceeding 2026-05-23 01:56:44 +02:00
mAi
8e195cb497 feat(submissions): t-paliad-242 — Schriftsätze tab shows full catalog grouped by proceeding
Per m's 2026-05-23 ask: from any project, surface every available
template/generator instead of just the project's own proceeding.

Backend (GET /api/projects/{id}/submissions):
- drop the proceeding_type_id filter; JOIN deadline_rules with
  proceeding_types to return every active+published filing rule
  across every active proceeding
- response gains proceeding_code, proceeding_name, proceeding_name_en
  per row plus project_proceeding_code at the top so the frontend
  can pin the project's own group
- has_template now reflects "per-submission .docx wired in
  submissionTemplateRegistry"; the editor still falls back to the
  universal HL Patents Style for everything else (t-paliad-238)
- can_see_project gate unchanged; rules are static reference data
- sorted by (proceeding_code, submission_code)

Frontend:
- client/submissions.ts renders a grouped table: project's own
  proceeding pinned to the top with a lime border + "(dieses
  Projekt)" suffix, every other proceeding alphabetised below
- "Generieren" + "Bearbeiten" buttons stay on every row (editor
  handles missing variables via [KEIN WERT: …])
- "universell"/"universal" badge surfaces for rules without a
  per-submission template — informational, not blocking
- soften the no_proceeding hint so the catalog still renders below
- entity-table-group-header CSS, including --own modifier and a
  read-only override so group rows don't pretend to be clickable

Verified: 103 filing rules across 19 proceedings surface (de.inf.lg,
upc.inf.cfi, epa.opp.opd, etc.). go build + go vet + go test
./internal/... + bun run build clean.
2026-05-23 01:55:32 +02:00
mAi
1f7de99493 Merge: t-paliad-241 — demo Klageerwiderung template + placeholder wiring 2026-05-23 01:33:22 +02:00
mAi
0adcc2c826 Merge: t-paliad-240 — Schriftsätze sidebar + global drafts index 2026-05-23 01:30:32 +02:00
mAi
2c7ac6423f feat(submissions): t-paliad-241 — demo Klageerwiderung template wired
Authored a per-submission-code .docx template for `de.inf.lg.erwidg`
exercising every placeholder SubmissionVarsService resolves (45 keys
across firm/today/user/project/parties/rule/deadline namespaces), so
the Submissions draft editor has variables to substitute and the
sidebar/preview feature can be demonstrated end-to-end.

Pieces:

- `scripts/gen-demo-submission-template/` — one-shot Go authoring tool
  that emits a minimal but Word-compatible .docx zip with a fake
  Klageerwiderung skeleton in German. Each placeholder lives in its own
  <w:r> run so the renderer's pass-1 (format-preserving) substitution
  catches it without falling into the cross-run merge path. Output is
  byte-reproducible (fixed mtime).

- `internal/handlers/files.go` — added `submissionTemplateRegistry`
  (submission_code → fileRegistry slug) plus
  `fetchSubmissionTemplateBytes` helper that reuses the Gitea proxy
  cache infra. Registered one entry for `de.inf.lg.erwidg`. The file
  itself was uploaded to mWorkRepo at
  `6 - material/Templates/Word/Paliad/HLC/de.inf.lg.erwidg.docx`
  (mWorkRepo commit 9633524).

- `internal/handlers/submission_drafts.go` —
  `resolveSubmissionTemplate` now tries the per-code lookup first;
  falls back to the universal HL Patents Style for any code that
  doesn't have a per-firm template registered, matching the cronus
  design fallback chain §8.

The existing HL Patents Style .dotm is untouched (still the universal
fallback and still the source for the format-only /generate path).
Future per-submission templates register one fileRegistry entry +
one submissionTemplateRegistry row.
2026-05-23 01:30:24 +02:00
mAi
436c1b41bb feat(submissions): t-paliad-240 — Schriftsätze sidebar + global drafts index
Add a top-level Schriftsätze entry under the Werkzeuge sidebar group
plus a new /submissions page that lists every draft the caller owns
across visible projects. Each row links to the per-project editor at
/projects/{id}/submissions/{code}/draft/{draft_id}.

Backend: SubmissionDraftService.ListAllForUser joins paliad.submission_drafts
with paliad.projects, gated by paliad.can_see_project for visibility. New
GET /api/user/submission-drafts endpoint exposes the rows; the page route
GET /submissions is gateOnboarded'd alongside the other project surfaces.

Frontend: submissions-index.tsx renders an entity-table; submissions-index.ts
hydrates from /api/user/submission-drafts and wires the row-click contract
(skip clicks on inner a/button). DE primary, EN secondary i18n.
2026-05-23 01:29:56 +02:00
mAi
2c5f85b802 Merge: t-paliad-238 Slice A — dedicated Submissions draft editor + merge engine 2026-05-23 00:06:50 +02:00
mAi
d3aade5aac feat(submissions): t-paliad-238 Slice A — dedicated draft editor page
Adds the dedicated Submissions/Schriftsätze editor at
/projects/{id}/submissions/{code}/draft (and …/draft/{draft_id}) per
docs/design-submission-page-2026-05-22.md.

Lawyer picks (or creates) a named draft, edits placeholder variables
in a sticky sidebar, sees a read-only HTML preview of the merged
document body, and exports a .docx with project state + lawyer
overrides resolved. Drafts persist in paliad.submission_drafts
keyed on (project_id, submission_code, user_id, name) with RLS via
can_see_project; updates and deletes additionally gated on owner-only
(Q-E4 owner-scoped pick, m-confirmed).

Resurrected from git history per the design's "no rewrite" plan:
  SubmissionVarsService    ← commit 1765d5e (Slice 2 with patent_number_upc)
  SubmissionRenderer       ← commit 8ea3509 (in-house merge engine — the
                             lukasjarosch/go-docx library refuses sibling
                             placeholders in one run, which patent submissions
                             use routinely)
  ConvertDotmToDocx        ← existing format-only convert (kept; reused as
                             pre-pass so .dotm inputs strip macros before
                             merge)

New code:
  paliad.submission_drafts  migration 119 (idempotent — DROP POLICY IF EXISTS
                            + CREATE; CREATE OR REPLACE for the shared trigger
                            function). Applied to live DB.
  SubmissionDraftService    CRUD + autosave-friendly Update + Export/RenderPreview
                            entry points
  RenderHTML method         new on the renderer; walks the same merged
                            document.xml as Render but emits HTML for the
                            preview pane (Q-E3 server-side pick)
  7 API handlers            list / create / get / patch / delete / preview / export
  2 page routes             /draft and /draft/{draft_id}
  submission-draft.tsx      stand-alone editor page (header / sidebar /
                            preview / export button); served via
                            dist/submission-draft.html
  submission-draft.ts       client bundle — autosave (500ms debounce),
                            draft switcher, rename, delete, export with
                            blob download

Tab integration: existing /projects/{id}/#tab-submissions rows get
[Bearbeiten] alongside the existing [Generieren] one-click format-only
path — additive, no removal.

Slice A template: universal HL Patents Style .dotm (same path
t-paliad-230 uses). resolveSubmissionTemplate carries the
submission_code parameter so Slice B's TemplateRegistry wiring (per-
code .docx fallback chain) is a one-function swap.

Audit trail: paliad.system_audit_log row per export
(event_type='submission.exported') + paliad.project_events row
(event_type='submission_exported', timeline_kind='custom_milestone')
so the export surfaces on the project's Verlauf / SmartTimeline. No
paliad.documents write (Q-E2 inventor pick, head-ratified).

Tests: TestRender_* / TestPlaceholderRegex_* / TestRenderHTML_* +
TestLegalSourcePretty / TestOurSide* / TestPatentNumberUPC — all
green. go build / go vet / go test ./internal/... / bun run build all
clean.

Migration slot taken: 119.
2026-05-23 00:06:08 +02:00
mAi
17d2fff661 Merge: t-paliad-239 — Add Checklist button on project Checklists tab 2026-05-22 23:56:50 +02:00
mAi
c6a5416611 feat(projects): t-paliad-239 — add Checklist button on project Checklists tab
The project-detail Checklists tab now exposes an "Add Checklist"
button that opens a template picker modal. Picking a template POSTs
to /api/checklists/{slug}/instances with the current project_id and
the template title as the instance name; the table refreshes and a
transient success banner confirms the add. Reuses the catalog cache
across the tab renderer and modal so the second open doesn't refetch.

Closes the UX cul-de-sac in the previous empty-state copy that told
users to leave the page and create instances on the Vorlagen-Seite.
2026-05-22 23:56:14 +02:00
mAi
d590be4bb7 Merge: t-paliad-237 — anchor lookup traverses linked proceedings 2026-05-22 23:43:59 +02:00
mAi
f7374a67cd docs(submissions): t-paliad-238 design — dedicated Submissions/Schriftsätze page
Adds docs/design-submission-page-2026-05-22.md (~600 lines) — a
dedicated submission-draft page at /projects/{id}/submissions/{code}/draft
with sidebar variable editor + read-only HTML preview + .docx export.

Reuses (resurrects from git) the deleted Slice 1 backend that t-paliad-230
ripped out — SubmissionVarsService (3677c81 + 1765d5e), in-house
SubmissionRenderer (8ea3509), TemplateRegistry (3677c81). All four
compile against today's services with zero API drift.

New schema: paliad.submission_drafts keyed on
(project_id, submission_code, user_id, name) with RLS via can_see_project.

Three slices: A = schema + page + variables-only export against universal
.docx; B = per-submission_code templates with fallback-chain registry;
C = toggleable passages.

Four material picks escalated to head in §11 (template authoring effort,
paliad.documents row, server-vs-client preview, inter-user draft
visibility). All other open questions defaulted to inventor (R)
recommendations from task brief.

No code. Read-only design phase per inventor → coder gate.
2026-05-22 23:43:51 +02:00
mAi
3ff1b23238 fix(timeline): t-paliad-237 — anchor lookup must traverse linked proceedings
On a CCR sub-project the SmartTimeline renders the parent inf project's
rules in the parent_context lane (correct — the CCR depends on the inf
schedule). Clicking "Datum setzen" on those rows bubbled up as a
generic "Konnte das Datum nicht setzen." because RecordAnchor only
looked up the rule under the CCR's own proceeding_type_id; for an
inf rule like upc.inf.cfi.soc that returned sql.ErrNoRows and dropped
into the catch-all error.

The anchor handler now mirrors the read view's broader rule scope: on
sql.ErrNoRows for a CCR project, we retry the lookup against the
parent project's proceeding_type_id. If the rule is found there, we
reject with a new CrossProceedingAnchorError carrying the parent
project's id + title so the frontend can render a clear DE/EN message
and a clickable link back to the parent ("anchor it on the
infringement proceeding, not the counterclaim"). We deliberately do
NOT auto-route the write across projects — that would silently mutate
the inf project's actuals and is out of scope per the brief.

Genuine "unknown submission_code" failures still surface as
ErrInvalidInput; the predecessor_missing 409 path keeps its existing
shape (the two errors discriminate on the response's `error` field).

Adds a Live-DB integration test that seeds an inf-only rule + a CCR
under a real inf project and verifies all three paths: CCR rejects
cross-proceeding, parent inf project accepts the same code, unknown
codes still report unknown_submission_code.
2026-05-22 23:43:15 +02:00
mAi
a88269c7c1 Merge: hotfix checklist detail page authored slugs 2026-05-22 23:32:12 +02:00
mAi
3d85ce5444 hotfix(checklists): serve detail page for authored slugs (u-a-…)
m's 2026-05-22 report: user-authored checklists appear in the overview
list but clicking through to /checklists/u-a-<id> 404s.

Root cause: handleChecklistDetailPage only consulted
checklists.Find(slug), which is the STATIC compile-time catalog.
Authored checklists (t-paliad-225) live in the DB and never appear
there, so every authored slug fell into the http.NotFound branch even
though /api/checklists returned them in the overview.

Fix: when the static lookup misses AND a DB-backed catalog is wired,
ask checklistCatalog.Find(ctx, uid, slug). The catalog enforces
visibility — slugs the caller can't see still return 404 (via
ErrNotVisible), so this doesn't open a leak. The static path is
unchanged.
2026-05-22 23:32:12 +02:00
mAi
903225b593 Merge: tesla — dashboard widget size clamp on read + write 2026-05-22 15:53:59 +02:00
mAi
4cd2f05d33 fix(dashboard): t-paliad-238 — hidden widgets render at proper size in edit mode
Symptom (m, 2026-05-22): "super slim columns which I can move but not
resize - and they seem greyed out." Hidden widgets in edit mode were
rendering as 1×1 slivers because applyLayout left their inline grid-
column empty — placeWidgets skipped non-visible entries entirely, so
CSS Grid auto-flowed them into the next free cell at 1/12th width.
The greyed-out + no-resize-handle parts were correct UX signalling
that the widget is hidden; the slim rendering was the bug.

Fix:
- placeWidgets() gains a {includeHidden} option. When true, a second
  pass places hidden widgets after the visible pass — collision-aware
  + cursor-aware so the hidden tray stacks below the active layout
  without ever displacing a visible widget. applyLayout() passes
  includeHidden:true in edit mode.
- materializePositions() keeps the default (hidden widgets retain
  their stored coordinates so un-hiding restores them in place).

Server-side recovery (belt-and-braces):
- SanitizeForRead now also clamps each widget's W/H/X against the
  catalog Min/Max + grid bounds on load. Stale rows with W below MinW
  (or above MaxW, or X+W overflowing the grid) heal on the next
  /api/me/dashboard-layout GET and the cleaned spec is persisted
  back. W=0 stays 0 (auto/default sentinel — the placer expands it).
- The validator stays strict on write; the read-path sanitiser only
  exists to recover users who got into a bad state under the old
  rules.

Tests:
- bun: 4 new cases in dashboard-grid.test.ts pin includeHidden
  behaviour (hidden skipped by default, two-pass ordering, multi-
  hidden, no-overlap invariant).
- go: 7 sub-tests in dashboard_layout_spec_test.go cover each
  SanitizeForRead clamp (MinW, MaxW, grid-width, MaxH, X+W overflow,
  W=0 sentinel, negative X) plus a round-trip Validate guarantee.
2026-05-22 15:53:19 +02:00
mAi
b4f5af7f70 Merge: t-paliad-236 — demote Projekt archivieren into Edit modal 2026-05-22 15:52:35 +02:00
mAi
83b00d13fe feat(projects): demote "Projekt archivieren" into Edit modal danger zone (t-paliad-236)
Archive is a rare, deliberate action — it doesn't deserve real estate next
to navigation / common actions on the project view. Move it from the
prominent entity-detail-footer button into the bottom of the Edit Project
modal as a tertiary btn-link-danger inside a visually separated
.modal-danger-zone (top-bordered section, right-aligned).

The visibility wiring (project-delete-wrap, admin-gated in renderHeader)
and click handler (project-delete-btn → delete-modal confirm flow) keep
the same DOM ids, so the existing confirm-modal and POST behaviour are
unchanged. Backend (/api/projects/{id} status=archived) untouched.
2026-05-22 15:51:34 +02:00
mAi
34372ca4c8 Merge: project detail trio — partner-units scan + submissions 404 + client_number nil-coercion 2026-05-22 15:48:47 +02:00
mAi
65308651dd fix(projects): three project-detail page hotfixes
m hit a cluster of three bugs on /projects/{id}/submissions:

1. 500 on /api/projects/{id}/partner-units — DerivationService.AttachedUnit
   scanned derive_unit_roles (text[]) into a plain []string. sqlx returns
   []uint8 for array columns without an adapter. Swap to pq.StringArray
   (same shape as the other array-scanned types in the codebase).

2. 404 on /projects/{id}/submissions — every other project-tab path
   (history, deadlines, team, checklists, …) is registered in handlers.go
   routing all to handleProjectsDetailPage so deep links work, but the
   submissions tab added in t-paliad-230 never got the matching route.
   Result: m navigates to the share-able URL and gets the 404 chrome.
   Add the missing route entry.

3. Create / update project rejected by projekte_client_number_check —
   the CHECK is `client_number IS NULL OR matches '^[0-9]{6}$'`, but the
   form sends empty string "" for an unset field. The Create path passed
   `*input.ClientNumber` raw; the Update path's appendSetSkippable did
   the same. Both now route through a new nullableTrimmed helper that
   coerces empty/whitespace to nil → SQL NULL → constraint accepts.
   matter_number gets the same treatment for symmetry.

Verified the SQL by EXPLAIN against the live DB on the today-filter
hotfix (becf4f0). These three fixes only change Go-side type / nil-
coercion, so no SQL-syntax exposure.
2026-05-22 15:48:47 +02:00
mAi
d088de95eb Merge: hotfix today filter SQL syntax 2026-05-22 15:29:15 +02:00
mAi
becf4f0ce3 hotfix(deadlines): use date(completed_at) not ::date — sqlx named-param bug
Production down (Termin/Fristen list returning 503) since 13:28 UTC on
my own 6c40823 deploy:

  ERROR service: prepare list deadlines:
  pq: syntax error at or near ":" at position 24:68 (42601)

Root cause: sqlx's named-parameter parser scans for `:identifier`
tokens and rewrites them into positional placeholders. The Postgres
cast operator `::` is two consecutive `:`. So `completed_at::date`
gets read as `completed_at:` + `:date` placeholder; the parser strips
the cast and leaves a bare `:` next to `date`, which Postgres rejects.

Same query rewritten with the function form `date(completed_at)`
avoids the lexer collision. Verified against the live DB via EXPLAIN
before pushing.

Lesson for future: tests in internal/services/ don't exercise the SQL
path because there's no DB fixture in the service-layer unit tests.
EXPLAIN-against-live or a real DB integration test is the only way to
catch this kind of SQL regression. Filing as architecture follow-up.
2026-05-22 15:29:15 +02:00
mAi
924dbd9768 Merge branch 'mai/knuth/coder-paliadin-chat' 2026-05-22 15:19:32 +02:00
mAi
6c40823038 Merge: Heute filter retains done-today deadlines 2026-05-22 15:18:59 +02:00
mAi
007ebc2794 fix(deadlines): "Heute" filter retains deadlines completed today
m's 2026-05-22 observation: checking off a deadline on the Heute view
made it disappear immediately — no sense of progress, no record that
the day's work is getting done.

Root cause: filterDeadlines was filtering on `status = 'pending'` even
for the Heute bucket. The bucket should be a date-scoped view of the
day's deadlines, not a pending-only queue.

Fix: include items where `due_date = today` AND either still pending
OR completed today (`completed_at::date = :today`). Items completed on
earlier dates still drop out — the bucket stays "today's work" rather
than "everything that was ever due today".

Frontend already renders completed deadlines as strikethrough/green
via `frist-urgency-done` (see frontend/src/client/events.ts:254), so
no client change needed.

Dashboard counter (`SELECT … COUNT(*) FILTER WHERE status='pending'`)
intentionally unchanged — keeps the lime card a "remaining to do"
indicator, like an unread-mail badge.
2026-05-22 15:18:59 +02:00
mAi
cdd27d674e feat(paliadin): stream + honest late-recovery (t-paliad-235)
m's 14:56 observation: long Paliadin turns showed "Verbindung verloren —
Antwort wird nachgereicht …" but never delivered. The aichat backend
finished the turn upstream; paliad's HTTP client had given up at 130 s
and the legacy filesystem janitor never ran for the aichat path.

Three intertwined fixes, all shipped together because they share the
same wire shape and the same UI states:

1. Switch the aichat backend to /chat/turn/stream
   - new AichatPaliadinService.RunTurnStream relays incremental chunks
   - SSE parser handles default `data:` frames (chunk/meta/done/error)
     and named `event: heartbeat` frames per the upstream contract
   - no more 130 s hard ceiling — stream stays open as long as data or
     heartbeats flow; silenceTimeout (90 s) catches a true upstream
     stall instead

2. Proof-of-life thinking events
   - handler emits `event: thinking` every 5 s while the upstream is
     silent (synthesised locally) AND relays aichat's `heartbeat`
     events as thinking pings
   - frontend renders a lime-dot pulse + monospace counter inside the
     assistant bubble — the user can SEE the chat is still working

3. Honest disconnect copy + real late-recovery
   - new dispatching endpoint GET /api/paliadin/turns/{id}/recover
   - aichat backend: asks aichat via GET /chat/conversations and
     /chat/conversations/{id}/turns whether the turn actually finished
   - legacy backend: falls through to the local row read (janitor)
   - frontend swaps "wird nachgereicht" → "Lade frische Antwort …"
     while the recovery polls; on confirmed "lost" swaps to
     "Antwort konnte nicht zugestellt werden — bitte erneut stellen"
   - migration 118 adds aichat_conversation_id to paliadin_turns so
     the recovery has a fast path when the done frame arrived before
     the drop

Streaming + recovery are a no-op for PALIADIN_BACKEND=legacy: the
StreamingPaliadin interface is detected via type assertion, the
LocalPaliadinService stays on the one-shot RunTurn + filesystem
janitor path.

13 new unit tests cover the SSE parser, the conversation-API client,
and the match-assistant-response helper.

go build ./... + go test ./internal/... + go test ./cmd/server/...
+ bun run build all clean.
2026-05-22 15:17:24 +02:00
mAi
28de2e56d0 Merge: t-paliad-233 — print views default portrait + landscape opt-ins 2026-05-21 22:03:18 +02:00
mAi
af073f87da fix(print): default to portrait, opt-in landscape for wide surfaces (t-paliad-233)
The smart-timeline-chart block in global.css declared @page { size: A4
landscape } inside @media print. @page rules are global even when nested
in selectors, so this leaked landscape onto every printed surface in
paliad — not just the chart.

Switch to named-page strategy:

- Default @page { size: A4 portrait; margin: 1.5cm 1.2cm }
- @page paliad-landscape { size: A4 landscape; margin: 1.5cm }
- @media print: body.<surface> { page: paliad-landscape } opts surfaces
  that need width into landscape via per-page body classes

Landscape opt-ins:
- body.page-kostenrechner — wide fee-tier tables
- body.page-projects-chart — horizontal Smart Timeline chart
- body.events-view-calendar — /events Kalender tab (month grid)
- body.views-shape-active-calendar / -timeline — Custom Views shapes
- body.verfahrensablauf-view-timeline — horizontal procedure timeline

Body classes:
- kostenrechner.tsx, projects-chart.tsx, verfahrensablauf.tsx now set
  page-<slug> on body
- verfahrensablauf.ts toggles verfahrensablauf-view-(timeline|columns)
  in initViewToggle
- views.ts toggles views-shape-active-<shape> in setActiveShape (mirrors
  the existing events.ts events-view-* pattern)

General print polish in the universal block (the catch-all at the bottom
of global.css):
- Hide .fab / .fab-button / .edit-mode-handle / .paliadin-widget /
  [data-print-hide] in print
- thead { display: table-header-group } so headers repeat across pages
- tr/th/td page-break-inside: avoid so rows don't split mid-cell
- h1-h6 page-break-after: avoid, orphans/widows: 3 for p/h*/li
- print-color-adjust: exact on brand-coloured headers + status pills
- a[href^="http"]::after content: " (" attr(href) ")" prints external
  URLs after their link text (opt-out via data-print-url="hide")
- body font-size: 11pt for print readability

Verified via Playwright on static dist build that:
- Default surfaces (dashboard, projects, fristenrechner, agenda, admin)
  match no page: rule → portrait
- kostenrechner, projects-chart match the landscape rule
- verfahrensablauf-view-columns → portrait, -view-timeline → landscape
- views-shape-active-list/-cards → portrait, -calendar/-timeline →
  landscape
- /events default (events-view-cards) → portrait, calendar toggle →
  landscape

go build ./... + go test ./internal/... + bun test (99 pass) + bun
run build all clean.
2026-05-21 22:01:46 +02:00
mAi
f22e918048 Merge: hotfix compose env — SUPABASE_SERVICE_ROLE_KEY 2026-05-21 21:50:43 +02:00
mAi
79d98cfeb8 hotfix(compose): declare SUPABASE_SERVICE_ROLE_KEY in web env block
m reported "Add-User-Pfad ist nicht konfiguriert (SUPABASE_SERVICE_ROLE_KEY
fehlt am Server)" when trying to add a user account on /admin/team.

Root cause: the value was provisioned in Dokploy's compose env block
(I confirmed it via compose.one API), but docker-compose.yml's
`environment:` section never declared the variable. Docker compose
only forwards env vars that are listed in `environment:` — Dokploy's
project-level env is just a source of `${…}` interpolation, not an
automatic injection.

Fix: add `- SUPABASE_SERVICE_ROLE_KEY=${SUPABASE_SERVICE_ROLE_KEY:-}`
alongside the other Supabase keys. The `:-` default keeps the compose
parseable on deployments that haven't provisioned the key (those still
get the existing /admin/team 503 fallback log line).

After the auto-deploy, cmd/server/main.go:139 will log
"supabase admin API configured — /admin/team Add-User path active"
instead of "SUPABASE_SERVICE_ROLE_KEY not set".
2026-05-21 21:50:43 +02:00
mAi
19d95d6f5b Merge: hotfix paliadin /chat/turn user_id 2026-05-21 21:21:37 +02:00
mAi
17d149c09e hotfix(paliadin): ship user_id on /chat/turn (aichat tenant-DB requirement)
m reported "ai chat seems not to be wired anymore" + the frontend
showed "Verbindung verloren. Antwort wird nachgereicht…".

Root cause: aichat on mRiver added a tenant-DB layer that demands
`user_id` on every /chat/turn request:

  {"error":{"code":"bad_request",
            "message":"user_id is required when a tenant DB is
                       configured","retryable":false}}

aichat itself is healthy (/chat/health 200, paliadin session ok:true,
last successful turn was ~2.6h ago). The paliad side built and shipped
an aichatTurnRequest without user_id, so every turn since the tenant-DB
flip 400s; paliad's SSE relay receives no upstream data and closes
empty, producing the user-visible "Verbindung verloren".

Fix: add UserID to aichatTurnRequest (json: user_id, mandatory now),
populate from req.UserID.String() at the call site. The userID was
already in scope (used for JWT mint + username lookup); the struct just
wasn't shipping it.

Regression test in TestRunTurn_HappyPath_ViaCallHTTP asserts
captured.UserID == request UUID so a future struct edit that drops the
field fails CI instead of production.
2026-05-21 21:21:32 +02:00
mAi
7c7030c5bf Merge: t-paliad-232 — Verfahrenstyp picker + Schriftsätze CTA 2026-05-21 15:45:59 +02:00
mAi
da8389b6e3 feat(projects): t-paliad-232 Verfahrenstyp picker + Schriftsätze CTA
Two-part fix from m's 2026-05-21 finding that the Schriftsätze tab
told users "Bitte zuerst einen Verfahrenstyp setzen" while the
project form had no field to set it. The `proceeding_type_id`
column was already on `paliad.projects` and accepted by the API.

  Part 1 — Verfahrenstyp picker on the case-fields block

    * frontend/src/components/ProjectFormFields.tsx — new optional
      <select id="project-proceeding-type-id"> rendered between
      Aktenzeichen and Mandantenrolle inside the type=case block.
      First option is "(nicht gesetzt)" / "(unset)".
    * frontend/src/client/project-form.ts — shared
      loadProceedingTypes() + populateProceedingTypeSelect()
      helpers. Options sorted by `code` (de.* → dpma.* → epa.* →
      upc.*). readPayload sends `proceeding_type_id` only when the
      user picked a value; prefillForm restores the saved id via
      dataset.preselect to survive the async populate race.
    * frontend/src/client/projects-new.ts — kicks off populate on
      DOMContentLoaded.
    * frontend/src/client/projects-detail.ts — edit-modal preload
      now awaits populate; the local loadProceedingTypes duplicate
      (used by the counterclaim modal) is replaced by the shared
      helper so both surfaces hit the same cache.

  Part 2 — Actionable empty-state on the Schriftsätze tab

    * frontend/src/projects-detail.tsx — the static <p> empty-state
      becomes a div with a "Projekt bearbeiten" button.
    * frontend/src/client/projects-detail.ts — openEditModal now
      accepts an optional focusFieldID; the new
      #project-submissions-edit-cta click handler calls it with
      "project-proceeding-type-id" so the picker is scrolled into
      view and focused right after the modal opens.

  i18n: new keys projects.field.proceeding_type{,.unset,.hint} and
  projects.detail.submissions.empty.no_proceeding.cta; reworded
  no_proceeding copy to match the new "edit the project" CTA.

  Backend already validates via validateProceedingTypeCategory
  (mig 087/088 fristenrechner-category guard). Added
  TestProjectService_CaseProceedingTypePicker exercising both the
  happy and reject paths through a `case`-typed Create.

Manual test path: open any case project → Edit → the Verfahrenstyp
picker shows below Aktenzeichen → save → the Schriftsätze tab now
lists the submission codes. Clicking the empty-state CTA jumps
straight to the picker.
2026-05-21 15:45:19 +02:00
mAi
7967839f78 Merge: t-paliad-230 — submission generator format-only convert (.dotm → .docx) 2026-05-21 15:26:31 +02:00
mAi
d86cac0b53 feat(submissions): t-paliad-230 format-only .dotm→.docx convert
m's 2026-05-21 scope reduction of the t-paliad-215 submission generator:
ship a demo that hands the lawyer the firm style template as a clean
.docx. No variable-merge engine, no per-submission template registry,
no fallback chain — the merge slice is deferred to a future task.

Replaces the previous engine (template registry + variable bag +
{{placeholder}} renderer + dual project_events/documents writes) with:

* services.ConvertDotmToDocx — single-function .dotm/.docm/.dotx → .docx
  format converter that strips word/vbaProject.bin, word/vbaData.xml,
  word/customizations.xml, and word/_rels/vbaProject.bin.rels, rewrites
  [Content_Types].xml (demotes the macro/template main type to plain
  docx, drops the .bin Default Extension and the macro Overrides), and
  rewrites word/_rels/document.xml.rels to drop the vbaProject +
  keyMapCustomizations relationships. Idempotent on a plain .docx.
  archive/zip + regex stdlib only — no new third-party dependencies.

* handlers/submissions.go — POST /api/projects/{id}/submissions/{code}
  /generate fetches the cached HL Patents Style .dotm (via a new
  fetchHLPatentsStyleBytes accessor on files.go that shares the same
  cache as /files/{slug}), converts, writes one paliad.system_audit_log
  row (event_type='submission.generated', metadata={submission_code,
  rule_name, filename}), and streams the .docx as an attachment. GET
  /api/projects/{id}/submissions still lists filing rules but
  has_template is unconditionally true (one universal template).

* Filename per design §7: {rule.name}-{project.case_number}-{YYYY-MM-DD}
  .docx, with Umlauts ASCII-folded and slashes → underscores.

Drops services/submission_templates.go, services/submission_vars.go,
and the wiring in cmd/server/main.go + handlers/handlers.go that bound
them together. Frontend client switched to POST.

Verified the converter against the real HL Patents Style.dotm (361 KB
input → 243 KB output, 46 parts in output zip):

  unzip -tq /tmp/hl-patents-style.converted.docx   → No errors
  python3 -c "import zipfile, xml.etree.ElementTree as ET; \
              z=zipfile.ZipFile('/tmp/hl-patents-style.converted.docx'); \
              [ET.fromstring(z.read(p)) for p in z.namelist() if p.endswith('.xml')]"
  uv run --with python-docx python3 -c "import docx; \
              d=docx.Document('/tmp/hl-patents-style.converted.docx'); \
              print(len(d.paragraphs), 'paragraphs', len(d.styles), 'styles')"
              → 236 paragraphs, 168 styles, 1 section

All assertions passed: every Override in [Content_Types].xml resolves
to a real part, every internal Target in document.xml.rels resolves,
zero macro-related residue, and the document body + styles + theme
survive untouched.

go test -run TestBootSmoke ./cmd/server/... clean (route additions
register without conflict on the Go ServeMux).
2026-05-21 15:23:24 +02:00
mAi
69f45893a3 Merge: t-paliad-231 — mailto: team selection on project Team tab 2026-05-21 15:18:42 +02:00
mAi
9f339747e5 feat(team): mailto: selection on project-detail Team tab (t-paliad-231)
Non-admins can now select team members directly on the project detail
Team tab and open a mailto: link in their local mail client with every
selected member queued in the To: line. No server call, no audit row —
the existing /admin/team server-SMTP broadcast (t-paliad-147) stays
admin-only and untouched.

Behaviour:
- Checkbox column on every team-body row (direct + ancestor-inherited).
  Rows for users without an email render a disabled checkbox so the
  column geometry stays uniform.
- Tri-state master checkbox in the header row toggles every visible,
  email-bearing row.
- Single "Mail an Auswahl" button above the table, disabled while the
  selection is empty. When one or more rows are selected the label
  picks up "(N)" and the title attribute spells out the count.
- Click composes mailto:a@x,b@y via the existing buildMailtoHref
  helper from broadcast.ts (RFC 6068 comma join + encodeURIComponent
  per address) and sets window.location.href. Pure client side.
- Selection is pruned to currently-rendered, email-bearing user_ids
  on every renderTeam call so removed members or members who lose
  their email drop out automatically.
2026-05-21 15:17:52 +02:00
mAi
7c3c84454d Merge: t-paliad-229 — changelog catch-up May 2026 2026-05-21 15:03:44 +02:00
mAi
61210943d9 content(changelog): drop submission-generator entry per task scope
t-paliad-229 hard rule: "Don't write release notes for things still
in design phase (submission generator, etc.)". Klageerwiderung
shipped end-to-end via t-paliad-215 Slice 1, but m flagged the whole
submission generator as too early for the public changelog — only
one template, more to follow. Removing the 2026-05-19 entry; the 9
other entries remain unchanged.
2026-05-21 15:01:54 +02:00
mAi
74783e7a89 content(changelog): t-paliad-229 — catch up changelog for May 2026
Adds 10 user-visible entries covering everything shipped since the
2026-04-30 entries. Newest first, voice and length match the
established pattern.

- 2026-05-21 Configurable dashboard (drag/drop edit mode, resize,
  per-widget options, widget catalog, firm-wide admin default,
  collision-aware placement — bundles t-paliad-219 Slice A+B+C +
  m/paliad#69 + #70)
- 2026-05-20 User-authored checklists (Wizard + explicit sharing +
  admin firm-wide promotion + template versioning — t-paliad-225
  Slice A+B+C)
- 2026-05-20 Approvals: suggest changes (third inbox action,
  counter-proposal modal, Verlauf integration — t-paliad-216 +
  t-paliad-217)
- 2026-05-20 Client role + auto-derived project codes (t-paliad-222 =
  m/paliad#47 + #50)
- 2026-05-19 Submissions: Klageerwiderung als Word-Datei (Schriftsätze
  tab + first .docx template — t-paliad-215)
- 2026-05-19 Personal data export (xlsx/csv/json on /settings +
  per-project subtree export — t-paliad-214)
- 2026-05-15 Custom Views (Meine Sichten + list/cards/calendar/timeline
  + exports — t-paliad-144 + t-paliad-177 + t-paliad-211)
- 2026-05-07 Projects page redesign (tree + chips + pin + search + Cards
  view — t-paliad-149 PR 1+2)
- 2026-05-06 Four-eyes approvals (dual-control on deadline/appointment
  CRUD + admin policies UI — t-paliad-138 + t-paliad-154)
- 2026-05-05 Fristenrechner v3 (Pathway A/B + decision tree + concept
  layer + DE/EPA/DPMA expansion — t-paliad-131 / 133 / 134 / 136)

go build ./... + go test ./internal/changelog/... clean.
2026-05-21 15:00:53 +02:00
mAi
062afb6cc5 Merge: hotfix project tree ltree-on-text outage 2026-05-21 14:52:56 +02:00
mAi
47b869dddf hotfix(projects): drop ltree operators on text path — production outage
Production-down: project tree returned the
"Projektverwaltung zurzeit nicht verfügbar" message because every
PopulateProjectCodes call raised:

  ERROR service: populate project codes: bulk fetch:
  pq: operator does not exist: text @> text at position 13:38 (42883)

Root cause: paliad.projects.path is stored as TEXT (dot-separated
UUIDs), not as the ltree extension type. The rest of the codebase
treats it accordingly — can_see_project uses
string_to_array(path, '.')::uuid[]; export_service.go uses LIKE
patterns; export_service.go even spells it out:
"Subtree-aware queries via paliad.projects.path (ltree as text)."

The new project-code helper (t-paliad-222 / m/paliad#50) was the only
caller using ltree operators (@>, nlevel) against this text column.
Postgres correctly rejected text @> text — no such operator exists.

Fix: rewrite both queries (BuildProjectCode + PopulateProjectCodes) to
walk ancestors via string_to_array(path, '.')::uuid[], consistent with
the existing visibility predicate. Ordering uses array_position
instead of nlevel. Query shape validated against the live DB.

Pure-function tests (assemble + segment) untouched and passing. The
gap that let this ship: no integration test exercises the actual SQL
— it only tests the pure assembler. Filing a follow-up issue for a
real-DB regression test.
2026-05-21 14:52:50 +02:00
mAi
c4c4fa267f Merge: fix dashboard deadline link query preservation 2026-05-21 14:23:07 +02:00
mAi
d555d5f679 fix(dashboard): preserve query string on /deadlines → /events redirect
m's 2026-05-21 14:20 report: dashboard "Diese Woche" card linked to
/deadlines?status=this_week but the 301 to /events?type=deadline dropped
the query string, landing on the default Pending filter instead of the
This-Week bucket.

Two-part fix:

1. handleDeadlinesListRedirect now appends r.URL.RawQuery to the
   target so any filter (status, project_id, event_type, …) survives
   the redirect. Regression test pins all three shapes (no query,
   single param, multi param).

2. Dashboard summary cards point at the canonical
   /events?type=deadline&status=… URL directly — saves the 301 bounce
   and matches the URL the events page itself reads on load.

The five card values (overdue/today/this_week/next_week/later) are all
in STATUS_OPTIONS_DEADLINE in frontend/src/client/events.ts, so the
events page filter chip picks them up natively.
2026-05-21 14:23:04 +02:00
mAi
875d0c149a Merge: m/paliad#70 — collision-aware widget placement (dashboard overlap fix)
Follow-up to m/paliad#69. Mixed-size rows (e.g. 2-col widget next to 1-col)
no longer visually overlap because:

- Grid occupancy map now accounts for each widget's full colspan footprint,
  not just its origin cell.
- Drop-target hit detection excludes cells covered by another widget's
  colspan.
- Resize-grow shifts conflicting siblings to the next free cell (m's
  recommended behaviour per the issue body).

Tesla stays persistent on mai/tesla/dashboard-overlap for follow-up
dashboard tweaks per m's continuity ask.
2026-05-21 10:49:45 +02:00
mAi
92d0340d74 fix(dashboard): t-paliad-228 — collision-aware widget placement (m/paliad#70)
After m/paliad#69's edit-mode overhaul, widgets visually overlapped on
mixed-size rows: a 12-col + 6-col swap, an auto-flow widget landing on
an explicit blocker, or a resize-grow into a sibling all produced
layouts that ignored colspan footprints when computing occupancy.

Extracts placement math from dashboard.ts into a pure ./dashboard-grid
module and adds an occupancy bitmap. Every visible widget is placed
once; explicit-position collisions are resolved by searching downward
from the requested row for the first w×h block that fits, preferring
the requested column. Resize-grow + drag-drop swap now reliably
produce no-overlap layouts because the placer cleans up after them.

x+w > GRID_COLUMNS is clamped in the placer instead of rendered as an
overflow — matches the validator's hard rule on the wire.

Adds 14 dashboard-grid.test.ts regressions covering the mixed-width
swap, resize-grow shifting siblings, multi-row widgets, and the
overflow clamp. Pure tests — no DOM.
2026-05-21 10:48:10 +02:00
mAi
f8c6206afe Merge: m/paliad#69 — dashboard edit-mode overhaul (drag/drop + resize + per-widget options)
Three regressions / gaps on newton's just-shipped Slice B+C addressed.

- **Drag/drop reorder**: rebuilt on a single proper 12-col grid (newton's
  implementation had per-row containers which blocked cross-row drops + the
  swap heuristic only handled adjacent same-size cells). Drop hit detection
  now works across the entire grid; recalc step uses real grid coordinates;
  any widget moves anywhere, autosaves.
- **Resize**: bottom-right resize handle added (visible only in edit mode).
  Snaps to valid 1x1 / 2x1 / 2x2 grid sizes; sibling widgets reflow on
  resize; autosave via the same PUT /api/user/dashboard path.
- **Per-widget options expansion**: widget catalog entries now carry an
  option schema (limits, position, content/view-type). Settings pane
  renders the right controls dynamically per schema. Deadlines widget
  exposes list / calendar / timeline-strip view picker; activity widget
  full / compact toggle; etc.

No schema migration — option schema rides on the existing user_dashboard_layouts
jsonb. Backward-compat: legacy layouts (without per-widget options) hydrate
with catalog defaults.
2026-05-21 09:56:08 +02:00
99 changed files with 14719 additions and 2043 deletions

View File

@@ -151,6 +151,14 @@ func main() {
eventTypeSvc := services.NewEventTypeService(pool, users)
deadlineSvc := services.NewDeadlineService(pool, projectSvc, eventTypeSvc)
partySvc := services.NewPartyService(pool, projectSvc)
// t-paliad-238 — dedicated submission draft editor. The variable
// bag service is shared between the renderer (export) and the
// preview HTML path. Resurrected from t-paliad-215 Slice 1 backend
// (commits 3677c81 + 1765d5e + 8ea3509).
submissionVarsSvc := services.NewSubmissionVarsService(pool, projectSvc, partySvc, users)
submissionRenderer := services.NewSubmissionRenderer()
submissionDraftSvc := services.NewSubmissionDraftService(pool, projectSvc, submissionVarsSvc, submissionRenderer)
// t-paliad-225 Slice A — user-authored checklist templates.
// Slice B adds checklist_shares grants + admin promotion.
checklistCatalogSvc := services.NewChecklistCatalogService(pool)
@@ -160,7 +168,8 @@ func main() {
Project: projectSvc,
Team: teamSvc,
PartnerUnit: partnerUnitSvc,
Party: services.NewPartyService(pool, projectSvc),
Party: partySvc,
SubmissionDraft: submissionDraftSvc,
Deadline: deadlineSvc,
Appointment: appointmentSvc,
CalDAV: caldavSvc,
@@ -229,19 +238,10 @@ func main() {
// Nil-safe: empty firm row falls back to the factory layout.
svcBundle.DashboardLayout.SetFirmDefaultService(svcBundle.FirmDashboardDefault)
// t-paliad-215 Slice 1 — submission generator. Three services
// stitched together by handlers/submissions.go: registry pulls
// templates from Gitea (reuses GITEA_TOKEN env), vars builds
// the placeholder map from project + parties + rule, renderer
// merges {{placeholder}} tokens into the .docx.
svcBundle.SubmissionRegistry = services.NewTemplateRegistry(giteaToken, branding.Name)
svcBundle.SubmissionVars = services.NewSubmissionVarsService(
pool,
svcBundle.Project,
svcBundle.Party,
svcBundle.Users,
)
svcBundle.SubmissionRenderer = services.NewSubmissionRenderer()
// t-paliad-230 — submission generator (format-only). No
// service wiring needed: handlers/submissions.go reuses the
// existing files.go HL Patents Style cache and calls
// services.ConvertDotmToDocx (stateless function).
// Paliadin backend selection.
//

View File

@@ -8,6 +8,7 @@ services:
- SUPABASE_URL=${SUPABASE_URL}
- SUPABASE_ANON_KEY=${SUPABASE_ANON_KEY}
- SUPABASE_JWT_SECRET=${SUPABASE_JWT_SECRET}
- SUPABASE_SERVICE_ROLE_KEY=${SUPABASE_SERVICE_ROLE_KEY:-}
- GITEA_TOKEN=${GITEA_TOKEN}
- DATABASE_URL=${DATABASE_URL}
- CALDAV_ENCRYPTION_KEY=${CALDAV_ENCRYPTION_KEY}

View File

@@ -0,0 +1,668 @@
# Design — Dedicated Submission/Schriftsätze page (t-paliad-238)
**Author:** cronus (inventor)
**Date:** 2026-05-22
**Issue:** m/paliad (mai task t-paliad-238)
**Branch:** `mai/cronus/inventor-dedicated`
**Status:** DESIGN READY FOR REVIEW
**Prior art:** `docs/design-submission-generator-2026-05-19.md` (t-paliad-215). This doc deepens that design rather than replacing it — every section below references the corresponding §x there when the shape is reused.
---
## §0 TL;DR
Today's "Schriftsätze" tab on the project detail page lists each filing-type rule and offers a one-click [Generieren] that streams a clean (format-only) `.docx` of the universal HL Patents Style template. There is no customization — variables, parties, dates, optional passages: none of it is filled in. The lawyer downloads the firm style, opens it in Word, and types everything by hand.
This design adds a **dedicated submission page** at `/projects/{id}/submissions/{code}/draft` where the lawyer:
1. Picks (or creates) a named **draft** for one (project, submission_code).
2. Sees a sidebar with every `{{placeholder}}` the merge engine knows, pre-filled from the project's data (parties, court, case number, dates, legal_source) — editable inline. Auto-saved.
3. Sees a read-only preview pane showing the merged document body as HTML.
4. Clicks **Export → .docx** to download a fully-merged Word file (template + project + lawyer overrides), ready to edit.
Old [Generieren] button stays as the one-click "quick export with empty placeholders" path; the new [Bearbeiten] button next to it deep-links to the draft editor. Drafts persist as `paliad.submission_drafts` rows so the lawyer can come back next week, multiple drafts per submission code, RLS through `paliad.can_see_project`.
**Reuses** the deleted Slice 1 backend (`SubmissionVarsService` from commit `3677c81`, in-house `SubmissionRenderer` from `8ea3509`, `patent_number_upc` helper from `1765d5e`) wholesale — those files are salvageable from git history and slot back in with one new service (`SubmissionDraftService`) and the new schema. **Reuses** the `internal/handlers/files.go` Gitea proxy pattern for per-submission_code templates in `m/mWorkRepo/templates/{FIRM_NAME}/{code}.docx` (chain: firm → base/code → base/family → skeleton) — same fallback chain m locked in the 2026-05-19 design (§5).
Three slices: **A** = schema + new page + variables-only export against the universal `.dotm` (one slice; ships the editor end-to-end); **B** = per-`submission_code` `.docx` templates with the fallback-chain registry (template authoring is the bottleneck, not code); **C** = toggleable passages (boilerplate sections the lawyer can include/exclude before export).
Read-only inventor design. Implementation gate is m's go/no-go on this doc through head.
---
## §1 Premises verified live (2026-05-22)
Anchored against the running paliad codebase + youpc Supabase, not against CLAUDE.md or memory. Every claim that load-bears the design was checked against the live system.
| Claim | Verification |
|---|---|
| Today's `/api/projects/{id}/submissions` is **format-only**; no variables. | `internal/handlers/submissions.go:155-245`: handler fetches the universal `hl-patents-style.dotm` from the in-process `fileRegistry` cache, calls `services.ConvertDotmToDocx`, writes one `system_audit_log` row, streams. No project data merged. `frontend/src/client/submissions.ts` confirms the client side: POST → blob → download. The richer engine (`SubmissionVarsService` + `TemplateRegistry` + `SubmissionRenderer`) was reverted to format-only in commit `d86cac0` (t-paliad-230). |
| Original Slice 1 backend is preserved in git history and salvageable. | `git show 3677c81:internal/services/submission_vars.go` (484 LoC, 7-namespace placeholder bag), `git show 8ea3509:internal/services/submission_render.go` (in-house run-fragmentation-aware merger, ~315 LoC), `git show 3677c81:internal/services/submission_templates.go` (442 LoC fallback-chain registry), `git show 1765d5e:internal/services/submission_vars.go` (Slice 2 added `{{project.patent_number_upc}}` helper). All four files compile against today's services (`ProjectService`, `PartyService`, `UserService`, `branding.Name`) — no API drift since 2026-05-20. |
| `paliad.projects` carries everything the variable bag needs. | `internal/models/project.go:123``Title, Reference, CaseNumber, Court, PatentNumber, FilingDate, GrantDate, OurSide, InstanceLevel, ProceedingTypeID, ClientNumber, MatterNumber`. Unchanged since the original design. |
| `paliad.parties` carries party data scoped per project. | `internal/models/project.go:567` (`Party{ID, ProjectID, Name, Role, Representative, ContactInfo}`); `PartyService.ListForProject(ctx, userID, projectID)` already exists at `internal/services/party_service.go`. Visibility flows from `ProjectService.GetByID``can_see_project`. |
| `paliad.deadline_rules` published rows resolve by `submission_code`. | The same query the format-only handler uses (`internal/handlers/submissions.go:255-280`) — `lifecycle_state='published' AND is_active=true ORDER BY sequence_order LIMIT 1`. Today the corpus carries ~254 rules, ~214 published; covers DE-inf-LG, DE-inf-OLG, DE-inf-BGH, UPC-inf-CFI, DE-PatG-DPMA, DE-PatG-BPatG, EPO oppositions. |
| Migration tracker is at 106; file list extends to 118 (other-branch work) on the worktree. | `SELECT version FROM paliad.paliad_schema_migrations ORDER BY version DESC LIMIT 1` → 106. `ls internal/db/migrations/``…118_paliadin_aichat_conversation`. The next free number for *this* branch's migration is **119** (collisions only if another worktree commits 119 first, in which case the coder picks the next unused). |
| `paliad.can_see_project(uuid)` is the canonical RLS predicate. | Mig 055; every other table that gates on project visibility uses it. The new `submission_drafts` table follows the same pattern. |
| The Schriftsätze tab already exists on project detail. | `frontend/src/projects-detail.tsx:91` (`data-tab="submissions"`), section `#tab-submissions` at line 629. Empty / no-proceeding / table-of-rules states already wired. The page-level route `GET /projects/{id}/submissions` exists at `internal/handlers/handlers.go:472` and renders the same project detail page with the submissions tab pre-selected (`#tab-submissions` URL fragment + tab activation). **No new top-level route needed**; this design adds a *deeper* route `/projects/{id}/submissions/{code}/draft` and `/draft/{draftID}`. |
| `internal/handlers/files.go` carries the Gitea proxy + SHA-cache pattern. | Same template the original Slice 1 design lifted (in `templates/_base/de.inf.lg.erwidg.docx @ SHA 7f97b7f9` per memory). 5-min refresh, in-process cache, single-replica deployment. Reusable wholesale. |
| `lukasjarosch/go-docx` is NOT a deal we made. | The original 2026-05-19 design recommended it, but the shipped Slice 1 (commit `8ea3509`) went with an **in-house renderer** because the library refuses to replace sibling `{{a}} ./. {{b}}` placeholders in the same run. The in-house engine handles cross-run fragmentation in ~315 LoC. **This design reuses the in-house engine, no new Go dependency.** Memory entry `ca6de586` corroborates the engine decision verbatim. |
| `FIRM_NAME` defaults to "HLC", overridable. | `internal/branding.Name` (read once at process start). Templates land under `templates/HLC/...` for the default; the fallback chain handles per-firm overrides without code change. |
| The PoC Paliadin is owner-gated; the submission page is NOT. | `internal/services/paliadin.go:52``PaliadinOwnerEmail = "matthias.siebels@hoganlovells.com"`. This is the LLM-shell-out boundary, irrelevant to template-merge. Every paliad user who can see a project can edit its submission drafts. |
| The `entity-table` row contract is enforced. | `.claude/CLAUDE.md` → "Whole-card / whole-row click → use a JS row handler". The new draft list (when a submission_code has multiple drafts) follows the same pattern. |
**Doc-vs-live conflicts found:** none material. `docs/project-status.md` doesn't mention t-paliad-215 or t-paliad-230 yet — that's a documentation lag, not a design risk.
---
## §2 m's decisions (2026-05-22)
The task brief (mai task t-paliad-238 description) carries inventor recommendations (R) for ten open questions. Per project CLAUDE.md inventor → head escalation policy: inventor defaults to (R) unless the pick is materially expensive or risk-bearing, in which case the head escalates to m. The matrix below records the (R) defaults this design adopts; the four genuinely-material picks are escalated to head in §11.
| # | Question (from task brief) | Default adopted | Source |
|---|---|---|---|
| Q1 | Page location | **Deep page under project — `/projects/{id}/submissions/{code}/draft` and `…/draft/{draftID}`** | (R) — keeps URL self-describing and shareable with the project. |
| Q2 | State persistence | **Server-side draft, `paliad.submission_drafts` keyed on `(project_id, submission_code, user_id, name)` with autosave** | (R) — multiple drafts per code, named; resumable across sessions. |
| Q3 | Variable layer | **Resurrect `submission_vars.go` from commit `3677c81` + `1765d5e` (incl. `patent_number_upc`); resolve at export time** | (R) — proven shape, ~30 placeholders, 7 namespaces. |
| Q4 | Customization surface (UI) | **Structured sidebar (variable list, editable values) + read-only HTML preview pane** | (R) — sidebar drives the merge; preview reflects the result. |
| Q5 | Template source | **(a) per-`submission_code` `.docx` in `m/mWorkRepo/templates/{FIRM_NAME}/...` via Gitea proxy + fallback chain** | (R) — Word is the authoring surface lawyers know; mWorkRepo is the existing vehicle. |
| Q6 | Customization options beyond variables | **v1: variables only. Toggleable passages = Slice C** | (R) — citation insertion waits for the sources system. |
| Q7 | Migration / data shape | **See §4** | (R) — followed task brief's column list, refined for RLS + cascade + index. |
| Q8 | Export endpoint | **`POST /api/projects/{id}/submissions/{code}/drafts/{draftID}/export``.docx`** | (R) — reuses `ConvertDotmToDocx` strip-macros path but adds merge step. |
| Q9 | Schriftsätze tab integration | **Keep list + existing "Generieren" (one-click format-only); add new "Bearbeiten" button per row that deep-links to `/projects/{id}/submissions/{code}/draft`** | (R) — additive, no churn for users who only want the firm style. |
| Q10 | Variable-merge library | **In-house renderer from commit `8ea3509` (no new Go module)** | (R) — the 2026-05-19 design recommended `lukasjarosch/go-docx`, but the shipped Slice 1 reverted to an in-house engine because the library refused sibling placeholders. The in-house engine handles run-fragmentation in ~315 LoC and is already battle-tested against the corpus. |
Inventor-defaulted (not in the (R) matrix; clear right answer):
| # | Topic | Default | Reasoning |
|---|---|---|---|
| D1 | Authorization | `paliad.can_see_project(project_id)` only. No profession floor. | Matches every other write surface on a project. Draft is a Word doc; lawyer's substantive review happens downstream. |
| D2 | Missing-placeholder behaviour | `[KEIN WERT: {key}]` / `[NO VALUE: {key}]` in the rendered preview AND in the exported .docx, per `DefaultMissingMarker(lang)` from `8ea3509` | Same call the original design made. Lawyer sees the gap in Word, fixes in paliad, regenerates. Better than 400ing. |
| D3 | Editor surface for templates | Gitea-only for v1 (admin edits .docx in Word, commits to mWorkRepo). | Per the original design §5. A paliad-side uploader is a Slice C+ affordance only if Gitea round-trip is friction. |
| D4 | Audit trail | One `paliad.system_audit_log` row per export (`event_type='submission.exported'`) + one `paliad.project_events` row (`event_type='submission_exported'`) so the export surfaces in Verlauf / SmartTimeline. **Draft create/update do NOT audit** — autosave noise would dominate the log. | Mirrors the existing `submission.generated` row from `internal/handlers/submissions.go:333-339`. The Verlauf entry is the user-visible footprint; the system_audit_log entry is the admin-visible audit footprint. |
| D5 | Preview engine | Server-side merge → render to HTML for preview pane. Same `SubmissionRenderer` walks the .docx, but for the preview it strips `<w:r>` / `<w:p>` to plain HTML paragraphs (no styling beyond paragraph breaks + bold/italic carry-through). The export endpoint produces the real .docx with all formatting preserved. | Cheaper than client-side OOXML parsing; matches the read-only Q4 contract. The preview is a fidelity guide, not a WYSIWYG editor — final formatting comes from Word. |
| D6 | Draft autosave cadence | Debounce 500ms after the lawyer stops typing in a variable field; PATCH `…/drafts/{draftID}` with the diff. No optimistic locking — last-write-wins per (project, submission_code, user) draft, and we never multi-user a single draft (one row per `user_id`). | Standard textarea autosave; the data is the lawyer's own draft, not a shared object. |
| D7 | Variable contract surfacing | Each placeholder in the sidebar shows: dotted key (e.g. `project.case_number`), human label (DE/EN), current resolved value (from project state), and an editable override field. Override empty → fall back to project state at export. Override filled → carry the lawyer's value into the merge. | Lawyer never has to leave the page to fix a project-level field; AND lawyer can locally override (e.g. "Court is wrong on this draft, but I don't want to edit the project") without polluting project state. |
| D8 | Draft naming | First draft per (project, submission_code, user) auto-named "Entwurf 1" (DE) / "Draft 1" (EN). Lawyer can rename inline. Subsequent drafts auto-name "Entwurf 2", etc. The (project_id, submission_code, user_id, name) tuple is the unique constraint — two drafts can't share a name for the same submission of the same project. | Lets the lawyer keep a "submitted version" and a "scratch" version side-by-side. |
---
## §3 Architecture overview
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ Project detail (existing) — /projects/{id} with #tab-submissions │
│ ┌───────────────────────────────────────────────────────────────────────┐ │
│ │ Schriftsätze tab │ │
│ │ Klageerwiderung [Bearbeiten ↗] [Generieren ↓] │ │
│ │ Schriftsatz der Klägerin (SoC) [Bearbeiten ↗] [Generieren ↓] │ │
│ │ Replik [Bearbeiten ↗] [Generieren ↓] │ │
│ └────────┬──────────────────────────────────────────┬─────────────────────┘ │
│ │ "Bearbeiten" deep-link │ "Generieren" = │
│ │ │ existing one-click │
│ ▼ │ format-only export │
└───────────┼───────────────────────────────────────────┼──────────────────────┘
│ │
▼ │
┌──────────────────────────────────────────────────────────────────────────────┐
│ NEW Submission draft page — /projects/{id}/submissions/{code}/draft │
│ (lands on most-recent draft for this user, or creates "Entwurf 1") │
│ │
│ ┌──── Sidebar (sticky left) ────────┐ ┌──── Preview pane (right) ───────┐ │
│ │ Schriftsatz: Klageerwiderung │ │ [HTML-rendered merge of │ │
│ │ Entwurf 1 ▼ [+ Neuer Entwurf] │ │ template + variables + │ │
│ │ ───────────────────────────────── │ │ overrides] │ │
│ │ project.case_number │ │ │ │
│ │ 2 O 123/25 [override?] │ │ Klage gegen die │ │
│ │ parties.claimant.name │ │ Beklagte BMW AG, vertreten │ │
│ │ BMW AG [override?] │ │ durch … │ │
│ │ deadline.due_date │ │ │ │
│ │ 2026-06-12 [override?] │ │ Sehr geehrte Damen und Herren, │ │
│ │ ... │ │ │ │
│ │ │ │ [KEIN WERT: project.our_side] │ │
│ │ [✎ Bearbeiten] inline │ │ │ │
│ └───────────────────────────────────┘ └──────────────────────────────────┘ │
│ │
│ [⬇ Als .docx exportieren] │
└──────────────────────────────────┬───────────────────────────────────────────┘
POST /api/projects/{id}/submissions/{code}/drafts/{draftID}/export
┌──────────────────────────────────────────────────────────────────────────────┐
│ handlers/submission_drafts.go (NEW) │
│ 1. Auth: ProjectService.GetByID → can_see_project │
│ 2. Load draft row (RLS via project visibility) │
│ 3. SubmissionVarsService.Build (project + parties + rule + next-Frist) │
│ 4. Apply draft.overrides on top of bag │
│ 5. TemplateRegistry.Resolve(code) — fallback chain → bytes + SHA │
│ (Slice A: skips registry, fetches the universal .dotm directly) │
│ 6. SubmissionRenderer.Render(bytes, bag, missingMarker) → .docx bytes │
│ 7. Audit: system_audit_log + project_events │
│ 8. Stream .docx with Content-Disposition: attachment │
└──────────────────────────────────────────────────────────────────────────────┘
```
**No backend changes to today's Schriftsätze tab** — its list endpoint + one-click generate stay exactly as they are. The new page is additive.
---
## §4 Schema (`paliad.submission_drafts`)
Migration `119_submission_drafts.up.sql` (next free number on this branch; coder bumps if 119 is taken at write time).
```sql
CREATE TABLE paliad.submission_drafts (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
project_id uuid NOT NULL REFERENCES paliad.projects(id) ON DELETE CASCADE,
submission_code text NOT NULL,
user_id uuid NOT NULL REFERENCES paliad.users(id) ON DELETE CASCADE,
name text NOT NULL, -- "Entwurf 1", lawyer-renameable
overrides jsonb NOT NULL DEFAULT '{}'::jsonb, -- { "project.case_number": "2 O 999/25", ... }
-- empty value = "don't override, use bag"
-- present key = "use this verbatim"
last_exported_at timestamptz, -- NULL until first export
last_exported_sha text, -- template SHA at last export (audit aid)
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT submission_drafts_unique_per_user
UNIQUE (project_id, submission_code, user_id, name)
);
CREATE INDEX submission_drafts_project_user_idx
ON paliad.submission_drafts (project_id, user_id, submission_code, updated_at DESC);
ALTER TABLE paliad.submission_drafts ENABLE ROW LEVEL SECURITY;
CREATE POLICY submission_drafts_visible
ON paliad.submission_drafts
FOR ALL
USING (paliad.can_see_project(project_id));
-- updated_at trigger pattern (same shape as paliad.notizen, etc.).
CREATE TRIGGER submission_drafts_updated_at
BEFORE UPDATE ON paliad.submission_drafts
FOR EACH ROW EXECUTE FUNCTION paliad.tg_set_updated_at();
```
**No changes to `paliad.deadline_rules`.** The task brief floats a `template_body_de/_en` Markdown column as alternative (b) — rejected per Q5 default. Templates stay in Gitea.
**No changes to `paliad.documents`.** The original Slice 1 design wrote an `audit-only` row (`file_path NULL`) per generation; this design **does not**`system_audit_log` + `project_events` carry the audit trail, and `paliad.documents` is reserved for actually-uploaded documents (a Phase 2 affordance per §13.5 of the 2026-05-19 design). If m wants the `documents` row for symmetry with future "I uploaded my edited version" UX, the coder can land it in a follow-up migration; it's not load-bearing for this design.
### 4.1 RLS read-vs-write
`can_see_project` is the only gate — the policy applies to FOR ALL operations. Anyone who can see a project can create / read / update / export drafts under that project, for their own user_id. Inter-user draft visibility (paralegal sees associate's drafts) is **NOT** a requirement in v1 — the unique constraint includes `user_id` and we don't expose a "drafts by other users on this project" endpoint. Multi-user collaboration on a single draft is out of scope.
### 4.2 Down migration
```sql
DROP TABLE IF EXISTS paliad.submission_drafts;
```
No data loss concern at design time — feature ships without legacy drafts.
---
## §5 Service layer
### 5.1 Resurrect from git (no new code)
```
internal/services/submission_vars.go RESURRECT from 3677c81 + Slice 2 patch from 1765d5e (patent_number_upc)
internal/services/submission_render.go REPLACE the format-only convert with the in-house renderer from 8ea3509.
KEEP the convert helper (ConvertDotmToDocx) — Slice A still needs it to
strip macros from the universal .dotm before the merge step runs.
internal/services/submission_templates.go RESURRECT from 3677c81 — Gitea-backed TemplateRegistry with fallback chain.
NOT wired in Slice A (universal .dotm only); wired in Slice B.
```
The three files were ~926 LoC + 350 LoC + 35 LoC patch when shipped. They compile against today's services (`ProjectService`, `PartyService`, `UserService`, `branding.Name`); zero API drift since their deletion. The resurrection is a copy-paste from `git show`, plus a one-line wiring in `cmd/server/main.go` + `internal/handlers/handlers.go`.
### 5.2 New service — `SubmissionDraftService`
```go
// internal/services/submission_draft_service.go (NEW, ~300 LoC)
type SubmissionDraftService struct {
db *sqlx.DB
projects *ProjectService
}
type SubmissionDraft struct {
ID uuid.UUID
ProjectID uuid.UUID
SubmissionCode string
UserID uuid.UUID
Name string
Overrides PlaceholderMap // jsonb → map[string]string
LastExportedAt *time.Time
LastExportedSHA *string
CreatedAt, UpdatedAt time.Time
}
// List returns every draft for (project, submission_code, user) ordered by updated_at DESC.
// Visibility flows through projects.GetByID.
func (s *SubmissionDraftService) List(ctx context.Context, userID, projectID uuid.UUID, submissionCode string) ([]SubmissionDraft, error)
// Get returns a single draft by ID, gated on project visibility.
func (s *SubmissionDraftService) Get(ctx context.Context, userID, draftID uuid.UUID) (*SubmissionDraft, error)
// EnsureLatest returns the user's most-recently-updated draft for (project, submission_code).
// Creates "Entwurf 1" / "Draft 1" if none exists. Idempotent on repeat calls.
func (s *SubmissionDraftService) EnsureLatest(ctx context.Context, userID, projectID uuid.UUID, submissionCode, lang string) (*SubmissionDraft, error)
// Create makes a new draft with an auto-incremented "Entwurf N" name (lawyer can rename via Update).
func (s *SubmissionDraftService) Create(ctx context.Context, userID, projectID uuid.UUID, submissionCode, lang string) (*SubmissionDraft, error)
// Update patches the draft. Permitted fields: name, overrides. last_exported_* is set by the export handler.
func (s *SubmissionDraftService) Update(ctx context.Context, userID, draftID uuid.UUID, patch DraftPatch) (*SubmissionDraft, error)
// Delete archives the draft. ON DELETE CASCADE from project takes care of project-archival fallout.
func (s *SubmissionDraftService) Delete(ctx context.Context, userID, draftID uuid.UUID) error
// MarkExported updates last_exported_at + last_exported_sha after a successful export.
func (s *SubmissionDraftService) MarkExported(ctx context.Context, draftID uuid.UUID, sha string) error
```
`DraftPatch` is a `struct { Name *string; Overrides *PlaceholderMap }` — nil pointer = "no change", non-nil = "set to this". `Overrides` is replace-semantics (lawyer's sidebar sends the full map); the service does not merge.
### 5.3 Wiring
```go
// cmd/server/main.go (additions, no replacements)
draftSvc := services.NewSubmissionDraftService(db, projectSvc)
varsSvc := services.NewSubmissionVarsService(db, projectSvc, partySvc, userSvc)
// Slice B only:
tplRegistry := services.NewTemplateRegistry(os.Getenv("GITEA_TOKEN"), branding.Name)
```
No new env var. `GITEA_TOKEN` is already documented in CLAUDE.md and used by `internal/handlers/files.go`.
---
## §6 UI surface
### 6.1 Page layout
`/projects/{id}/submissions/{code}/draft` lands on the user's latest draft for that (project, code). `/projects/{id}/submissions/{code}/draft/{draftID}` opens a specific draft (e.g. "Entwurf 2"). Both routes call the same renderer + client bundle; the difference is which draft `EnsureLatest` vs `Get` returns.
```
┌──────────────────────────────────────────────────────────────────────────────┐
│ ← Zurück zum Projekt: BMW AG ./. Bosch GmbH │
│ Schriftsatz: Klageerwiderung (DE.ZPO.276.1) • Entwurf 1 │
│ [⬇ Als .docx exportieren] │
├────────── Sidebar (sticky) ────────────────┬─────── Preview ────────────────┤
│ Entwurf 1 ▼ │ [HTML-rendered merge] │
│ • Entwurf 1 (zuletzt 23 Mai 2026) │ │
│ • Entwurf 2 (zuletzt 20 Mai 2026) │ An das Landgericht München I │
│ • [+ Neuer Entwurf] │ Pacellistr. 5 │
│ │ 80333 München │
│ ───────────────────────────────────────── │ │
│ Variablen │ In der Sache │
│ firm.name HLC │ │
│ project.case_number 2 O 123/25 [✎] │ BMW AG, vertreten durch … │
│ project.court LG München I [✎] │ — Klägerin — │
│ parties.claimant.name BMW AG [✎] │ │
│ parties.defendant.name Bosch GmbH [✎] │ gegen │
│ parties.defendant.representative │ │
│ Dr. Maria Schmidt [✎] │ Bosch GmbH … │
│ deadline.due_date 2026-06-12 [✎] │ — Beklagte — │
│ rule.legal_source_pretty │ │
│ § 276 Abs. 1 ZPO ✓ │ Sehr geehrte Damen und Herren,│
│ … │ │
│ │ [KEIN WERT: project.our_side] │
│ ───────────────────────────────────────── │ │
│ [Entwurf umbenennen] [Entwurf löschen] │ │
└────────────────────────────────────────────┴────────────────────────────────┘
```
Sidebar grouping (top-to-bottom, locale-aware labels):
1. **Schriftsatz** (rule.* — read-only metadata: name, legal_source_pretty, primary_party)
2. **Mandanten & Parteien** (parties.*)
3. **Verfahren** (project.* — case_number, court, patent_number, patent_number_upc, our_side, …)
4. **Frist** (deadline.* — due_date, computed_from)
5. **Kanzlei & Datum** (firm.*, user.*, today.*)
Each placeholder row shows: human label (DE/EN), resolved value, edit icon. Click [✎] expands an inline text input pre-filled with the current value. Blur or Enter → debounced autosave (500ms). Empty override → revert to bag value.
### 6.2 Preview pane
Read-only HTML. The same `SubmissionRenderer.Render(...)` call that produces the .docx for export ALSO produces a sidecar HTML preview (the in-house renderer walks `<w:p>` / `<w:r>` runs and emits `<p>` / inline `<strong>` / `<em>` based on `<w:b>` / `<w:i>` flags). Preview re-renders on every autosave round-trip (cheap: server-side merge, ~10ms for a 5-page brief). Loading state: ghost-skeleton paragraphs during the round-trip.
This is the SLIGHTLY non-trivial coder piece: the in-house renderer today emits .docx; the coder adds a parallel `RenderHTML` path that walks the same tree but emits HTML. Same regex, same run-merge logic, different writer. Coder estimates ~120 LoC on top of the resurrected `submission_render.go`.
### 6.3 Routing + handlers
```
GET /projects/{id}/submissions/{code}/draft → page (lands on latest, creates if none)
GET /projects/{id}/submissions/{code}/draft/{draftID} → page (specific draft)
GET /api/projects/{id}/submissions/{code}/drafts → list drafts for current user
POST /api/projects/{id}/submissions/{code}/drafts → create new draft → returns row + redirect target
GET /api/projects/{id}/submissions/{code}/drafts/{draftID} → single draft + resolved bag + HTML preview
PATCH /api/projects/{id}/submissions/{code}/drafts/{draftID} → update name / overrides; returns new preview
DELETE /api/projects/{id}/submissions/{code}/drafts/{draftID} → delete
POST /api/projects/{id}/submissions/{code}/drafts/{draftID}/export
→ .docx download (application/vnd.openxmlformats-officedocument.wordprocessingml.document)
```
Page-route handler is `handleSubmissionDraftPage` in `internal/handlers/submission_drafts.go` — calls `handleProjectsDetailPage` shape (returns HTML for an SSR layout) with a deep-route flag, OR ships an entirely new TSX page module. Inventor default: **new TSX page** at `frontend/src/submission-draft.tsx` rendering its own layout. Lighter than retrofitting the existing project-detail page with conditional panels, and the URL semantics demand it (`#tab-submissions` is the tab; `/draft/{id}` is a distinct page).
### 6.4 Schriftsätze tab — additive change
```diff
- // Each row: [Generieren ↓]
+ // Each row: [Bearbeiten ↗] [Generieren ↓]
```
`[Bearbeiten ↗]``window.location.href = "/projects/{id}/submissions/{code}/draft"`. `[Generieren ↓]` stays as today (one-click format-only export of the universal .dotm). For users who want zero-config "give me a clean firm style template", `[Generieren]` is the path; for users who want a merged draft, `[Bearbeiten]` is the path.
Per the `.entity-table` row contract in CLAUDE.md, the row itself becomes clickable (navigates to `/draft`), with the `Generieren` button stopping propagation. The `entity-table--readonly` modifier is removed.
---
## §7 Variable contract (v1 placeholder set)
Reproduced from the resurrected `submission_vars.go` (commits `3677c81` + `1765d5e`). The sidebar's "Variablen" section enumerates this list in the exact same order as `addProjectVars` / `addPartyVars` / etc., grouped per §6.1.
```
firm.name — branding.Name (HLC or FIRM_NAME override)
firm.signature_block — empty in v1 (Phase 2 affordance)
today — 2026-05-22 (ISO, Europe/Berlin)
today.iso — ISO short
today.long_de — "22. Mai 2026"
today.long_en — "22 May 2026"
user.display_name — paliad.users.display_name
user.email — paliad.users.email
user.office — paliad.users.office
project.title — paliad.projects.title
project.reference — paliad.projects.reference
project.case_number — paliad.projects.case_number
project.court — paliad.projects.court
project.patent_number — DE/inline form "EP 1 234 567 B1"
project.patent_number_upc — UPC parenthesised form "EP 1 234 567 (B1)" (Slice 2 helper, 1765d5e)
project.filing_date — ISO date
project.grant_date — ISO date
project.our_side — claimant | defendant
project.our_side_de — "Klägerin" | "Beklagte"
project.our_side_en — "Claimant" | "Defendant"
project.instance_level — lg | olg | bgh | cfi | …
project.client_number — paliad.projects.client_number
project.matter_number — paliad.projects.matter_number
project.proceeding.code — e.g. "de.inf.lg"
project.proceeding.name — locale-aware (DE: Verletzungsklage am Landgericht)
project.proceeding.name_de — explicit DE
project.proceeding.name_en — explicit EN
parties.claimant.name — first paliad.parties row with role='claimant'
parties.claimant.representative
parties.defendant.name — first row with role='defendant'
parties.defendant.representative
parties.other.name — first non-claimant/defendant row
parties.other.representative
rule.submission_code — "de.inf.lg.erwidg"
rule.name — locale-aware ("Klageerwiderung" / "Statement of Defence")
rule.name_de
rule.name_en
rule.legal_source — "DE.ZPO.276.1"
rule.legal_source_pretty — "§ 276 Abs. 1 ZPO" / "Section 276(1) ZPO"
rule.primary_party — claimant | defendant | court | both
rule.event_type — filing | hearing | decision
deadline.due_date — ISO of next pending deadline for this rule on this project
deadline.due_date_long_de — "12. Juni 2026"
deadline.due_date_long_en — "12 June 2026"
deadline.original_due_date — ISO if extended
deadline.computed_from — anchor description (e.g. "Klagezustellung am 14.05.2026 + 6 Wochen")
deadline.title — deadline.title
deadline.source — "rule" | "manual" | …
```
Variable bag construction is `SubmissionVarsService.Build(ctx, in)` — exactly the function in `3677c81`'s `submission_vars.go`, no changes.
### 7.1 Override semantics
The lawyer's `overrides` map (jsonb in `submission_drafts`) shadows the bag at export time:
```go
bag := varsSvc.Build(ctx, ...).Placeholders // ~30 keys, resolved from project state
for k, v := range draft.Overrides { // lawyer's edits
if v == "" {
delete(bag, k) // empty override means "force missing marker"
} else {
bag[k] = v // non-empty override replaces
}
}
docx := renderer.Render(templateBytes, bag, missingMarker(lang))
```
Edge case: lawyer types empty string into a field that was resolved from the project. Decision: empty override forces the `[KEIN WERT: …]` marker. Lawyer's intent ("blank this out, I'll fill manually in Word") is honoured rather than silently falling back to project state. Sidebar UX: empty override field is annotated "→ [KEIN WERT: …]" so the lawyer sees the consequence before exporting.
---
## §8 Template authoring (mWorkRepo layout, naming, fallback chain)
### 8.1 Slice A — universal .dotm only
Slice A merges the variable bag into the same universal HL Patents Style .dotm that today's format-only convert ships. **The .dotm body must carry `{{placeholder}}` tokens** — currently it doesn't (it's a firm style template, not a per-submission template). m has two ways to seed Slice A:
- **8.1.a** — author one universal template (`m/mWorkRepo/templates/_base/_universal.docx` or similar) with `{{firm.name}}`, `{{rule.name}}`, `{{project.case_number}}`, `{{parties.claimant.name}}`, etc. The merge engine fills these and outputs a draft that's still a generic letter shape but pre-populated.
- **8.1.b** — author one Klageerwiderung-shaped template (`m/mWorkRepo/templates/HLC/de.inf.lg.erwidg.docx`) and route Slice A's export to that path for `submission_code='de.inf.lg.erwidg'`, with a hard-coded fall-back to `_universal.docx` for any other code. This is essentially Slice A + B's first template — wins both rounds.
Inventor recommendation: **8.1.b**. Strictly more useful, identical engine code, identical mWorkRepo round-trip. The Slice A → Slice B transition is then "add more templates", not "rewire the resolver".
### 8.2 Slice B — fallback-chain registry
Layout reproduced from the 2026-05-19 design §5.1:
```
m/mWorkRepo (existing repo, already proxied)
└── templates/
├── HLC/ # FIRM_NAME-keyed override dir
│ ├── de.inf.lg.erwidg.docx # Slice A target (per 8.1.b above)
│ ├── de.inf.lg.klage.docx # Slice B addition
│ ├── upc.inf.cfi.soc.docx # Slice B addition
│ └── upc.inf.cfi.sod.docx # Slice B addition
├── _base/ # Cross-firm baseline
│ ├── de.inf.lg.erwidg.docx # base equivalent (Slice C+)
│ ├── de.inf.lg.docx # proceeding-family fallback
│ ├── upc.inf.cfi.docx
│ ├── _skeleton.docx # ultra-generic fallback
│ └── _universal.docx # the v1 Slice A "any code" template
└── README.md # placeholder reference for template authors
```
Naming: `{submission_code}.docx`. Family fallback uses the first three dot-segments (`de.inf.lg` from `de.inf.lg.erwidg`). Skeleton is the ultra-generic fallback (letterhead + party block + court address + signature stub).
### 8.3 Lookup algorithm
```go
// services/submission_templates.go (resurrected from 3677c81)
func (r *TemplateRegistry) candidates(submissionCode string) []string {
family := familyOf(submissionCode)
out := []string{
fmt.Sprintf("templates/%s/%s.docx", r.firmName, submissionCode),
fmt.Sprintf("templates/_base/%s.docx", submissionCode),
}
if family != "" && family != submissionCode {
out = append(out, fmt.Sprintf("templates/_base/%s.docx", family))
}
out = append(out, "templates/_base/_skeleton.docx")
return out
}
```
Gitea proxy: same `internal/handlers/files.go` shape. 5-min SHA refresh, in-process cache, `GITEA_TOKEN` for auth. The original `submission_templates.go` already implements this end-to-end; the coder re-applies it from `git show 3677c81`.
### 8.4 No template at all — Slice A vs Slice B
Slice A: the universal template always resolves; `ErrNoTemplate` is impossible.
Slice B: if every candidate in the fallback chain 404s, the handler returns 503 + `"Vorlagen-Repository nicht erreichbar"` in the UI (same handling as the original Slice 1 design §5.4). Since the chain ends at `_skeleton.docx`, this only fires when the mWorkRepo itself is misconfigured.
### 8.5 Template authoring task lands outside this design
Inventor flags but does not assign: HLC must author the per-submission_code `.docx` templates. Slice A's `_universal.docx` is one document. Slice B adds Klageerwiderung, Klageerhebung, SoC, SoD, … iteratively. **Template authoring runs in parallel with engine code**; the coder ships the engine, m + HLC ships the templates. The two converge before the slice closes.
This is the m-escalated piece (see §11): without per-submission templates, Slice B is engine-only.
---
## §9 Slice plan
### Slice A — schema + new page + variables-only export against universal .docx
Ships the editor end-to-end with one template.
| Deliverable | Files |
|---|---|
| Migration 119 — `submission_drafts` table + RLS + trigger | `internal/db/migrations/119_submission_drafts.{up,down}.sql` |
| `SubmissionVarsService` resurrected | `internal/services/submission_vars.go` (from `3677c81` + Slice 2 patch `1765d5e`) |
| `SubmissionRenderer` resurrected with new `RenderHTML` | `internal/services/submission_render.go` (from `8ea3509`); adds `RenderHTML(...) string` for preview |
| `SubmissionDraftService` | `internal/services/submission_draft_service.go` (NEW) |
| Handlers (page + 7 API endpoints) | `internal/handlers/submission_drafts.go` (NEW) |
| Wiring | `cmd/server/main.go`, `internal/handlers/handlers.go` |
| Page TSX | `frontend/src/submission-draft.tsx` (NEW) |
| Client bundle | `frontend/src/client/submission-draft.ts` (NEW) |
| Schriftsätze tab update | `frontend/src/projects-detail.tsx` (rows get [Bearbeiten]), `frontend/src/client/submissions.ts` (handler) |
| i18n | new keys under `projects.detail.submissions.draft.*` and `submissions.draft.*` (page-level) |
| One template at `m/mWorkRepo/templates/_base/_universal.docx` (8.1.b → also `templates/HLC/de.inf.lg.erwidg.docx`) | mWorkRepo, separate PR by m |
| Tests | `internal/services/submission_render_test.go` (resurrected + RenderHTML), `internal/services/submission_vars_test.go` (round-trip), handler smoke |
Acceptance:
1. Opening `/projects/{id}/submissions/de.inf.lg.erwidg/draft` lands on the user's latest draft (or creates "Entwurf 1").
2. Sidebar renders ~30 placeholders, pre-filled from project state.
3. Editing a sidebar value autosaves within 500ms and updates the preview pane.
4. Multiple drafts per (project, code, user) supported; switcher in sidebar.
5. Clicking "Als .docx exportieren" downloads a merged `.docx` (universal template + project + lawyer overrides).
6. `system_audit_log` row appears on export (`event_type='submission.exported'`).
7. `project_events` row appears on export and surfaces in Verlauf.
8. RLS: caller without `can_see_project` gets 404 on the page and 404 on every draft API.
9. Schriftsätze tab on project detail shows [Bearbeiten] alongside [Generieren].
10. `go build ./... && go vet ./... && go test ./... && bun run build` clean.
### Slice B — per-submission_code templates + fallback chain
Engine is unchanged from Slice A; this slice wires `TemplateRegistry` into the export endpoint and lights up per-code templates.
| Deliverable | Files |
|---|---|
| `TemplateRegistry` resurrected | `internal/services/submission_templates.go` (from `3677c81`) |
| Handler swaps Slice A's `fetchHLPatentsStyleBytes` for `templateRegistry.Resolve(code)` | `internal/handlers/submission_drafts.go` |
| `has_template` boolean per row in Schriftsätze tab list (today: unconditionally true; under Slice B: depends on registry probe) | `internal/handlers/submissions.go` |
| Templates authored in mWorkRepo: at least Klageerwiderung + Klageerhebung + SoC + SoD | mWorkRepo PR by m |
| Tests for fallback chain | `internal/services/submission_templates_test.go` (resurrect from history if it existed; otherwise new) |
Acceptance:
1. Pushing `m/mWorkRepo/templates/HLC/upc.inf.cfi.soc.docx` makes the SoC draft page resolve that template within 5 min (or instantly via `POST /api/files/refresh`).
2. `has_template=false` rows in the Schriftsätze tab show [Keine Vorlage] instead of [Bearbeiten]/[Generieren]. Existing list ordering preserved.
3. `last_exported_sha` on `submission_drafts` records which SHA the lawyer exported against.
4. Misconfigured repo (every fallback 404s) → 503 with clear error.
### Slice C — toggleable passages
Lawyer can include/exclude boilerplate sections before export.
| Deliverable | Notes |
|---|---|
| `passages` jsonb column on `submission_drafts` | `migration 120` (or whatever's free at land time): `passages jsonb NOT NULL DEFAULT '{}'::jsonb``{"intro": true, "patent_validity_attack": false, "non_infringement": true}`. |
| Template syntax for passage blocks | `{{#passage intro}}…{{/passage}}` — start/end markers, merger drops the block when the corresponding `passages.{key}` is false. The in-house renderer's run-fragmentation handling extends to the new tokens cleanly. |
| Sidebar UI | "Passagen" group above "Variablen", per-passage toggle (on by default), help text per passage. |
| Template author API | `templates/README.md` documents the passage syntax + a worked example. |
Acceptance: turning off `non_infringement` in the sidebar of a Klageerwiderung draft removes the corresponding section from the exported .docx; preview reflects immediately.
Slices D+ (not detailed here): citation insertion from the sources system (waits for that surface), per-firm template overrides (registry already supports this), `/admin/submission-templates` variable contract sidebar.
---
## §10 Out of scope
- AI-drafted prose (the 2026-05-19 design §11 sketch; still deferred).
- PDF export. v1 ships `.docx` only; the lawyer's Word does the PDF step.
- Multi-user collaboration on a single draft. Each draft is owner-scoped (`user_id`).
- Real-time co-editing. Last-write-wins per draft; no operational transforms.
- An in-paliad WYSIWYG editor for `.docx` content. Preview is read-only; final edits happen in Word.
- A paliad-side template uploader. Gitea stays as the editor for templates until lawyers complain about the round-trip.
- Translation of templates DE↔EN. Templates are mono-locale; the variable bag is bilingual.
- Citation insertion from the sources system. Waits for the sources surface m parked.
- Frist-detail "Exportieren" button. The submission page is reachable only from the project's Schriftsätze tab in v1; a Frist-level deep-link is a Slice D+ affordance.
- Validation of the rendered draft against any legal rule. The engine produces text; the lawyer's substantive review is downstream.
- Sending the draft to court / e-filing. The lawyer downloads and handles transmission outside paliad.
---
## §11 Material picks escalated to head
Per project CLAUDE.md inventor → head policy, the four picks below carry enough cost or risk to deserve head's read. Head ratifies (or escalates to m) before the coder shift starts.
### Q-E1 — Template authoring effort
Slice A needs at least one custom-authored template (`_universal.docx` or `de.inf.lg.erwidg.docx`) carrying `{{placeholder}}` tokens. Slice B needs four more (Klageerhebung, SoC, SoD, Erwiderung). The engine ships independently of template content, but the feature is unfinished without lawyer-authored templates.
**Inventor pick:** ship Slice A with **one** lawyer-authored template (8.1.b: `templates/HLC/de.inf.lg.erwidg.docx`) + the universal fallback. m + HLC owns the authoring; the coder owns the engine. Slices A and template-1 land together.
**Material because:** without a template, the feature looks broken in user testing. Head decides: does m commit to authoring or reviewing the first template before Slice A merges, or does Slice A merge engine-only and we accept the "format-only export with placeholders" intermediate state for a week?
### Q-E2 — `paliad.documents` row on export
The original Slice 1 design wrote an audit-only `paliad.documents` row (`file_path NULL`, `doc_type='generated_submission'`) per generation, on the theory that "Documents" would become the canonical listing UI. This design defers that.
**Inventor pick:** **no** `paliad.documents` write. `system_audit_log` + `project_events` carry the audit trail. The `documents` table is reserved for actually-uploaded documents (Phase 2 of the broader docs roadmap).
**Material because:** if head agrees, we skip a column repurpose (`ai_extracted` jsonb being used for generation provenance — the 2026-05-19 design noted this was ugly). If head disagrees, the coder lands the row inside Slice A.
### Q-E3 — Preview render — server or client?
Server-side: `RenderHTML(...)` on the in-house renderer, round-trip per autosave. Cheaper to build, costs ~10ms server-side per keystroke (debounced 500ms).
Client-side: ship the merged document body as JSON of paragraph runs, render in TS. Faster preview, harder to build (parallel render path in TS), and **diverges** the preview from the export shape (export still goes server-side).
**Inventor pick:** **server-side**. Single source of truth for the merge logic. The 500ms debounce already absorbs the round-trip; a 10ms server merge plus 50ms HTTP RTT is sub-perceptible.
**Material because:** if head wants the client-side preview for fully-offline draft editing, the coder needs a TS port of `substituteInDocumentXML`. Bigger build, but no round-trip latency on every keystroke.
### Q-E4 — Inter-user draft visibility
Today's design: each user sees only their own drafts. If two associates on the same project both draft a Klageerwiderung, they don't see each other's drafts (each has their own row).
**Inventor pick:** **owner-scoped (status quo of this design)**. The unique constraint includes `user_id`; the `List` endpoint filters by current user.
**Material because:** if head wants project-team visibility ("paralegal sees associate's draft for review"), the unique constraint shifts to `(project_id, submission_code, name)` (drop `user_id`), the RLS already covers the read path (`can_see_project`), and `submission_drafts` becomes a project-team resource. **This is a Phase-shape change** — the lawyer model differs. Inventor flags it because the change is cheap to make now (one column + one constraint) and expensive to make later (drafts already accumulate per-user). Head's call.
---
## §12 Implementation notes
For the coder, not for head.
- **Resurrection is `git show`, not "re-write".** The four file revisions (`3677c81:internal/services/submission_vars.go`, `1765d5e:internal/services/submission_vars.go` for the Slice 2 patch, `8ea3509:internal/services/submission_render.go`, `3677c81:internal/services/submission_templates.go`) can be applied via `git checkout 3677c81 -- internal/services/submission_vars.go` etc. The coder should verify each compiles against today's `cmd/server/main.go` wiring before applying.
- **Renderer's `RenderHTML` is new.** The .docx walker today emits OOXML bytes; the HTML emitter walks the same tree and emits `<p>` / `<strong>` / `<em>` / `<br>`. ~120 LoC on top of the resurrected file. Same regex (`placeholderRegex`), same run-merge logic, different writer.
- **Sidebar variable schema needs a label table.** The variable contract from §7 is keyed by dotted paths; the sidebar UI needs DE/EN labels per key. Coder adds `services/submission_var_labels.go` with a `map[string]struct{LabelDE, LabelEN, HelpDE, HelpEN}` for the ~30 keys. (Mirrors `internal/services/email_template_variables.go` shape — same lawyer-facing pattern paliad already ships at `/admin/email-templates`.)
- **Autosave race.** The lawyer types fast → multiple PATCHes in flight. Coder uses a request-ID-debouncing pattern on the client (cancel in-flight PATCH when a new one starts) and last-write-wins on the server. No version column on the draft row in v1.
- **Empty-override semantics in the jsonb.** `overrides = {"project.case_number": ""}` means "force missing marker". `overrides = {}` (key absent) means "fall back to bag". The service code distinguishes — careful with `omitempty`.
- **i18n key audit.** Add `projects.detail.submissions.action.edit`, `submissions.draft.title`, `submissions.draft.export`, `submissions.draft.sidebar.{firm,project,parties,deadline,user}.group`, `submissions.draft.rename`, `submissions.draft.delete`, `submissions.draft.new`, etc. Roughly 35 new keys in DE + EN.
- **`entity-table` row contract.** Schriftsätze tab today carries `entity-table--readonly`. Slice A removes that modifier and adds a row-click handler that navigates to `/projects/{id}/submissions/{code}/draft`, skipping clicks on the inner [Generieren] button. Matches the pattern in `frontend/src/client/checklists.ts`, `client/projects-detail.ts`, `client/deadlines.ts`.
- **Migration 119 may collide.** Other worktrees (paliadin aichat, mig 118) may land 119 before this branch merges. Coder verifies at land time; bump to the next free number if needed.
---
## §13 Acceptance gate
Per inventor SKILL.md + project CLAUDE.md: this design needs head's go/no-go before any coder is hired. After head ratifies (with or without escalating §11 to m):
- The head decides whether to hire the same worker as `/mai-coder` with this design as the brief, or a fresh coder.
- A coder shift takes this doc as the spec, ships Slice A, opens a PR (no self-merge).
- Slices B and C are SEPARATE tasks — not auto-spawned.
Inventor parks here.

View File

@@ -18,6 +18,9 @@ import { renderProjects } from "./src/projects";
import { renderProjectsNew } from "./src/projects-new";
import { renderProjectsDetail } from "./src/projects-detail";
import { renderProjectsChart } from "./src/projects-chart";
import { renderSubmissionDraft } from "./src/submission-draft";
import { renderSubmissionsIndex } from "./src/submissions-index";
import { renderSubmissionsNew } from "./src/submissions-new";
import { renderEvents } from "./src/events";
import { renderDeadlinesNew } from "./src/deadlines-new";
import { renderDeadlinesDetail } from "./src/deadlines-detail";
@@ -252,6 +255,9 @@ async function build() {
join(import.meta.dir, "src/client/projects-new.ts"),
join(import.meta.dir, "src/client/projects-detail.ts"),
join(import.meta.dir, "src/client/projects-chart.ts"),
join(import.meta.dir, "src/client/submission-draft.ts"),
join(import.meta.dir, "src/client/submissions-index.ts"),
join(import.meta.dir, "src/client/submissions-new.ts"),
join(import.meta.dir, "src/client/events.ts"),
join(import.meta.dir, "src/client/deadlines-new.ts"),
join(import.meta.dir, "src/client/deadlines-detail.ts"),
@@ -376,6 +382,9 @@ async function build() {
await Bun.write(join(DIST, "projects-new.html"), renderProjectsNew());
await Bun.write(join(DIST, "projects-detail.html"), renderProjectsDetail());
await Bun.write(join(DIST, "projects-chart.html"), renderProjectsChart());
await Bun.write(join(DIST, "submission-draft.html"), renderSubmissionDraft());
await Bun.write(join(DIST, "submissions-index.html"), renderSubmissionsIndex());
await Bun.write(join(DIST, "submissions-new.html"), renderSubmissionsNew());
// t-paliad-115 — shared EventsPage at the canonical /events URL.
// One HTML output; defaultType="all" baked in. Sidebar Fristen /
// Termine entries point at /events?type=… and events.ts re-highlights

View File

@@ -2,6 +2,7 @@ import { initI18n, t, tDyn, getLang } from "./i18n";
import { initSidebar } from "./sidebar";
import { initNotes } from "./notes";
import { projectIndent } from "./project-indent";
import { openWithdrawWarningModal } from "./components/withdraw-warning-modal";
interface Appointment {
id: string;
@@ -25,6 +26,9 @@ interface PendingApprovalRequest {
requested_at: string;
required_role: string;
requester_name?: string;
// t-paliad-252 — used by the withdraw warning modal to pick the right
// copy (CREATE warns about deletion; UPDATE/COMPLETE about revert).
lifecycle_event?: string;
}
interface Me {
@@ -43,6 +47,10 @@ let project: Project | null = null;
let allProjects: Project[] = [];
let pendingRequest: PendingApprovalRequest | null = null;
let me: Me | null = null;
// t-paliad-252 — see deadlines-detail.ts. Routes Save to the new
// /api/approval-requests/{id}/edit-entity endpoint when the user picked
// "Termin bearbeiten" in the withdraw warning modal.
let pendingEditMode = false;
function parseAppointmentID(): string | null {
const parts = window.location.pathname.split("/").filter(Boolean);
@@ -207,10 +215,14 @@ function renderHeader() {
}
// Freeze the edit form + delete button while a request is in flight.
// t-paliad-252 — when the user picked "Termin bearbeiten" in the
// withdraw modal, pendingEditMode unfreezes the form so Save can route
// to /edit-entity (which keeps the request pending + merges payload).
const form = document.getElementById("appointment-edit-form") as HTMLFormElement | null;
if (form) {
const freeze = isPending && !pendingEditMode;
form.querySelectorAll<HTMLInputElement | HTMLSelectElement | HTMLTextAreaElement | HTMLButtonElement>("input, select, textarea, button[type=submit]")
.forEach((el) => { el.disabled = isPending; });
.forEach((el) => { el.disabled = freeze; });
}
const deleteBtn = document.getElementById("appointment-delete-btn") as HTMLButtonElement | null;
if (deleteBtn) deleteBtn.disabled = isPending;
@@ -263,6 +275,39 @@ async function saveEdit(ev: Event) {
submitBtn.disabled = true;
try {
// t-paliad-252 — pending-edit mode routes through /edit-entity which
// keeps the request pending + merges fields into payload. clear_project
// and project_id are NOT in the counter-allowlist (yet) — the requester
// can't move projects on a pending request from this surface.
if (pendingEditMode && pendingRequest) {
const editFields = { ...payload };
delete editFields.clear_project;
const resp = await fetch(
`/api/approval-requests/${pendingRequest.id}/edit-entity`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fields: editFields }),
},
);
if (resp.ok) {
const fresh = await fetch(`/api/appointments/${appointment.id}`);
if (fresh.ok) appointment = await fresh.json();
await loadPendingRequest();
// Exit pending-edit mode so the form re-freezes (still pending).
pendingEditMode = false;
renderHeader();
fillEditForm();
msg.textContent = t("appointments.detail.saved");
msg.className = "form-msg form-msg-ok";
} else {
const data = await resp.json().catch(() => ({}) as { error?: string; message?: string });
msg.textContent = data.message || data.error || t("appointments.error.generic");
msg.className = "form-msg form-msg-error";
}
return;
}
const resp = await fetch(`/api/appointments/${appointment.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -312,12 +357,37 @@ async function deleteAppointment() {
}
}
// t-paliad-252 — withdraw warning modal replaces the old confirm().
// Returns:
// "edit" → unfreeze the edit form (pending-edit mode); Save will
// route through /api/approval-requests/{id}/edit-entity
// "withdraw" → destructive: the existing /revoke endpoint
// null → user cancelled
async function withdrawAppointmentRequest() {
if (!appointment || !pendingRequest) return;
if (!confirm(t("approvals.withdraw.confirm") || "Anfrage wirklich zurückziehen?")) return;
const btn = document.getElementById("appointment-withdraw-btn") as HTMLButtonElement | null;
if (btn) btn.disabled = true;
try {
const action = await openWithdrawWarningModal({
entityType: "appointment",
lifecycleEvent: pendingRequest.lifecycle_event ?? "create",
});
if (action === null) {
if (btn) btn.disabled = false;
return;
}
if (action === "edit") {
pendingEditMode = true;
if (btn) btn.disabled = false;
// renderHeader re-evaluates the freeze and unfreezes the form now
// that pendingEditMode is set. Focus the first editable field so the
// user can type immediately.
renderHeader();
const titleEl = document.getElementById("appointment-title-edit") as HTMLInputElement | null;
titleEl?.focus();
return;
}
// action === "withdraw" → destructive path.
const resp = await fetch(`/api/approval-requests/${pendingRequest.id}/revoke`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -328,9 +398,12 @@ async function withdrawAppointmentRequest() {
if (fresh.ok) {
appointment = await fresh.json();
await loadPendingRequest();
renderHeader();
fillEditForm();
} else {
// CREATE lifecycle: entity gone → back to the list.
window.location.href = "/events?type=appointment";
}
renderHeader();
fillEditForm();
} else {
const data = await resp.json().catch(() => ({}) as { message?: string; error?: string });
const msg = document.getElementById("appointment-edit-msg")!;

View File

@@ -0,0 +1,149 @@
// t-paliad-252 / m/paliad#83 — withdraw warning modal.
//
// Before t-paliad-252 the deadline + appointment detail pages did a
// confirm() dialog before POSTing to /api/approval-requests/{id}/revoke.
// For pending CREATE lifecycles that endpoint silently DELETES the
// underlying entity row — m's "withdrawing the approval deletes the event"
// surprise.
//
// This modal replaces the confirm() with three explicit paths:
//
// 1. Cancel — does nothing
// 2. Termin bearbeiten (primary) — opens the edit form; saving routes
// through POST /approval-requests/{id}/
// edit-entity which keeps the request
// pending and merges the new fields
// into approval_request.payload
// 3. Endgültig zurückziehen + — destructive; current /revoke
// löschen behaviour (delete for CREATE, revert
// for UPDATE/COMPLETE, cancel for
// DELETE-lifecycle requests)
//
// Built on the unified openModal() primitive (t-paliad-217 Slice A) so the
// three-button row sits cleanly inside the body — the primitive only
// supports one secondary action, but we paint the destructive button as a
// separate row above the footer.
import { t } from "../i18n";
import { openModal } from "./modal";
export type WithdrawAction = "edit" | "withdraw";
export interface WithdrawWarningArgs {
// entityType drives the copy ("event" vs "appointment" labels).
entityType: "deadline" | "appointment";
// lifecycleEvent of the pending request; copy adapts (CREATE warns about
// deletion; UPDATE/COMPLETE warn about revert; DELETE warns about
// cancelling the deletion request).
lifecycleEvent: "create" | "update" | "complete" | "delete" | string;
}
// openWithdrawWarningModal resolves with the chosen action, or null if the
// user dismissed via Cancel / Esc / backdrop / browser back-button.
export async function openWithdrawWarningModal(
args: WithdrawWarningArgs,
): Promise<WithdrawAction | null> {
const body = document.createElement("div");
body.className = "withdraw-warning-body";
// Lead paragraph + sub-paragraph adapt to lifecycle so the user always
// knows what the destructive button will actually do. The /revoke
// backend behaviour:
// - create → DELETE the entity (the "surprise" m flagged)
// - update → revert to pre_image
// - complete → revert to pre-complete state
// - delete → cancel the delete request (entity stays alive)
const intro = document.createElement("p");
intro.className = "withdraw-warning-intro";
intro.textContent = leadCopyFor(args);
body.appendChild(intro);
const sub = document.createElement("p");
sub.className = "withdraw-warning-sub muted";
sub.textContent = subCopyFor(args);
body.appendChild(sub);
// The destructive button lives inside the body — the openModal primitive
// only exposes one secondary button slot, and we want the safe "Edit"
// path to be the primary CTA. Painting it in red here, separated from
// the footer, signals "this is the dangerous option" without competing
// visually with the primary CTA.
const destructiveRow = document.createElement("div");
destructiveRow.className = "withdraw-warning-destructive-row";
const destructiveBtn = document.createElement("button");
destructiveBtn.type = "button";
destructiveBtn.className = "btn btn-danger withdraw-warning-destructive-btn";
destructiveBtn.textContent = t("approvals.withdraw.destructive.label");
destructiveRow.appendChild(destructiveBtn);
body.appendChild(destructiveRow);
return new Promise<WithdrawAction | null>((resolve) => {
let chosen: WithdrawAction | null = null;
// The destructive button has to close the modal and return "withdraw".
// We need access to the modal's internal close() — fortunately openModal
// exposes it via the primary handler's first arg. We pass through the
// outer resolve and let the primary handler (Edit) own the close-fn
// route. For the destructive button we resolve the outer promise
// directly and then synthesise an ESC keypress so the modal dismisses
// — or, simpler, set chosen and use the secondary "Cancel" path that
// the modal already supports. (openModal's onClose fires on every
// dismiss path including the primary handler resolution.)
destructiveBtn.addEventListener("click", () => {
chosen = "withdraw";
// The unified openModal primitive (modal.ts) wires its dismiss path
// through the native <dialog>'s `cancel` event. Dispatching it on
// the parent <dialog> runs the same finish() → onClose → resolve
// sequence as ESC / backdrop. We then map the resolved `null` back
// to "withdraw" via the captured `chosen` in onClose below.
const dialogEl = body.closest("dialog");
dialogEl?.dispatchEvent(new Event("cancel"));
});
void openModal<WithdrawAction>({
title: t("approvals.withdraw.modal.title"),
body,
size: "md",
classNames: "withdraw-warning-modal",
primary: {
label: t("approvals.withdraw.primary.label"),
handler: (close) => {
chosen = "edit";
close("edit");
},
},
secondary: { label: t("approvals.withdraw.cancel") },
onClose: () => {
// Resolves whatever was chosen via the destructive button OR the
// primary handler. ESC / backdrop / secondary clear `chosen` to
// null which is the right "cancel" semantics.
resolve(chosen);
},
});
});
}
function leadCopyFor(args: WithdrawWarningArgs): string {
switch (args.lifecycleEvent) {
case "create":
return args.entityType === "appointment"
? t("approvals.withdraw.lead.create.appointment")
: t("approvals.withdraw.lead.create.deadline");
case "delete":
return t("approvals.withdraw.lead.delete");
default:
// update / complete / unknown → revert semantics
return t("approvals.withdraw.lead.update");
}
}
function subCopyFor(args: WithdrawWarningArgs): string {
switch (args.lifecycleEvent) {
case "create":
return t("approvals.withdraw.sub.create");
case "delete":
return t("approvals.withdraw.sub.delete");
default:
return t("approvals.withdraw.sub.update");
}
}

View File

@@ -0,0 +1,285 @@
import { describe, expect, test } from "bun:test";
import {
GRID_COLUMNS,
clampH,
clampW,
placeWidgets,
type WidgetPlacementInput,
} from "./dashboard-grid";
// Regression suite for m/paliad#70 (t-paliad-228): the post-#69 edit
// mode produced overlapping widgets when a 2-col widget sat next to a
// 1-col widget on the same row, when a drag swapped widgets of
// different widths, and when a resize grew a widget into a sibling. The
// fix moved the placement math into ./dashboard-grid + made it
// collision-aware. These tests pin the no-overlap invariant.
function spec(
key: string,
x: number | undefined,
y: number | undefined,
w: number,
h = 1,
visible = true,
): WidgetPlacementInput {
return { key, visible, x, y, w, h };
}
// hasOverlap returns true if any placed pair shares a cell. O(n²) is
// fine — layouts cap at 32 widgets and the tests stay tiny.
function hasOverlap(rects: Map<string, { x: number; y: number; w: number; h: number }>): string | null {
const list = Array.from(rects.entries());
for (let i = 0; i < list.length; i++) {
const [ka, a] = list[i];
for (let j = i + 1; j < list.length; j++) {
const [kb, b] = list[j];
const xOverlap = a.x < b.x + b.w && b.x < a.x + a.w;
const yOverlap = a.y < b.y + b.h && b.y < a.y + a.h;
if (xOverlap && yOverlap) return `${ka}${kb} at (${a.x},${a.y},${a.w}x${a.h}) vs (${b.x},${b.y},${b.w}x${b.h})`;
}
}
return null;
}
describe("placeWidgets — basic auto-flow", () => {
test("places two 6-wide widgets side by side on row 0", () => {
const out = placeWidgets([
spec("a", undefined, undefined, 6),
spec("b", undefined, undefined, 6),
]);
expect(out.get("a")).toEqual({ x: 0, y: 0, w: 6, h: 1 });
expect(out.get("b")).toEqual({ x: 6, y: 0, w: 6, h: 1 });
expect(hasOverlap(out)).toBeNull();
});
test("wraps when row doesn't fit", () => {
const out = placeWidgets([
spec("a", undefined, undefined, 8),
spec("b", undefined, undefined, 8),
]);
expect(out.get("a")!.y).toBe(0);
expect(out.get("b")!.y).toBeGreaterThan(0);
expect(hasOverlap(out)).toBeNull();
});
test("hidden widgets are skipped and reserve no cells", () => {
const out = placeWidgets([
spec("hidden", 0, 0, 12, 1, false),
spec("visible", undefined, undefined, 6),
]);
expect(out.has("hidden")).toBe(false);
expect(out.get("visible")).toEqual({ x: 0, y: 0, w: 6, h: 1 });
});
});
describe("placeWidgets — explicit positions, no collision", () => {
test("trusts non-colliding explicit positions exactly", () => {
const out = placeWidgets([
spec("a", 0, 0, 6),
spec("b", 6, 0, 6),
spec("c", 0, 1, 12),
]);
expect(out.get("a")).toEqual({ x: 0, y: 0, w: 6, h: 1 });
expect(out.get("b")).toEqual({ x: 6, y: 0, w: 6, h: 1 });
expect(out.get("c")).toEqual({ x: 0, y: 1, w: 12, h: 1 });
expect(hasOverlap(out)).toBeNull();
});
});
describe("placeWidgets — mixed-width collision (m/paliad#70 regression)", () => {
test("1-col + 2-col on same row do not overlap when both explicit", () => {
// Half-width left + half-width right is the canonical 'two widgets per
// row' layout; pre-fix this was fine but the next regression below
// exercises the actual bug.
const out = placeWidgets([
spec("left", 0, 0, 6),
spec("right", 6, 0, 6),
]);
expect(hasOverlap(out)).toBeNull();
});
test("4-col + 8-col both claiming (0,0) end up non-overlapping", () => {
// Simulates a post-#69 layout where a 4-wide widget sits at (0, 0)
// and an 8-wide widget got accidentally placed at (0, 0) too (e.g.
// a buggy reset path or a stale spec from before #70). Placer must
// honour the first one's position and fit the second somewhere
// free — landing it on the same row at x=4 is acceptable (better
// density) as long as nothing overlaps.
const out = placeWidgets([
spec("first", 0, 0, 4),
spec("colliding", 0, 0, 8),
]);
expect(out.get("first")).toEqual({ x: 0, y: 0, w: 4, h: 1 });
expect(out.get("colliding")!.w).toBe(8);
expect(hasOverlap(out)).toBeNull();
});
test("drag-drop swap of 12-wide onto 6-wide does not overlap", () => {
// Setup before swap:
// A at (0, 0, w=12) — full width row 0
// B at (0, 1, w=6) — half row 1 left
// C at (6, 1, w=6) — half row 1 right
// User drags A onto B. reorderViaDnd swaps (x, y):
// A.x=0, A.y=1
// B.x=0, B.y=0
// Result must not overlap C.
const out = placeWidgets([
spec("a", 0, 1, 12),
spec("b", 0, 0, 6),
spec("c", 6, 1, 6),
]);
expect(hasOverlap(out)).toBeNull();
});
test("auto-flow widget steps past explicit blocker on same row", () => {
// Explicit widget at (6, 0, w=6); auto-flow widget would pack into
// (0, 0, w=6) which is fine — but the next auto-flow widget at w=6
// would want (6, 0) which is taken. Placer must wrap it.
const out = placeWidgets([
spec("flow-a", undefined, undefined, 6),
spec("anchored", 6, 0, 6),
spec("flow-b", undefined, undefined, 6),
]);
expect(out.get("flow-a")).toEqual({ x: 0, y: 0, w: 6, h: 1 });
expect(out.get("anchored")).toEqual({ x: 6, y: 0, w: 6, h: 1 });
expect(out.get("flow-b")!.y).toBeGreaterThan(0);
expect(hasOverlap(out)).toBeNull();
});
});
describe("placeWidgets — resize-grow shifts siblings", () => {
test("growing a 6-wide to 12-wide bumps the sibling on the same row", () => {
// Pre-resize state:
// A at (0, 0, w=6)
// B at (6, 0, w=6)
// User resizes A to w=12. resizeWidget() updates A.w but leaves B
// at (6, 0). Placer must shift B down.
const out = placeWidgets([
spec("a", 0, 0, 12),
spec("b", 6, 0, 6),
]);
expect(out.get("a")).toEqual({ x: 0, y: 0, w: 12, h: 1 });
expect(out.get("b")!.y).toBeGreaterThan(0);
expect(hasOverlap(out)).toBeNull();
});
test("growing widget pushes only the first colliding sibling", () => {
// A grows to 12-wide; B and C on row 0 are both colliding. Both must
// move; their relative order on row 0 is preserved (B at x=0, C at
// x=6) on row 1.
const out = placeWidgets([
spec("a", 0, 0, 12),
spec("b", 0, 0, 4),
spec("c", 4, 0, 4),
]);
expect(hasOverlap(out)).toBeNull();
expect(out.get("a")!.y).toBe(0);
expect(out.get("b")!.y).toBeGreaterThan(0);
expect(out.get("c")!.y).toBeGreaterThan(0);
});
});
describe("placeWidgets — explicit position overflow clamp", () => {
test("x+w > GRID_COLUMNS is clamped not rejected", () => {
// A 12-wide widget with x=6 would extend past col 11. Placer must
// clamp x to 0 (or wherever fits) so the widget renders inside the
// grid.
const out = placeWidgets([
spec("wide", 6, 0, 12),
]);
const r = out.get("wide")!;
expect(r.x + r.w).toBeLessThanOrEqual(GRID_COLUMNS);
expect(r.w).toBe(12);
});
});
describe("placeWidgets — vertical (multi-row) widgets", () => {
test("a 2-row-tall widget reserves both rows", () => {
const out = placeWidgets([
spec("tall", 0, 0, 6, 2),
spec("collides-on-row-1", 0, 1, 6, 1),
]);
expect(out.get("tall")).toEqual({ x: 0, y: 0, w: 6, h: 2 });
// The colliding widget must move because tall covers cols 0..5
// on both row 0 and row 1. The placer may shift it to the right
// half of row 1 (cols 6..11) or to a later row — either is fine
// as long as nothing overlaps.
const other = out.get("collides-on-row-1")!;
expect(other.x >= 6 || other.y >= 2).toBe(true);
expect(hasOverlap(out)).toBeNull();
});
});
describe("placeWidgets — includeHidden (edit mode)", () => {
test("hidden widgets are skipped by default", () => {
const out = placeWidgets([
spec("visible", 0, 0, 6),
spec("hidden", 0, 0, 6, 1, false),
]);
expect(out.has("visible")).toBe(true);
expect(out.has("hidden")).toBe(false);
});
test("includeHidden:true places hidden widgets after visible ones", () => {
// Regression for m/paliad#73 / t-paliad-238: in edit mode hidden
// widgets MUST receive a placement, otherwise applyLayout leaves
// their inline grid-column empty and CSS Grid auto-flows them as
// 1×1 slivers ("super slim greyed-out column").
const out = placeWidgets([
spec("active", 0, 0, 12),
spec("hidden", 0, 0, 6, 1, false),
], { includeHidden: true });
expect(out.has("hidden")).toBe(true);
const h = out.get("hidden")!;
// Must keep its requested width (6), not collapse to 1.
expect(h.w).toBe(6);
// Must land below the visible widget — never overlap or steal cells.
expect(h.y).toBeGreaterThanOrEqual(1);
expect(hasOverlap(out)).toBeNull();
});
test("includeHidden two-pass: visible widgets keep priority over hidden", () => {
// Hidden widget stored at (0, 0) shouldn't displace a visible
// widget that wants (0, 0). The visible pass runs first, claims
// (0, 0); the hidden widget is then placed wherever free — the
// placer happily fits it next to the visible widget on the same
// row if there's room. The hard invariant is just no-overlap.
const out = placeWidgets([
spec("active", 0, 0, 6),
spec("hidden-at-origin", 0, 0, 6, 1, false),
], { includeHidden: true });
expect(out.get("active")).toEqual({ x: 0, y: 0, w: 6, h: 1 });
expect(out.has("hidden-at-origin")).toBe(true);
expect(hasOverlap(out)).toBeNull();
});
test("multiple hidden widgets all receive valid placements", () => {
const out = placeWidgets([
spec("a", 0, 0, 12),
spec("h1", undefined, undefined, 6, 1, false),
spec("h2", undefined, undefined, 6, 1, false),
spec("h3", undefined, undefined, 12, 1, false),
], { includeHidden: true });
expect(out.size).toBe(4);
for (const r of out.values()) {
expect(r.w).toBeGreaterThanOrEqual(1);
expect(r.x + r.w).toBeLessThanOrEqual(GRID_COLUMNS);
}
expect(hasOverlap(out)).toBeNull();
});
});
describe("clamp helpers", () => {
test("clampW respects min/max bounds", () => {
expect(clampW(2, { min_w: 4, max_w: 12 })).toBe(4);
expect(clampW(20, { min_w: 4, max_w: 12 })).toBe(12);
expect(clampW(0, { default_w: 6 })).toBe(6);
expect(clampW(NaN, { default_w: 8 })).toBe(8);
});
test("clampH respects min/max bounds and MAX_ROW_SPAN", () => {
expect(clampH(0, { default_h: 2 })).toBe(2);
expect(clampH(99, undefined)).toBe(5); // MAX_ROW_SPAN
expect(clampH(1, { min_h: 3 })).toBe(3);
});
});

View File

@@ -0,0 +1,264 @@
// dashboard-grid — pure layout math for the dashboard widget grid.
//
// Lives outside dashboard.ts so the placement logic is importable from
// tests without dragging in the DOM-side rendering code. The grid is a
// 12-column CSS Grid matching internal/services/dashboard_layout_spec.go;
// rows grow vertically as widgets are placed.
//
// The core invariant is no-overlap: after placeWidgets() returns, every
// pair of widgets occupies disjoint cells. Pre-overhaul callers wrote
// computePlacements() to trust explicit (x, y) without checking — that
// produced visual overlap whenever a drag or resize landed a widget on
// cells another widget already covered (m/paliad#70). The collision-
// aware placer below shifts colliding widgets to the next free row so
// the rendered grid never overlaps regardless of the input spec.
export const GRID_COLUMNS = 12;
export const MAX_ROW_SPAN = 5;
// Hard cap on the row-scan depth in findFreeSlot. The widget cap on a
// single layout is 32 (LayoutWidgetCap on the Go side); each row holds
// at least one widget, so 256 rows is an order-of-magnitude buffer
// against runaway loops on pathological inputs.
const MAX_SCAN_ROWS = 256;
export interface PlacedRect {
x: number;
y: number;
w: number;
h: number;
}
// WidgetSizeBound captures the per-widget min/max/default clamps the
// catalog publishes. Optional fields keep callers from having to
// synthesize zeroes when the catalog entry is missing.
export interface WidgetSizeBound {
default_w?: number;
default_h?: number;
min_w?: number;
max_w?: number;
min_h?: number;
max_h?: number;
}
// WidgetPlacementInput is the per-widget data the placer consumes. The
// catalog bound is optional — when missing, defaults fall back to a
// full-width 1-row widget.
export interface WidgetPlacementInput {
key: string;
visible: boolean;
x?: number;
y?: number;
w?: number;
h?: number;
bound?: WidgetSizeBound;
}
export function clampW(w: number, bound: WidgetSizeBound | undefined): number {
let v = Math.round(w);
if (!Number.isFinite(v) || v <= 0) v = bound?.default_w ?? GRID_COLUMNS;
v = Math.max(1, Math.min(GRID_COLUMNS, v));
if (bound?.min_w && v < bound.min_w) v = bound.min_w;
if (bound?.max_w && v > bound.max_w) v = bound.max_w;
return v;
}
export function clampH(h: number, bound: WidgetSizeBound | undefined): number {
let v = Math.round(h);
if (!Number.isFinite(v) || v <= 0) v = bound?.default_h ?? 1;
v = Math.max(1, Math.min(MAX_ROW_SPAN, v));
if (bound?.min_h && v < bound.min_h) v = bound.min_h;
if (bound?.max_h && v > bound.max_h) v = bound.max_h;
return v;
}
// Occupancy bitmap: one row → Uint8Array of GRID_COLUMNS bits. Rows are
// created lazily so the map only stores rows the layout actually
// reaches. Cell value 1 = occupied.
class Occupancy {
private rows = new Map<number, Uint8Array>();
row(y: number): Uint8Array {
let r = this.rows.get(y);
if (!r) {
r = new Uint8Array(GRID_COLUMNS);
this.rows.set(y, r);
}
return r;
}
free(x: number, y: number, w: number, h: number): boolean {
if (x < 0 || y < 0 || x + w > GRID_COLUMNS) return false;
for (let yy = y; yy < y + h; yy++) {
const row = this.row(yy);
for (let xx = x; xx < x + w; xx++) {
if (row[xx]) return false;
}
}
return true;
}
mark(x: number, y: number, w: number, h: number): void {
for (let yy = y; yy < y + h; yy++) {
const row = this.row(yy);
for (let xx = x; xx < x + w; xx++) row[xx] = 1;
}
}
}
// findFreeSlot scans for the first (x, y) where a w×h block fits without
// collision, starting at row startY. At each row preferX is tried first
// — that keeps a widget close to its requested column when only the row
// is blocked. Falls back to left-to-right scan within the row, then to
// the next row. Caller guarantees w ≤ GRID_COLUMNS.
function findFreeSlot(
occ: Occupancy,
startY: number,
w: number,
h: number,
preferX: number,
): { x: number; y: number } {
for (let y = startY; y < startY + MAX_SCAN_ROWS; y++) {
if (preferX >= 0 && preferX + w <= GRID_COLUMNS && occ.free(preferX, y, w, h)) {
return { x: preferX, y };
}
for (let x = 0; x + w <= GRID_COLUMNS; x++) {
if (x === preferX) continue;
if (occ.free(x, y, w, h)) return { x, y };
}
}
// Pathological fallback — caller's widget cap (32) makes this
// unreachable in practice. Snap to the bottom-left so the widget at
// least renders somewhere visible instead of vanishing.
return { x: 0, y: startY + MAX_SCAN_ROWS };
}
// PlaceOptions tunes the placer for the caller's render-vs-persist
// needs.
export interface PlaceOptions {
// When true, hidden widgets are placed too — for edit-mode rendering
// where the user can see + un-hide them inline. The two-pass order
// (visible first, then hidden) guarantees hidden widgets never
// displace visible ones: they get whatever cells are left below the
// active layout. Default false matches view-mode behaviour and the
// persistence path (materializePositions) where hidden widgets
// retain their stored coordinates instead of being repacked.
//
// Without this option, hidden widgets in edit mode were left without
// an explicit grid-column inline style by applyLayout(), so CSS Grid
// auto-flowed them into the next free cell at 1×1 — the "super slim
// greyed-out column" symptom of m/paliad#73 / t-paliad-238.
includeHidden?: boolean;
}
// placeWidgets assigns no-overlap grid coordinates to widgets. By
// default only visible widgets receive placements; pass
// {includeHidden:true} to also place hidden widgets after the visible
// pass (used by applyLayout in edit mode).
//
// Algorithm — per pass:
// 1. Clamp w/h against catalog bounds.
// 2. If the spec carries explicit x and y, try that slot. On a
// collision, search downward starting at the requested y for the
// first free w×h block (preferring the requested x).
// 3. If only x is explicit, search from y=0 at that x.
// 4. Otherwise auto-flow: pack left-to-right under a running cursor;
// when the row doesn't fit or is blocked by an explicitly-placed
// widget, wrap to the next free row.
//
// The mixed-spec case (some widgets explicit, others auto-flow) is the
// real-world layout — placing the explicit widgets first would change
// the visual order, so we keep input order and let auto-flow widgets
// step around any explicit blockers via the same collision search.
//
// Two-pass behaviour for hidden widgets: the visible pass owns its
// own auto-flow cursor; the hidden pass continues from where the
// visible pass left off so the hidden widgets stack right under the
// active layout. The shared Occupancy bitmap guarantees the second
// pass can never overlap a placed visible widget.
export function placeWidgets(
widgets: WidgetPlacementInput[],
options: PlaceOptions = {},
): Map<string, PlacedRect> {
const out = new Map<string, PlacedRect>();
const occ = new Occupancy();
// Auto-flow cursor — advances as we place flowed widgets. cursorY
// tracks the row currently being filled; rowMaxH is the tallest
// widget in that row so wrapping advances past it (not just past the
// new widget's height — that would let taller previous neighbours
// overlap into the wrap row).
let cursorX = 0;
let cursorY = 0;
let rowMaxH = 0;
const placeOne = (w: WidgetPlacementInput): void => {
const dw = clampW(w.w ?? w.bound?.default_w ?? GRID_COLUMNS, w.bound);
const dh = clampH(w.h ?? w.bound?.default_h ?? 1, w.bound);
const hasX = typeof w.x === "number";
const hasY = typeof w.y === "number";
let placed: { x: number; y: number };
if (hasX && hasY) {
// Clamp x so the widget never overflows the right edge — drag/
// resize gestures can produce x+w > GRID_COLUMNS otherwise.
const prefX = Math.max(0, Math.min(GRID_COLUMNS - dw, w.x as number));
const prefY = Math.max(0, w.y as number);
if (occ.free(prefX, prefY, dw, dh)) {
placed = { x: prefX, y: prefY };
} else {
placed = findFreeSlot(occ, prefY, dw, dh, prefX);
}
} else if (hasX) {
const prefX = Math.max(0, Math.min(GRID_COLUMNS - dw, w.x as number));
placed = findFreeSlot(occ, 0, dw, dh, prefX);
} else {
// Auto-flow. Wrap the cursor when the widget wouldn't fit in the
// remaining columns of the current row, then ask findFreeSlot to
// honour the cursor's preferred (x, y) — that lets it step past
// any explicit widget that already claimed cells under the
// cursor.
if (cursorX + dw > GRID_COLUMNS) {
cursorY += rowMaxH || 1;
cursorX = 0;
rowMaxH = 0;
}
placed = findFreeSlot(occ, cursorY, dw, dh, cursorX);
if (placed.y > cursorY) {
// Wrap was forced by a collision deeper than the current row.
cursorY = placed.y;
rowMaxH = 0;
}
cursorX = placed.x + dw;
if (dh > rowMaxH) rowMaxH = dh;
}
occ.mark(placed.x, placed.y, dw, dh);
out.set(w.key, { x: placed.x, y: placed.y, w: dw, h: dh });
};
// Pass 1: visible widgets. They own the active layout.
for (const w of widgets) {
if (!w.visible) continue;
placeOne(w);
}
// Pass 2: hidden widgets (edit-mode only). Wrap the cursor to the
// start of the next row before the second pass so the hidden tray
// visually separates from the active layout — even if the last
// visible widget left half a row open.
if (options.includeHidden) {
if (cursorX > 0) {
cursorY += rowMaxH || 1;
cursorX = 0;
rowMaxH = 0;
}
for (const w of widgets) {
if (w.visible) continue;
placeOne(w);
}
}
return out;
}

View File

@@ -2,6 +2,16 @@ import { initI18n, onLangChange, t, tDyn, getLang, translateEvent } from "./i18n
import { initSidebar } from "./sidebar";
import { renderAgendaTimeline, type AgendaItem } from "./agenda-render";
import { openModal } from "./components/modal";
import {
GRID_COLUMNS,
MAX_ROW_SPAN,
placeWidgets,
clampW as gridClampW,
clampH as gridClampH,
type PlacedRect,
type WidgetPlacementInput,
type WidgetSizeBound,
} from "./dashboard-grid";
interface DashboardUser {
id: string;
@@ -156,10 +166,9 @@ interface WidgetCatalogEntry {
settings?: WidgetSettingsSchema | null;
}
// Grid constants — must match internal/services/dashboard_layout_spec.go
const GRID_COLUMNS = 12;
const MAX_ROW_SPAN = 5;
// Grid constants — must match internal/services/dashboard_layout_spec.go.
// Re-exported from ./dashboard-grid so the placement math is shared with
// the unit tests; the names below keep the local imports tidy.
declare global {
interface Window {
__PALIAD_DASHBOARD__?: DashboardData | null;
@@ -1913,10 +1922,15 @@ function applyLayout(): void {
if (k) byKey.set(k, el);
});
// Compute effective placements (with auto-flow fill-in for missing
// y values). The visible widgets are placed deterministically so the
// grid renders identically across reloads.
const placements = computePlacements(currentLayout.widgets);
// Compute effective placements. In edit mode we also include hidden
// widgets so they render at their stored (or default) dimensions
// dimmed-but-visible — without this they'd inherit no inline grid-
// column and CSS Grid would auto-flow them as 1×1 slivers, producing
// the "super slim greyed-out column" symptom (m/paliad#73). In view
// mode hidden widgets are display:none and reserve no cells.
const placements = computePlacements(currentLayout.widgets, {
includeHidden: editMode,
});
for (const w of currentLayout.widgets) {
const el = byKey.get(w.key);
@@ -1937,74 +1951,51 @@ function applyLayout(): void {
}
}
// PlacedRect is the resolved grid position for a widget — non-zero w/h,
// concrete x/y (0-indexed) derived from spec values plus auto-flow
// fill-in for missing y values.
interface PlacedRect { x: number; y: number; w: number; h: number; }
// computePlacements assigns explicit grid coordinates to every visible
// widget. Spec values win when present; missing values fall back to:
// - w: catalog default_w, else GRID_COLUMNS
// - h: catalog default_h, else 1
// - x: 0 when also missing y; else as given
// - y: auto-flow — packs left-to-right under the running cursor,
// wrapping when the row doesn't fit.
// computePlacements is the local adapter — it walks the layout's widgets,
// resolves each widget's catalog bound, and hands the spec to the pure
// placeWidgets() in ./dashboard-grid. The pure placer carries the no-
// overlap invariant: if two widgets request colliding cells (drag-drop
// swap with mismatched widths, resize-grow into a sibling, etc.) the
// later one is shifted down to the next free row. See m/paliad#70.
//
// Auto-flow keeps pre-overhaul layouts (no positions on the wire)
// rendering as a tidy single column without the visual mess the old
// applyLayout produced. Hidden widgets are skipped — they contribute
// no placement and don't reserve row space.
function computePlacements(widgets: DashboardWidgetRef[]): Map<string, PlacedRect> {
const out = new Map<string, PlacedRect>();
// Track the tallest widget on the row currently being filled, so
// wrapping advances cursorY past the bottom of the row (not just by
// the new widget's height — that would let taller previous neighbours
// overlap). Mirrors the Go-side packer in FactoryDefaultLayout.
let cursorX = 0, cursorY = 0, rowMaxH = 0;
for (const w of widgets) {
if (!w.visible) continue;
const def = lookupCatalog(w.key);
const dw = clampW(w.w ?? def?.default_w ?? GRID_COLUMNS, def);
const dh = clampH(w.h ?? def?.default_h ?? 1, def);
let x = typeof w.x === "number" ? w.x : -1;
let y = typeof w.y === "number" ? w.y : -1;
if (x < 0) {
if (cursorX + dw > GRID_COLUMNS) {
cursorY += rowMaxH;
cursorX = 0;
rowMaxH = 0;
}
x = cursorX;
y = cursorY;
cursorX += dw;
if (dh > rowMaxH) rowMaxH = dh;
} else {
// Explicit x/y from the spec — trust it. Don't move the cursor
// because explicit positions can land anywhere; auto-flow widgets
// are positioned independently.
if (y < 0) y = cursorY;
}
out.set(w.key, { x, y, w: dw, h: dh });
}
return out;
// includeHidden=true is used by applyLayout in edit mode to also place
// hidden widgets after the visible pass — so the hidden tray renders
// at proper size below the active layout. Default (false) matches the
// persistence + render paths where hidden widgets carry no placement.
function computePlacements(
widgets: DashboardWidgetRef[],
options: { includeHidden?: boolean } = {},
): Map<string, PlacedRect> {
const inputs: WidgetPlacementInput[] = widgets.map((w) => ({
key: w.key,
visible: w.visible,
x: w.x,
y: w.y,
w: w.w,
h: w.h,
bound: toBound(lookupCatalog(w.key)),
}));
return placeWidgets(inputs, options);
}
function clampW(w: number, def: WidgetCatalogEntry | undefined): number {
let v = Math.round(w);
if (!Number.isFinite(v) || v <= 0) v = def?.default_w ?? GRID_COLUMNS;
v = Math.max(1, Math.min(GRID_COLUMNS, v));
if (def?.min_w && v < def.min_w) v = def.min_w;
if (def?.max_w && v > def.max_w) v = def.max_w;
return v;
return gridClampW(w, toBound(def));
}
function clampH(h: number, def: WidgetCatalogEntry | undefined): number {
let v = Math.round(h);
if (!Number.isFinite(v) || v <= 0) v = def?.default_h ?? 1;
v = Math.max(1, Math.min(MAX_ROW_SPAN, v));
if (def?.min_h && v < def.min_h) v = def.min_h;
if (def?.max_h && v > def.max_h) v = def.max_h;
return v;
return gridClampH(h, toBound(def));
}
function toBound(def: WidgetCatalogEntry | undefined): WidgetSizeBound | undefined {
if (!def) return undefined;
return {
default_w: def.default_w,
default_h: def.default_h,
min_w: def.min_w,
max_w: def.max_w,
min_h: def.min_h,
max_h: def.max_h,
};
}
// filterByHorizonDays drops items whose key date is more than `days`

View File

@@ -9,6 +9,8 @@ import {
type EventType,
type PickerHandle,
} from "./event-types";
import { openWithdrawWarningModal } from "./components/withdraw-warning-modal";
import { formatRuleLabel, formatRuleLabelHTML, formatCustomRuleLabelHTML } from "./rule-label";
interface Deadline {
id: string;
@@ -20,6 +22,9 @@ interface Deadline {
source: string;
rule_id?: string;
rule_code?: string;
// t-paliad-258 — lawyer's free-text rule label when the deadline was
// saved in Custom mode. Mutually exclusive with rule_id.
custom_rule_text?: string;
notes?: string;
created_at: string;
completed_at?: string;
@@ -38,6 +43,9 @@ interface PendingApprovalRequest {
requested_at: string;
required_role: string;
requester_name?: string;
// t-paliad-252 — used by the withdraw warning modal to pick the right
// copy (CREATE warns about deletion; UPDATE/COMPLETE about revert).
lifecycle_event?: string;
}
let eventTypePicker: PickerHandle | null = null;
@@ -54,7 +62,21 @@ interface DeadlineRule {
id: string;
code?: string;
name: string;
name_en?: string;
rule_code?: string;
legal_source?: string | null;
// t-paliad-258 — canonical event_type for Auto-mode rule resolution
// when the user flips to Auto on the edit form.
concept_default_event_type_id?: string | null;
proceeding_type_id?: number | null;
}
interface ProceedingType {
id: number;
jurisdiction: string;
name: string;
name_en?: string;
sort_order?: number;
}
interface Me {
@@ -70,6 +92,30 @@ let me: Me | null = null;
let allProjects: Project[] = [];
let pendingRequest: PendingApprovalRequest | null = null;
// t-paliad-258 — Auto/Custom rule editor state. Mirrors the create form.
// On enterEdit we initialise the mode from the persisted deadline:
// rule_id set → "auto"
// custom_rule_text set, no rule_id → "custom"
// neither set → "auto" (so the Type-driven
// resolver fills in immediately).
type RuleMode = "auto" | "custom";
let ruleMode: RuleMode = "auto";
let allRules: DeadlineRule[] = [];
let rulesByID = new Map<string, DeadlineRule>();
let proceedingTypesByID = new Map<number, ProceedingType>();
// t-paliad-252 — when the user chose "Edit event" in the withdraw warning
// modal, the entity is still in approval_status='pending'. Save must POST
// to /api/approval-requests/{id}/edit-entity (which keeps the request
// pending + merges the new fields into payload) instead of the regular
// PATCH /api/deadlines/{id} (which 409s during pending). Cleared on exit
// from edit mode + after a successful save.
let pendingEditMode = false;
// pendingEnterEdit — late-bound by initEdit() so the withdraw warning
// modal handler (initWithdraw) can route into pending-edit mode without
// duplicating the edit-mode toggle logic.
let pendingEnterEdit: (() => void) | null = null;
function parseDeadlineID(): string | null {
const parts = window.location.pathname.split("/").filter(Boolean);
if (parts[0] !== "deadlines" || !parts[1]) return null;
@@ -165,17 +211,66 @@ function populateProjectPicker() {
sel.value = deadline.project_id;
}
async function loadRule(ruleID: string) {
async function loadAllRules() {
try {
const resp = await fetch(`/api/deadline-rules`);
if (!resp.ok) return;
const all: DeadlineRule[] = await resp.json();
rule = all.find((r) => r.id === ruleID) || null;
allRules = (await resp.json()) as DeadlineRule[];
rulesByID = new Map(allRules.map((r) => [r.id, r]));
} catch {
/* non-fatal */
}
}
async function loadProceedingTypes() {
try {
const resp = await fetch("/api/proceeding-types-db");
if (!resp.ok) return;
const types: ProceedingType[] = await resp.json();
proceedingTypesByID = new Map(types.map((pt) => [pt.id, pt]));
} catch {
/* non-fatal */
}
}
function lookupRule(ruleID: string): DeadlineRule | null {
return rulesByID.get(ruleID) || null;
}
// resolveAutoRuleForType mirrors the create-form resolver: pick the
// canonical rule for the chosen event_type, prioritising the project's
// proceeding then jurisdiction match.
function resolveAutoRuleForType(eventTypeID: string): DeadlineRule | null {
const candidates = allRules.filter((r) => r.concept_default_event_type_id === eventTypeID);
if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0];
const projID = deadline?.project_id;
const proj = projID ? allProjects.find((p) => p.id === projID) as (Project & { proceeding_type_id?: number | null }) | undefined : undefined;
if (proj && proj.proceeding_type_id) {
const exact = candidates.find((r) => r.proceeding_type_id === proj.proceeding_type_id);
if (exact) return exact;
}
const et = eventTypeByID.get(eventTypeID);
if (et?.jurisdiction && et.jurisdiction !== "any") {
const want = et.jurisdiction === "EPO" ? "EPA" : et.jurisdiction;
const jurMatch = candidates.find((r) => {
const pt = r.proceeding_type_id ? proceedingTypesByID.get(r.proceeding_type_id) : undefined;
return pt?.jurisdiction === want;
});
if (jurMatch) return jurMatch;
}
return candidates[0];
}
function currentAutoRule(): DeadlineRule | null {
const picked = eventTypePicker?.getIDs() ?? [];
if (picked.length !== 1) return null;
return resolveAutoRuleForType(picked[0]);
}
async function loadMe() {
try {
const resp = await fetch("/api/me");
@@ -227,9 +322,15 @@ function render() {
}
const ruleEl = document.getElementById("deadline-rule-display")!;
// t-paliad-258 — display priority:
// 1. catalog rule (canonical Name · Citation pattern)
// 2. custom_rule_text + Custom badge
// 3. legacy rule_code-only (Fristenrechner saves)
// 4. "—"
if (rule) {
const code = rule.rule_code || rule.code || "";
ruleEl.textContent = code ? `${code}${rule.name}` : rule.name;
ruleEl.innerHTML = formatRuleLabelHTML(rule, esc);
} else if (deadline.custom_rule_text && deadline.custom_rule_text.trim()) {
ruleEl.innerHTML = formatCustomRuleLabelHTML(deadline.custom_rule_text, esc);
} else if (deadline.rule_code) {
// Fristenrechner-saved deadlines carry rule_code directly without
// a rule_id (no rule UUID round-trips through the public API).
@@ -353,6 +454,48 @@ function render() {
}
}
function refreshRuleAutoDisplay(): void {
const panel = document.getElementById("deadline-rule-auto-display");
const text = document.getElementById("deadline-rule-auto-text");
if (!panel || !text) return;
if (ruleMode !== "auto") {
panel.style.display = "none";
return;
}
panel.style.display = "";
const r = currentAutoRule();
if (r) {
text.textContent = formatRuleLabel(r);
text.classList.remove("rule-auto-text--empty");
return;
}
const picked = eventTypePicker?.getIDs() ?? [];
const fallback = picked.length === 1
? (t("deadlines.field.rule.auto_no_match") || "Keine Regel zur gewählten Verfahrenshandlung")
: (t("deadlines.field.rule.auto_pick_type") || "Wählen Sie zuerst eine Verfahrenshandlung");
text.textContent = fallback;
text.classList.add("rule-auto-text--empty");
}
function applyRuleModeUI(): void {
const toggleBtn = document.getElementById("deadline-rule-mode-toggle") as HTMLButtonElement | null;
const autoPanel = document.getElementById("deadline-rule-auto-display");
const customInput = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
if (!toggleBtn || !autoPanel || !customInput) return;
if (ruleMode === "auto") {
autoPanel.style.display = "";
customInput.style.display = "none";
toggleBtn.textContent = t("deadlines.field.rule.mode.toggle_to_custom") || "Eigene Regel eingeben";
toggleBtn.setAttribute("data-i18n", "deadlines.field.rule.mode.toggle_to_custom");
} else {
autoPanel.style.display = "none";
customInput.style.display = "";
toggleBtn.textContent = t("deadlines.field.rule.mode.toggle_to_auto") || "Zurück zu Auto";
toggleBtn.setAttribute("data-i18n", "deadlines.field.rule.mode.toggle_to_auto");
}
refreshRuleAutoDisplay();
}
function initEdit() {
const titleDisplay = document.getElementById("deadline-title-display")!;
const titleEdit = document.getElementById("deadline-title-edit") as HTMLInputElement;
@@ -366,6 +509,11 @@ function initEdit() {
const etEdit = document.getElementById("deadline-event-types-edit");
const projectLink = document.getElementById("deadline-project-link") as HTMLAnchorElement;
const projectEdit = document.getElementById("deadline-project-edit") as HTMLSelectElement | null;
const titleDefaultBtn = document.getElementById("deadline-title-default-btn") as HTMLButtonElement | null;
const ruleDisplay = document.getElementById("deadline-rule-display");
const ruleEdit = document.getElementById("deadline-rule-edit");
const ruleCustomInput = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
const ruleToggleBtn = document.getElementById("deadline-rule-mode-toggle") as HTMLButtonElement | null;
function enterEdit() {
titleDisplay.style.display = "none";
@@ -381,6 +529,20 @@ function initEdit() {
projectEdit.style.display = "";
projectEdit.value = deadline.project_id;
}
if (titleDefaultBtn) titleDefaultBtn.style.display = "";
// t-paliad-258 — show the Auto/Custom rule editor + initialise mode
// from the persisted deadline. Display element stays visible so the
// user keeps "before / after" context while editing.
if (ruleEdit) ruleEdit.style.display = "";
if (ruleDisplay) ruleDisplay.style.display = "none";
if (deadline?.custom_rule_text && !deadline.rule_id) {
ruleMode = "custom";
if (ruleCustomInput) ruleCustomInput.value = deadline.custom_rule_text;
} else {
ruleMode = "auto";
if (ruleCustomInput) ruleCustomInput.value = "";
}
applyRuleModeUI();
saveBtn.style.display = "";
editBtn.style.display = "none";
titleEdit.focus();
@@ -399,12 +561,71 @@ function initEdit() {
projectEdit.style.display = "none";
projectLink.style.display = "";
}
if (titleDefaultBtn) titleDefaultBtn.style.display = "none";
if (ruleEdit) ruleEdit.style.display = "none";
if (ruleDisplay) ruleDisplay.style.display = "";
saveBtn.style.display = "none";
editBtn.style.display = "";
pendingEditMode = false;
}
// Rule mode toggle (Auto ↔ Custom). The Auto resolver re-runs every
// time the Type picker changes, so just-toggling-to-Auto immediately
// surfaces a fresh resolution.
ruleToggleBtn?.addEventListener("click", () => {
ruleMode = ruleMode === "auto" ? "custom" : "auto";
applyRuleModeUI();
if (ruleMode === "custom") ruleCustomInput?.focus();
});
// t-paliad-252 — expose enterEdit so the withdraw warning modal can
// route into pending-edit mode without re-running the edit-button
// visibility gate (which hides the button during pending).
pendingEnterEdit = () => {
pendingEditMode = true;
enterEdit();
};
editBtn.addEventListener("click", enterEdit);
// t-paliad-251 Part 4 — Standardtitel button.
// Recipe (mirror of computeDefaultTitle in deadlines-new.ts):
// head = event_type label (if exactly one Typ chip in edit)
// || Auto-resolved rule's canonical label (Name · Citation)
// || saved rule's canonical label
// || custom_rule_text (when in Custom mode + non-empty)
// || rule_code-only legacy fallback
// || "Neue Frist" fallback
// suffix = " — <project.reference>" when not already in head
titleDefaultBtn?.addEventListener("click", () => {
if (!deadline) return;
let head = "";
const ids = eventTypePicker?.getIDs() ?? deadline.event_type_ids ?? [];
if (ids.length === 1) {
const et = eventTypeByID.get(ids[0]);
if (et) head = eventTypeLabel(et);
}
if (!head) {
const r = ruleMode === "auto" ? (currentAutoRule() ?? rule) : null;
if (r) head = formatRuleLabel(r);
}
if (!head && ruleMode === "custom") {
const txt = ruleCustomInput?.value.trim() || "";
if (txt) head = txt;
}
if (!head && rule) {
head = formatRuleLabel(rule);
}
if (!head && deadline.rule_code) {
head = deadline.rule_code;
}
if (!head) head = t("deadlines.field.title.default_fallback");
const ref = project?.reference?.trim() || "";
if (ref && !head.includes(ref)) head = `${head}${ref}`;
titleEdit.value = head;
titleEdit.focus();
});
saveBtn.addEventListener("click", async () => {
if (!deadline) return;
const newTitle = titleEdit.value.trim();
@@ -424,6 +645,48 @@ function initEdit() {
if (projectEdit && projectEdit.value && projectEdit.value !== deadline.project_id) {
payload.project_id = projectEdit.value;
}
// t-paliad-258 — rule_set discriminator tells the service this
// PATCH carries an Auto/Custom rule change. Both columns are
// mutually exclusive at the persistence boundary.
payload.rule_set = true;
if (ruleMode === "auto") {
const r = currentAutoRule();
payload.rule_id = r ? r.id : null;
payload.custom_rule_text = null;
} else {
const txt = ruleCustomInput?.value.trim() || "";
payload.rule_id = null;
payload.custom_rule_text = txt || null;
}
// t-paliad-252 — pending-edit mode routes through the new endpoint
// that updates the entity + merges payload into the still-pending
// approval_request. Outside pending-edit mode the regular PATCH
// path remains the authoritative one (with its existing 409-on-
// pending guard).
if (pendingEditMode && pendingRequest) {
const resp = await fetch(
`/api/approval-requests/${pendingRequest.id}/edit-entity`,
{
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ fields: payload }),
},
);
if (resp.ok) {
const fresh = await fetch(`/api/deadlines/${deadline.id}`);
if (fresh.ok) deadline = await fresh.json();
await loadPendingRequest();
render();
} else {
const body = await resp.json().catch(() => null);
const msg = (body && (body.message || body.error))
|| (t("approvals.withdraw.error") || "Fehler");
window.alert(msg);
}
return;
}
const resp = await fetch(`/api/deadlines/${deadline.id}`, {
method: "PATCH",
headers: { "Content-Type": "application/json" },
@@ -501,19 +764,39 @@ function initReopen() {
});
}
// initWithdraw — t-paliad-160 §C+E. Reuses the existing
// /api/approval-requests/{id}/revoke endpoint (no new server route
// needed). After the revoke lands, the entity goes back to
// approval_status='approved' and the page reloads to refresh the
// in-memory state cleanly.
// initWithdraw — t-paliad-160 §C+E + t-paliad-252.
//
// Click flow: open the withdraw warning modal (replaces the old
// confirm()). The modal returns one of:
//
// "edit" — open the edit form in pending-edit mode; Save calls
// /api/approval-requests/{id}/edit-entity which keeps the
// request pending + merges the new fields into payload
// "withdraw" — destructive: call the existing /revoke endpoint
// (DELETE entity for CREATE, revert for UPDATE/COMPLETE,
// cancel-delete for DELETE lifecycle)
// null — user cancelled; nothing happens
function initWithdraw() {
const btn = document.getElementById("deadline-withdraw-btn") as HTMLButtonElement | null;
if (!btn) return;
btn.addEventListener("click", async () => {
if (!deadline || !pendingRequest) return;
if (!window.confirm(t("approvals.withdraw.confirm") || "Anfrage wirklich zurückziehen?")) return;
btn.disabled = true;
try {
const action = await openWithdrawWarningModal({
entityType: "deadline",
lifecycleEvent: pendingRequest.lifecycle_event ?? "create",
});
if (action === null) {
btn.disabled = false;
return;
}
if (action === "edit") {
btn.disabled = false;
pendingEnterEdit?.();
return;
}
// action === "withdraw" → existing destructive path.
const resp = await fetch(`/api/approval-requests/${pendingRequest.id}/revoke`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@ -521,14 +804,16 @@ function initWithdraw() {
});
if (resp.ok) {
// Re-fetch the entity so approval_status flips back to 'approved'
// and the badge / buttons rerender accordingly.
// and the badge / buttons rerender accordingly. For CREATE
// lifecycle the entity is gone, so the 404 surfaces as a reload.
const r = await fetch(`/api/deadlines/${deadline.id}`);
if (r.ok) {
deadline = await r.json();
await loadPendingRequest();
render();
} else {
window.location.reload();
// CREATE lifecycle deleted the entity — bounce to the list.
window.location.href = "/events?type=deadline";
}
} else {
btn.disabled = false;
@@ -592,8 +877,14 @@ async function main() {
notfound.style.display = "block";
return;
}
await Promise.all([loadProject(deadline.project_id), loadAllProjects(), loadPendingRequest()]);
if (deadline.rule_id) await loadRule(deadline.rule_id);
await Promise.all([
loadProject(deadline.project_id),
loadAllProjects(),
loadPendingRequest(),
loadAllRules(),
loadProceedingTypes(),
]);
if (deadline.rule_id) rule = lookupRule(deadline.rule_id);
// Load event types in parallel; render once ready (the picker re-renders
// chips off the cached map, and the display element re-renders on the
@@ -614,6 +905,11 @@ async function main() {
eventTypePicker = attachEventTypePicker(pickerHost, {
initialIDs: deadline.event_type_ids ?? [],
currentUserAdmin: me?.global_role === "global_admin",
onChange: () => {
// Type change shifts the Auto-resolved rule. Refresh the
// read-only display panel (no-op outside edit mode / Custom).
refreshRuleAutoDisplay();
},
});
}

View File

@@ -1,4 +1,4 @@
import { initI18n, t, tDyn } from "./i18n";
import { initI18n, t, tDyn, getLang } from "./i18n";
import { initSidebar } from "./sidebar";
import {
attachEventTypePicker,
@@ -8,22 +8,21 @@ import {
type PickerHandle,
} from "./event-types";
import { projectIndent } from "./project-indent";
import { formatRuleLabel } from "./rule-label";
let eventTypePicker: PickerHandle | null = null;
let currentUserAdmin = false;
let eventTypesByID = new Map<string, EventType>();
// expandedOverride flips to true when the user clicks "Anderen Typ
// wählen" on the collapsed inline summary. Sticky for the rest of the
// form session — cleared only when the user reverts the rule to "Keine
// Regel". When true, the picker stays visible regardless of whether
// the chip matches the rule's canonical default.
let expandedOverride = false;
interface Project {
id: string;
reference?: string | null;
title: string;
path: string;
// Used by the Type→Rule resolver to narrow rule candidates to the
// project's own proceeding when one applies. Optional because clients
// and matter-level projects don't carry a proceeding type.
proceeding_type_id?: number | null;
}
interface DeadlineRule {
@@ -32,23 +31,37 @@ interface DeadlineRule {
name: string;
name_en: string;
rule_code?: string;
// t-paliad-165 — canonical event_type for this rule's concept,
// hydrated server-side from paliad.deadline_concept_event_types.
// Drives auto-fill of the Typ chip when the user picks this rule.
legal_source?: string | null;
proceeding_type_id?: number | null;
sequence_order?: number;
// t-paliad-165 — canonical event_type for the rule's concept. The
// catalog is indexed by it so we can resolve Type → canonical Rule.
concept_default_event_type_id?: string | null;
}
// Rules indexed by id so the Regel-change handler can look up the
// concept's canonical event_type without re-fetching.
let rulesByID = new Map<string, DeadlineRule>();
interface ProceedingType {
id: number;
code: string;
name: string;
name_en?: string;
jurisdiction: string;
sort_order?: number;
}
// Last event_type the rule auto-filled. Tracked so we can tell whether
// the picker still reflects the rule's suggestion (replace silently on
// new rule pick) or whether the user has manually edited (leave alone,
// surface the mismatch warning instead).
let lastAutoFilledEventTypeID: string | null = null;
// Rule mode (t-paliad-258 / m/paliad#89). The form has two states:
// auto — rule_id resolved from the chosen event_type, rendered
// read-only as "Auto: Name · Citation".
// custom — free-text input; submits as custom_rule_text on the API.
type RuleMode = "auto" | "custom";
let ruleMode: RuleMode = "auto";
let rulesByID = new Map<string, DeadlineRule>();
let allRules: DeadlineRule[] = [];
let proceedingTypesByID = new Map<number, ProceedingType>();
let projectsByID = new Map<string, Project>();
let preselectedProjectID = "";
let preselectedProjectIDLocal = "";
function esc(s: string): string {
const d = document.createElement("div");
@@ -62,6 +75,13 @@ function showError(msg: string) {
el.className = "form-msg form-msg-error";
}
function proceedingLabel(pt: ProceedingType | undefined): string {
if (!pt) return "";
const lang = getLang();
const name = (lang === "en" && pt.name_en) ? pt.name_en : pt.name;
return `${pt.jurisdiction}${name}`;
}
async function loadProjects() {
const sel = document.getElementById("deadline-project") as HTMLSelectElement;
const hint = document.getElementById("deadline-project-empty-hint")!;
@@ -69,6 +89,7 @@ async function loadProjects() {
const resp = await fetch("/api/projects");
if (!resp.ok) return;
const projects: Project[] = await resp.json();
projectsByID = new Map(projects.map((p) => [p.id, p]));
if (projects.length === 0) {
hint.style.display = "";
hint.innerHTML = `${esc(t("deadlines.field.akte.empty"))} <a href="/projects/new">${esc(t("deadlines.field.akte.empty.link"))}</a>`;
@@ -82,7 +103,7 @@ async function loadProjects() {
const ref = p.reference || "";
const indent = projectIndent(p.path);
options.push(
`<option value="${esc(p.id)}"${isSelected}>${indent}${esc(ref)} \u2014 ${esc(p.title)}</option>`,
`<option value="${esc(p.id)}"${isSelected}>${indent}${esc(ref)} ${esc(p.title)}</option>`,
);
}
sel.innerHTML = options.join("");
@@ -91,122 +112,166 @@ async function loadProjects() {
}
}
async function loadProceedingTypes() {
try {
const resp = await fetch("/api/proceeding-types-db");
if (!resp.ok) return;
const types: ProceedingType[] = await resp.json();
proceedingTypesByID = new Map(types.map((pt) => [pt.id, pt]));
} catch {
/* non-fatal */
}
}
async function loadRules() {
// Optional: load rules so user can attach. We pull all rules; small set.
const sel = document.getElementById("deadline-rule") as HTMLSelectElement;
try {
const resp = await fetch("/api/deadline-rules");
if (!resp.ok) return;
const rules: DeadlineRule[] = await resp.json();
rulesByID = new Map(rules.map((r) => [r.id, r]));
const opts: string[] = [
`<option value="" data-i18n="deadlines.field.rule.none">${esc(t("deadlines.field.rule.none"))}</option>`,
];
for (const r of rules) {
const code = r.rule_code || r.code || "";
const label = code ? `${code} \u2014 ${r.name}` : r.name;
opts.push(`<option value="${esc(r.id)}">${esc(label)}</option>`);
}
sel.innerHTML = opts.join("");
allRules = (await resp.json()) as DeadlineRule[];
rulesByID = new Map(allRules.map((r) => [r.id, r]));
} catch {
/* non-fatal — rule select stays at "no rule" */
/* non-fatal — rule display falls back to "—" */
}
}
// t-paliad-165 follow-up — drive the collapsed/expanded view of the Typ
// picker. The two modes are mutually exclusive:
// resolveAutoRuleForType picks the best-match catalog rule for the
// chosen event type, scoring by:
// 1. project's proceeding_type_id (if known) — exact match wins,
// 2. otherwise event_type.jurisdiction matches the rule's proceeding's
// jurisdiction (EPA→EPO canonicalised),
// 3. otherwise the first candidate in canonical sequence_order.
//
// collapsed: rule selected + canonical event_type known + picker
// contains exactly [default] + user hasn't clicked "Anderen Typ
// wählen". Hides the chip cluster, surfaces a single inline
// summary "Klageerwiderung (vorgegeben durch Regel)" + an
// override link.
//
// expanded: every other case — no rule, no default for the rule,
// picker has been edited, or expandedOverride is sticky after the
// user clicked the override link. Picker visible; mismatch warning
// surfaces yellow when the rule expected a different event_type.
function refreshRuleView(): void {
const collapsed = document.getElementById("deadline-event-type-collapsed");
const collapsedLabel = document.getElementById("deadline-event-type-collapsed-label");
const pickerHost = document.getElementById("deadline-event-types");
const warn = document.getElementById("deadline-event-type-rule-mismatch");
if (!collapsed || !collapsedLabel || !pickerHost || !warn) return;
// Returns null when no rule maps. Callers render that as "no Auto rule
// available" so the user can flip to Custom or pick a different Type.
function resolveAutoRuleForType(eventTypeID: string, projectID: string): DeadlineRule | null {
const candidates = allRules.filter((r) => r.concept_default_event_type_id === eventTypeID);
if (candidates.length === 0) return null;
if (candidates.length === 1) return candidates[0];
const ruleID = (document.getElementById("deadline-rule") as HTMLSelectElement | null)?.value || "";
const rule = ruleID ? rulesByID.get(ruleID) : undefined;
const expected = rule?.concept_default_event_type_id ?? null;
const project = projectID ? projectsByID.get(projectID) : undefined;
if (project?.proceeding_type_id) {
const exact = candidates.find((r) => r.proceeding_type_id === project.proceeding_type_id);
if (exact) return exact;
}
const et = eventTypesByID.get(eventTypeID);
if (et?.jurisdiction && et.jurisdiction !== "any") {
const want = et.jurisdiction === "EPO" ? "EPA" : et.jurisdiction;
const jurMatch = candidates.find((r) => {
const pt = r.proceeding_type_id ? proceedingTypesByID.get(r.proceeding_type_id) : undefined;
return pt?.jurisdiction === want;
});
if (jurMatch) return jurMatch;
}
return candidates[0];
}
// currentAutoRule returns the catalog rule the Auto mode would resolve
// to for the current form state, or null when no Type is picked or no
// rule maps. Centralised so the Auto display, submitForm, and the
// Standardtitel button all agree on the same resolution.
function currentAutoRule(): DeadlineRule | null {
const picked = eventTypePicker?.getIDs() ?? [];
if (picked.length !== 1) return null;
const projectID = (document.getElementById("deadline-project") as HTMLSelectElement | null)?.value || "";
return resolveAutoRuleForType(picked[0], projectID);
}
const pickerMatchesDefault =
expected !== null && picked.length === 1 && picked[0] === expected;
const wantsCollapsed =
!expandedOverride && ruleID !== "" && expected !== null && pickerMatchesDefault;
if (wantsCollapsed) {
const et = eventTypesByID.get(expected!);
collapsedLabel.textContent = et ? eventTypeLabel(et) : "";
collapsed.style.display = "";
pickerHost.style.display = "none";
warn.style.display = "none";
// refreshRuleAutoDisplay updates the read-only Auto display panel to
// reflect the rule that would be saved in Auto mode. Hides itself when
// the user is in Custom mode (the input takes its place).
function refreshRuleAutoDisplay(): void {
const panel = document.getElementById("deadline-rule-auto-display");
const text = document.getElementById("deadline-rule-auto-text");
if (!panel || !text) return;
if (ruleMode !== "auto") {
panel.style.display = "none";
return;
}
panel.style.display = "";
const rule = currentAutoRule();
if (rule) {
text.textContent = formatRuleLabel(rule);
text.classList.remove("rule-auto-text--empty");
return;
}
const picked = eventTypePicker?.getIDs() ?? [];
const fallback = picked.length === 1
? (t("deadlines.field.rule.auto_no_match") || "Keine Regel zur gewählten Verfahrenshandlung")
: (t("deadlines.field.rule.auto_pick_type") || "Wählen Sie zuerst eine Verfahrenshandlung");
text.textContent = fallback;
text.classList.add("rule-auto-text--empty");
}
collapsed.style.display = "none";
pickerHost.style.display = "";
// Mismatch warning: rule expected an event_type AND the picker
// doesn't contain it. (When the picker is empty + no override, no
// warning — user is free to leave it blank.)
if (expected && picked.length > 0 && !picked.includes(expected)) {
warn.style.display = "";
function applyRuleModeUI(): void {
const toggleBtn = document.getElementById("deadline-rule-mode-toggle") as HTMLButtonElement | null;
const autoPanel = document.getElementById("deadline-rule-auto-display");
const customInput = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
if (!toggleBtn || !autoPanel || !customInput) return;
if (ruleMode === "auto") {
autoPanel.style.display = "";
customInput.style.display = "none";
toggleBtn.textContent = t("deadlines.field.rule.mode.toggle_to_custom") || "Eigene Regel eingeben";
toggleBtn.setAttribute("data-i18n", "deadlines.field.rule.mode.toggle_to_custom");
} else {
warn.style.display = "none";
autoPanel.style.display = "none";
customInput.style.display = "";
toggleBtn.textContent = t("deadlines.field.rule.mode.toggle_to_auto") || "Zurück zu Auto";
toggleBtn.setAttribute("data-i18n", "deadlines.field.rule.mode.toggle_to_auto");
}
refreshRuleAutoDisplay();
}
function setRuleMode(mode: RuleMode): void {
ruleMode = mode;
applyRuleModeUI();
if (mode === "custom") {
const input = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
input?.focus();
}
}
// applyRuleAutoFill replaces the picker silently when it still reflects
// the previous rule's suggestion (or is empty); leaves a manually-edited
// picker alone. Called whenever the Regel select changes.
function applyRuleAutoFill(): void {
if (!eventTypePicker) return;
const ruleID = (document.getElementById("deadline-rule") as HTMLSelectElement | null)?.value || "";
const rule = ruleID ? rulesByID.get(ruleID) : undefined;
const expected = rule?.concept_default_event_type_id ?? null;
const current = eventTypePicker.getIDs();
// computeDefaultTitle — t-paliad-251 Part 4. Priority order picks the head:
// 1. event_type label (when exactly one Typ chip is set)
// 2. canonical rule name (when Auto resolves to a rule)
// 3. custom rule text (when in Custom mode)
// 4. proceeding type name (when project carries one)
// 5. fallback i18n key
// Suffix: " — <project-reference>" when not already in head.
function computeDefaultTitle(): string {
const projectID = (document.getElementById("deadline-project") as HTMLSelectElement | null)?.value || "";
const project = projectID ? projectsByID.get(projectID) : undefined;
const picked = eventTypePicker?.getIDs() ?? [];
// Reset the override on transition to "Keine Regel" — fresh form
// session. Otherwise expandedOverride stays sticky.
if (ruleID === "") {
expandedOverride = false;
let head = "";
if (picked.length === 1) {
const et = eventTypesByID.get(picked[0]);
if (et) head = eventTypeLabel(et);
}
const pickerStillReflectsLastSuggestion =
lastAutoFilledEventTypeID !== null &&
current.length === 1 &&
current[0] === lastAutoFilledEventTypeID;
const pickerIsEmpty = current.length === 0;
if (expected) {
if (pickerIsEmpty || pickerStillReflectsLastSuggestion) {
eventTypePicker.setIDs([expected]);
lastAutoFilledEventTypeID = expected;
if (!head) {
if (ruleMode === "auto") {
const rule = currentAutoRule();
if (rule) head = formatRuleLabel(rule);
} else {
const customInput = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
const txt = customInput?.value.trim() || "";
if (txt) head = txt;
}
} else if (pickerStillReflectsLastSuggestion) {
// New rule has no canonical event_type — clear the stale auto-fill
// so the picker doesn't carry a chip from the old rule.
eventTypePicker.setIDs([]);
lastAutoFilledEventTypeID = null;
}
refreshRuleView();
}
if (!head && project?.proceeding_type_id) {
const pt = proceedingTypesByID.get(project.proceeding_type_id);
if (pt) head = proceedingLabel(pt);
}
if (!head) {
head = t("deadlines.field.title.default_fallback");
}
function initBackLinks() {
if (preselectedProjectID) {
const back = document.getElementById("deadline-new-back") as HTMLAnchorElement;
const cancel = document.getElementById("deadline-new-cancel") as HTMLAnchorElement;
back.href = `/projects/${preselectedProjectID}/deadlines`;
cancel.href = `/projects/${preselectedProjectID}/deadlines`;
const ref = project?.reference?.trim() || "";
if (ref && !head.includes(ref)) {
return `${head}${ref}`;
}
return head;
}
async function submitForm(e: Event) {
@@ -217,7 +282,6 @@ async function submitForm(e: Event) {
const projectID = (document.getElementById("deadline-project") as HTMLSelectElement).value;
const title = (document.getElementById("deadline-title") as HTMLInputElement).value.trim();
const due = (document.getElementById("deadline-due") as HTMLInputElement).value;
const ruleID = (document.getElementById("deadline-rule") as HTMLSelectElement).value;
const notes = (document.getElementById("deadline-notes") as HTMLTextAreaElement).value.trim();
if (!projectID || !title || !due) {
@@ -234,7 +298,15 @@ async function submitForm(e: Event) {
due_date: due,
source: "manual",
};
if (ruleID) payload.rule_id = ruleID;
// Rule field: Auto resolves to rule_id, Custom sends the free text.
if (ruleMode === "auto") {
const rule = currentAutoRule();
if (rule) payload.rule_id = rule.id;
} else {
const customInput = document.getElementById("deadline-rule-custom-input") as HTMLInputElement | null;
const txt = customInput?.value.trim() || "";
if (txt) payload.custom_rule_text = txt;
}
if (notes) payload.notes = notes;
const eventTypeIDs = eventTypePicker?.getIDs() ?? [];
if (eventTypeIDs.length > 0) payload.event_type_ids = eventTypeIDs;
@@ -252,8 +324,8 @@ async function submitForm(e: Event) {
return;
}
const created = await resp.json();
if (preselectedProjectID) {
window.location.href = `/projects/${preselectedProjectID}/deadlines`;
if (preselectedProjectIDLocal) {
window.location.href = `/projects/${preselectedProjectIDLocal}/deadlines`;
} else {
window.location.href = `/deadlines/${created.id}`;
}
@@ -275,6 +347,16 @@ function detectPreselect() {
if (fromQuery) preselectedProjectID = fromQuery;
}
function initBackLinks() {
if (preselectedProjectID) {
const back = document.getElementById("deadline-new-back") as HTMLAnchorElement;
const cancel = document.getElementById("deadline-new-cancel") as HTMLAnchorElement;
back.href = `/projects/${preselectedProjectID}/deadlines`;
cancel.href = `/projects/${preselectedProjectID}/deadlines`;
}
preselectedProjectIDLocal = preselectedProjectID;
}
async function loadMe() {
try {
const resp = await fetch("/api/me");
@@ -288,8 +370,6 @@ async function loadMe() {
// t-paliad-154 — fetch the effective approval policy for (project,
// deadline, create) and reveal the form-time hint when it applies.
// Hidden when no policy applies. Re-runs on project change so the hint
// updates if the user picks a different project mid-form.
async function refreshApprovalHint(): Promise<void> {
const hint = document.getElementById("deadline-approval-hint");
const text = document.getElementById("deadline-approval-hint-text");
@@ -308,7 +388,6 @@ async function refreshApprovalHint(): Promise<void> {
hint.style.display = "none";
return;
}
// t-paliad-160 split-grammar (with M1 legacy fallback).
const eff = await resp.json() as {
requires_approval?: boolean;
min_role?: string | null;
@@ -343,44 +422,51 @@ document.addEventListener("DOMContentLoaded", async () => {
// Default due to today
const dueInput = document.getElementById("deadline-due") as HTMLInputElement;
if (!dueInput.value) dueInput.value = new Date().toISOString().split("T")[0];
await Promise.all([loadProjects(), loadRules(), loadMe()]);
await Promise.all([loadProjects(), loadProceedingTypes(), loadRules(), loadMe()]);
const pickerHost = document.getElementById("deadline-event-types");
if (pickerHost) {
eventTypePicker = attachEventTypePicker(pickerHost, {
currentUserAdmin,
onChange: () => refreshRuleView(),
onChange: () => {
// Type change shifts which Auto rule resolves; re-render the
// read-only Auto display panel.
refreshRuleAutoDisplay();
},
});
}
// t-paliad-165 follow-up — preload event_types so the collapsed
// summary can render the type's label inline without an extra round
// trip when the user picks a Regel.
// Preload event_types for the Auto display + Standardtitel resolver.
fetchEventTypes()
.then((types) => {
eventTypesByID = new Map(types.map((et) => [et.id, et]));
refreshRuleView();
refreshRuleAutoDisplay();
})
.catch(() => {/* non-fatal — collapsed view falls back to empty label */});
// t-paliad-165 — Regel change auto-fills the Typ chip from the rule's
// concept's canonical event_type, when the picker hasn't been
// manually edited away from the previous rule's suggestion.
document.getElementById("deadline-rule")?.addEventListener("change", () => {
applyRuleAutoFill();
.catch(() => {/* non-fatal */});
// Rule mode toggle.
document.getElementById("deadline-rule-mode-toggle")?.addEventListener("click", () => {
setRuleMode(ruleMode === "auto" ? "custom" : "auto");
});
// "Anderen Typ wählen" — sticky expanded mode so the picker stays
// visible even when the chip still matches the rule's default.
document.getElementById("deadline-event-type-override-btn")?.addEventListener("click", () => {
expandedOverride = true;
refreshRuleView();
// Move focus into the picker's search box so the user can type
// immediately without an extra click.
const search = document.querySelector<HTMLInputElement>(
"#deadline-event-types .event-type-search",
);
search?.focus();
});
// Wire approval-hint refresh: on first render + on project change.
applyRuleModeUI();
// Approval-hint refresh: on first render + on project change.
void refreshApprovalHint();
document.getElementById("deadline-project")?.addEventListener("change", () => {
void refreshApprovalHint();
// Project change can shift which Auto rule resolves (via the
// project's proceeding_type_id).
refreshRuleAutoDisplay();
});
// t-paliad-251 Part 4 — Standardtitel button.
document.getElementById("deadline-title-default-btn")?.addEventListener("click", () => {
const titleInput = document.getElementById("deadline-title") as HTMLInputElement | null;
if (!titleInput) return;
const derived = computeDefaultTitle();
if (derived) titleInput.value = derived;
titleInput.focus();
});
});

View File

@@ -686,6 +686,33 @@ export function openBrowseEventTypesModal(
return new Promise<string[] | null>((resolve) => {
let selected = new Set<string>(opts.initialIDs);
let searchQuery = "";
// t-paliad-251 — court-type filter chips. `null` = "Alle" (any
// jurisdiction). Any non-null value matches event_types.jurisdiction;
// "any" is mapped to NULL/missing rows via jurisdictionMatches().
let activeJurisdiction: string | null = null;
// Surface every jurisdiction present in the data — "any" stays bucketed
// separately so users still have a "show generic-only" chip. EPA is
// canonicalised to EPO in event_types (see mig 074); the chip label
// shows EPA to match the legal vocabulary the lawyers use.
const jurisdictionsPresent = new Set<string>();
for (const et of opts.types) {
const j = (et.jurisdiction ?? "").trim();
if (j) jurisdictionsPresent.add(j);
}
const JURISDICTION_ORDER = ["UPC", "EPO", "DPMA", "DE", "any"];
const chipJurisdictions = JURISDICTION_ORDER.filter((j) => jurisdictionsPresent.has(j));
// Any jurisdiction in the data that isn't in our ordered list lands at
// the end so the chip row never silently drops a court flavour.
for (const j of jurisdictionsPresent) {
if (!chipJurisdictions.includes(j)) chipJurisdictions.push(j);
}
function chipLabel(j: string): string {
if (j === "EPO") return "EPA";
if (j === "any") return t("event_types.browse.jurisdiction.none");
return j;
}
const overlay = document.createElement("div");
overlay.className = "modal-overlay event-type-browse-overlay";
@@ -694,6 +721,15 @@ export function openBrowseEventTypesModal(
<div class="event-type-browse-header">
<h2 id="event-type-browse-title">${esc(t("event_types.browse.title"))}</h2>
<input type="text" class="event-type-browse-search" data-role="search" placeholder="${esc(t("event_types.browse.search"))}" autocomplete="off" />
<div class="event-type-browse-chips" data-role="chips" role="group" aria-label="${esc(t("event_types.browse.jurisdiction.filter_label"))}">
<button type="button" class="event-type-browse-chip event-type-browse-chip--active" data-jurisdiction="" data-role="chip-all">${esc(t("event_types.browse.jurisdiction.all"))}</button>
${chipJurisdictions
.map(
(j) =>
`<button type="button" class="event-type-browse-chip" data-jurisdiction="${esc(j)}">${esc(chipLabel(j))}</button>`,
)
.join("")}
</div>
</div>
<div class="event-type-browse-list" data-role="list" tabindex="-1"></div>
<div class="event-type-browse-actions">
@@ -711,6 +747,7 @@ export function openBrowseEventTypesModal(
const countEl = overlay.querySelector<HTMLElement>("[data-role=count]")!;
const cancelBtn = overlay.querySelector<HTMLButtonElement>("[data-role=cancel]")!;
const applyBtn = overlay.querySelector<HTMLButtonElement>("[data-role=apply]")!;
const chipButtons = overlay.querySelectorAll<HTMLButtonElement>(".event-type-browse-chip");
const groups = groupByCategory(opts.types);
@@ -721,6 +758,12 @@ export function openBrowseEventTypesModal(
return j;
}
function jurisdictionMatches(et: EventType): boolean {
if (activeJurisdiction === null) return true;
const j = (et.jurisdiction ?? "").trim();
return j === activeJurisdiction;
}
function updateCount() {
countEl.textContent = t("event_types.browse.selected_count").replace(
"{n}",
@@ -731,6 +774,7 @@ export function openBrowseEventTypesModal(
function renderList() {
const q = searchQuery.trim().toLowerCase();
const matches = (et: EventType) => {
if (!jurisdictionMatches(et)) return false;
if (!q) return true;
return (
et.label_de.toLowerCase().includes(q) ||
@@ -783,6 +827,16 @@ export function openBrowseEventTypesModal(
renderList();
});
chipButtons.forEach((btn) => {
btn.addEventListener("click", () => {
const raw = btn.dataset.jurisdiction ?? "";
activeJurisdiction = raw === "" ? null : raw;
chipButtons.forEach((b) => b.classList.remove("event-type-browse-chip--active"));
btn.classList.add("event-type-browse-chip--active");
renderList();
});
});
function close(value: string[] | null) {
document.removeEventListener("keydown", onKey);
overlay.remove();

View File

@@ -9,6 +9,7 @@ import {
} from "./event-types";
import { projectIndent } from "./project-indent";
import { mountCalendar, type CalendarHandle, type CalendarItem } from "./calendar/mount-calendar";
import { formatRuleLabelHTML, formatCustomRuleLabelHTML } from "./rule-label";
// Two-eyes glyph 👀 inside .approval-pill--icon. m's 2026-05-08 follow-
// up: "two eyes instead of the one." Emoji rather than SVG keeps the
@@ -66,6 +67,9 @@ interface EventListItem {
rule_code?: string;
rule_name?: string;
rule_name_en?: string;
// t-paliad-258 — free-text rule label when the deadline was created
// via the Custom rule path. Mutually exclusive with rule_id.
custom_rule_text?: string;
event_type_ids?: string[];
// appointment-only
@@ -264,13 +268,26 @@ function urgencyClass(item: EventListItem): string {
function ruleDisplay(item: EventListItem): string {
if (item.type !== "deadline") return "";
// Prefer the saved citation (RoP.023, R.151) over the rule name —
// REGEL is meant for the legal reference, not the rule's display
// name (which is the title column's job).
if (item.rule_code && item.rule_code.trim()) return esc(item.rule_code);
const lang = getLang();
const localized = lang === "en" ? item.rule_name_en : item.rule_name;
if (localized && localized.trim()) return esc(localized);
// t-paliad-258 addendum — canonical display contract: Name primary,
// Citation muted secondary ("Notice of Appeal · UPC.RoP.220.1").
// Custom rules render the lawyer's free text + a "Custom" badge.
// Legacy rule-code-only saves (Fristenrechner, no rule_id) still
// show the bare citation as last-resort fallback.
const hasName = (item.rule_name && item.rule_name.trim()) ||
(item.rule_name_en && item.rule_name_en.trim());
if (hasName || (item.rule_code && item.rule_code.trim())) {
return formatRuleLabelHTML(
{
name: item.rule_name || "",
name_en: item.rule_name_en,
rule_code: item.rule_code,
},
esc,
);
}
if (item.custom_rule_text && item.custom_rule_text.trim()) {
return formatCustomRuleLabelHTML(item.custom_rule_text, esc);
}
return "&mdash;";
}

View File

@@ -429,8 +429,13 @@ function renderProcedureResults(data: DeadlineResponse) {
<span class="timeline-trigger-date">${t("deadlines.trigger.label")}: ${formatDate(data.triggerDate)}</span>
</div>`;
// Pass the chip-strip perspective through as `side` so the column
// bucketer keeps the user's own party on the left (Unsere Seite) —
// t-paliad-257: the old Proaktiv/Reaktiv labels lied when the user
// was on the defendant side, the new labels demand we route the
// user's party into the `ours` column.
const bodyHtml = procedureView === "columns"
? renderColumnsBody(data, { editable: true, showNotes })
? renderColumnsBody(data, { editable: true, showNotes, side: currentPerspective })
: renderTimelineBody(data, { showParty: true, editable: true, showNotes });
container.innerHTML = headerHtml + bodyHtml;

View File

@@ -27,6 +27,7 @@ const translations: Record<Lang, Record<string, string>> = {
"nav.glossar": "Glossar",
"nav.gebuehrentabellen": "Geb\u00fchrentabellen",
"nav.checklisten": "Checklisten",
"nav.submissions": "Schriftsätze",
"nav.gerichte": "Gerichte",
"nav.logout": "Abmelden",
"nav.akten": "Akten",
@@ -301,9 +302,9 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.view.timeline": "Zeitstrahl",
"deadlines.view.columns": "Spalten",
"deadlines.notes.show": "Hinweise anzeigen",
"deadlines.col.proactive": "Proaktiv",
"deadlines.col.ours": "Unsere Seite",
"deadlines.col.court": "Gericht",
"deadlines.col.reactive": "Reaktiv",
"deadlines.col.opponent": "Gegnerseite",
"deadlines.col.both": "Beide Parteien",
// Trigger-event mode (PR-2 \u2014 youpc-parity)
"deadlines.mode.procedure": "Verfahrensablauf",
@@ -416,6 +417,14 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.perspective.defendant.title": "Beklagtenseite — versteckt typische Kläger-Schriftsätze",
"deadlines.perspective.appeal_filed_by.label": "Berufung eingelegt durch:",
"deadlines.perspective.predefined_hint": "vorgegeben durch Akte",
"deadlines.side.label": "Seite:",
"deadlines.side.claimant": "Klägerseite",
"deadlines.side.defendant": "Beklagtenseite",
"deadlines.side.both": "Beide",
"deadlines.appellant.label": "Berufung durch:",
"deadlines.appellant.claimant": "Klägerseite",
"deadlines.appellant.defendant": "Beklagtenseite",
"deadlines.appellant.none": "—",
"deadlines.event.composite.label": "Zusammengesetzt:",
"deadlines.event.unit.days.one": "Tag",
"deadlines.event.unit.days.many": "Tage",
@@ -873,11 +882,15 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.field.title.placeholder": "z.\u202fB. Klageerwiderung einreichen",
"deadlines.field.due": "F\u00e4lligkeitsdatum",
"deadlines.field.rule": "Regel (optional)",
"deadlines.field.rule.none": "Keine Regel",
"deadlines.field.rule.autofill": "Typ vorgegeben durch Regel — entfernen, um zu überschreiben.",
"deadlines.field.rule.autofill_inline": " (vorgegeben durch Regel)",
"deadlines.field.rule.mismatch": "Hinweis: Typ widerspricht Regel — Sie haben den Typ überschrieben.",
"deadlines.field.rule.override": "Anderen Typ wählen",
"deadlines.field.rule.auto_badge": "Auto",
"deadlines.field.rule.auto_no_match": "Keine Regel zur gewählten Verfahrenshandlung",
"deadlines.field.rule.auto_pick_type": "Wählen Sie zuerst eine Verfahrenshandlung",
"deadlines.field.rule.custom_badge": "Eigen",
"deadlines.field.rule.custom_placeholder": "z.B. interner Review-Termin, Mandantengespräch",
"deadlines.field.rule.mode.toggle_to_auto": "Zurück zu Auto",
"deadlines.field.rule.mode.toggle_to_custom": "Eigene Regel eingeben",
"deadlines.field.title.default_btn": "Standardtitel",
"deadlines.field.title.default_fallback": "Neue Frist",
"deadlines.field.notes": "Notizen (optional)",
"deadlines.field.notes.placeholder": "Hinweise, Verweise, n\u00e4chste Schritte\u2026",
"deadlines.error.required": "Akte, Titel und F\u00e4lligkeitsdatum sind Pflichtfelder.",
@@ -1335,7 +1348,10 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.field.grant_date": "Erteilungstag",
"projects.field.court": "Gericht",
"projects.field.case_number": "Aktenzeichen (Gericht)",
"projects.field.proceeding_type_id": "Verfahrensart",
"projects.field.proceeding_type_id": "Verfahrenstyp",
"projects.field.proceeding_type": "Verfahrenstyp",
"projects.field.proceeding_type.unset": "(nicht gesetzt)",
"projects.field.proceeding_type.hint": "Bestimmt, welche Schriftsätze-Vorlagen für dieses Verfahren angezeigt werden.",
"projects.field.our_side": "Wir vertreten",
"projects.field.our_side.hint": "Bestimmt die Voreinstellung der Perspektive im Fristenrechner-Determinator. Lässt sich dort jederzeit überschreiben.",
"projects.field.our_side.unset": "Unbekannt / nicht gesetzt",
@@ -1422,17 +1438,67 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.tab.notizen": "Notizen",
"projects.detail.tab.checklisten": "Checklisten",
"projects.detail.tab.submissions": "Schriftsätze",
"projects.detail.tab.settings": "Verwaltung",
"projects.detail.export.button": "Daten exportieren",
"projects.detail.export.tooltip": "Daten dieses Projekts (mit Unter-Projekten) als Excel + JSON + CSV herunterladen.",
"projects.detail.submissions.empty": "Für dieses Verfahren sind keine Schriftsätze hinterlegt.",
"projects.detail.submissions.empty.no_proceeding": "Bitte zuerst einen Verfahrenstyp setzen.",
"projects.detail.settings.export.heading": "Daten exportieren",
"projects.detail.settings.export.description": "Lade alle Daten dieses Projekts (inkl. Unter-Projekten) als Excel + JSON + CSV-Archiv herunter.",
"projects.detail.settings.archive.heading": "Projekt archivieren",
"projects.detail.settings.archive.description": "Archivieren erfolgt aus dem Bearbeiten-Dialog (Gefahrenbereich).",
"projects.detail.settings.archive.cta": "Bearbeiten öffnen",
"projects.detail.submissions.empty": "Es sind aktuell keine Schriftsatzvorlagen hinterlegt.",
"projects.detail.submissions.empty.no_proceeding": "Für dieses Projekt ist noch kein Verfahrenstyp gesetzt — der Katalog unten zeigt trotzdem alle Vorlagen.",
"projects.detail.submissions.empty.no_proceeding.cta": "Projekt bearbeiten",
"projects.detail.submissions.col.name": "Schriftsatz",
"projects.detail.submissions.col.party": "Partei",
"projects.detail.submissions.col.source": "Rechtsgrundlage",
"projects.detail.submissions.col.action": "",
"projects.detail.submissions.action.generate": "Generieren",
"projects.detail.submissions.action.no_template": "Keine Vorlage",
"projects.detail.submissions.action.edit": "Bearbeiten",
"projects.detail.submissions.hint": "Schriftsätze werden direkt aus dem Projekt heraus als .docx generiert. Anpassen, drucken, einreichen.",
// t-paliad-238 — dedicated draft editor page.
"submissions.draft.title": "Schriftsatz bearbeiten — Paliad",
"submissions.draft.back": "← Zurück zum Projekt",
"submissions.draft.loading": "Lädt…",
"submissions.draft.notfound": "Schriftsatz nicht gefunden oder keine Berechtigung.",
"submissions.draft.action.export": "Als .docx exportieren",
"submissions.draft.action.new": "+ Neuer Entwurf",
"submissions.draft.action.delete": "Löschen",
"submissions.draft.switcher.label": "Entwurf",
"submissions.draft.name.placeholder": "Name dieses Entwurfs",
"submissions.draft.preview.title": "Vorschau",
"submissions.draft.preview.hint": "Read-only Vorschau — finale Bearbeitung in Word.",
// t-paliad-240 — global Schriftsätze drafts index page.
"submissions.index.title": "Schriftsätze — Paliad",
"submissions.index.heading": "Schriftsätze",
"submissions.index.subtitle": "Ihre Schriftsatz-Entwürfe über alle sichtbaren Projekte.",
"submissions.index.loading": "Lädt…",
"submissions.index.empty": "Noch keine Entwürfe. Beginnen Sie mit einem neuen Entwurf — mit oder ohne Projekt.",
"submissions.index.empty.cta": "+ Neuer Entwurf",
"submissions.index.error": "Schriftsätze konnten nicht geladen werden.",
"submissions.index.col.project": "Projekt",
"submissions.index.col.submission": "Schriftsatz",
"submissions.index.col.draft": "Entwurf",
"submissions.index.col.updated": "Zuletzt geändert",
"submissions.index.action.new": "+ Neuer Entwurf",
// t-paliad-243 — global Schriftsatz picker (/submissions/new).
"submissions.new.title": "Neuer Schriftsatz — Paliad",
"submissions.new.back": "← Zurück zur Übersicht",
"submissions.new.heading": "Neuer Schriftsatz",
"submissions.new.subtitle": "Wählen Sie eine Vorlage. Optional verknüpfen Sie den Entwurf mit einem Projekt — sonst füllen Sie alle Variablen manuell.",
"submissions.new.search.placeholder": "Suche nach Schriftsatz, Code oder Norm…",
"submissions.new.loading": "Lädt…",
"submissions.new.error": "Katalog konnte nicht geladen werden.",
"submissions.new.col.name": "Schriftsatz",
"submissions.new.col.party": "Partei",
"submissions.new.col.source": "Rechtsgrundlage",
"submissions.new.col.actions": "Entwurf starten",
"submissions.new.empty.filtered": "Keine passenden Schriftsätze. Filter zurücksetzen.",
"submissions.new.picker.title": "Projekt wählen",
"submissions.new.picker.placeholder": "Projekt suchen (Titel oder Aktenzeichen)…",
"submissions.new.picker.loading": "Lädt Projekte…",
"submissions.new.picker.empty": "Keine sichtbaren Projekte.",
"projects.detail.verlauf.empty": "Noch keine Ereignisse aufgezeichnet.",
"projects.detail.verlauf.loadMore": "Mehr laden",
// SmartTimeline (t-paliad-171, Slice 1).
@@ -1546,9 +1612,14 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.checklisten.col.name": "Name",
"projects.detail.checklisten.col.progress": "Fortschritt",
"projects.detail.checklisten.col.created": "Angelegt",
"projects.detail.checklisten.hint.prefix": "Instanzen werden auf der Vorlagen-Seite unter ",
"projects.detail.checklisten.hint.prefix": "Vorlagen werden auf der ",
"projects.detail.checklisten.hint.link": "Checklisten",
"projects.detail.checklisten.hint.suffix": " angelegt.",
"projects.detail.checklisten.hint.suffix": "-Seite angelegt und bearbeitet.",
"projects.detail.checklisten.add": "Checkliste hinzuf\u00fcgen",
"projects.detail.checklisten.add.search": "Vorlage suchen\u2026",
"projects.detail.checklisten.add.empty_pick": "Keine passenden Vorlagen gefunden.",
"projects.detail.checklisten.add.created": "Checkliste hinzugef\u00fcgt.",
"projects.detail.checklisten.add.error": "Checkliste konnte nicht angelegt werden.",
"projects.detail.delete": "Projekt archivieren",
"projects.detail.delete.confirm.title": "Projekt wirklich archivieren?",
"projects.detail.delete.confirm.body": "Das Projekt wird archiviert. Es kann nicht direkt wiederhergestellt werden.",
@@ -1595,6 +1666,14 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.team.invite.hint": "Benutzer nicht gefunden?",
"projects.detail.team.invite.hint_email": "Niemand mit dieser E-Mail.",
"projects.detail.team.invite.cta": "Einladen",
// t-paliad-231 — pure-client mailto: button on the Team tab. No
// server call; opens the local mail client with every selected
// member queued in the To: line.
"projects.team.mailto.label": "Mail an Auswahl",
"projects.team.mailto.empty": "Mindestens ein Mitglied auswählen",
"projects.team.mailto.count": "{n} ausgewählt",
"projects.team.mailto.select_all": "Alle sichtbaren auswählen",
"projects.team.mailto.select_row": "Mitglied auswählen",
"projects.view.tree": "Baumansicht",
"projects.tree.toggle": "Aufklappen / Zuklappen",
"projects.tree.loading": "Baum wird geladen\u2026",
@@ -2036,8 +2115,13 @@ const translations: Record<Lang, Record<string, string>> = {
"paliadin.error.timeout": "Paliadin antwortet nicht (Timeout 60s). Nochmal versuchen.",
"paliadin.error.connection_lost": "Verbindung verloren.",
"paliadin.error.upstream": "Fehler beim Senden.",
"paliadin.error.upstream_silence": "Paliadin meldet sich nicht mehr — Verbindung wird beendet.",
"paliadin.late.waiting": "Antwort wird nachgereicht, sobald sie eintrifft …",
"paliadin.late.checking": "Verbindung verloren — Paliadin denkt vielleicht noch. Lade frische Antwort …",
"paliadin.late.lost": "Antwort konnte nicht zugestellt werden — bitte Frage erneut stellen.",
"paliadin.late.marker": "verspätet",
"paliadin.thinking": "Paliadin denkt nach",
"paliadin.thinking.seconds": "{seconds}s",
"paliadin.widget.title": "Paliadin",
"paliadin.widget.trigger": "Paliadin (Cmd+J)",
"paliadin.widget.empty": "Was kann ich für dich tun?",
@@ -2365,6 +2449,8 @@ const translations: Record<Lang, Record<string, string>> = {
"event_types.browse.cancel": "Abbrechen",
"event_types.browse.selected_count": "{n} ausgewählt",
"event_types.browse.jurisdiction.none": "Allgemein",
"event_types.browse.jurisdiction.all": "Alle Gerichte",
"event_types.browse.jurisdiction.filter_label": "Nach Gerichtsart filtern",
"event_types.filter.all": "Alle Typen",
"event_types.filter.untyped": "— Ohne Typ —",
"event_types.filter.search": "Typ suchen…",
@@ -2510,6 +2596,17 @@ const translations: Record<Lang, Record<string, string>> = {
"approvals.withdraw.cta": "Genehmigungsanfrage zurückziehen",
"approvals.withdraw.confirm": "Genehmigungsanfrage wirklich zurückziehen?",
"approvals.withdraw.error": "Fehler beim Zurückziehen",
"approvals.withdraw.cancel": "Abbrechen",
"approvals.withdraw.modal.title": "Genehmigungsanfrage zurückziehen?",
"approvals.withdraw.primary.label": "Termin bearbeiten",
"approvals.withdraw.destructive.label": "Endgültig zurückziehen und löschen",
"approvals.withdraw.lead.create.deadline": "Wenn Sie die Anfrage zurückziehen, wird die Frist gelöscht.",
"approvals.withdraw.lead.create.appointment": "Wenn Sie die Anfrage zurückziehen, wird der Termin gelöscht.",
"approvals.withdraw.lead.update": "Wenn Sie die Anfrage zurückziehen, werden die vorgeschlagenen Änderungen verworfen — der Eintrag kehrt in den Zustand vor Ihrer Bearbeitung zurück.",
"approvals.withdraw.lead.delete": "Wenn Sie die Löschanfrage zurückziehen, bleibt der Eintrag bestehen.",
"approvals.withdraw.sub.create": "Alternativ können Sie den Eintrag stattdessen bearbeiten. Die Anfrage bleibt offen und der Genehmiger sieht Ihre neuen Werte.",
"approvals.withdraw.sub.update": "Alternativ können Sie Ihre Änderungen bearbeiten und neu absenden. Die Anfrage bleibt offen.",
"approvals.withdraw.sub.delete": "Sind Sie sicher, dass Sie die Löschanfrage zurückziehen möchten?",
"approvals.pending_create.label": "Erstellung wartet auf Genehmigung",
"approvals.pending_update.label": "Änderung wartet auf Genehmigung",
"approvals.pending_complete.label": "Erledigung wartet auf Genehmigung",
@@ -2904,6 +3001,7 @@ const translations: Record<Lang, Record<string, string>> = {
"nav.glossar": "Glossary",
"nav.gebuehrentabellen": "Fee Schedules",
"nav.checklisten": "Checklists",
"nav.submissions": "Submissions",
"nav.gerichte": "Courts",
"nav.logout": "Sign Out",
"nav.akten": "Matters",
@@ -3175,9 +3273,9 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.view.timeline": "Timeline",
"deadlines.view.columns": "Columns",
"deadlines.notes.show": "Show details",
"deadlines.col.proactive": "Proactive",
"deadlines.col.ours": "Client Side",
"deadlines.col.court": "Court",
"deadlines.col.reactive": "Reactive",
"deadlines.col.opponent": "Opponent Side",
"deadlines.col.both": "Both parties",
"deadlines.adjusted": "Adjusted",
"deadlines.adjusted.reason": "weekend/holiday",
@@ -3297,6 +3395,14 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.perspective.defendant.title": "Defendant side — hides typical claimant submissions",
"deadlines.perspective.appeal_filed_by.label": "Appeal filed by:",
"deadlines.perspective.predefined_hint": "predefined from project",
"deadlines.side.label": "Side:",
"deadlines.side.claimant": "Claimant",
"deadlines.side.defendant": "Defendant",
"deadlines.side.both": "Both",
"deadlines.appellant.label": "Appeal filed by:",
"deadlines.appellant.claimant": "Claimant",
"deadlines.appellant.defendant": "Defendant",
"deadlines.appellant.none": "—",
"deadlines.event.composite.label": "Composite:",
"deadlines.event.unit.days.one": "day",
"deadlines.event.unit.days.many": "days",
@@ -3747,11 +3853,15 @@ const translations: Record<Lang, Record<string, string>> = {
"deadlines.field.title.placeholder": "e.g. File statement of defence",
"deadlines.field.due": "Due date",
"deadlines.field.rule": "Rule (optional)",
"deadlines.field.rule.none": "No rule",
"deadlines.field.rule.autofill": "Type set by rule — remove to override.",
"deadlines.field.rule.autofill_inline": " (set by rule)",
"deadlines.field.rule.mismatch": "Note: type contradicts rule — you have overridden the type.",
"deadlines.field.rule.override": "Choose another type",
"deadlines.field.rule.auto_badge": "Auto",
"deadlines.field.rule.auto_no_match": "No rule maps to the chosen Type",
"deadlines.field.rule.auto_pick_type": "Pick a Type first",
"deadlines.field.rule.custom_badge": "Custom",
"deadlines.field.rule.custom_placeholder": "e.g. internal review meeting, client call",
"deadlines.field.rule.mode.toggle_to_auto": "Back to Auto",
"deadlines.field.rule.mode.toggle_to_custom": "Enter custom rule",
"deadlines.field.title.default_btn": "Default title",
"deadlines.field.title.default_fallback": "New deadline",
"deadlines.field.notes": "Notes (optional)",
"deadlines.field.notes.placeholder": "References, hints, next steps\u2026",
"deadlines.error.required": "Matter, title and due date are required.",
@@ -4191,6 +4301,9 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.field.court": "Court",
"projects.field.case_number": "Case number (court)",
"projects.field.proceeding_type_id": "Proceeding type",
"projects.field.proceeding_type": "Proceeding type",
"projects.field.proceeding_type.unset": "(unset)",
"projects.field.proceeding_type.hint": "Determines which submission templates show up on this proceeding.",
"projects.field.our_side": "We represent",
"projects.field.our_side.hint": "Pre-selects the perspective chip in the Fristenrechner Determinator. Always overridable from there.",
"projects.field.our_side.unset": "Unknown / not set",
@@ -4277,17 +4390,66 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.tab.notizen": "Notes",
"projects.detail.tab.checklisten": "Checklists",
"projects.detail.tab.submissions": "Submissions",
"projects.detail.tab.settings": "Settings",
"projects.detail.export.button": "Export data",
"projects.detail.export.tooltip": "Download this project's data (including sub-projects) as Excel + JSON + CSV.",
"projects.detail.submissions.empty": "No submissions are configured for this proceeding.",
"projects.detail.submissions.empty.no_proceeding": "Please set a proceeding type first.",
"projects.detail.settings.export.heading": "Export data",
"projects.detail.settings.export.description": "Download all data for this project (including sub-projects) as an Excel + JSON + CSV archive.",
"projects.detail.settings.archive.heading": "Archive project",
"projects.detail.settings.archive.description": "Archiving happens in the edit dialog (danger zone).",
"projects.detail.settings.archive.cta": "Open edit dialog",
"projects.detail.submissions.empty": "No submission templates are configured yet.",
"projects.detail.submissions.empty.no_proceeding": "No proceeding type is set for this project yet — the catalog below still lists every template.",
"projects.detail.submissions.empty.no_proceeding.cta": "Edit project",
"projects.detail.submissions.col.name": "Submission",
"projects.detail.submissions.col.party": "Party",
"projects.detail.submissions.col.source": "Legal basis",
"projects.detail.submissions.col.action": "",
"projects.detail.submissions.action.generate": "Generate",
"projects.detail.submissions.action.no_template": "No template",
"projects.detail.submissions.action.edit": "Edit",
"projects.detail.submissions.hint": "Submissions are generated as .docx directly from the project. Edit, print, file.",
// t-paliad-238 — dedicated draft editor page.
"submissions.draft.title": "Edit submission — Paliad",
"submissions.draft.back": "← Back to project",
"submissions.draft.loading": "Loading…",
"submissions.draft.notfound": "Submission not found or insufficient access.",
"submissions.draft.action.export": "Export as .docx",
"submissions.draft.action.new": "+ New draft",
"submissions.draft.action.delete": "Delete",
"submissions.draft.switcher.label": "Draft",
"submissions.draft.name.placeholder": "Name of this draft",
"submissions.draft.preview.title": "Preview",
"submissions.draft.preview.hint": "Read-only preview — final formatting in Word.",
// t-paliad-240 — global submissions drafts index page.
"submissions.index.title": "Submissions — Paliad",
"submissions.index.heading": "Submissions",
"submissions.index.subtitle": "Your submission drafts across every visible project.",
"submissions.index.loading": "Loading…",
"submissions.index.empty": "No drafts yet. Start a new draft — with or without a project.",
"submissions.index.empty.cta": "+ New draft",
"submissions.index.error": "Could not load submissions.",
"submissions.index.col.project": "Project",
"submissions.index.col.submission": "Submission",
"submissions.index.col.draft": "Draft",
"submissions.index.col.updated": "Last updated",
"submissions.index.action.new": "+ New draft",
"submissions.new.title": "New submission — Paliad",
"submissions.new.back": "← Back to drafts",
"submissions.new.heading": "New submission",
"submissions.new.subtitle": "Pick a template. Optionally bind it to a project — otherwise all variables are filled manually.",
"submissions.new.search.placeholder": "Search by name, code or statute…",
"submissions.new.loading": "Loading…",
"submissions.new.error": "Could not load catalog.",
"submissions.new.col.name": "Submission",
"submissions.new.col.party": "Party",
"submissions.new.col.source": "Legal source",
"submissions.new.col.actions": "Start draft",
"submissions.new.empty.filtered": "No submissions match the filters. Reset them to see the full catalog.",
"submissions.new.picker.title": "Pick a project",
"submissions.new.picker.placeholder": "Search project (title or reference)…",
"submissions.new.picker.loading": "Loading projects…",
"submissions.new.picker.empty": "No visible projects.",
"projects.detail.verlauf.empty": "No events recorded yet.",
"projects.detail.verlauf.loadMore": "Load more",
"projects.detail.smarttimeline.empty": "No events captured yet.",
@@ -4400,9 +4562,14 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.checklisten.col.name": "Name",
"projects.detail.checklisten.col.progress": "Progress",
"projects.detail.checklisten.col.created": "Created",
"projects.detail.checklisten.hint.prefix": "Instances are created on the template page under ",
"projects.detail.checklisten.hint.prefix": "Templates are created and edited on the ",
"projects.detail.checklisten.hint.link": "Checklists",
"projects.detail.checklisten.hint.suffix": ".",
"projects.detail.checklisten.hint.suffix": " page.",
"projects.detail.checklisten.add": "Add checklist",
"projects.detail.checklisten.add.search": "Search template…",
"projects.detail.checklisten.add.empty_pick": "No matching templates.",
"projects.detail.checklisten.add.created": "Checklist added.",
"projects.detail.checklisten.add.error": "Could not create checklist.",
"projects.detail.delete": "Archive project",
"projects.detail.delete.confirm.title": "Archive project?",
"projects.detail.delete.confirm.body": "The project will be archived. It cannot be directly restored.",
@@ -4449,6 +4616,12 @@ const translations: Record<Lang, Record<string, string>> = {
"projects.detail.team.invite.hint": "User not found?",
"projects.detail.team.invite.hint_email": "No one with that email.",
"projects.detail.team.invite.cta": "Invite",
// t-paliad-231 — pure-client mailto: button on the Team tab.
"projects.team.mailto.label": "Mail to selection",
"projects.team.mailto.empty": "Select at least one member",
"projects.team.mailto.count": "{n} selected",
"projects.team.mailto.select_all": "Select all visible",
"projects.team.mailto.select_row": "Select member",
"projects.view.tree": "Tree view",
"projects.tree.toggle": "Expand / collapse",
"projects.tree.loading": "Loading tree…",
@@ -4885,8 +5058,13 @@ const translations: Record<Lang, Record<string, string>> = {
"paliadin.error.timeout": "Paliadin didn't respond in time (60s). Try again.",
"paliadin.error.connection_lost": "Connection lost.",
"paliadin.error.upstream": "Send failed.",
"paliadin.error.upstream_silence": "Paliadin went silent — closing the connection.",
"paliadin.late.waiting": "Will fill in the response when it arrives …",
"paliadin.late.checking": "Connection lost — Paliadin may still be thinking. Fetching fresh answer …",
"paliadin.late.lost": "Answer couldn't be delivered — please ask again.",
"paliadin.late.marker": "late",
"paliadin.thinking": "Paliadin is thinking",
"paliadin.thinking.seconds": "{seconds}s",
"paliadin.widget.title": "Paliadin",
"paliadin.widget.trigger": "Paliadin (Cmd+J)",
"paliadin.widget.empty": "What can I help you with?",
@@ -5214,6 +5392,8 @@ const translations: Record<Lang, Record<string, string>> = {
"event_types.browse.cancel": "Cancel",
"event_types.browse.selected_count": "{n} selected",
"event_types.browse.jurisdiction.none": "Any",
"event_types.browse.jurisdiction.all": "All courts",
"event_types.browse.jurisdiction.filter_label": "Filter by court type",
"event_types.filter.all": "All types",
"event_types.filter.untyped": "— Untyped —",
"event_types.filter.search": "Search type…",
@@ -5359,6 +5539,17 @@ const translations: Record<Lang, Record<string, string>> = {
"approvals.withdraw.cta": "Withdraw approval request",
"approvals.withdraw.confirm": "Withdraw the approval request?",
"approvals.withdraw.error": "Failed to withdraw",
"approvals.withdraw.cancel": "Cancel",
"approvals.withdraw.modal.title": "Withdraw approval request?",
"approvals.withdraw.primary.label": "Edit event",
"approvals.withdraw.destructive.label": "Withdraw permanently and delete",
"approvals.withdraw.lead.create.deadline": "Withdrawing this request will delete the deadline.",
"approvals.withdraw.lead.create.appointment": "Withdrawing this request will delete the appointment.",
"approvals.withdraw.lead.update": "Withdrawing this request will discard your proposed changes — the entry will revert to its state before your edit.",
"approvals.withdraw.lead.delete": "Withdrawing the delete request will keep the entry alive.",
"approvals.withdraw.sub.create": "Alternatively, you can edit the entry instead. The request stays open and the approver will see your new values.",
"approvals.withdraw.sub.update": "Alternatively, you can edit your changes and resubmit. The request stays open.",
"approvals.withdraw.sub.delete": "Are you sure you want to withdraw the delete request?",
"approvals.pending_create.label": "Awaits approval (creation)",
"approvals.pending_update.label": "Awaits approval (change)",
"approvals.pending_complete.label": "Awaits approval (completion)",

View File

@@ -1,15 +1,24 @@
// Late-response polling. The Go backend's pollForResponse window is
// 60 s; if Claude writes the response file after that (because the
// tmux pane was busy mid-turn when the message arrived), the SSE
// stream has already closed with an `error` event. The Janitor
// (services.LocalPaliadinService.runJanitor) then patches the
// paliadin_turns row when the file lands.
// Late-response polling (t-paliad-235 rewrite).
//
// This module is the FE half of that loop: after the bubble shows an
// error, the caller registers the turn here. We poll
// `/api/paliadin/turns/{id}` every 3 s for up to 10 minutes; once the
// row has a non-empty response, we hand it back so the caller can
// swap the bubble content in place.
// When the SSE stream closes mid-turn with an error event, the bubble
// can't tell from the wire whether (a) the upstream is still finishing
// the turn and we just lost transport, or (b) the upstream is truly
// dead.
//
// This module hits the dispatching recovery endpoint
// `/api/paliadin/turns/{id}/recover`, which knows the active backend:
//
// - aichat backend → asks aichat via its conversation API whether
// the turn actually completed upstream
// - legacy backend → reads the local row (paliad's filesystem
// janitor patches it when claude writes the
// response file late)
//
// The endpoint returns:
//
// recovery_state="recovered" → response is in the payload, render it
// recovery_state="pending" → keep polling
// recovery_state="lost" → upstream is truly gone, give up
export interface LateTurn {
turn_id: string;
@@ -28,6 +37,10 @@ export interface LatePollOptions {
intervalMs?: number; // default 3000
maxDurationMs?: number; // default 600000 (10 min)
onLateResponse: (turn: LateTurn) => void;
// onLost — backend confirmed the turn is unrecoverable. Caller should
// swap the bubble copy to the "verloren" string. Distinct from
// onGiveUp (which fires only on the local timeout).
onLost?: () => void;
onGiveUp?: () => void;
}
@@ -35,6 +48,20 @@ export interface LatePollHandle {
cancel: () => void;
}
interface RecoverResponse {
turn_id: string;
started_at: string;
response: string | null;
error_code: string | null;
finished_at: string | null;
duration_ms: number | null;
used_tools: string[];
rows_seen: number[];
chip_count: number;
classifier_tag: string | null;
recovery_state: "recovered" | "pending" | "lost";
}
export function pollForLateResponse(opts: LatePollOptions): LatePollHandle {
const interval = opts.intervalMs ?? 3000;
const maxDuration = opts.maxDurationMs ?? 10 * 60 * 1000;
@@ -50,18 +77,24 @@ export function pollForLateResponse(opts: LatePollOptions): LatePollHandle {
return;
}
try {
const r = await fetch(`/api/paliadin/turns/${opts.turnId}`, {
const r = await fetch(`/api/paliadin/turns/${opts.turnId}/recover`, {
credentials: "same-origin",
});
if (r.ok) {
const turn = (await r.json()) as LateTurn;
if (turn.response && turn.response.length > 0) {
opts.onLateResponse(turn);
const body = (await r.json()) as RecoverResponse;
if (body.recovery_state === "recovered" && body.response) {
opts.onLateResponse(toLateTurn(body));
return;
}
}
// 404: row gone (very unlikely) — give up.
if (r.status === 404) {
if (body.recovery_state === "lost") {
opts.onLost?.();
return;
}
// pending — keep polling
} else if (r.status === 404) {
// Row gone — give up. Different signal from `lost`: a missing row
// is a paliad-side bookkeeping problem; aichat may still have the
// answer but we can't surface it without the row.
opts.onGiveUp?.();
return;
}
@@ -72,7 +105,8 @@ export function pollForLateResponse(opts: LatePollOptions): LatePollHandle {
};
// First poll deliberately runs after one interval so we don't race
// the 60 s timeout on the very first tick.
// the dispatch endpoint on the very first tick (gives the upstream a
// moment to actually settle the row after the stream drop).
timer = window.setTimeout(tick, interval);
return {
@@ -82,3 +116,17 @@ export function pollForLateResponse(opts: LatePollOptions): LatePollHandle {
},
};
}
function toLateTurn(body: RecoverResponse): LateTurn {
return {
turn_id: body.turn_id,
response: body.response,
error_code: body.error_code,
finished_at: body.finished_at,
duration_ms: body.duration_ms,
used_tools: body.used_tools ?? [],
rows_seen: body.rows_seen ?? [],
chip_count: body.chip_count ?? 0,
classifier_tag: body.classifier_tag,
};
}

View File

@@ -381,11 +381,32 @@ async function sendTurn(): Promise<void> {
const es = new EventSource(turnRes.sse_url);
activeStream = es;
startWidgetThinking(placeholder);
let fullText = "";
es.addEventListener("thinking", (ev) => {
let elapsed = 0;
try {
const data = JSON.parse((ev as MessageEvent).data || "{}");
if (typeof data.elapsed_seconds === "number") elapsed = data.elapsed_seconds;
} catch {
/* ignore */
}
updateWidgetThinking(placeholder, elapsed);
});
es.addEventListener("content", (ev) => {
try {
const data = JSON.parse((ev as MessageEvent).data);
if (typeof data.delta === "string" && data.delta) {
// Streamed delta (aichat backend) — append.
stopWidgetThinking(placeholder);
fullText += data.delta;
setBubbleText(placeholder, fullText);
return;
}
// Legacy one-shot full-text payload.
fullText = String(data.text || "");
stopWidgetThinking(placeholder);
setBubbleText(placeholder, fullText);
} catch {
/* ignore parse error */
@@ -393,13 +414,15 @@ async function sendTurn(): Promise<void> {
});
es.addEventListener("end", () => {
placeholder.dataset.streaming = "false";
stopWidgetThinking(placeholder);
history.push({ role: "assistant", text: fullText || "", ts: new Date().toISOString() });
saveHistory();
cleanupStream();
});
es.addEventListener("error", () => {
stopWidgetThinking(placeholder);
const errText = t("paliadin.error.connection_lost");
setBubbleText(placeholder, errText + " " + t("paliadin.late.waiting"));
setBubbleText(placeholder, errText + " " + t("paliadin.late.checking"));
placeholder.classList.add("paliadin-widget-bubble--error");
placeholder.classList.add("paliadin-widget-bubble--late-pending");
placeholder.dataset.streaming = "false";
@@ -412,6 +435,39 @@ async function sendTurn(): Promise<void> {
});
}
function startWidgetThinking(bubble: HTMLElement): void {
if (bubble.querySelector(".paliadin-widget-thinking")) return;
// Clear the static placeholder text — the live pulse + counter is
// the canonical "denkt nach" signal.
const textNode = bubble.querySelector(".paliadin-widget-bubble-text");
if (textNode) textNode.textContent = "";
const node = document.createElement("div");
node.className = "paliadin-widget-thinking";
node.innerHTML = `
<span class="paliadin-widget-thinking-dot" aria-hidden="true"></span>
<span class="paliadin-widget-thinking-label"></span>
<span class="paliadin-widget-thinking-elapsed"></span>
`;
const label = node.querySelector(".paliadin-widget-thinking-label")!;
label.textContent = t("paliadin.thinking");
bubble.appendChild(node);
updateWidgetThinking(bubble, 0);
}
function updateWidgetThinking(bubble: HTMLElement, elapsedSeconds: number): void {
const node = bubble.querySelector(".paliadin-widget-thinking") as HTMLElement | null;
if (!node) return;
const elapsed = node.querySelector(".paliadin-widget-thinking-elapsed");
if (elapsed) {
const s = elapsedSeconds < 0 ? 0 : Math.round(elapsedSeconds);
elapsed.textContent = t("paliadin.thinking.seconds").replace("{seconds}", String(s));
}
}
function stopWidgetThinking(bubble: HTMLElement): void {
bubble.querySelector(".paliadin-widget-thinking")?.remove();
}
function cleanupStream(): void {
activeStream?.close();
activeStream = null;
@@ -427,13 +483,24 @@ function startWidgetLatePoll(turnId: string, bubble: HTMLElement): void {
lateWidgetPolls.delete(turnId);
applyWidgetLateResponse(bubble, turn);
},
onLost: () => {
lateWidgetPolls.delete(turnId);
applyWidgetLost(bubble);
},
onGiveUp: () => {
lateWidgetPolls.delete(turnId);
applyWidgetLost(bubble);
},
});
lateWidgetPolls.set(turnId, handle);
}
function applyWidgetLost(bubble: HTMLElement): void {
bubble.classList.remove("paliadin-widget-bubble--late-pending");
bubble.classList.add("paliadin-widget-bubble--lost");
setBubbleText(bubble, t("paliadin.late.lost"));
}
function applyWidgetLateResponse(bubble: HTMLElement, turn: LateTurn): void {
if (!turn.response) return;
bubble.classList.remove(

View File

@@ -3,16 +3,25 @@ import { initSidebar } from "./sidebar";
import { renderResponseHTML } from "./paliadin-render";
import { pollForLateResponse, type LateTurn, type LatePollHandle } from "./paliadin-late-poll";
// Paliadin chat panel client (t-paliad-146 PoC).
// Paliadin chat panel client (t-paliad-146 PoC, streaming upgrade
// t-paliad-235).
//
// State machine: empty → typing → sending → streaming → done.
// State machine: empty → typing → sending → thinking → streaming → done.
// History lives in localStorage under "paliadin:history:<sessionId>"
// — design §0.5.4 session-only persistence.
//
// SSE consumer subscribes to `event: meta`, `event: content`,
// `event: end`, `event: error`, `event: ping`. Backend currently
// emits one `content` blob per turn (real chunked streaming is
// production-v1; PoC simulates with a typewriter effect).
// `event: thinking`, `event: end`, `event: error`, `event: ping`.
//
// `content` events from the aichat backend arrive as incremental
// `{delta: "..."}` chunks; the bubble accumulates them in real time —
// no typewriter simulation needed. Legacy backends still emit a single
// `{text: "..."}` payload and we fall back to the typewriter for that
// shape.
//
// `thinking` events fire while the upstream is alive but hasn't
// produced content yet (or stalled mid-stream); the bubble renders a
// pulse + counter so the user can SEE the chat is still working.
interface HistoryEntry {
role: "user" | "assistant";
@@ -167,25 +176,53 @@ async function sendTurn(text: string): Promise<void> {
const es = new EventSource(turnRes.sse_url);
currentEventSource = es;
// Show the thinking pulse immediately — the placeholder text already
// says "denkt nach", but the visible pulse + counter is the live
// proof-of-life signal m needs to trust that the chat is working.
startThinkingIndicator(placeholder);
// Reset the streamed accumulator for this turn.
placeholder.dataset.fullText = "";
es.addEventListener("meta", () => {
// Could surface a "thinking" indicator; placeholder text already does.
});
es.addEventListener("thinking", (ev) => {
let elapsed = 0;
try {
const data = JSON.parse((ev as MessageEvent).data || "{}");
if (typeof data.elapsed_seconds === "number") {
elapsed = data.elapsed_seconds;
}
} catch {
/* ignore */
}
updateThinkingIndicator(placeholder, elapsed);
});
es.addEventListener("content", (ev) => {
const data = JSON.parse((ev as MessageEvent).data);
const delta = typeof data.delta === "string" ? data.delta : "";
if (delta) {
// Aichat streaming path — accumulate the delta into the bubble.
stopThinkingIndicator(placeholder);
const current = placeholder.dataset.fullText ?? "";
const next = current + delta;
placeholder.dataset.fullText = next;
writeStreamedText(placeholder, next);
return;
}
// Legacy one-shot path — full body in `text`.
const text = String(data.text || "");
// Cache the full text on the bubble so finishBubble can render the
// complete response even when the typewriter is mid-flight when end
// arrives. textContent reflects only what's been typed so far and
// would otherwise truncate the rendered Markdown (m, 2026-05-08 —
// saw "## Proje" instead of the full 1408-byte body).
placeholder.dataset.fullText = text;
stopThinkingIndicator(placeholder);
typewriter(placeholder, text);
});
es.addEventListener("end", (ev) => {
const data = JSON.parse((ev as MessageEvent).data);
placeholder.dataset.streaming = "false";
stopThinkingIndicator(placeholder);
finishBubble(placeholder, data);
history.push({
role: "assistant",
@@ -210,12 +247,12 @@ async function sendTurn(text: string): Promise<void> {
es.addEventListener("error", (ev) => {
const errText = friendlyErrorMessage((ev as MessageEvent).data);
// Annotate the error bubble with a "warten auf späte Antwort" hint
// so m knows the turn isn't dead; if Claude finishes after the
// 60 s window the Janitor (services.LocalPaliadinService.runJanitor)
// patches the row and pollForLateResponse swaps in the real reply.
stopThinkingIndicator(placeholder);
// Honest copy: we don't claim "nachgereicht" because the recovery
// path may report "lost". Frame it as "checking" while we ask the
// backend whether the turn actually completed upstream.
placeholder.querySelector(".paliadin-bubble-text")!.textContent =
errText + " " + t("paliadin.late.waiting");
errText + " " + t("paliadin.late.checking");
placeholder.classList.add("paliadin-bubble--error");
placeholder.classList.add("paliadin-bubble--late-pending");
placeholder.dataset.streaming = "false";
@@ -232,6 +269,65 @@ async function sendTurn(text: string): Promise<void> {
});
}
// =============================================================================
// thinking indicator — proof-of-life pulse + elapsed counter
// =============================================================================
function startThinkingIndicator(bubble: HTMLElement): void {
// Append a thinking node next to the bubble text (sibling, so the
// typewriter rewriting text content doesn't clobber it). The node
// shows a pulse dot + the elapsed counter.
let node = bubble.querySelector(".paliadin-thinking") as HTMLElement | null;
if (node) return; // already running
// Clear the static placeholder text — the live pulse + counter is
// now the canonical "denkt nach" signal. Leaving the text in place
// would render the same phrase twice.
const textNode = bubble.querySelector(".paliadin-bubble-text");
if (textNode) textNode.textContent = "";
node = document.createElement("div");
node.className = "paliadin-thinking";
node.innerHTML = `
<span class="paliadin-thinking-dot" aria-hidden="true"></span>
<span class="paliadin-thinking-label"></span>
<span class="paliadin-thinking-elapsed"></span>
`;
const label = node.querySelector(".paliadin-thinking-label")!;
label.textContent = t("paliadin.thinking");
bubble.appendChild(node);
// Initial 0s — replaced as soon as a thinking event arrives or our
// local ticker fires.
updateThinkingIndicator(bubble, 0);
}
function updateThinkingIndicator(bubble: HTMLElement, elapsedSeconds: number): void {
const node = bubble.querySelector(".paliadin-thinking") as HTMLElement | null;
if (!node) return;
const elapsed = node.querySelector(".paliadin-thinking-elapsed");
if (elapsed) {
elapsed.textContent = formatThinkingSeconds(elapsedSeconds);
}
}
function stopThinkingIndicator(bubble: HTMLElement): void {
bubble.querySelector(".paliadin-thinking")?.remove();
}
function formatThinkingSeconds(s: number): string {
if (s < 0) s = 0;
return t("paliadin.thinking.seconds").replace("{seconds}", String(Math.round(s)));
}
// writeStreamedText fills the bubble with raw text as it accumulates.
// Cheaper than the typewriter — we already have the real cadence from
// the wire, no need to simulate it.
function writeStreamedText(bubble: HTMLElement, text: string): void {
const node = bubble.querySelector(".paliadin-bubble-text");
if (!node) return;
node.textContent = text;
const stream = document.getElementById("paliadin-stream");
if (stream) stream.scrollTop = stream.scrollHeight;
}
// Server emits SSE error events as JSON `{code, message}`. Map known
// codes to localised, user-friendly text; fall through to a generic
// "connection lost" for anything we don't recognise (including raw
@@ -361,11 +457,12 @@ function finishBubble(bubble: HTMLElement, data: any): void {
}
// startLatePoll registers the Janitor-patched row poller for one
// errored turn. When the row gains a response we swap the bubble's
// content + drop the error class + retroactively replace the history
// entry (which was never written for the failed turn — append now so
// reload renders the late reply).
// startLatePoll registers the recovery-endpoint poller for one errored
// turn. When the row gains a response we swap the bubble's content +
// drop the error class + retroactively replace the history entry
// (which was never written for the failed turn — append now so reload
// renders the late reply). When the backend confirms the turn is
// "lost", we swap the bubble to the honest "verloren" copy.
function startLatePoll(turnId: string, bubble: HTMLElement): void {
// Avoid duplicate pollers for the same turn (e.g. SSE error fires
// twice in some browsers when the connection drops).
@@ -376,13 +473,25 @@ function startLatePoll(turnId: string, bubble: HTMLElement): void {
latePolls.delete(turnId);
applyLateResponse(bubble, turn);
},
onLost: () => {
latePolls.delete(turnId);
applyLostResponse(bubble);
},
onGiveUp: () => {
latePolls.delete(turnId);
applyLostResponse(bubble);
},
});
latePolls.set(turnId, handle);
}
function applyLostResponse(bubble: HTMLElement): void {
bubble.classList.remove("paliadin-bubble--late-pending");
bubble.classList.add("paliadin-bubble--lost");
const node = bubble.querySelector(".paliadin-bubble-text");
if (node) node.textContent = t("paliadin.late.lost");
}
function applyLateResponse(bubble: HTMLElement, turn: LateTurn): void {
if (!turn.response) return;
bubble.classList.remove("paliadin-bubble--error", "paliadin-bubble--late-pending");

View File

@@ -1,8 +1,37 @@
import { t, tDyn } from "./i18n";
import { t, tDyn, getLang } from "./i18n";
// Shared logic for the Project form rendered by ProjectFormFields.tsx.
// Used by /projects/new and the edit modal on /projects/{id}.
export interface ProceedingTypeRow {
id: number;
code: string;
name: string;
name_en: string;
jurisdiction?: string;
is_active: boolean;
}
let proceedingTypesCache: ProceedingTypeRow[] | null = null;
// loadProceedingTypes fetches active fristenrechner-category proceeding
// types — the only set a project may bind to (mig 087/088 + service
// validation guard `validateProceedingTypeCategory`). Cached at module
// level so the page only pays for one fetch even when both the new-
// project page and the edit modal exercise the picker.
export async function loadProceedingTypes(): Promise<ProceedingTypeRow[]> {
if (proceedingTypesCache) return proceedingTypesCache;
try {
const resp = await fetch("/api/proceeding-types-db?category=fristenrechner");
if (!resp.ok) return [];
const rows = ((await resp.json()) ?? []) as ProceedingTypeRow[];
proceedingTypesCache = rows.filter((r) => r.is_active);
return proceedingTypesCache;
} catch {
return [];
}
}
export interface ProjectMini {
id: string;
title: string;
@@ -136,6 +165,34 @@ export function wireTypeChange() {
typeSel.addEventListener("change", () => showFieldsForType(typeSel.value));
}
// populateProceedingTypeSelect fills #project-proceeding-type-id with one
// option per fristenrechner-category proceeding type, ordered by `code`
// (so the user scans `de.*`, `dpma.*`, `epa.*`, `upc.*` in stable
// jurisdiction-grouped order). The first option is the empty "unset"
// choice already in the markup; this helper only appends rows below it.
// Idempotent — clearing rows[1..] on re-call so a re-open of the edit
// modal doesn't double-render the list.
export async function populateProceedingTypeSelect(): Promise<void> {
const sel = tryGet("project-proceeding-type-id") as HTMLSelectElement | null;
if (!sel) return;
const rows = await loadProceedingTypes();
rows.sort((a, b) => a.code.localeCompare(b.code));
while (sel.options.length > 1) sel.remove(1);
const isEN = getLang() === "en";
for (const row of rows) {
const opt = document.createElement("option");
opt.value = String(row.id);
const label = isEN && row.name_en ? row.name_en : row.name;
opt.textContent = `${label} (${row.code})`;
sel.appendChild(opt);
}
// Honour a pre-selection value that prefillForm wrote before the
// option set existed. dataset.preselect is set to "" or the saved id;
// restoring it here keeps the edit modal's saved value visible.
const preselect = sel.dataset.preselect;
if (preselect !== undefined) sel.value = preselect;
}
// readPayload collects the form's current values into a CreateProjectInput /
// UpdateProjectInput compatible JSON payload. Returns null + sets msg when
// title is missing.
@@ -208,6 +265,22 @@ export function readPayload(
stringField("project-court", "court");
stringField("project-case-number", "case_number");
// Proceeding type — optional picker. Per t-paliad-232, an empty
// pick simply omits the key from the payload (create: column stays
// NULL; edit: server's `omitempty` skips the SET). Clearing a
// previously-set value isn't supported in this slice; once bound,
// a project's proceeding type can be swapped but not unset from
// the form. The server's validateProceedingTypeCategory backs the
// selected id with a category check.
const ptSel = tryGet("project-proceeding-type-id") as HTMLSelectElement | null;
if (ptSel) {
const v = ptSel.value.trim();
if (v) {
const n = parseInt(v, 10);
if (!isNaN(n)) payload.proceeding_type_id = n;
}
}
// Client Role (DB column: our_side) — case-only after t-paliad-222.
// The select uses "" for the unset option; the service maps empty
// string to NULL via nullableOurSide.
@@ -259,6 +332,16 @@ export function prefillForm(p: Record<string, unknown>) {
if (osSel) osSel.value = String(p.our_side ?? "");
const ocEl = tryGet("project-opponent-code") as HTMLInputElement | null;
if (ocEl) ocEl.value = String(p.opponent_code ?? "");
// Proceeding-type picker — populated lazily by populateProceedingTypeSelect.
// Set the value here even if the options haven't arrived yet; the post-
// populate render runs ApplyProceedingTypeValue to re-select the saved id
// once the option exists.
const ptSel = tryGet("project-proceeding-type-id") as HTMLSelectElement | null;
if (ptSel) {
const v = p.proceeding_type_id == null ? "" : String(p.proceeding_type_id);
ptSel.dataset.preselect = v;
ptSel.value = v;
}
getTA("project-description").value = String(p.description ?? "");
getSel("project-status").value = String(p.status ?? "active");
}

View File

@@ -8,11 +8,15 @@ import {
wireTypeChange,
prefillForm,
readPayload,
populateProceedingTypeSelect,
loadProceedingTypes as loadProceedingTypesShared,
} from "./project-form";
import { mountFilterBar, type BarHandle } from "./filter-bar";
import type { FilterSpec, RenderSpec } from "./views/types";
import { renderSmartTimeline, type TimelineEvent as SmartTimelineEvent, type LaneInfo as SmartTimelineLane } from "./views/shape-timeline";
import { loadAndRenderSubmissions } from "./submissions";
import { buildMailtoHref, type BroadcastRecipient } from "./broadcast";
import { formatRuleLabelHTML, formatCustomRuleLabelHTML } from "./rule-label";
interface Project {
id: string;
@@ -139,6 +143,11 @@ interface Deadline {
status: string;
rule_id?: string;
rule_code?: string;
rule_name?: string;
rule_name_en?: string;
// t-paliad-258 — free-text rule label when the deadline was saved in
// Custom mode. Mutually exclusive with rule_id.
custom_rule_text?: string;
// Populated by the union endpoint (/api/events) which is what the project
// detail page calls — used for attribution when the row lives on a
// descendant project (t-paliad-139).
@@ -172,7 +181,8 @@ type TabId =
| "appointments"
| "notes"
| "checklists"
| "submissions";
| "submissions"
| "settings";
const VALID_TABS: TabId[] = [
"history",
@@ -184,6 +194,7 @@ const VALID_TABS: TabId[] = [
"notes",
"checklists",
"submissions",
"settings",
];
// Legacy German tab slugs that may appear in bookmarked URLs after the
@@ -211,6 +222,9 @@ interface ChecklistTemplateSummary {
slug: string;
titleDE: string;
titleEN: string;
descriptionDE?: string;
descriptionEN?: string;
regime?: string;
itemCount: number;
}
@@ -236,6 +250,12 @@ let attachedUnits: AttachedUnit[] = [];
let allUnits: { id: string; name: string; office: string }[] = [];
let userOptions: { id: string; display_name: string; email: string; profession?: string }[] = [];
// t-paliad-231 — checkbox selection backing the "Mail an Auswahl"
// mailto: button on the Team tab. Pure client state, wiped on page
// navigation. Pruned to currently-visible user_ids on every renderTeam
// so removed/filtered-out members don't ride along in the next mailto.
const selectedMailUserIDs: Set<string> = new Set();
const EVENTS_PAGE_SIZE = 50;
let eventsHasMore = false;
let eventsLoadingMore = false;
@@ -791,6 +811,9 @@ interface UnionEvent {
status?: string;
rule_id?: string;
rule_code?: string;
rule_name?: string;
rule_name_en?: string;
custom_rule_text?: string;
start_at?: string;
end_at?: string;
location?: string;
@@ -818,6 +841,9 @@ async function loadDeadlines(id: string) {
status: it.status ?? "pending",
rule_id: it.rule_id,
rule_code: it.rule_code,
rule_name: it.rule_name,
rule_name_en: it.rule_name_en,
custom_rule_text: it.custom_rule_text,
project_title: it.project_title,
}));
} else {
@@ -987,6 +1013,27 @@ function fmtDateOnly(iso: string): string {
}
}
// formatDeadlineRuleCell renders the REGEL column for the project
// detail Fristen table using the canonical t-paliad-258 contract:
// 1. catalog rule (rule_name / rule_name_en + rule_code) → "Name · Code"
// 2. custom_rule_text → text + "Custom" badge
// 3. legacy rule_code-only saves → bare citation
// 4. otherwise "—"
function formatDeadlineRuleCell(f: Deadline): string {
const hasName = (f.rule_name && f.rule_name.trim()) ||
(f.rule_name_en && f.rule_name_en.trim());
if (hasName || (f.rule_code && f.rule_code.trim())) {
return formatRuleLabelHTML(
{ name: f.rule_name || "", name_en: f.rule_name_en, rule_code: f.rule_code },
esc,
);
}
if (f.custom_rule_text && f.custom_rule_text.trim()) {
return formatCustomRuleLabelHTML(f.custom_rule_text, esc);
}
return "—";
}
function urgencyClass(due: string, status: string): string {
if (status === "completed") return "frist-urgency-done";
const today = new Date();
@@ -1025,7 +1072,7 @@ function renderDeadlines() {
</td>
<td class="frist-col-due ${urgency}"><span class="frist-due-dot"></span>${fmtDateOnly(f.due_date)}</td>
<td class="frist-col-title ${titleClass}">${esc(f.title)}${attributionChip(f.project_id, f.project_title)}</td>
<td class="frist-col-rule">${f.rule_code ? esc(f.rule_code) : "—"}</td>
<td class="frist-col-rule">${formatDeadlineRuleCell(f)}</td>
<td><span class="entity-status-chip entity-status-${esc(f.status)}">${esc(statusLabel)}</span></td>
</tr>`;
})
@@ -1173,13 +1220,16 @@ function renderHeader() {
netdocs.style.display = "none";
}
// Delete visibility: partner/admin only
// Delete visibility: partner/admin only. The Verwaltung tab's archive
// sub-section mirrors the same gate (t-paliad-245) — it only points at
// the Edit-modal danger zone, so it's pointless to show when the danger
// zone itself is hidden.
const deleteWrap = document.getElementById("project-delete-wrap")!;
if (me && (me.global_role === "global_admin")) {
deleteWrap.style.display = "";
} else {
deleteWrap.style.display = "none";
}
const archiveSection = document.getElementById("project-settings-archive");
const canArchive = !!me && me.global_role === "global_admin";
deleteWrap.style.display = canArchive ? "" : "none";
if (archiveSection) archiveSection.style.display = canArchive ? "" : "none";
updateSettingsTabVisibility();
}
// wrapEventTitleLink — kept for the dashboard activity feed which reuses
@@ -1443,36 +1493,9 @@ function initSmartTimelineAddModal(id: string) {
initCounterclaimRoute(id, modal, choices, form);
}
interface ProceedingTypeRow {
id: number;
code: string;
name: string;
name_en: string;
jurisdiction?: string;
is_active: boolean;
}
let proceedingTypesCache: ProceedingTypeRow[] | null = null;
// loadProceedingTypes fetches active proceeding types for the project
// picker. Phase 3 Slice 5 (t-paliad-186) restricts project-binding to
// fristenrechner-category codes (design §3.F + m's Q2 ruling), so the
// picker only ever shows those — never the 7 legacy litigation codes
// (INF / REV / CCR / APM / APP / AMD / ZPO_CIVIL). The matching
// server-side service validation + DB trigger (mig 088) are the
// defence-in-depth backstops for any non-UI writer.
async function loadProceedingTypes(): Promise<ProceedingTypeRow[]> {
if (proceedingTypesCache) return proceedingTypesCache;
try {
const resp = await fetch("/api/proceeding-types-db?category=fristenrechner");
if (!resp.ok) return [];
const rows = ((await resp.json()) ?? []) as ProceedingTypeRow[];
proceedingTypesCache = rows.filter((r) => r.is_active);
return proceedingTypesCache;
} catch {
return [];
}
}
// loadProceedingTypes is shared from ./project-form so the counterclaim
// modal here and the project-edit picker hit the same cache.
const loadProceedingTypes = loadProceedingTypesShared;
function initCounterclaimRoute(
id: string,
@@ -1649,18 +1672,34 @@ function showTab(tab: TabId) {
}
let checklistInstancesInited = false;
async function loadAndRenderChecklistInstances(projectID: string) {
if (checklistInstancesInited) return;
let checklistCatalogLoaded = false;
// loadChecklistCatalog populates `checklistTemplates` (slug → template) from
// `/api/checklists`. Reused by the tab renderer and the add-instance modal so
// the second open doesn't refetch the catalog (t-paliad-239).
async function loadChecklistCatalog(): Promise<ChecklistTemplateSummary[]> {
if (checklistCatalogLoaded) return Object.values(checklistTemplates);
try {
const resp = await fetch(`/api/checklists`);
const list = resp.ok ? (((await resp.json()) as ChecklistTemplateSummary[]) ?? []) : [];
checklistTemplates = {};
for (const tpl of list) checklistTemplates[tpl.slug] = tpl;
checklistCatalogLoaded = true;
return list;
} catch {
return [];
}
}
async function loadAndRenderChecklistInstances(projectID: string, force = false) {
if (checklistInstancesInited && !force) return;
checklistInstancesInited = true;
try {
const [instResp, tplResp] = await Promise.all([
const [instResp] = await Promise.all([
fetch(`/api/projects/${projectID}/checklists`),
fetch(`/api/checklists`),
loadChecklistCatalog(),
]);
checklistInstances = instResp.ok ? ((await instResp.json()) ?? []) : [];
const templates = tplResp.ok ? (((await tplResp.json()) as ChecklistTemplateSummary[]) ?? []) : [];
checklistTemplates = {};
for (const tpl of templates) checklistTemplates[tpl.slug] = tpl;
} catch {
checklistInstances = [];
}
@@ -1720,6 +1759,143 @@ function renderChecklistInstances() {
});
}
// initAddChecklistModal wires the "Checkliste hinzufügen" button on the
// project-detail Checklists tab (t-paliad-239). Opens a template picker
// modal; on pick, POSTs to /api/checklists/{slug}/instances with the
// current project_id and the template title as the instance name.
function initAddChecklistModal(projectID: string) {
const addBtn = document.getElementById("checklist-add-btn") as HTMLButtonElement | null;
const modal = document.getElementById("add-checklist-modal") as HTMLDivElement | null;
const closeBtn = document.getElementById("add-checklist-close") as HTMLButtonElement | null;
const search = document.getElementById("add-checklist-search") as HTMLInputElement | null;
const list = document.getElementById("add-checklist-list") as HTMLDivElement | null;
const empty = document.getElementById("add-checklist-empty") as HTMLParagraphElement | null;
const modalMsg = document.getElementById("add-checklist-msg") as HTMLParagraphElement | null;
const tabMsg = document.getElementById("project-checklists-msg") as HTMLParagraphElement | null;
if (!addBtn || !modal || !closeBtn || !search || !list || !empty || !modalMsg || !tabMsg) return;
const close = () => {
modal.style.display = "none";
modalMsg.textContent = "";
modalMsg.className = "form-msg";
};
const renderPicker = () => {
const isEN = getLang() === "en";
const q = search.value.trim().toLowerCase();
const all = Object.values(checklistTemplates);
all.sort((a, b) => {
const at = (isEN ? a.titleEN : a.titleDE) || a.slug;
const bt = (isEN ? b.titleEN : b.titleDE) || b.slug;
return at.localeCompare(bt, isEN ? "en" : "de");
});
const filtered = q
? all.filter((tpl) => {
const title = (isEN ? tpl.titleEN : tpl.titleDE) || "";
const desc = (isEN ? tpl.descriptionEN : tpl.descriptionDE) || "";
return title.toLowerCase().includes(q)
|| desc.toLowerCase().includes(q)
|| (tpl.regime || "").toLowerCase().includes(q);
})
: all;
if (filtered.length === 0) {
list.innerHTML = "";
empty.style.display = "";
return;
}
empty.style.display = "none";
list.innerHTML = filtered.map((tpl) => {
const title = (isEN ? tpl.titleEN : tpl.titleDE) || tpl.slug;
const desc = (isEN ? tpl.descriptionEN : tpl.descriptionDE) || "";
const regime = tpl.regime || "";
const regimeChip = regime
? `<span class="checklist-regime checklist-regime-${escapeHtml(regime)}">${escapeHtml(regime)}</span>`
: "";
const descLine = desc ? `<p class="add-checklist-row-desc">${escapeHtml(desc)}</p>` : "";
return `<button type="button" class="add-checklist-row" data-slug="${escapeHtml(tpl.slug)}">
<div class="add-checklist-row-head">
<span class="add-checklist-row-title">${escapeHtml(title)}</span>
${regimeChip}
</div>
${descLine}
</button>`;
}).join("");
list.querySelectorAll<HTMLButtonElement>(".add-checklist-row").forEach((btn) => {
btn.addEventListener("click", () => {
const slug = btn.dataset.slug!;
void pickTemplate(slug, btn);
});
});
};
const pickTemplate = async (slug: string, btn: HTMLButtonElement) => {
const tpl = checklistTemplates[slug];
if (!tpl) return;
const isEN = getLang() === "en";
const name = (isEN ? tpl.titleEN : tpl.titleDE) || tpl.slug;
list.querySelectorAll<HTMLButtonElement>(".add-checklist-row").forEach((b) => {
b.disabled = true;
});
modalMsg.textContent = "";
modalMsg.className = "form-msg";
try {
const resp = await fetch(`/api/checklists/${encodeURIComponent(slug)}/instances`, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ name, project_id: projectID }),
});
if (!resp.ok) {
modalMsg.textContent = t("projects.detail.checklisten.add.error");
modalMsg.className = "form-msg form-msg-error";
list.querySelectorAll<HTMLButtonElement>(".add-checklist-row").forEach((b) => {
b.disabled = false;
});
return;
}
close();
flashTabMsg(t("projects.detail.checklisten.add.created"));
await loadAndRenderChecklistInstances(projectID, true);
} catch {
modalMsg.textContent = t("projects.detail.checklisten.add.error");
modalMsg.className = "form-msg form-msg-error";
list.querySelectorAll<HTMLButtonElement>(".add-checklist-row").forEach((b) => {
b.disabled = false;
});
}
};
let flashTimer = 0;
const flashTabMsg = (text: string) => {
tabMsg.textContent = text;
tabMsg.className = "form-msg form-msg-success";
if (flashTimer) window.clearTimeout(flashTimer);
flashTimer = window.setTimeout(() => {
tabMsg.textContent = "";
tabMsg.className = "form-msg";
}, 3500);
};
addBtn.addEventListener("click", async () => {
await loadChecklistCatalog();
search.value = "";
modalMsg.textContent = "";
modalMsg.className = "form-msg";
renderPicker();
modal.style.display = "flex";
search.focus();
});
closeBtn.addEventListener("click", close);
modal.addEventListener("click", (e) => { if (e.target === e.currentTarget) close(); });
search.addEventListener("input", renderPicker);
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && modal.style.display !== "none") close();
});
}
function escapeHtml(s: string): string {
const d = document.createElement("div");
d.textContent = s;
@@ -1753,9 +1929,14 @@ async function prepareEditForm() {
// as the new parent (server would reject anyway).
await loadParentCandidates(project?.id);
initParentPicker();
await populateProceedingTypeSelect();
}
function openEditModal() {
// openEditModal opens the project-edit modal, optionally scrolling +
// focusing a specific field after the form is prefilled. Callers like
// the Schriftsätze empty-state CTA pass focusFieldID="project-proceeding-
// type-id" to land the user directly on the picker they came to set.
function openEditModal(focusFieldID?: string) {
if (!project) return;
const modal = document.getElementById("project-edit-modal");
const msg = document.getElementById("project-edit-msg");
@@ -1791,6 +1972,19 @@ function openEditModal() {
};
}
renderTypeChangeWarning();
if (focusFieldID) {
// Wait a tick so the modal has laid out before scrolling — the
// wrapping flex container is display:flex so the field's offset
// height is only reliable after the next animation frame.
requestAnimationFrame(() => {
const target = document.getElementById(focusFieldID);
if (!target) return;
target.scrollIntoView({ behavior: "smooth", block: "center" });
if (target instanceof HTMLSelectElement || target instanceof HTMLInputElement) {
target.focus();
}
});
}
});
msg.textContent = "";
msg.className = "form-msg";
@@ -1869,13 +2063,37 @@ function initEditModal() {
const msg = document.getElementById("project-edit-msg") as HTMLParagraphElement | null;
if (!editBtn || !modal || !closeBtn || !cancelBtn || !form || !msg) return;
editBtn.addEventListener("click", openEditModal);
editBtn.addEventListener("click", () => openEditModal());
closeBtn.addEventListener("click", closeEditModal);
cancelBtn.addEventListener("click", closeEditModal);
modal.addEventListener("click", (e) => {
if (e.target === e.currentTarget) closeEditModal();
});
// Schriftsätze empty-state CTA — when the panel reports "no proceeding
// set", clicking the button opens the edit modal directly on the
// Verfahrenstyp picker so the lawyer can resolve the gap in one step
// (t-paliad-232).
const submissionsCTA = document.getElementById(
"project-submissions-edit-cta",
) as HTMLButtonElement | null;
if (submissionsCTA) {
submissionsCTA.addEventListener("click", () => {
openEditModal("project-proceeding-type-id");
});
}
// Verwaltung → Projekt archivieren — opens the edit modal scrolled to
// the danger-zone archive button (t-paliad-245).
const archiveLink = document.getElementById(
"project-settings-archive-link",
) as HTMLButtonElement | null;
if (archiveLink) {
archiveLink.addEventListener("click", () => {
openEditModal("project-delete-btn");
});
}
form.addEventListener("submit", async (e) => {
e.preventDefault();
if (!project) return;
@@ -2092,6 +2310,7 @@ async function main() {
initSmartTimelineClientToggle(id);
initSmartTimelineAddModal(id);
initAttachUnitForm(id);
initAddChecklistModal(id);
initNotesContainer(id);
mountVerlaufFilterBar(id);
wireExportButton(id);
@@ -2507,6 +2726,7 @@ async function loadUserList() {
function renderTeam() {
const body = document.getElementById("team-body")!;
const empty = document.getElementById("team-empty")!;
const mailtoControls = document.getElementById("team-mailto-controls") as HTMLDivElement | null;
// Existing team-body shows the direct + ancestor-inherited members
// returned by /api/projects/{id}/team. The derived + descendant
@@ -2517,12 +2737,21 @@ function renderTeam() {
if (totalRows === 0) {
body.innerHTML = "";
empty.style.display = "";
if (mailtoControls) mailtoControls.style.display = "none";
selectedMailUserIDs.clear();
syncMailtoButton();
syncMasterCheckbox();
renderDescendantStaffed();
renderDerivedMembers();
renderAttachedUnits();
return;
}
empty.style.display = "none";
if (mailtoControls) mailtoControls.style.display = teamMembers.length > 0 ? "" : "none";
// Prune the selection to whoever is actually rendered in team-body
// right now (e.g. a member just got removed). Invariant: selection ⊆
// currently-visible team-body rows.
pruneMailSelectionToVisible();
// t-paliad-223: callers with effective_project_admin authority see an
// inline <select> on the Rolle cell. Everyone else sees the read-only
@@ -2563,7 +2792,17 @@ function renderTeam() {
? renderResponsibilitySelect(m.user_id, responsibility)
: `<span class="projekt-team-responsibility">${esc(responsibilityLabel)}</span>`;
// t-paliad-231: per-row checkbox feeding selectedMailUserIDs. Only
// rows with a real email participate in the mailto: build; rows
// without are still rendered with a disabled checkbox so the
// column geometry stays uniform.
const hasEmail = !!(m.user_email && m.user_email.trim());
const checked = hasEmail && selectedMailUserIDs.has(m.user_id) ? " checked" : "";
const disabled = hasEmail ? "" : " disabled";
const checkboxCell = `<td class="team-col-select"><input type="checkbox" class="team-mail-select" data-user-id="${esc(m.user_id)}" data-email="${escAttr(m.user_email || "")}" aria-label="${escAttr(t("projects.team.mailto.select_row") || "Mitglied auswählen")}"${checked}${disabled} /></td>`;
return `<tr>
${checkboxCell}
<td><strong>${esc(m.user_display_name || m.user_email)}</strong>
<span class="form-hint">&middot; ${esc(m.user_email)}${officeLabel ? " &middot; " + esc(officeLabel) : ""}</span></td>
<td><span class="${profCls}" title="${escAttr(professionTitle)}">${esc(professionLabel)}</span></td>
@@ -2574,6 +2813,21 @@ function renderTeam() {
})
.join("");
// t-paliad-231 — wire row checkboxes + master + mailto button.
body.querySelectorAll<HTMLInputElement>(".team-mail-select").forEach((cb) => {
cb.addEventListener("change", () => {
const userID = cb.dataset.userId!;
if (cb.checked) selectedMailUserIDs.add(userID);
else selectedMailUserIDs.delete(userID);
syncMailtoButton();
syncMasterCheckbox();
});
});
wireMailtoMaster();
wireMailtoButton();
syncMailtoButton();
syncMasterCheckbox();
body.querySelectorAll<HTMLButtonElement>(".team-remove-btn").forEach((btn) => {
btn.addEventListener("click", async () => {
if (!project) return;
@@ -2786,17 +3040,21 @@ function canExportProject(): boolean {
);
}
// wireExportButton reveals + hooks up the project-export button on the
// tabs nav. Triggers a download via a transient <a download> — same
// pattern as the personal export in client/settings.ts.
// wireExportButton reveals the Export sub-section of the Verwaltung tab
// (t-paliad-245) and hooks up the project-export button. Triggers a
// download via a transient <a download> — same pattern as the personal
// export in client/settings.ts.
function wireExportButton(projectID: string): void {
const section = document.getElementById("project-settings-export") as HTMLElement | null;
const btn = document.getElementById("project-export-btn") as HTMLButtonElement | null;
if (!btn) return;
if (!section || !btn) return;
if (!canExportProject()) {
btn.style.display = "none";
section.style.display = "none";
updateSettingsTabVisibility();
return;
}
btn.style.display = "";
section.style.display = "";
updateSettingsTabVisibility();
btn.addEventListener("click", () => {
const a = document.createElement("a");
a.href = `/api/projects/${encodeURIComponent(projectID)}/export`;
@@ -2807,6 +3065,17 @@ function wireExportButton(projectID: string): void {
});
}
// updateSettingsTabVisibility hides the Verwaltung tab when none of its
// sub-sections are visible to the current user — an empty tab is worse
// UX than no tab. Called whenever a sub-section's visibility flips.
function updateSettingsTabVisibility(): void {
const tab = document.querySelector<HTMLElement>('.entity-tab[data-tab="settings"]');
if (!tab) return;
const exportShown = document.getElementById("project-settings-export")?.style.display !== "none";
const archiveShown = document.getElementById("project-settings-archive")?.style.display !== "none";
tab.style.display = exportShown || archiveShown ? "" : "none";
}
function canRemoveTeamMember(m: ProjectTeamMember): boolean {
if (!me) return false;
if (m.user_id === me.id) return true;
@@ -2860,6 +3129,113 @@ async function showTeamErrorToast(resp: Response): Promise<void> {
}, 5000);
}
// t-paliad-231 — mailto: selection helpers for the Team tab. The
// admin-only server SMTP broadcast (POST /api/team/broadcast) lives
// elsewhere; this is the non-admin / quick-CC variant that opens the
// user's local mail client. Pure client; no server call.
function pruneMailSelectionToVisible(): void {
const visible = new Set<string>();
for (const m of teamMembers) {
if (m.user_email && m.user_email.trim()) visible.add(m.user_id);
}
for (const id of Array.from(selectedMailUserIDs)) {
if (!visible.has(id)) selectedMailUserIDs.delete(id);
}
}
function selectedMailRecipients(): BroadcastRecipient[] {
const out: BroadcastRecipient[] = [];
for (const m of teamMembers) {
if (!selectedMailUserIDs.has(m.user_id)) continue;
if (!m.user_email || !m.user_email.trim()) continue;
out.push({
user_id: m.user_id,
email: m.user_email,
display_name: m.user_display_name || m.user_email,
first_name: (m.user_display_name || m.user_email).trim().split(/\s+/)[0] ?? "",
role_on_project: m.responsibility || "member",
});
}
return out;
}
function syncMailtoButton(): void {
const btn = document.getElementById("team-mailto-btn") as HTMLButtonElement | null;
const label = document.getElementById("team-mailto-label") as HTMLSpanElement | null;
if (!btn || !label) return;
const n = selectedMailRecipients().length;
const baseLabel = t("projects.team.mailto.label") || "Mail an Auswahl";
if (n === 0) {
btn.disabled = true;
label.textContent = baseLabel;
btn.title = t("projects.team.mailto.empty") || "Mindestens ein Mitglied auswählen";
} else {
btn.disabled = false;
label.textContent = `${baseLabel} (${n})`;
const tooltip = (t("projects.team.mailto.count") || "{n} ausgewählt").replace("{n}", String(n));
btn.title = tooltip;
}
}
function syncMasterCheckbox(): void {
const master = document.getElementById("team-select-master") as HTMLInputElement | null;
if (!master) return;
// Only count rows that actually rendered with an enabled checkbox —
// members without an email don't participate.
const checkboxes = document.querySelectorAll<HTMLInputElement>(
"#team-body .team-mail-select:not(:disabled)",
);
const total = checkboxes.length;
let selected = 0;
checkboxes.forEach((cb) => {
if (selectedMailUserIDs.has(cb.dataset.userId!)) selected++;
});
master.disabled = total === 0;
if (total === 0 || selected === 0) {
master.checked = false;
master.indeterminate = false;
} else if (selected === total) {
master.checked = true;
master.indeterminate = false;
} else {
master.checked = false;
master.indeterminate = true;
}
}
// wireMailtoMaster is idempotent — registers once via a sentinel data
// attr so re-renders don't stack click handlers.
function wireMailtoMaster(): void {
const master = document.getElementById("team-select-master") as HTMLInputElement | null;
if (!master || master.dataset.wired === "1") return;
master.dataset.wired = "1";
master.addEventListener("change", () => {
const turnOn = master.checked;
document
.querySelectorAll<HTMLInputElement>("#team-body .team-mail-select:not(:disabled)")
.forEach((cb) => {
const id = cb.dataset.userId!;
if (turnOn) selectedMailUserIDs.add(id);
else selectedMailUserIDs.delete(id);
cb.checked = turnOn;
});
syncMailtoButton();
syncMasterCheckbox();
});
}
function wireMailtoButton(): void {
const btn = document.getElementById("team-mailto-btn") as HTMLButtonElement | null;
if (!btn || btn.dataset.wired === "1") return;
btn.dataset.wired = "1";
btn.addEventListener("click", (e) => {
e.preventDefault();
const recipients = selectedMailRecipients();
if (recipients.length === 0) return;
window.location.href = buildMailtoHref(recipients);
});
}
function initTeamForm(id: string) {
const addBtn = document.getElementById("team-add-btn") as HTMLButtonElement | null;
const form = document.getElementById("team-form") as HTMLFormElement | null;

View File

@@ -6,6 +6,7 @@ import {
wireTypeChange,
showFieldsForType,
readPayload,
populateProceedingTypeSelect,
} from "./project-form";
// /projects/new client. Posts v2 CreateProjectInput shape using the shared
@@ -106,5 +107,8 @@ document.addEventListener("DOMContentLoaded", async () => {
await loadParentCandidates();
initParentPicker();
await applyParentFromQueryString();
// Fire-and-forget — the picker is hidden until type=case, so no need
// to block initial render on the fetch.
void populateProceedingTypeSelect();
submitForm();
});

View File

@@ -0,0 +1,87 @@
// rule-label — canonical display contract for deadline rules.
//
// t-paliad-258 / m/paliad#89 addendum. Previously each surface (deadline
// form, list rows, detail header, Schriftsätze tab, browse-a-proceeding)
// invented its own pattern: sometimes citation-only, sometimes name-only,
// sometimes "code — name". m flagged this on the first submissions in a
// proceeding sequence where the inconsistency was most visible.
//
// Canonical pattern: **Name primary, Citation muted secondary**.
// Text: "Notice of Appeal · UPC.RoP.220.1"
// HTML: <span class="rule-label-name">Notice of Appeal</span>
// <span class="rule-label-sep"> · </span>
// <span class="rule-label-cite">UPC.RoP.220.1</span>
//
// Custom rules (t-paliad-258 — free-text label entered by the lawyer):
// formatCustomRuleLabel produces "<text>" with a "Custom" badge slot
// so list/detail surfaces can render both shapes uniformly.
import { getLang, t } from "./i18n";
export interface RuleLike {
name: string;
name_en?: string | null;
// The catalog carries multiple citation fields depending on which
// surface populated it. Order of preference: legal_source > rule_code
// > code. All three are accepted so callers don't have to normalise.
rule_code?: string | null;
code?: string | null;
legal_source?: string | null;
}
// formatRuleLabel returns the canonical plain-text label.
// Falls back gracefully when either side is missing.
export function formatRuleLabel(r: RuleLike): string {
const lang = getLang();
const name = (lang === "en" && r.name_en) ? r.name_en : r.name;
const cite = ruleCitation(r);
if (name && cite) return `${name} · ${cite}`;
return name || cite || "";
}
// formatRuleLabelHTML returns the canonical HTML form with muted-citation
// styling. The caller passes the HTML-escape helper so we don't pull a
// dependency on a specific esc() module — every surface already has one.
export function formatRuleLabelHTML(r: RuleLike, esc: (s: string) => string): string {
const lang = getLang();
const name = (lang === "en" && r.name_en) ? r.name_en : r.name;
const cite = ruleCitation(r);
if (name && cite) {
return (
`<span class="rule-label-name">${esc(name)}</span>` +
`<span class="rule-label-sep"> · </span>` +
`<span class="rule-label-cite">${esc(cite)}</span>`
);
}
return esc(name || cite || "");
}
// ruleCitation returns the best-available citation string for a rule.
// Exported so callers that need the bare code (e.g. CalDAV exports,
// inline data attributes) can pull it without going through the label
// formatter.
export function ruleCitation(r: RuleLike): string {
return r.legal_source || r.rule_code || r.code || "";
}
// formatCustomRuleLabelHTML — render a free-text custom rule label with
// a "Custom" badge slot. Used by surfaces that may display either a
// catalog rule (formatRuleLabelHTML) or a custom one. Returns "" when
// the text is empty so callers can fall through to "—".
export function formatCustomRuleLabelHTML(text: string | null | undefined, esc: (s: string) => string): string {
const trimmed = (text ?? "").trim();
if (!trimmed) return "";
const badge = t("deadlines.field.rule.custom_badge") || "Custom";
return (
`<span class="rule-label-name">${esc(trimmed)}</span>` +
`<span class="rule-label-badge rule-label-badge--custom">${esc(badge)}</span>`
);
}
// formatCustomRuleLabel — plain-text equivalent of the above.
export function formatCustomRuleLabel(text: string | null | undefined): string {
const trimmed = (text ?? "").trim();
if (!trimmed) return "";
const badge = t("deadlines.field.rule.custom_badge") || "Custom";
return `${trimmed} · ${badge}`;
}

View File

@@ -11,6 +11,13 @@ const WIDTH_KEY = "paliad-sidebar-width";
const SIDEBAR_WIDTH_MIN = 180;
const SIDEBAR_WIDTH_MAX = 480;
const SIDEBAR_WIDTH_DEFAULT = 240;
// Per-tab scroll position of the .sidebar-nav scroll container. Persisted
// on every scroll event, restored on initSidebar() so a full-page nav
// click doesn't bounce the user back to the top of a long sidebar
// (Werkzeuge + projects + user views can easily overflow). sessionStorage
// scopes it to the tab — opening a sidebar link in a new tab (Cmd-click)
// starts that tab fresh at the top, which matches user expectation.
const SCROLL_KEY = "paliad.sidebar.scroll";
// toggleMobileSidebar opens or closes the slide-out drawer. Exposed so the
// BottomNav menu slot can call it without duplicating the open/close
@@ -49,6 +56,23 @@ function applySidebarWidth(px: number): void {
document.documentElement.style.setProperty("--sidebar-width", `${px}px`);
}
// readStoredScroll returns the persisted scrollTop or 0 when missing /
// malformed. Bounds are checked at apply time against the actual
// scrollHeight, so a stale value pointing past the current scroll range
// is harmless (the browser clamps assignments to [0, max]).
function readStoredScroll(): number {
const raw = sessionStorage.getItem(SCROLL_KEY);
if (raw === null) return 0;
const n = parseInt(raw, 10);
if (!Number.isFinite(n) || n < 0) return 0;
return n;
}
function applySidebarScroll(nav: HTMLElement, px: number): void {
if (px <= 0) return;
nav.scrollTop = px;
}
// migrateLegacyPinKey copies the pre-rebrand pin state into the new key on
// first load and removes the stale entry. Drop this fallback once the rename
// grace period is over.
@@ -79,6 +103,7 @@ export function initSidebar() {
const sidebar = document.querySelector<HTMLElement>(".sidebar");
if (!sidebar) return;
initSidebarResize(sidebar);
initSidebarScrollRestore(sidebar);
const pinBtn = sidebar.querySelector<HTMLButtonElement>(".sidebar-pin");
const hamburger = document.querySelector<HTMLButtonElement>(".sidebar-hamburger");
@@ -293,6 +318,29 @@ function initSidebarResize(sidebar: HTMLElement): void {
});
}
// initSidebarScrollRestore wires the .sidebar-nav scroll container to
// sessionStorage so the user's scroll position survives a full-page
// navigation (every sidebar link click is a real reload — see m/paliad#85).
// Restore is synchronous on init so the first paint is already at the
// right offset; the passive scroll listener persists subsequent moves.
// reapplySidebarScroll() exists so callers that mutate sidebar content
// async (initUserViewsGroup appending /api/user-views into the Ansichten
// group) can nudge the scroll back to where it was after the layout shift.
function initSidebarScrollRestore(sidebar: HTMLElement): void {
const nav = sidebar.querySelector<HTMLElement>(".sidebar-nav");
if (!nav) return;
applySidebarScroll(nav, readStoredScroll());
nav.addEventListener("scroll", () => {
sessionStorage.setItem(SCROLL_KEY, String(nav.scrollTop));
}, { passive: true });
}
function reapplySidebarScroll(): void {
const nav = document.querySelector<HTMLElement>(".sidebar .sidebar-nav");
if (!nav) return;
applySidebarScroll(nav, readStoredScroll());
}
// Changelog badge — fetches the count of entries newer than the locally
// stored "last seen" stamp and renders a dot + number on the Neuigkeiten
// link. Skipped on the changelog page itself because changelog.ts stamps
@@ -432,6 +480,11 @@ function initUserViewsGroup(): void {
for (const view of views) {
items.appendChild(renderUserViewItem(view, currentPath));
}
// The synchronous restore in initSidebarScrollRestore() happened
// before these views were appended, so a saved scrollTop that
// pointed below the Ansichten group would now sit on the wrong
// row. Re-apply once the layout has stabilised.
reapplySidebarScroll();
// After rendering, kick off count refresh for views that opted in.
for (const view of views) {
if (view.show_count) {

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,130 @@
import { initI18n, onLangChange, t, getLang } from "./i18n";
import { initSidebar } from "./sidebar";
// t-paliad-240 — global Schriftsätze drafts index. Loads
// /api/user/submission-drafts and renders one entity-table row per
// draft. Row click → editor at /projects/{project_id}/submissions/
// {submission_code}/draft/{draft_id}. Per project CLAUDE.md row-click
// contract: a table whose rows look clickable must navigate on click;
// inner links / buttons keep their own affordance.
interface DraftRow {
id: string;
project_id: string | null;
project_title: string | null;
project_reference?: string | null;
submission_code: string;
name: string;
last_exported_at?: string | null;
updated_at: string;
created_at: string;
}
let drafts: DraftRow[] = [];
function esc(s: string): string {
const d = document.createElement("div");
d.textContent = s;
return d.innerHTML;
}
function fmtDate(iso: string): string {
const d = new Date(iso);
if (isNaN(d.getTime())) return "";
const isEN = getLang() === "en";
return d.toLocaleDateString(isEN ? "en-GB" : "de-DE", {
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
minute: "2-digit",
});
}
async function load(): Promise<void> {
const loading = document.getElementById("submissions-index-loading")!;
const empty = document.getElementById("submissions-index-empty")!;
const error = document.getElementById("submissions-index-error")!;
const wrap = document.getElementById("submissions-index-tablewrap")!;
try {
const resp = await fetch("/api/user/submission-drafts");
if (!resp.ok) {
loading.style.display = "none";
error.style.display = "";
return;
}
const data = await resp.json();
drafts = (data.drafts ?? []) as DraftRow[];
} catch {
loading.style.display = "none";
error.style.display = "";
return;
}
loading.style.display = "none";
if (drafts.length === 0) {
empty.style.display = "";
wrap.style.display = "none";
return;
}
empty.style.display = "none";
wrap.style.display = "";
render();
}
function render(): void {
const body = document.getElementById("submissions-index-body")!;
const isEN = getLang() === "en";
const noProjectLabel = isEN ? "(no project)" : "(kein Projekt)";
body.innerHTML = drafts.map((d) => {
const projectCell = (() => {
if (!d.project_id) {
return `<span class="submissions-index-no-project">${esc(noProjectLabel)}</span>`;
}
const title = esc(d.project_title ?? "");
if (d.project_reference) {
return `<a href="/projects/${esc(d.project_id)}" class="checklist-instance-project"><span class="entity-ref">${esc(d.project_reference)}</span> ${title}</a>`;
}
return `<a href="/projects/${esc(d.project_id)}" class="checklist-instance-project">${title}</a>`;
})();
const href = d.project_id
? `/projects/${esc(d.project_id)}/submissions/${esc(d.submission_code)}/draft/${esc(d.id)}`
: `/submissions/draft/${esc(d.id)}`;
return `<tr class="submissions-index-row" data-href="${esc(href)}">
<td>${projectCell}</td>
<td>${esc(d.submission_code)}</td>
<td><a href="${esc(href)}" class="submissions-index-draft-name">${esc(d.name)}</a></td>
<td>${esc(fmtDate(d.updated_at))}</td>
</tr>`;
}).join("");
body.querySelectorAll<HTMLTableRowElement>(".submissions-index-row").forEach((row) => {
const href = row.dataset.href!;
row.addEventListener("click", (e) => {
// Inner <a> elements (project link, draft name) handle their own
// navigation — let the browser dispatch them.
if ((e.target as HTMLElement).closest("a, button")) return;
window.location.href = href;
});
});
// Keep tsc happy for the imported `t` (used only via data-i18n on
// static markup — keep the import so future dynamic strings can hook
// in without re-importing).
void t;
}
document.addEventListener("DOMContentLoaded", () => {
initI18n();
initSidebar();
onLangChange(() => {
if (drafts.length > 0) render();
});
void load();
});

View File

@@ -0,0 +1,368 @@
import { initI18n, getLang } from "./i18n";
import { initSidebar } from "./sidebar";
// t-paliad-243 — client for /submissions/new. Fetches the
// cross-proceeding submission catalog, groups it by proceeding, filters
// by text + chip, and offers two start paths per row: with project
// (modal picker) or without (project-less draft → /submissions/draft/{id}).
interface CatalogEntry {
submission_code: string;
name: string;
name_en: string;
event_type?: string;
primary_party?: string;
legal_source?: string;
has_template: boolean;
proceeding_code: string;
proceeding_name: string;
proceeding_name_en: string;
}
interface CatalogResponse {
entries: CatalogEntry[];
}
interface ProjectRow {
id: string;
title: string;
reference?: string | null;
}
interface State {
entries: CatalogEntry[];
activeProceeding: string | null; // null = all
searchTerm: string;
pickerForCode: string | null;
}
const state: State = {
entries: [],
activeProceeding: null,
searchTerm: "",
pickerForCode: null,
};
function isEN(): boolean {
return getLang() === "en";
}
function esc(s: string): string {
const d = document.createElement("div");
d.textContent = s;
return d.innerHTML;
}
function partyLabel(role: string | undefined): string {
switch ((role ?? "").toLowerCase()) {
case "claimant": return isEN() ? "Claimant" : "Klägerin";
case "defendant": return isEN() ? "Defendant" : "Beklagte";
case "both": return isEN() ? "Both" : "Beide";
case "court": return isEN() ? "Court" : "Gericht";
default: return "";
}
}
async function loadCatalog(): Promise<void> {
const loading = document.getElementById("submissions-new-loading")!;
const error = document.getElementById("submissions-new-error")!;
const wrap = document.getElementById("submissions-new-tablewrap")!;
try {
const resp = await fetch("/api/submissions/catalog");
if (!resp.ok) {
loading.style.display = "none";
error.style.display = "";
return;
}
const data = (await resp.json()) as CatalogResponse;
state.entries = data.entries ?? [];
} catch {
loading.style.display = "none";
error.style.display = "";
return;
}
loading.style.display = "none";
wrap.style.display = "";
renderChips();
renderTable();
}
function renderChips(): void {
const host = document.getElementById("submissions-new-proceeding-chips");
if (!host) return;
const seen = new Map<string, string>();
for (const e of state.entries) {
if (!seen.has(e.proceeding_code)) {
seen.set(e.proceeding_code, isEN() && e.proceeding_name_en ? e.proceeding_name_en : e.proceeding_name);
}
}
const chips: string[] = [];
const allLabel = isEN() ? "All" : "Alle";
const allActive = state.activeProceeding === null;
chips.push(`<button type="button" class="submissions-new-chip${allActive ? " submissions-new-chip--active" : ""}" data-code="">${esc(allLabel)}</button>`);
for (const [code, name] of seen) {
const active = state.activeProceeding === code;
chips.push(`<button type="button" class="submissions-new-chip${active ? " submissions-new-chip--active" : ""}" data-code="${esc(code)}">${esc(name)} <span class="submissions-new-chip-code">${esc(code)}</span></button>`);
}
host.innerHTML = chips.join("");
host.querySelectorAll<HTMLButtonElement>(".submissions-new-chip").forEach((btn) => {
btn.addEventListener("click", () => {
const code = btn.dataset.code ?? "";
state.activeProceeding = code === "" ? null : code;
renderChips();
renderTable();
});
});
}
function filtered(): CatalogEntry[] {
const term = state.searchTerm.trim().toLowerCase();
return state.entries.filter((e) => {
if (state.activeProceeding !== null && e.proceeding_code !== state.activeProceeding) {
return false;
}
if (term === "") return true;
const name = isEN() && e.name_en ? e.name_en : e.name;
const hay = [
name,
e.submission_code,
e.legal_source ?? "",
e.proceeding_code,
e.proceeding_name,
e.proceeding_name_en,
].join(" ").toLowerCase();
return hay.includes(term);
});
}
function renderTable(): void {
const body = document.getElementById("submissions-new-body");
const empty = document.getElementById("submissions-new-empty");
const wrap = document.getElementById("submissions-new-tablewrap");
if (!body || !empty || !wrap) return;
const rows = filtered();
if (rows.length === 0) {
wrap.style.display = "none";
empty.style.display = "";
return;
}
wrap.style.display = "";
empty.style.display = "none";
// Group by proceeding.
const groups = new Map<string, { name: string; entries: CatalogEntry[] }>();
for (const e of rows) {
const gname = isEN() && e.proceeding_name_en ? e.proceeding_name_en : e.proceeding_name;
const bucket = groups.get(e.proceeding_code);
if (bucket) {
bucket.entries.push(e);
} else {
groups.set(e.proceeding_code, { name: gname, entries: [e] });
}
}
const colspan = 4;
const html: string[] = [];
for (const [code, group] of groups) {
html.push(`<tr class="entity-table-group-header"><th colspan="${colspan}" scope="colgroup"><span class="entity-table-group-header__name">${esc(group.name)}</span> <span class="entity-table-group-header__code">${esc(code)}</span></th></tr>`);
for (const entry of group.entries) {
html.push(renderRow(entry));
}
}
body.innerHTML = html.join("");
body.querySelectorAll<HTMLButtonElement>(".submissions-new-start-no-project").forEach((btn) => {
btn.addEventListener("click", () => {
const code = btn.dataset.code;
if (code) void startDraft(code, null);
});
});
body.querySelectorAll<HTMLButtonElement>(".submissions-new-start-with-project").forEach((btn) => {
btn.addEventListener("click", () => {
const code = btn.dataset.code;
if (code) openProjectPicker(code);
});
});
}
function renderRow(entry: CatalogEntry): string {
const name = isEN() && entry.name_en ? entry.name_en : entry.name;
const source = entry.legal_source ?? "";
const templateBadge = entry.has_template
? ""
: ` <span class="submission-template-badge" title="${esc(isEN() ? "Uses the universal style template" : "Verwendet die universelle Stilvorlage")}">${esc(isEN() ? "universal" : "universell")}</span>`;
const withProject = isEN() ? "Mit Projekt…" : "Mit Projekt…";
const noProject = isEN() ? "Ohne Projekt" : "Ohne Projekt";
return `<tr class="submission-row">
<td>
<span class="submission-name">${esc(name)}</span>
<span class="submission-code">${esc(entry.submission_code)}</span>${templateBadge}
</td>
<td>${esc(partyLabel(entry.primary_party))}</td>
<td>${esc(source)}</td>
<td class="submission-action-cell">
<button type="button" class="btn-secondary btn-small submissions-new-start-with-project" data-code="${esc(entry.submission_code)}">${esc(withProject)}</button>
<button type="button" class="btn-primary btn-cta-lime btn-small submissions-new-start-no-project" data-code="${esc(entry.submission_code)}">${esc(noProject)}</button>
</td>
</tr>`;
}
async function startDraft(submissionCode: string, projectID: string | null): Promise<void> {
try {
const resp = await fetch("/api/submission-drafts", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ submission_code: submissionCode, project_id: projectID }),
});
if (!resp.ok) {
let detail = "";
try {
const data = (await resp.json()) as { error?: string };
detail = data.error ?? "";
} catch { /* ignore */ }
alert((isEN() ? "Failed to create draft." : "Entwurf konnte nicht angelegt werden.") + (detail ? `\n\n${detail}` : ""));
return;
}
const view = await resp.json() as { draft: { id: string; project_id: string | null; submission_code: string } };
const id = view.draft.id;
const pid = view.draft.project_id;
const code = view.draft.submission_code;
if (pid) {
window.location.href = `/projects/${pid}/submissions/${encodeURIComponent(code)}/draft/${id}`;
} else {
window.location.href = `/submissions/draft/${id}`;
}
} catch (err) {
console.error("submissions-new createDraft:", err);
alert(isEN() ? "Failed to create draft." : "Entwurf konnte nicht angelegt werden.");
}
}
// ─────────────────────────────────────────────────────────────────────
// Project picker modal
// ─────────────────────────────────────────────────────────────────────
let pickerProjects: ProjectRow[] = [];
let pickerLoaded = false;
function openProjectPicker(submissionCode: string): void {
state.pickerForCode = submissionCode;
const modal = document.getElementById("submissions-new-project-modal");
if (modal) modal.style.display = "";
if (!pickerLoaded) {
void loadPickerProjects();
} else {
renderPickerList();
}
const searchInput = document.getElementById("submissions-new-project-search") as HTMLInputElement | null;
if (searchInput) {
searchInput.value = "";
setTimeout(() => searchInput.focus(), 50);
}
}
function closeProjectPicker(): void {
state.pickerForCode = null;
const modal = document.getElementById("submissions-new-project-modal");
if (modal) modal.style.display = "none";
}
async function loadPickerProjects(): Promise<void> {
const loadingEl = document.getElementById("submissions-new-project-loading");
if (loadingEl) loadingEl.style.display = "";
try {
const resp = await fetch("/api/projects?status=active");
if (!resp.ok) throw new Error(`projects list ${resp.status}`);
const rows = (await resp.json()) as ProjectRow[];
pickerProjects = rows ?? [];
pickerLoaded = true;
} catch (err) {
console.error("submissions-new loadPickerProjects:", err);
pickerProjects = [];
} finally {
if (loadingEl) loadingEl.style.display = "none";
}
renderPickerList();
}
function renderPickerList(): void {
const list = document.getElementById("submissions-new-project-list");
const empty = document.getElementById("submissions-new-project-empty");
if (!list || !empty) return;
const searchInput = document.getElementById("submissions-new-project-search") as HTMLInputElement | null;
const term = (searchInput?.value ?? "").trim().toLowerCase();
const matches = pickerProjects.filter((p) => {
if (term === "") return true;
const hay = [p.title, p.reference ?? ""].join(" ").toLowerCase();
return hay.includes(term);
}).slice(0, 50);
if (matches.length === 0) {
list.innerHTML = "";
empty.style.display = "";
return;
}
empty.style.display = "none";
list.innerHTML = matches.map((p) => {
const ref = p.reference ? `<span class="entity-ref">${esc(p.reference)}</span> ` : "";
return `<li class="submissions-new-project-item" data-id="${esc(p.id)}">${ref}<span class="submissions-new-project-title">${esc(p.title)}</span></li>`;
}).join("");
list.querySelectorAll<HTMLLIElement>(".submissions-new-project-item").forEach((li) => {
li.addEventListener("click", () => {
const pid = li.dataset.id;
const code = state.pickerForCode;
if (pid && code) {
closeProjectPicker();
void startDraft(code, pid);
}
});
});
}
// ─────────────────────────────────────────────────────────────────────
// Boot
// ─────────────────────────────────────────────────────────────────────
function wireToolbar(): void {
const search = document.getElementById("submissions-new-search") as HTMLInputElement | null;
if (search) {
search.addEventListener("input", () => {
state.searchTerm = search.value;
renderTable();
});
}
const closeBtn = document.getElementById("submissions-new-project-modal-close");
if (closeBtn) closeBtn.addEventListener("click", () => closeProjectPicker());
const modal = document.getElementById("submissions-new-project-modal");
if (modal) {
modal.addEventListener("click", (e) => {
if (e.target === modal) closeProjectPicker();
});
}
const pickerSearch = document.getElementById("submissions-new-project-search") as HTMLInputElement | null;
if (pickerSearch) {
pickerSearch.addEventListener("input", () => renderPickerList());
}
document.addEventListener("keydown", (e) => {
if (e.key === "Escape" && state.pickerForCode) closeProjectPicker();
});
}
document.addEventListener("DOMContentLoaded", () => {
initI18n();
initSidebar();
wireToolbar();
void loadCatalog();
});

View File

@@ -1,10 +1,13 @@
// Submissions panel — fetches the project's submission catalog and
// renders one row per filing-type rule, with a [Generieren] action
// when a .docx template resolves server-side.
// Submissions panel — fetches the full submission catalog across every
// proceeding and renders it grouped by proceeding, with the project's
// own proceeding pinned at the top.
//
// t-paliad-215 Slice 1. Loaded lazily by the projects-detail tab
// switcher so projects without the Schriftsätze tab open don't pay
// for the per-row template-availability probes.
// t-paliad-215 Slice 1 introduced the per-project list. t-paliad-242
// broadened it to the catalog: from any project a lawyer can pick a
// Statement of Defence under UPC.INF.CFI, a Klageerwiderung under
// DE.INF.LG, an Opposition under EPO, etc. — the editor (t-paliad-238)
// handles missing variables gracefully via the [KEIN WERT: …] marker,
// so cross-proceeding picks still render cleanly.
function escapeHtml(s: string): string {
return s
@@ -23,11 +26,15 @@ interface SubmissionEntry {
primary_party?: string;
legal_source?: string;
has_template: boolean;
proceeding_code: string;
proceeding_name: string;
proceeding_name_en: string;
}
interface SubmissionListResponse {
project_id: string;
proceeding_type_id?: number;
project_proceeding_code?: string;
entries: SubmissionEntry[];
}
@@ -74,13 +81,13 @@ function render(data: SubmissionListResponse): void {
const body = document.getElementById("project-submissions-body");
if (!empty || !noProc || !wrap || !body) return;
if (data.proceeding_type_id == null || data.proceeding_type_id === 0) {
noProc.style.display = "";
empty.style.display = "none";
wrap.style.display = "none";
return;
}
noProc.style.display = "none";
// t-paliad-242: the catalog is shown to every project regardless of
// whether a proceeding is bound — the no-proceeding hint stays as a
// soft nudge above the table, but no longer hides the catalog.
noProc.style.display = data.proceeding_type_id == null || data.proceeding_type_id === 0
? ""
: "none";
if (data.entries.length === 0) {
empty.style.display = "";
wrap.style.display = "none";
@@ -90,29 +97,56 @@ function render(data: SubmissionListResponse): void {
wrap.style.display = "";
const isEN = document.documentElement.lang === "en";
body.innerHTML = data.entries.map((entry) => {
const name = isEN && entry.name_en ? entry.name_en : entry.name;
const party = formatParty(entry.primary_party, isEN);
const source = entry.legal_source ?? "";
const action = entry.has_template
? `<button type="button" class="btn-primary btn-cta-lime btn-small submission-generate-btn"
data-code="${escapeHtml(entry.submission_code)}"
data-project="${escapeHtml(data.project_id)}"
data-i18n="projects.detail.submissions.action.generate">${isEN ? "Generate" : "Generieren"}</button>`
: `<span class="submission-no-template" data-i18n="projects.detail.submissions.action.no_template">${isEN ? "No template" : "Keine Vorlage"}</span>`;
return `<tr class="submission-row">
<td>
<span class="submission-name">${escapeHtml(name)}</span>
<span class="submission-code">${escapeHtml(entry.submission_code)}</span>
</td>
<td>${escapeHtml(party)}</td>
<td>${escapeHtml(source)}</td>
<td class="submission-action-cell">${action}</td>
</tr>`;
}).join("");
// Wire button clicks. One click handler per render to avoid stale
// closures from the previous render's data.
// Group entries by proceeding_code. Build a stable group order:
// project's own proceeding first (when present), then alphabetical
// by proceeding_code for the rest.
const groups = new Map<string, { name: string; entries: SubmissionEntry[] }>();
for (const entry of data.entries) {
const key = entry.proceeding_code || "";
const groupName = isEN && entry.proceeding_name_en
? entry.proceeding_name_en
: entry.proceeding_name;
const bucket = groups.get(key);
if (bucket) {
bucket.entries.push(entry);
} else {
groups.set(key, { name: groupName, entries: [entry] });
}
}
const ownCode = data.project_proceeding_code ?? "";
const orderedCodes: string[] = [];
if (ownCode && groups.has(ownCode)) orderedCodes.push(ownCode);
for (const code of Array.from(groups.keys()).sort()) {
if (code !== ownCode) orderedCodes.push(code);
}
const ownSuffix = isEN ? " (this project)" : " (dieses Projekt)";
const colspan = 4;
const html: string[] = [];
for (const code of orderedCodes) {
const group = groups.get(code);
if (!group) continue;
const isOwn = code === ownCode;
const label = group.name + (isOwn ? ownSuffix : "");
const headerClass = isOwn
? "entity-table-group-header entity-table-group-header--own"
: "entity-table-group-header";
html.push(`<tr class="${headerClass}">`
+ `<th colspan="${colspan}" scope="colgroup">`
+ `<span class="entity-table-group-header__name">${escapeHtml(label)}</span>`
+ ` <span class="entity-table-group-header__code">${escapeHtml(code)}</span>`
+ `</th></tr>`);
for (const entry of group.entries) {
html.push(renderRow(entry, data.project_id, isEN));
}
}
body.innerHTML = html.join("");
// Wire button clicks. One handler per render to avoid stale closures
// from the previous render's data.
body.querySelectorAll<HTMLButtonElement>(".submission-generate-btn").forEach((btn) => {
btn.addEventListener("click", (e) => {
e.preventDefault();
@@ -122,6 +156,33 @@ function render(data: SubmissionListResponse): void {
});
}
function renderRow(entry: SubmissionEntry, projectID: string, isEN: boolean): string {
const name = isEN && entry.name_en ? entry.name_en : entry.name;
const party = formatParty(entry.primary_party, isEN);
const source = entry.legal_source ?? "";
const draftHref = `/projects/${encodeURIComponent(projectID)}/submissions/${encodeURIComponent(entry.submission_code)}/draft`;
const templateBadge = entry.has_template
? ""
: ` <span class="submission-template-badge" title="${isEN ? "Uses the universal style template" : "Verwendet die universelle Stilvorlage"}">${isEN ? "universal" : "universell"}</span>`;
const editBtn = `<a href="${escapeHtml(draftHref)}" class="btn-primary btn-cta-lime btn-small submission-edit-btn"
data-code="${escapeHtml(entry.submission_code)}"
data-i18n="projects.detail.submissions.action.edit">${isEN ? "Edit" : "Bearbeiten"}</a>`;
const generateBtn = `<button type="button" class="btn-secondary btn-small submission-generate-btn"
data-code="${escapeHtml(entry.submission_code)}"
data-project="${escapeHtml(projectID)}"
data-i18n="projects.detail.submissions.action.generate">${isEN ? "Generate" : "Generieren"}</button>`;
const action = `${editBtn} ${generateBtn}`;
return `<tr class="submission-row">
<td>
<span class="submission-name">${escapeHtml(name)}</span>
<span class="submission-code">${escapeHtml(entry.submission_code)}</span>${templateBadge}
</td>
<td>${escapeHtml(party)}</td>
<td>${escapeHtml(source)}</td>
<td class="submission-action-cell">${action}</td>
</tr>`;
}
function renderError(): void {
const empty = document.getElementById("project-submissions-empty");
const noProc = document.getElementById("project-submissions-no-proceeding");
@@ -159,7 +220,7 @@ async function onGenerateClick(btn: HTMLButtonElement): Promise<void> {
try {
const url = `/api/projects/${projectID}/submissions/${encodeURIComponent(code)}/generate`;
const resp = await fetch(url, { method: "GET" });
const resp = await fetch(url, { method: "POST" });
if (!resp.ok) {
let detail = "";
try {

View File

@@ -1,6 +1,6 @@
import { initI18n, onLangChange, t, tDyn } from "./i18n";
import { initSidebar } from "./sidebar";
import { openBroadcastModal, firstName, type BroadcastRecipient } from "./broadcast";
import { openBroadcastModal, firstName, buildMailtoHref, type BroadcastRecipient } from "./broadcast";
interface User {
id: string;
@@ -341,28 +341,64 @@ function buildProjectFilter() {
function buildBroadcastButton() {
const wrap = document.getElementById("team-broadcast-wrap");
if (!wrap) return;
if (!canBroadcast()) {
// Wait for /api/me so the affordance never flickers between admin (form)
// and non-admin (mailto) on initial paint. canBroadcast() already returns
// false when me is null but we'd briefly render the mailto anchor before
// the admin form, which is visually jarring.
if (!me) {
wrap.innerHTML = "";
wrap.style.display = "none";
return;
}
wrap.style.display = "";
wrap.innerHTML = `
<button type="button" class="btn btn-primary" id="team-broadcast-btn">
${esc(t("team.broadcast.button") || "E-Mail an Auswahl")} <span class="team-broadcast-count" id="team-broadcast-count">0</span>
</button>
`;
document.getElementById("team-broadcast-btn")?.addEventListener("click", () => onBroadcastClick());
const label = esc(t("team.broadcast.button") || "E-Mail an Auswahl");
const counter = `<span class="team-broadcast-count" id="team-broadcast-count">0</span>`;
if (canBroadcast()) {
// Admin path (global_admin or project-lead-of-selected): opens the
// in-app compose modal that POSTs to /api/team/broadcast.
wrap.innerHTML = `
<button type="button" class="btn btn-primary" id="team-broadcast-btn">
${label} ${counter}
</button>
`;
document.getElementById("team-broadcast-btn")?.addEventListener("click", () => onBroadcastClick());
} else {
// Non-admin path (t-paliad-244): native mailto: anchor pre-filled with
// the current filter set. href is refreshed in updateBroadcastButton()
// whenever filters change so the link always reflects what's visible.
wrap.innerHTML = `
<a class="btn btn-primary" id="team-broadcast-btn" href="mailto:">
${label} ${counter}
</a>
`;
}
}
function updateBroadcastButton() {
buildBroadcastButton();
const recipients = displayedRecipients();
const countEl = document.getElementById("team-broadcast-count");
if (countEl) {
const n = displayedRecipients().length;
countEl.textContent = String(n);
const btn = document.getElementById("team-broadcast-btn") as HTMLButtonElement | null;
if (btn) btn.disabled = n === 0;
if (countEl) countEl.textContent = String(recipients.length);
const btn = document.getElementById("team-broadcast-btn");
if (!btn) return;
if (btn.tagName === "BUTTON") {
(btn as HTMLButtonElement).disabled = recipients.length === 0;
} else {
// Anchor (non-admin): regenerate the mailto: href against the current
// visible recipients, and disable the affordance when empty so a click
// doesn't open an empty mail composer.
const a = btn as HTMLAnchorElement;
if (recipients.length === 0) {
a.setAttribute("href", "mailto:");
a.setAttribute("aria-disabled", "true");
a.style.pointerEvents = "none";
a.style.opacity = "0.5";
} else {
a.setAttribute("href", buildMailtoHref(recipients));
a.removeAttribute("aria-disabled");
a.style.pointerEvents = "";
a.style.opacity = "";
}
}
}
@@ -673,14 +709,21 @@ function renderSelectionFooter(): void {
"{n}",
String(n),
);
const sendLabel = esc(t("team.selection.send") || "E-Mail an Auswahl");
// t-paliad-244: mirror buildBroadcastButton() so the bottom send button
// behaves the same as the filter-bar one. Admin (canBroadcast) opens the
// compose modal; non-admin gets a native mailto: anchor pre-filled with
// the explicit selection.
const adminPath = canBroadcast();
const sendAction = adminPath
? `<button type="button" class="btn-primary" id="team-selection-send">${sendLabel}</button>`
: `<a class="btn-primary" id="team-selection-send" href="${buildMailtoHref(selectedRecipients())}">${sendLabel}</a>`;
footer.innerHTML = `
<span class="team-selection-count">${esc(countLabel)}</span>
<button type="button" class="btn-secondary btn-small" id="team-selection-clear">
${esc(t("team.selection.clear") || "Auswahl aufheben")}
</button>
<button type="button" class="btn-primary" id="team-selection-send">
${esc(t("team.selection.send") || "E-Mail an Auswahl")}
</button>
${sendAction}
`;
footer.style.display = "";
document.body.classList.add("team-has-selection");
@@ -691,9 +734,12 @@ function renderSelectionFooter(): void {
syncMasterCheckbox();
renderSelectionFooter();
});
document.getElementById("team-selection-send")?.addEventListener("click", () => {
onBroadcastFromSelection();
});
if (adminPath) {
document.getElementById("team-selection-send")?.addEventListener("click", () => {
onBroadcastFromSelection();
});
}
// Anchor path has no click handler — native href open is the action.
}
// selectedRecipients maps the explicit selection Set into the

View File

@@ -12,6 +12,7 @@ import { initI18n, t, tDyn, getLang, onLangChange } from "./i18n";
import { initSidebar } from "./sidebar";
import {
type DeadlineResponse,
type Side,
calculateDeadlines,
escHtml,
formatDate,
@@ -24,6 +25,70 @@ import {
let selectedType = "";
let lastResponse: DeadlineResponse | null = null;
// Perspective state (t-paliad-250 / m/paliad#81). URL-driven so the
// view is shareable and survives reload:
// ?side=claimant|defendant → swaps which column owns the user's
// side (proactive vs reactive label).
// Default null = claimant-on-the-left.
// ?appellant=claimant|defendant → collapses party=both rows into the
// appellant's column (no mirror).
// Only meaningful for role-swap
// proceedings (Appeal etc.). Default
// null = legacy mirror behaviour.
let currentSide: Side = null;
let currentAppellant: Side = null;
// Proceedings where one party initiates and "both" rows are role-swap
// (i.e. either party files depending on who acted at the lower
// instance). For these proceedings the appellant selector is meaningful
// — when set, "both" rows collapse to a single row in the appellant's
// column. For first-instance proceedings (Inf, Rev, …) the selector is
// hidden because there's no appellant axis.
//
// Today: every upc.apl.* family member plus dpma.appeal.* and
// de.inf.olg / de.inf.bgh / de.null.bgh (DE Berufung / Revision).
// Conservative — false negatives just hide a control; false positives
// would show an irrelevant control.
const APPELLANT_AXIS_PROCEEDINGS = new Set([
"upc.apl.merits",
"upc.apl.cost",
"upc.apl.order",
"de.inf.olg",
"de.inf.bgh",
"de.null.bgh",
"dpma.appeal.bpatg",
"dpma.appeal.bgh",
"epa.opp.boa",
]);
function hasAppellantAxis(proceedingType: string): boolean {
return APPELLANT_AXIS_PROCEEDINGS.has(proceedingType);
}
function readSideFromURL(): Side {
const raw = new URLSearchParams(window.location.search).get("side");
return raw === "claimant" || raw === "defendant" ? raw : null;
}
function readAppellantFromURL(): Side {
const raw = new URLSearchParams(window.location.search).get("appellant");
return raw === "claimant" || raw === "defendant" ? raw : null;
}
function writeSideToURL(s: Side) {
const url = new URL(window.location.href);
if (s === null) url.searchParams.delete("side");
else url.searchParams.set("side", s);
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
}
function writeAppellantToURL(a: Side) {
const url = new URL(window.location.href);
if (a === null) url.searchParams.delete("appellant");
else url.searchParams.set("appellant", a);
window.history.replaceState(null, "", url.pathname + (url.search ? url.search : "") + url.hash);
}
// Per-rule anchor overrides set by the click-to-edit affordance on
// timeline / column date cells. Posted as `anchorOverrides` to the
// /api/tools/fristenrechner calc so downstream rules re-anchor off the
@@ -154,20 +219,31 @@ async function doCalc() {
}
// triggerEventLabelFor picks the user-facing "Auslösendes Ereignis"
// label from the calc response. The root rule (isRootEvent=true) is
// the first event in the proceeding — e.g. Klageerhebung for
// upc.inf.cfi, Nichtigkeitsklage for upc.rev.cfi. Falls back to the
// active proceeding name if no root rule fires (shouldn't happen for
// healthy data, but safer than a blank). Fallback respects language —
// proceedingNameEN is consulted on EN before the DE proceedingName
// (m/paliad#58: prior fallback rendered DE on EN for sub-track
// proceedings like upc.ccr.cfi which had no rules → no root).
// label from the calc response. Precedence:
//
// 1. Server-supplied triggerEventLabel from proceeding_types
// (mig 121, m/paliad#81). UPC Appeal sets this to
// "Anfechtbare Entscheidung" / "Appealable Decision" — its rules
// all carry a non-zero duration off the trigger date so none is
// the root, and the proceedingName fallback ("Berufungsverfahren")
// misnamed the input as the proceeding itself.
// 2. Root rule (isRootEvent=true) — the first event in the
// proceeding, e.g. Klageerhebung for upc.inf.cfi,
// Nichtigkeitsklage for upc.rev.cfi.
// 3. Active proceeding name — last-resort fallback. Language-aware
// (m/paliad#58: prior code rendered DE on EN for sub-track
// proceedings like upc.ccr.cfi which had no rules → no root).
function triggerEventLabelFor(data: DeadlineResponse): string {
const lang = getLang();
const curated = lang === "en"
? (data.triggerEventLabelEN || data.triggerEventLabel)
: (data.triggerEventLabel || data.triggerEventLabelEN);
if (curated) return curated;
const root = data.deadlines.find((d) => d.isRootEvent);
if (root) {
return getLang() === "en" ? (root.nameEN || root.name) : (root.name || root.nameEN);
return lang === "en" ? (root.nameEN || root.name) : (root.name || root.nameEN);
}
if (getLang() === "en") {
if (lang === "en") {
return data.proceedingNameEN || data.proceedingName || "";
}
return data.proceedingName || data.proceedingNameEN || "";
@@ -213,7 +289,12 @@ function renderResults(data: DeadlineResponse) {
: "";
const bodyHtml = procedureView === "columns"
? renderColumnsBody(data, { editable: true, showNotes })
? renderColumnsBody(data, {
editable: true,
showNotes,
side: currentSide,
appellant: hasAppellantAxis(selectedType) ? currentAppellant : null,
})
: renderTimelineBody(data, { showParty: true, editable: true, showNotes });
container.innerHTML = headerHtml + noteHtml + bodyHtml;
@@ -276,6 +357,7 @@ function selectProceeding(btn: HTMLButtonElement) {
void populateCourtPicker("court-picker-row", "court-picker", selectedType);
syncFlagRows();
syncAppellantRowVisibility();
setProceedingPickerCollapsed(true, proceedingDisplayName(btn));
@@ -283,18 +365,53 @@ function selectProceeding(btn: HTMLButtonElement) {
scheduleCalc(0);
}
// syncAppellantRowVisibility hides the appellant selector for
// proceedings that have no appellant axis (first-instance Inf, Rev,
// …). Clears the in-memory state and the URL param when hidden so a
// shared link with ?appellant= doesn't leak into an unrelated
// proceeding's render.
function syncAppellantRowVisibility() {
const row = document.getElementById("appellant-row");
if (!row) return;
const visible = hasAppellantAxis(selectedType);
row.style.display = visible ? "" : "none";
if (!visible && currentAppellant !== null) {
currentAppellant = null;
writeAppellantToURL(null);
syncRadioGroup("appellant", "");
}
}
function syncRadioGroup(name: string, value: string) {
document.querySelectorAll<HTMLInputElement>(`input[type=radio][name=${name}]`).forEach((input) => {
input.checked = input.value === value;
});
}
function applyVerfahrensablaufViewBodyClass(view: ProcedureView) {
// Mirrors the events.ts pattern (body.events-view-*). The print
// stylesheet keys `body.verfahrensablauf-view-timeline` to
// `@page paliad-landscape`, so flipping this class is what lets a
// user print the horizontal timeline in landscape without affecting
// the columns view (which stays portrait).
document.body.classList.toggle("verfahrensablauf-view-timeline", view === "timeline");
document.body.classList.toggle("verfahrensablauf-view-columns", view === "columns");
}
function initViewToggle() {
const toggle = document.getElementById("fristen-view-toggle");
if (!toggle) return;
const initial = new URLSearchParams(window.location.search).get("view");
if (initial === "timeline") procedureView = "timeline";
applyVerfahrensablaufViewBodyClass(procedureView);
toggle.querySelectorAll<HTMLInputElement>("input[name=fristen-view]").forEach((input) => {
input.checked = input.value === procedureView;
input.addEventListener("change", () => {
if (!input.checked) return;
procedureView = input.value === "columns" ? "columns" : "timeline";
applyVerfahrensablaufViewBodyClass(procedureView);
const url = new URL(window.location.href);
if (procedureView === "columns") {
url.searchParams.delete("view");
@@ -309,6 +426,38 @@ function initViewToggle() {
toggle.style.display = "none";
}
// initPerspectiveControls hydrates side+appellant from the URL,
// reflects state into the radio inputs, and wires onchange handlers
// that update state + URL + re-render. Re-render path skips the
// /api/tools/fristenrechner round-trip — perspective is a pure
// projection of the last response, no backend involved.
function initPerspectiveControls() {
currentSide = readSideFromURL();
currentAppellant = readAppellantFromURL();
syncRadioGroup("side", currentSide ?? "");
syncRadioGroup("appellant", currentAppellant ?? "");
document.querySelectorAll<HTMLInputElement>("input[type=radio][name=side]").forEach((input) => {
input.addEventListener("change", () => {
if (!input.checked) return;
const v = input.value;
currentSide = (v === "claimant" || v === "defendant") ? v : null;
writeSideToURL(currentSide);
if (lastResponse) renderResults(lastResponse);
});
});
document.querySelectorAll<HTMLInputElement>("input[type=radio][name=appellant]").forEach((input) => {
input.addEventListener("change", () => {
if (!input.checked) return;
const v = input.value;
currentAppellant = (v === "claimant" || v === "defendant") ? v : null;
writeAppellantToURL(currentAppellant);
if (lastResponse) renderResults(lastResponse);
});
});
}
document.addEventListener("DOMContentLoaded", () => {
initI18n();
initSidebar();
@@ -378,6 +527,7 @@ document.addEventListener("DOMContentLoaded", () => {
}
initViewToggle();
initPerspectiveControls();
onLangChange(() => {
// Active-button name updates with language change (the data-i18n

View File

@@ -204,6 +204,12 @@ function setActiveShape(shape: RenderShape | null): void {
document.querySelectorAll<HTMLButtonElement>("#views-shape-chips [data-shape]").forEach((btn) => {
btn.classList.toggle("active", btn.dataset.shape === shape);
});
// Mirror the active shape on <body> so the print stylesheet can opt
// calendar / timeline into landscape (`@page paliad-landscape`) while
// list / cards stay portrait — t-paliad-233.
for (const s of ["list", "cards", "calendar", "timeline"]) {
document.body.classList.toggle(`views-shape-active-${s}`, shape === s);
}
}
let timelineHandle: ChartHandle | null = null;

View File

@@ -147,8 +147,22 @@ function formatColumn(row: ViewRow, col: string): string {
const s = (row.detail.status as string | undefined) ?? "";
return s ? t(("deadlines.status." + s) as I18nKey) : "—";
}
case "rule":
return (row.detail.rule_code as string | undefined) ?? "—";
case "rule": {
// t-paliad-258 — canonical "Name · Citation" pattern; fall back
// to custom_rule_text + " · Custom" for Custom-mode deadlines.
const lang = getLang();
const nameKey = lang === "en" ? "rule_name_en" : "rule_name";
const name = (row.detail[nameKey] as string | undefined)
|| (row.detail.rule_name as string | undefined)
|| "";
const cite = (row.detail.rule_code as string | undefined) ?? "";
if (name && cite) return `${name} · ${cite}`;
if (name) return name;
if (cite) return cite;
const custom = (row.detail.custom_rule_text as string | undefined) ?? "";
if (custom.trim()) return `${custom} · Custom`;
return "—";
}
case "event_type":
return (row.detail.event_type as string | undefined) ?? "—";
case "location":

View File

@@ -99,6 +99,21 @@ export interface PredecessorMissingPayload {
message_en: string;
}
// t-paliad-237 — server tells us the anchored rule belongs to the
// parent infringement project, not this CCR. Frontend renders the
// message with a clickable link to the parent project.
export interface CrossProceedingAnchorPayload {
error: "cross_proceeding_anchor";
requested_rule_code: string;
requested_rule_name_de: string;
requested_rule_name_en: string;
parent_project_id: string;
parent_project_title: string;
parent_project_url: string;
message_de: string;
message_en: string;
}
export interface RenderOptions {
// Today's date as ISO YYYY-MM-DD; defaults to "now in browser TZ".
today?: string;
@@ -822,7 +837,13 @@ function buildAnchorEditor(
return;
}
if (resp.status === 409) {
const payload = (await resp.json()) as PredecessorMissingPayload;
const payload = (await resp.json()) as
| PredecessorMissingPayload
| CrossProceedingAnchorPayload;
if (payload.error === "cross_proceeding_anchor") {
renderCrossProceedingError(msg, payload, opts);
return;
}
renderPredecessorError(msg, payload, ev, opts, dateInput, submit, cancel);
return;
}
@@ -886,6 +907,34 @@ function renderPredecessorError(
msg.appendChild(link);
}
// t-paliad-237 — rule belongs to the parent inf project, not this CCR.
// Render the bilingual message + a link to the parent project so the
// user can navigate over and anchor the rule there. We deliberately do
// NOT auto-route the write across projects (out of scope per brief).
function renderCrossProceedingError(
msg: HTMLElement,
payload: CrossProceedingAnchorPayload,
opts: RenderOptions,
): void {
msg.innerHTML = "";
msg.classList.add("smart-timeline-anchor-msg--error");
msg.classList.add("smart-timeline-anchor-msg--cross-proceeding");
const lang = (opts.lang ?? getLang()) === "en" ? "en" : "de";
const main = document.createElement("p");
main.textContent = lang === "en" ? payload.message_en : payload.message_de;
msg.appendChild(main);
const link = document.createElement("a");
link.className = "smart-timeline-anchor-parent-link";
link.href = payload.parent_project_url;
link.textContent =
lang === "en"
? `Open „${payload.parent_project_title}`
: `${payload.parent_project_title}“ öffnen`;
msg.appendChild(link);
}
function findRowForRuleCode(ruleCode: string): HTMLElement | null {
const rows = document.querySelectorAll<HTMLElement>(".smart-timeline-row");
for (const r of Array.from(rows)) {

View File

@@ -1,6 +1,7 @@
import { describe, expect, test } from "bun:test";
import {
type CalculatedDeadline,
bucketDeadlinesIntoColumns,
deadlineCardHtml,
} from "./verfahrensablauf-core";
@@ -65,3 +66,141 @@ describe("deadlineCardHtml — editable=true emits click-to-edit attrs", () => {
expect(html).not.toContain("data-rule-code=");
});
});
// Pure column-routing behaviour. Originally pinned by m/paliad#81
// (side + appellant axes), re-framed by m/paliad#88: the column
// axis is now "Unsere Seite vs Gegnerseite" ("WE always on the
// left") instead of the misleading Proaktiv/Reaktiv pair.
// Hits bucketDeadlinesIntoColumns directly so the assertions stay
// in pure-Node territory (renderColumnsBody goes through escHtml ->
// document.createElement which isn't available in plain bun test).
//
// Scenario fixture mirrors the UPC Appeal "both parties" case m
// pasted into #81: every filing rule carries party='both' so the
// legacy mirror path duplicates every row across both columns.
// With ?appellant= set, the duplicate must collapse to a single
// row in the appellant's column.
describe("bucketDeadlinesIntoColumns — side+appellant column routing (m/paliad#81, #88)", () => {
const both = (name: string, due: string): CalculatedDeadline => ({
code: name,
name,
nameEN: name,
party: "both",
priority: "mandatory",
ruleRef: "",
dueDate: due,
originalDate: due,
wasAdjusted: false,
isRootEvent: false,
isCourtSet: false,
});
const partySpecific = (party: string, name: string, due: string): CalculatedDeadline => ({
...both(name, due),
party,
});
test("default (no opts) mirrors 'both' rules into ours AND opponent — legacy behaviour preserved", () => {
const rows = bucketDeadlinesIntoColumns([both("Notice of Appeal", "2026-07-23")]);
expect(rows).toHaveLength(1);
expect(rows[0].ours.map((d) => d.name)).toEqual(["Notice of Appeal"]);
expect(rows[0].opponent.map((d) => d.name)).toEqual(["Notice of Appeal"]);
expect(rows[0].court).toHaveLength(0);
});
test("default (no side) places claimant on the left (ours) — 'we are claimant' fallback", () => {
const rows = bucketDeadlinesIntoColumns([
partySpecific("claimant", "Klageschrift", "2026-01-01"),
partySpecific("defendant", "Klageerwiderung", "2026-04-01"),
]);
expect(rows[0].ours.map((d) => d.name)).toEqual(["Klageschrift"]);
expect(rows[1].opponent.map((d) => d.name)).toEqual(["Klageerwiderung"]);
});
test("appellant=claimant collapses 'both' rules into ours when side=claimant (or default)", () => {
const rows = bucketDeadlinesIntoColumns(
[both("Notice of Appeal", "2026-07-23"), both("Statement of Grounds", "2026-09-23")],
{ appellant: "claimant" },
);
expect(rows.map((r) => r.ours.map((d) => d.name))).toEqual([
["Notice of Appeal"],
["Statement of Grounds"],
]);
rows.forEach((r) => expect(r.opponent).toHaveLength(0));
});
test("appellant=defendant collapses 'both' rules into opponent when side=null/claimant", () => {
const rows = bucketDeadlinesIntoColumns(
[both("Notice of Appeal", "2026-07-23")],
{ appellant: "defendant" },
);
expect(rows[0].ours).toHaveLength(0);
expect(rows[0].opponent.map((d) => d.name)).toEqual(["Notice of Appeal"]);
});
test("side=defendant flips which party owns 'ours' vs 'opponent' — WE always on the left", () => {
// User is on the defendant side: defendant filings land in 'ours'
// (left), claimant filings land in 'opponent' (right). Court rules
// stay in court regardless of side.
const rows = bucketDeadlinesIntoColumns(
[
partySpecific("claimant", "Klageschrift", "2026-01-01"),
partySpecific("defendant", "Klageerwiderung", "2026-04-01"),
partySpecific("court", "Urteil", "2026-10-01"),
],
{ side: "defendant" },
);
expect(rows[0].opponent.map((d) => d.name)).toEqual(["Klageschrift"]);
expect(rows[1].ours.map((d) => d.name)).toEqual(["Klageerwiderung"]);
expect(rows[2].court.map((d) => d.name)).toEqual(["Urteil"]);
});
test("side=defendant + appellant=defendant routes 'both' into 'ours' (user's own column)", () => {
// The user is the defendant AND the appellant, so the appellant's
// column == the user's own column == ours after the swap.
const rows = bucketDeadlinesIntoColumns(
[both("Notice of Appeal", "2026-07-23")],
{ side: "defendant", appellant: "defendant" },
);
expect(rows[0].ours.map((d) => d.name)).toEqual(["Notice of Appeal"]);
expect(rows[0].opponent).toHaveLength(0);
});
test("side=defendant + appellant=claimant routes 'both' into opponent (claimant ≠ us)", () => {
// Side flip + appellant axis combined: the claimant is the appellant
// but NOT us, so the collapsed 'both' row lands in the opponent
// column (right). This is the UPC Appeal "they appealed, we
// respond" scenario.
const rows = bucketDeadlinesIntoColumns(
[both("Notice of Appeal", "2026-07-23")],
{ side: "defendant", appellant: "claimant" },
);
expect(rows[0].opponent.map((d) => d.name)).toEqual(["Notice of Appeal"]);
expect(rows[0].ours).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([
partySpecific("claimant", "A", sameDate),
partySpecific("defendant", "B", sameDate),
partySpecific("court", "C", sameDate),
]);
expect(rows).toHaveLength(1);
expect(rows[0].ours.map((d) => d.name)).toEqual(["A"]);
expect(rows[0].opponent.map((d) => d.name)).toEqual(["B"]);
expect(rows[0].court.map((d) => d.name)).toEqual(["C"]);
});
test("unscheduled rows (no dueDate) trail dated rows, preserving declaration order", () => {
const rows = bucketDeadlinesIntoColumns([
partySpecific("court", "Oral Hearing", ""),
partySpecific("claimant", "Statement of Claim", "2026-01-01"),
partySpecific("court", "Decision", ""),
]);
expect(rows.map((r) => [r.ours, r.court, r.opponent].flat().map((d) => d.name))).toEqual([
["Statement of Claim"],
["Oral Hearing"],
["Decision"],
]);
});
});

View File

@@ -110,6 +110,16 @@ export interface DeadlineResponse {
// explains the framing. (m/paliad#58)
contextualNote?: string;
contextualNoteEN?: string;
// triggerEventLabel / triggerEventLabelEN: optional caption for the
// "Auslösendes Ereignis" / "Triggering event" field on
// /tools/verfahrensablauf. Populated from paliad.proceeding_types
// when set (mig 121). The page prefers this over the proceedingName
// fallback that fires when no rule has isRootEvent=true. UPC Appeal
// uses this so the field reads "Anfechtbare Entscheidung" /
// "Appealable Decision" instead of "Berufungsverfahren" / "Appeal".
// (m/paliad#81)
triggerEventLabel?: string;
triggerEventLabelEN?: string;
}
export interface CourtRow {
@@ -412,42 +422,124 @@ export function renderTimelineBody(data: DeadlineResponse, opts: CardOpts = { sh
return html;
}
// Three-column timeline layout: Proactive (claimant) | Court | Reactive
// (defendant). Each grid row shares a dueDate so same-day events line up
// across columns; party=both renders in BOTH the Proactive and Reactive
// cells of the row. Undated rows (Urteil etc.) trail the dated tail, each
// keyed by sequence-order so e.g. Urteil precedes Berufungseinlegung.
export function renderColumnsBody(data: DeadlineResponse, opts: Omit<CardOpts, "showParty"> = {}): string {
type Cell = CalculatedDeadline[];
type Row = { proactive: Cell; court: Cell; reactive: Cell };
// Three-column timeline layout: Unsere Seite | Gericht | Gegnerseite.
//
// The columns are user-perspective ("WE are always on the left", per
// t-paliad-257 / m/paliad#88). The old Proaktiv/Reaktiv axis lied:
// Klägerseite is sometimes proactive (filing the claim) and sometimes
// reactive (responding to a counterclaim), so the static "Proaktiv =
// Klägerseite" label-pair was wrong half the time. The new axis is
// "ours vs opponent" — the side toggle picks who WE are in this
// proceeding (Klägerseite vs Beklagtenseite, i.e. patentee vs alleged
// infringer / Einsprechender vs Patentinhaber, etc.), and rule
// placement re-resolves around that pick.
//
// Column assignment per deadline (default opts.side === null keeps
// the legacy claimant-on-the-left layout — i.e. "we are claimant"):
//
// - party=claimant → ours when side ∈ {null,"claimant"}, else opponent
// - party=defendant → opponent when side ∈ {null,"claimant"}, else ours
// - party=court → court (independent of side)
// - party=both → BOTH ours AND opponent (mirror)
//
// When `opts.appellant` is set (claimant|defendant), "both" rows
// collapse to a single row in the appellant's column — the intent is
// role-swap proceedings (UPC Appeal, Counterclaim, …) where "both"
// really means "either party files, depending on who initiated".
// Appellant axis is independent of `side`: in an Appeal CoA, the
// appellant selector pins which party appealed; the side toggle
// still picks which of those is us.
export type Side = "claimant" | "defendant" | null;
// Internal column-position alias. "ours" is always rendered in the
// left grid column ("Unsere Seite"); "opponent" is always the right
// column ("Gegnerseite"). Field names mirror the labels so the
// bucketing primitive reads as a direct mapping.
type ColumnPosition = "ours" | "opponent";
export interface ColumnsBodyOpts {
editable?: boolean;
showNotes?: 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).
side?: Side;
// appellant: which side initiated the appeal / counterclaim.
// When set, party=both rows go to the appellant's column ONLY
// (no mirror). Default null = mirror "both" into both cells
// (legacy behaviour). Independent of `side`.
appellant?: Side;
}
// ColumnsRow is the per-due-date bucket the renderer consumes. Public
// so unit tests can hit the pure routing logic without going through
// document.createElement (no jsdom in this repo).
export interface ColumnsRow {
key: string;
ours: CalculatedDeadline[];
court: CalculatedDeadline[];
opponent: CalculatedDeadline[];
}
export interface BucketingOpts {
side?: Side;
appellant?: Side;
}
// bucketDeadlinesIntoColumns is the pure routing primitive that
// renderColumnsBody uses. Extracted as its own export so the per-row
// column placement (including the side-swap + appellant-collapse
// logic from m/paliad#81 and the user-perspective re-frame from
// m/paliad#88) is unit-testable without a DOM. The returned rows are
// sorted: dated rows ascending by dueDate, then unscheduled rows in
// declaration order (each keyed by sequence).
export function bucketDeadlinesIntoColumns(
deadlines: CalculatedDeadline[],
opts: BucketingOpts = {},
): ColumnsRow[] {
const userSide: Side = opts.side ?? null;
// Default (side=null) treats the user as claimant — keeps the
// legacy claimant-on-the-left layout when no perspective is picked.
const claimantColumn: ColumnPosition = userSide === "defendant" ? "opponent" : "ours";
const defendantColumn: ColumnPosition = claimantColumn === "ours" ? "opponent" : "ours";
const appellantColumn: ColumnPosition | null =
opts.appellant === "claimant" ? claimantColumn
: opts.appellant === "defendant" ? defendantColumn
: null;
const UNSCHEDULED_PREFIX = "__unscheduled__";
const rowsMap = new Map<string, Row>();
const ensureRow = (key: string): Row => {
const rowsMap = new Map<string, ColumnsRow>();
const ensureRow = (key: string): ColumnsRow => {
let r = rowsMap.get(key);
if (!r) {
r = { proactive: [], court: [], reactive: [] };
r = { key, ours: [], court: [], opponent: [] };
rowsMap.set(key, r);
}
return r;
};
data.deadlines.forEach((dl, idx) => {
deadlines.forEach((dl, idx) => {
const key = dl.dueDate || `${UNSCHEDULED_PREFIX}${String(idx).padStart(4, "0")}`;
const row = ensureRow(key);
switch (dl.party) {
case "claimant":
row.proactive.push(dl);
row[claimantColumn].push(dl);
break;
case "defendant":
row.reactive.push(dl);
row[defendantColumn].push(dl);
break;
case "court":
row.court.push(dl);
break;
case "both":
row.proactive.push(dl);
row.reactive.push(dl);
if (appellantColumn !== null) {
// Role-swap collapse: appellant initiated → both → one row
// in appellant's column. Mirror suppressed.
row[appellantColumn].push(dl);
} else {
row.ours.push(dl);
row.opponent.push(dl);
}
break;
default:
row.court.push(dl);
@@ -462,17 +554,28 @@ export function renderColumnsBody(data: DeadlineResponse, opts: Omit<CardOpts, "
}
datedKeys.sort();
unscheduledKeys.sort();
const keys = [...datedKeys, ...unscheduledKeys];
return [...datedKeys, ...unscheduledKeys].map((k) => rowsMap.get(k)!);
}
export function renderColumnsBody(data: DeadlineResponse, opts: ColumnsBodyOpts = {}): string {
const userSide: Side = opts.side ?? null;
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 };
// 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;
const renderCell = (items: CalculatedDeadline[]): string => {
if (items.length === 0) {
return `<div class="fr-col-cell fr-col-cell--empty"></div>`;
}
const cards = items
.map((dl) => {
const mirrorTag = dl.party === "both"
const mirrorTag = showMirrorTag && dl.party === "both"
? `<div class="fr-col-mirror">↔ ${escHtml(t("deadlines.party.both.label"))}</div>`
: "";
return `<div class="fr-col-item ${dl.isRootEvent ? "fr-col-root" : ""}">
@@ -487,16 +590,19 @@ export function renderColumnsBody(data: DeadlineResponse, opts: Omit<CardOpts, "
const headerCell = (label: string, cls: string) =>
`<div class="fr-col-header ${cls}">${escHtml(label)}</div>`;
// Static labels — "Unsere Seite" is always the left column, regardless
// of which physical party (claimant vs defendant) occupies it. The
// bucketing primitive already routes the user's side into the `ours`
// bucket, so the header truth-fully describes the column contents.
let html = '<div class="fr-columns-view">';
html += headerCell(t("deadlines.col.proactive"), "fr-col-proactive");
html += headerCell(t("deadlines.col.ours"), "fr-col-ours");
html += headerCell(t("deadlines.col.court"), "fr-col-court");
html += headerCell(t("deadlines.col.reactive"), "fr-col-reactive");
html += headerCell(t("deadlines.col.opponent"), "fr-col-opponent");
for (const key of keys) {
const row = rowsMap.get(key)!;
html += renderCell(row.proactive);
for (const row of rows) {
html += renderCell(row.ours);
html += renderCell(row.court);
html += renderCell(row.reactive);
html += renderCell(row.opponent);
}
html += "</div>";
return html;

View File

@@ -171,6 +171,16 @@ export function ProjectFormFields(): string {
</div>
</div>
<div className="form-field">
<label htmlFor="project-proceeding-type-id" data-i18n="projects.field.proceeding_type">Verfahrenstyp</label>
<select id="project-proceeding-type-id">
<option value="" data-i18n="projects.field.proceeding_type.unset">(nicht gesetzt)</option>
</select>
<p className="form-hint" data-i18n="projects.field.proceeding_type.hint">
Bestimmt, welche Schriftsätze-Vorlagen für dieses Verfahren angezeigt werden.
</p>
</div>
<div className="form-field">
<label htmlFor="project-our-side" data-i18n="projects.field.client_role">Mandantenrolle</label>
<select id="project-our-side">

View File

@@ -13,6 +13,10 @@ const ICON_BOOK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" st
// at a glance.
const ICON_BOOK_OPEN = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M2 4h7a3 3 0 0 1 3 3v13a2 2 0 0 0-2-2H2z"/><path d="M22 4h-7a3 3 0 0 0-3 3v13a2 2 0 0 1 2-2h8z"/></svg>';
const ICON_TABLE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="3" width="18" height="18" rx="2"/><line x1="3" y1="9" x2="21" y2="9"/><line x1="3" y1="15" x2="21" y2="15"/><line x1="9" y1="3" x2="9" y2="21"/></svg>';
// Document-with-lines icon for /submissions (t-paliad-240) — distinct
// from ICON_BOOK / ICON_BOOK_OPEN / ICON_NEWSPAPER so the Schriftsätze
// affordance reads as "a draft document" at a glance.
const ICON_FILE_TEXT = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z"/><polyline points="14 2 14 8 20 8"/><line x1="8" y1="13" x2="16" y2="13"/><line x1="8" y1="17" x2="16" y2="17"/><line x1="8" y1="9" x2="10" y2="9"/></svg>';
const ICON_CHECK = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 11l3 3L22 4"/><path d="M21 12v7a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h11"/></svg>';
const ICON_GLOBE = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><line x1="2" y1="12" x2="22" y2="12"/><path d="M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10A15.3 15.3 0 0 1 12 2z"/></svg>';
const ICON_BUILDING = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M3 21h18"/><path d="M5 21V5a2 2 0 0 1 2-2h7a2 2 0 0 1 2 2v16"/><path d="M16 9h3a2 2 0 0 1 2 2v10"/><path d="M9 7h2"/><path d="M9 11h2"/><path d="M9 15h2"/></svg>';
@@ -175,6 +179,7 @@ export function Sidebar({ currentPath, authenticated = true }: SidebarProps): st
{group("nav.group.werkzeuge", "Werkzeuge",
navItem("/tools/fristenrechner", ICON_CLOCK, "nav.fristenrechner", "Fristenrechner", currentPath) +
navItem("/tools/verfahrensablauf", ICON_BOOK_OPEN, "nav.verfahrensablauf", "Verfahrensablauf", currentPath) +
navItem("/submissions", ICON_FILE_TEXT, "nav.submissions", "Schriftsätze", currentPath) +
navItem("/tools/kostenrechner", ICON_CALC, "nav.kostenrechner", "Kostenrechner", currentPath) +
navItem("/tools/gebuehrentabellen", ICON_TABLE, "nav.gebuehrentabellen", "Gebührentabellen", currentPath) +
navItem("/checklists", ICON_CHECK, "nav.checklisten", "Checklisten", currentPath) +

View File

@@ -112,23 +112,23 @@ export function renderDashboard(): string {
{/* Traffic-light deadline summary (4+1: Überfällig conditional + 4 universal — t-paliad-110) */}
<CollapsibleSection id="summary" widgetKey="deadline-summary" headingI18n="dashboard.summary.heading" headingDe="Fristen auf einen Blick">
<div className="dashboard-summary-grid">
<a href="/deadlines?status=overdue" className="dashboard-card dashboard-card-red" id="dashboard-card-overdue">
<a href="/events?type=deadline&status=overdue" className="dashboard-card dashboard-card-red" id="dashboard-card-overdue">
<div className="dashboard-card-count" id="dashboard-count-overdue">0</div>
<div className="dashboard-card-label" data-i18n="dashboard.summary.overdue">&Uuml;berf&auml;llig</div>
</a>
<a href="/deadlines?status=today" className="dashboard-card dashboard-card-today" id="dashboard-card-today">
<a href="/events?type=deadline&status=today" className="dashboard-card dashboard-card-today" id="dashboard-card-today">
<div className="dashboard-card-count" id="dashboard-count-today">0</div>
<div className="dashboard-card-label" data-i18n="dashboard.summary.today">Heute</div>
</a>
<a href="/deadlines?status=this_week" className="dashboard-card dashboard-card-amber" id="dashboard-card-thisweek">
<a href="/events?type=deadline&status=this_week" className="dashboard-card dashboard-card-amber" id="dashboard-card-thisweek">
<div className="dashboard-card-count" id="dashboard-count-this-week">0</div>
<div className="dashboard-card-label" data-i18n="dashboard.summary.this_week">Diese Woche</div>
</a>
<a href="/deadlines?status=next_week" className="dashboard-card dashboard-card-green" id="dashboard-card-nextweek">
<a href="/events?type=deadline&status=next_week" className="dashboard-card dashboard-card-green" id="dashboard-card-nextweek">
<div className="dashboard-card-count" id="dashboard-count-next-week">0</div>
<div className="dashboard-card-label" data-i18n="dashboard.summary.next_week">N&auml;chste Woche</div>
</a>
<a href="/deadlines?status=later" className="dashboard-card dashboard-card-later" id="dashboard-card-later">
<a href="/events?type=deadline&status=later" className="dashboard-card dashboard-card-later" id="dashboard-card-later">
<div className="dashboard-card-count" id="dashboard-count-later">0</div>
<div className="dashboard-card-label" data-i18n="dashboard.summary.later">Sp&auml;ter</div>
</a>

View File

@@ -41,6 +41,19 @@ export function renderDeadlinesDetail(): string {
<div className="entity-detail-title-col">
<h1 id="deadline-title-display" />
<input type="text" id="deadline-title-edit" className="entity-title-input" style="display:none" />
{/* t-paliad-251 Part 4 — Standardtitel button only
visible in edit mode; clicking replaces the
title with a default derived from the project
and the deadline's event types / rule. */}
<button
type="button"
id="deadline-title-default-btn"
className="btn-link-action"
style="display:none"
data-i18n="deadlines.field.title.default_btn"
>
Standardtitel
</button>
<div className="entity-detail-meta">
<span id="deadline-due-chip" className="frist-due-chip" />
<span id="deadline-status-chip" className="entity-status-chip" />
@@ -95,7 +108,36 @@ export function renderDeadlinesDetail(): string {
</dd>
<dt data-i18n="deadlines.detail.rule">Regel</dt>
<dd id="deadline-rule-display">&mdash;</dd>
<dd>
<span id="deadline-rule-display">&mdash;</span>
{/* t-paliad-258 — Auto / Custom rule editor.
Mirrors /deadlines/new: read-only Auto display
(resolved from Type) or free-text Custom input,
with a toggle link. Hidden outside edit mode. */}
<div className="rule-edit-block" id="deadline-rule-edit" style="display:none">
<button
type="button"
id="deadline-rule-mode-toggle"
className="btn-link-action"
data-i18n="deadlines.field.rule.mode.toggle_to_custom"
>
Eigene Regel eingeben
</button>
<div className="rule-mode-auto" id="deadline-rule-auto-display">
<span className="form-hint-badge" data-i18n="deadlines.field.rule.auto_badge">Auto</span>
<span id="deadline-rule-auto-text" className="rule-auto-text">&mdash;</span>
</div>
<input
type="text"
id="deadline-rule-custom-input"
className="rule-mode-custom"
style="display:none"
placeholder="z.B. interner Review-Termin"
data-i18n-placeholder="deadlines.field.rule.custom_placeholder"
maxLength={200}
/>
</div>
</dd>
<dt data-i18n="deadlines.detail.source">Quelle</dt>
<dd id="deadline-source-display" />

View File

@@ -45,7 +45,22 @@ export function renderDeadlinesNew(): string {
</div>
<div className="form-field">
<label htmlFor="deadline-title" data-i18n="deadlines.field.title">Titel</label>
<div className="form-field-label-row">
<label htmlFor="deadline-title" data-i18n="deadlines.field.title">Titel</label>
{/* t-paliad-251 Part 4 — derive a Standardtitel from the
currently-known context (event type → rule → proceeding
type → fallback) with the project reference as suffix.
Always replaces the title; no destructive confirmation
because the user invoked it explicitly. */}
<button
type="button"
id="deadline-title-default-btn"
className="btn-link-action"
data-i18n="deadlines.field.title.default_btn"
>
Standardtitel
</button>
</div>
<input
type="text"
id="deadline-title"
@@ -57,58 +72,42 @@ export function renderDeadlinesNew(): string {
<div className="form-field" id="deadline-event-type-field">
<label data-i18n="deadlines.field.event_type">Typ (optional)</label>
{/* t-paliad-165 follow-up — collapsed view: when a Regel
is selected and a default event_type is known, the
Typ chip is hidden and the type is rendered inline
as a single read-only summary with an "Anderen Typ
wählen" link that re-expands the picker. */}
<div
className="event-type-collapsed"
id="deadline-event-type-collapsed"
style="display:none"
>
<span
className="event-type-collapsed-label"
id="deadline-event-type-collapsed-label"
/>
<span
className="event-type-collapsed-source"
data-i18n="deadlines.field.rule.autofill_inline"
>
&nbsp;(vorgegeben durch Regel)
</span>
<button
type="button"
className="event-type-collapsed-override"
id="deadline-event-type-override-btn"
data-i18n="deadlines.field.rule.override"
>
Anderen Typ w&auml;hlen
</button>
</div>
<div id="deadline-event-types" className="event-type-picker-host" />
{/* Soft warning when the user is in expanded mode AND
has picked an event_type that doesn't include the
rule's canonical default. Reuses the existing
yellow form-hint--warning style; never blocking. */}
<p
className="form-hint form-hint--warning"
id="deadline-event-type-rule-mismatch"
style="display:none"
data-i18n="deadlines.field.rule.mismatch"
>
Hinweis: Typ widerspricht Regel &mdash; Sie haben den Typ &uuml;berschrieben.
</p>
</div>
{/* m/paliad#56 — Regel sits directly beneath the Typ
picker so the parent/child relationship reads at a
glance. Due date is its own row below. */}
{/* t-paliad-258 / m/paliad#89 — binary Rule field.
Auto (default): rule_id derived from the chosen
Type, displayed read-only with a canonical
"Name · Citation" label. Custom: free-text input,
no catalog FK. Toggle switches modes. */}
<div className="form-field">
<label htmlFor="deadline-rule" data-i18n="deadlines.field.rule">Regel (optional)</label>
<select id="deadline-rule">
<option value="" data-i18n="deadlines.field.rule.none">Keine Regel</option>
</select>
<div className="form-field-label-row">
<label data-i18n="deadlines.field.rule">Regel</label>
<button
type="button"
id="deadline-rule-mode-toggle"
className="btn-link-action"
data-i18n="deadlines.field.rule.mode.toggle_to_custom"
>
Eigene Regel eingeben
</button>
</div>
<div className="rule-mode-auto" id="deadline-rule-auto-display">
<span
className="form-hint-badge"
data-i18n="deadlines.field.rule.auto_badge"
>Auto</span>
<span id="deadline-rule-auto-text" className="rule-auto-text">&mdash;</span>
</div>
<input
type="text"
id="deadline-rule-custom-input"
className="rule-mode-custom"
style="display:none"
placeholder="z.B. interner Review-Termin"
data-i18n-placeholder="deadlines.field.rule.custom_placeholder"
maxLength={200}
/>
</div>
<div className="form-field">

View File

@@ -682,9 +682,20 @@ export type I18nKey =
| "approvals.tab.mine"
| "approvals.tab.pending_mine"
| "approvals.title"
| "approvals.withdraw.cancel"
| "approvals.withdraw.confirm"
| "approvals.withdraw.cta"
| "approvals.withdraw.destructive.label"
| "approvals.withdraw.error"
| "approvals.withdraw.lead.create.appointment"
| "approvals.withdraw.lead.create.deadline"
| "approvals.withdraw.lead.delete"
| "approvals.withdraw.lead.update"
| "approvals.withdraw.modal.title"
| "approvals.withdraw.primary.label"
| "approvals.withdraw.sub.create"
| "approvals.withdraw.sub.delete"
| "approvals.withdraw.sub.update"
| "bottomnav.add"
| "bottomnav.add.appointment"
| "bottomnav.add.appointment.sub"
@@ -1112,6 +1123,10 @@ export type I18nKey =
| "deadlines.adjusted.weekend"
| "deadlines.adjusted.weekend.saturday"
| "deadlines.adjusted.weekend.sunday"
| "deadlines.appellant.claimant"
| "deadlines.appellant.defendant"
| "deadlines.appellant.label"
| "deadlines.appellant.none"
| "deadlines.calculate"
| "deadlines.card.calc.add_to_project"
| "deadlines.card.calc.add_to_project.disabled"
@@ -1138,8 +1153,8 @@ export type I18nKey =
| "deadlines.col.court"
| "deadlines.col.due"
| "deadlines.col.event_type"
| "deadlines.col.proactive"
| "deadlines.col.reactive"
| "deadlines.col.opponent"
| "deadlines.col.ours"
| "deadlines.col.rule"
| "deadlines.col.status"
| "deadlines.col.title"
@@ -1227,12 +1242,16 @@ export type I18nKey =
| "deadlines.field.notes"
| "deadlines.field.notes.placeholder"
| "deadlines.field.rule"
| "deadlines.field.rule.autofill"
| "deadlines.field.rule.autofill_inline"
| "deadlines.field.rule.mismatch"
| "deadlines.field.rule.none"
| "deadlines.field.rule.override"
| "deadlines.field.rule.auto_badge"
| "deadlines.field.rule.auto_no_match"
| "deadlines.field.rule.auto_pick_type"
| "deadlines.field.rule.custom_badge"
| "deadlines.field.rule.custom_placeholder"
| "deadlines.field.rule.mode.toggle_to_auto"
| "deadlines.field.rule.mode.toggle_to_custom"
| "deadlines.field.title"
| "deadlines.field.title.default_btn"
| "deadlines.field.title.default_fallback"
| "deadlines.field.title.placeholder"
| "deadlines.filter.akte"
| "deadlines.filter.akte.all"
@@ -1366,6 +1385,10 @@ export type I18nKey =
| "deadlines.search.placeholder"
| "deadlines.search.results.count"
| "deadlines.search.results.count_one"
| "deadlines.side.both"
| "deadlines.side.claimant"
| "deadlines.side.defendant"
| "deadlines.side.label"
| "deadlines.source.caldav"
| "deadlines.source.fristenrechner"
| "deadlines.source.imported"
@@ -1574,6 +1597,8 @@ export type I18nKey =
| "event_types.browse.apply"
| "event_types.browse.cancel"
| "event_types.browse.empty"
| "event_types.browse.jurisdiction.all"
| "event_types.browse.jurisdiction.filter_label"
| "event_types.browse.jurisdiction.none"
| "event_types.browse.search"
| "event_types.browse.selected_count"
@@ -1904,6 +1929,7 @@ export type I18nKey =
| "nav.paliadin"
| "nav.projekte"
| "nav.soon.tooltip"
| "nav.submissions"
| "nav.team"
| "nav.termine"
| "nav.user_views.new"
@@ -1985,8 +2011,11 @@ export type I18nKey =
| "paliadin.error.shim_error"
| "paliadin.error.timeout"
| "paliadin.error.upstream"
| "paliadin.error.upstream_silence"
| "paliadin.heading"
| "paliadin.input.placeholder"
| "paliadin.late.checking"
| "paliadin.late.lost"
| "paliadin.late.marker"
| "paliadin.late.waiting"
| "paliadin.reset"
@@ -1996,6 +2025,8 @@ export type I18nKey =
| "paliadin.starter.week"
| "paliadin.stop"
| "paliadin.tagline"
| "paliadin.thinking"
| "paliadin.thinking.seconds"
| "paliadin.title"
| "paliadin.widget.close"
| "paliadin.widget.context.on_page"
@@ -2132,6 +2163,11 @@ export type I18nKey =
| "projects.detail.appointments.form.cancel"
| "projects.detail.appointments.form.submit"
| "projects.detail.back"
| "projects.detail.checklisten.add"
| "projects.detail.checklisten.add.created"
| "projects.detail.checklisten.add.empty_pick"
| "projects.detail.checklisten.add.error"
| "projects.detail.checklisten.add.search"
| "projects.detail.checklisten.col.created"
| "projects.detail.checklisten.col.name"
| "projects.detail.checklisten.col.progress"
@@ -2177,6 +2213,11 @@ export type I18nKey =
| "projects.detail.parteien.role.defendant"
| "projects.detail.parteien.role.thirdparty"
| "projects.detail.save"
| "projects.detail.settings.archive.cta"
| "projects.detail.settings.archive.description"
| "projects.detail.settings.archive.heading"
| "projects.detail.settings.export.description"
| "projects.detail.settings.export.heading"
| "projects.detail.smarttimeline.add.cancel"
| "projects.detail.smarttimeline.add.choice.amend"
| "projects.detail.smarttimeline.add.choice.appointment"
@@ -2250,6 +2291,7 @@ export type I18nKey =
| "projects.detail.smarttimeline.track.only.counterclaim"
| "projects.detail.smarttimeline.track.only.parent"
| "projects.detail.smarttimeline.track.only.parent_context"
| "projects.detail.submissions.action.edit"
| "projects.detail.submissions.action.generate"
| "projects.detail.submissions.action.no_template"
| "projects.detail.submissions.col.action"
@@ -2258,12 +2300,14 @@ export type I18nKey =
| "projects.detail.submissions.col.source"
| "projects.detail.submissions.empty"
| "projects.detail.submissions.empty.no_proceeding"
| "projects.detail.submissions.empty.no_proceeding.cta"
| "projects.detail.submissions.hint"
| "projects.detail.tab.checklisten"
| "projects.detail.tab.fristen"
| "projects.detail.tab.kinder"
| "projects.detail.tab.notizen"
| "projects.detail.tab.parteien"
| "projects.detail.tab.settings"
| "projects.detail.tab.submissions"
| "projects.detail.tab.team"
| "projects.detail.tab.termine"
@@ -2354,6 +2398,9 @@ export type I18nKey =
| "projects.field.parent.hint"
| "projects.field.parent.placeholder"
| "projects.field.patent_number"
| "projects.field.proceeding_type"
| "projects.field.proceeding_type.hint"
| "projects.field.proceeding_type.unset"
| "projects.field.proceeding_type_id"
| "projects.field.ref"
| "projects.field.ref.placeholder"
@@ -2399,6 +2446,11 @@ export type I18nKey =
| "projects.team.error.generic"
| "projects.team.error.last_admin"
| "projects.team.inherited.hint"
| "projects.team.mailto.count"
| "projects.team.mailto.empty"
| "projects.team.mailto.label"
| "projects.team.mailto.select_all"
| "projects.team.mailto.select_row"
| "projects.team.profession.associate"
| "projects.team.profession.hint"
| "projects.team.profession.none"
@@ -2476,6 +2528,45 @@ export type I18nKey =
| "search.no_results"
| "search.placeholder"
| "sidebar.resize.title"
| "submissions.draft.action.delete"
| "submissions.draft.action.export"
| "submissions.draft.action.new"
| "submissions.draft.back"
| "submissions.draft.loading"
| "submissions.draft.name.placeholder"
| "submissions.draft.notfound"
| "submissions.draft.preview.hint"
| "submissions.draft.preview.title"
| "submissions.draft.switcher.label"
| "submissions.draft.title"
| "submissions.index.action.new"
| "submissions.index.col.draft"
| "submissions.index.col.project"
| "submissions.index.col.submission"
| "submissions.index.col.updated"
| "submissions.index.empty"
| "submissions.index.empty.cta"
| "submissions.index.error"
| "submissions.index.heading"
| "submissions.index.loading"
| "submissions.index.subtitle"
| "submissions.index.title"
| "submissions.new.back"
| "submissions.new.col.actions"
| "submissions.new.col.name"
| "submissions.new.col.party"
| "submissions.new.col.source"
| "submissions.new.empty.filtered"
| "submissions.new.error"
| "submissions.new.heading"
| "submissions.new.loading"
| "submissions.new.picker.empty"
| "submissions.new.picker.loading"
| "submissions.new.picker.placeholder"
| "submissions.new.picker.title"
| "submissions.new.search.placeholder"
| "submissions.new.subtitle"
| "submissions.new.title"
| "team.broadcast.body"
| "team.broadcast.body_placeholder"
| "team.broadcast.button"

View File

@@ -104,7 +104,7 @@ export function renderKostenrechner(): string {
<title data-i18n="kosten.title">Prozesskostenrechner &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar">
<body className="has-sidebar page-kostenrechner">
<Sidebar currentPath="/tools/kostenrechner" />
<BottomNav currentPath="/tools/kostenrechner" />

View File

@@ -27,7 +27,7 @@ export function renderProjectsChart(): string {
<title data-i18n="projects.chart.title">Projekt-Chart &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar">
<body className="has-sidebar page-projects-chart">
<Sidebar currentPath="/projects" />
<BottomNav currentPath="/projects" />

View File

@@ -89,20 +89,9 @@ export function renderProjectsDetail(): string {
<a className="entity-tab" data-tab="notes" href="#" data-i18n="projects.detail.tab.notizen">Notizen</a>
<a className="entity-tab" data-tab="checklists" href="#" data-i18n="projects.detail.tab.checklisten">Checklisten</a>
<a className="entity-tab" data-tab="submissions" href="#" data-i18n="projects.detail.tab.submissions">Schriftsätze</a>
{/* t-paliad-214 Slice 2 — project-subtree export button.
Sits at the end of the tab nav. Hidden by default; the
client unhides it after /api/me confirms the caller can
extract (responsibility ∈ {lead, member} OR global_admin). */}
<button
type="button"
id="project-export-btn"
className="entity-tab entity-tab-action"
style="display:none"
title=""
data-i18n-title="projects.detail.export.tooltip"
data-i18n="projects.detail.export.button">
Daten exportieren
</button>
{/* Verwaltung — rare admin actions (export, archive). Sits
last in the tab list per t-paliad-245. */}
<a className="entity-tab" data-tab="settings" href="#" data-i18n="projects.detail.tab.settings">Verwaltung</a>
</nav>
{/* History (Verlauf) — t-paliad-171 SmartTimeline Slice 1.
@@ -286,9 +275,33 @@ export function renderProjectsDetail(): string {
<p className="form-msg" id="team-msg" />
</form>
{/* t-paliad-231 — pure-client mailto: for non-admins.
Button stays disabled until at least one row is
selected; click opens a mailto: with every selected
member in the To: line. No server call. */}
<div className="party-controls team-mailto-controls" id="team-mailto-controls" style="display:none">
<button
type="button"
id="team-mailto-btn"
className="btn-secondary btn-small"
disabled
data-i18n-title="projects.team.mailto.empty"
title="Mindestens ein Mitglied ausw&auml;hlen"
>
<span id="team-mailto-label" data-i18n="projects.team.mailto.label">Mail an Auswahl</span>
</button>
</div>
<table className="party-table">
<thead>
<tr>
<th className="team-col-select">
<input
type="checkbox"
id="team-select-master"
aria-label="Alle sichtbaren ausw&auml;hlen"
/>
</th>
<th data-i18n="projects.detail.team.col.name">Name</th>
<th data-i18n="projects.detail.team.col.profession">Profession</th>
<th data-i18n="projects.detail.team.col.responsibility">Rolle</th>
@@ -572,6 +585,12 @@ export function renderProjectsDetail(): string {
{/* Checklists (Checklisten) */}
<section className="entity-tab-panel" id="tab-checklists" style="display:none">
<div className="party-controls">
<button id="checklist-add-btn" className="btn-primary btn-cta-lime btn-small" type="button" data-i18n="projects.detail.checklisten.add">
Checkliste hinzuf&uuml;gen
</button>
</div>
<p className="form-msg" id="project-checklists-msg" />
<p id="project-checklists-empty" className="entity-events-empty" style="display:none" data-i18n="projects.detail.checklisten.empty">
F&uuml;r dieses Projekt sind noch keine Checklisten-Instanzen erfasst.
</p>
@@ -589,25 +608,35 @@ export function renderProjectsDetail(): string {
</table>
</div>
<p className="tool-subtitle checklists-hint">
<span data-i18n="projects.detail.checklisten.hint.prefix">Instanzen werden auf der Vorlagen-Seite unter </span>
<span data-i18n="projects.detail.checklisten.hint.prefix">Vorlagen werden auf der </span>
<a href="/checklists" data-i18n="projects.detail.checklisten.hint.link">Checklisten</a>
<span data-i18n="projects.detail.checklisten.hint.suffix"> angelegt.</span>
<span data-i18n="projects.detail.checklisten.hint.suffix">-Seite angelegt und bearbeitet.</span>
</p>
</section>
{/* Submissions (Schriftsätze) — t-paliad-215 Slice 1.
Lists the project's filing-type rules with a per-row
[Generieren] button when a .docx template resolves
in the registry's fallback chain (firm → base/code →
base/family → skeleton). Empty for projects with no
proceeding bound; otherwise enumerates every active
filing rule for the proceeding. */}
{/* Submissions (Schriftsätze) — t-paliad-242 broadened
the original t-paliad-215 list to the full
cross-proceeding catalog. The table shows every
active filing rule across every proceeding, grouped
by proceeding; the project's own proceeding is
pinned to the top. The no-proceeding hint stays as
a soft nudge above the catalog (the table renders
regardless). */}
<section className="entity-tab-panel" id="tab-submissions" style="display:none">
<p id="project-submissions-no-proceeding" className="entity-events-empty" style="display:none" data-i18n="projects.detail.submissions.empty.no_proceeding">
Bitte zuerst einen Verfahrenstyp setzen.
</p>
<div id="project-submissions-no-proceeding" className="entity-events-empty" style="display:none">
<p data-i18n="projects.detail.submissions.empty.no_proceeding">
Für dieses Projekt ist noch kein Verfahrenstyp gesetzt der Katalog unten zeigt trotzdem alle Vorlagen.
</p>
<button
type="button"
id="project-submissions-edit-cta"
className="btn-primary btn-small"
data-i18n="projects.detail.submissions.empty.no_proceeding.cta">
Projekt bearbeiten
</button>
</div>
<p id="project-submissions-empty" className="entity-events-empty" style="display:none" data-i18n="projects.detail.submissions.empty">
Für dieses Verfahren sind keine Schriftsätze hinterlegt.
Es sind aktuell keine Schriftsatzvorlagen hinterlegt.
</p>
<div className="entity-table-wrap" id="project-submissions-tablewrap" style="display:none">
<table className="entity-table entity-table--readonly">
@@ -627,11 +656,38 @@ export function renderProjectsDetail(): string {
</p>
</section>
<div className="entity-detail-footer" id="project-delete-wrap" style="display:none">
<button id="project-delete-btn" className="btn-secondary" type="button" data-i18n="projects.detail.delete">
Projekt archivieren
</button>
</div>
{/* Verwaltung — rare admin actions (export, archive). Each
sub-section hides itself if the caller is not entitled
(export: §4 gate; archive: global_admin). */}
<section className="entity-tab-panel" id="tab-settings" style="display:none">
<div className="settings-section" id="project-settings-export" style="display:none">
<h3 className="entity-section-heading" data-i18n="projects.detail.settings.export.heading">Daten exportieren</h3>
<p className="tool-subtitle" data-i18n="projects.detail.settings.export.description">
Lade alle Daten dieses Projekts (inkl. Unter-Projekten) als Excel + JSON + CSV-Archiv herunter.
</p>
<button
type="button"
id="project-export-btn"
className="btn-secondary"
data-i18n="projects.detail.export.button">
Daten exportieren
</button>
</div>
<div className="settings-section" id="project-settings-archive" style="display:none">
<h3 className="entity-section-heading" data-i18n="projects.detail.settings.archive.heading">Projekt archivieren</h3>
<p className="tool-subtitle" data-i18n="projects.detail.settings.archive.description">
Archivieren erfolgt aus dem Bearbeiten-Dialog (Gefahrenbereich).
</p>
<button
type="button"
id="project-settings-archive-link"
className="btn-secondary"
data-i18n="projects.detail.settings.archive.cta">
Bearbeiten öffnen
</button>
</div>
</section>
</div>
{/* Full edit modal — same form as /projects/new, pre-filled. */}
@@ -663,6 +719,33 @@ export function renderProjectsDetail(): string {
<button type="submit" className="btn-primary btn-cta-lime" data-i18n="projects.detail.save">Speichern</button>
</div>
</form>
{/* Danger zone — destructive action, visually separated from Save/Cancel. */}
<div className="modal-danger-zone" id="project-delete-wrap" style="display:none">
<button id="project-delete-btn" className="btn-link-danger" type="button" data-i18n="projects.detail.delete">
Projekt archivieren
</button>
</div>
</div>
</div>
{/* Add-checklist-instance modal (t-paliad-239) — picks a
template and POSTs to /api/checklists/{slug}/instances
with the current project_id; the row appears in the
Checklists tab list on success. */}
<div className="modal-overlay" id="add-checklist-modal" style="display:none">
<div className="modal-card modal-card-wide">
<div className="modal-header">
<h2 data-i18n="projects.detail.checklisten.add">Checkliste hinzuf&uuml;gen</h2>
<button className="modal-close" id="add-checklist-close" type="button">&times;</button>
</div>
<div className="form-field">
<input type="text" id="add-checklist-search" autocomplete="off" data-i18n-placeholder="projects.detail.checklisten.add.search" placeholder="Vorlage suchen&hellip;" />
</div>
<div className="add-checklist-list" id="add-checklist-list" />
<p className="entity-events-empty" id="add-checklist-empty" style="display:none" data-i18n="projects.detail.checklisten.add.empty_pick">
Keine passenden Vorlagen gefunden.
</p>
<p className="form-msg" id="add-checklist-msg" />
</div>
</div>

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,143 @@
import { h } from "./jsx";
import { Sidebar } from "./components/Sidebar";
import { PaliadinWidget } from "./components/PaliadinWidget";
import { BottomNav } from "./components/BottomNav";
import { Footer } from "./components/Footer";
import { PWAHead } from "./components/PWAHead";
// t-paliad-238 Slice A — dedicated Submissions/Schriftsätze editor page.
//
// Lawyer picks (or creates) a draft for one (project, submission_code),
// edits placeholder variables in a sticky sidebar, sees a read-only
// HTML preview of the merged document, and exports the result as
// .docx. Drafts persist server-side per paliad.submission_drafts.
//
// Pure shell: client/submission-draft.ts hydrates draft list + variable
// form + preview pane after page load. The same dist/submission-draft.html
// serves every (project_id, submission_code, [draft_id]) URL.
//
// Design ref: docs/design-submission-page-2026-05-22.md §6.
export function renderSubmissionDraft(): string {
return "<!DOCTYPE html>" + (
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#BFF355" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<PWAHead />
<title data-i18n="submissions.draft.title">Schriftsatz bearbeiten &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar page-submission-draft">
<Sidebar currentPath="/projects" />
<BottomNav currentPath="/projects" />
<main>
<section className="tool-page submission-draft-page">
<div className="container">
<a
id="submission-draft-back-link"
href="/projects"
className="back-link"
data-i18n="submissions.draft.back">
&larr; Zur&uuml;ck zum Projekt
</a>
<div id="submission-draft-loading" className="entity-loading">
<p data-i18n="submissions.draft.loading">L&auml;dt&hellip;</p>
</div>
<div id="submission-draft-notfound" className="entity-empty" style="display:none">
<p data-i18n="submissions.draft.notfound">
Schriftsatz nicht gefunden oder keine Berechtigung.
</p>
</div>
<div id="submission-draft-error" className="entity-empty" style="display:none" />
<div id="submission-draft-body" style="display:none">
<header className="submission-draft-header">
<div className="submission-draft-header-text">
<h1 id="submission-draft-title" />
<p id="submission-draft-subtitle" className="tool-subtitle" />
</div>
<div className="submission-draft-header-actions">
<button
id="submission-draft-export-btn"
type="button"
className="btn-primary btn-cta-lime"
data-i18n="submissions.draft.action.export">
Als .docx exportieren
</button>
</div>
</header>
<div className="submission-draft-grid">
{/* Sidebar — draft switcher + variable groups. */}
<aside className="submission-draft-sidebar" id="submission-draft-sidebar">
<div className="submission-draft-switcher">
<label htmlFor="submission-draft-pick" data-i18n="submissions.draft.switcher.label">
Entwurf
</label>
<select id="submission-draft-pick" />
<button
type="button"
id="submission-draft-new-btn"
className="btn-small btn-secondary"
data-i18n="submissions.draft.action.new">
+ Neuer Entwurf
</button>
</div>
<div className="submission-draft-name-row">
<input
type="text"
id="submission-draft-name"
className="entity-form-input"
data-i18n-placeholder="submissions.draft.name.placeholder"
placeholder="Name dieses Entwurfs"
/>
<button
type="button"
id="submission-draft-delete-btn"
className="btn-small btn-link-danger"
data-i18n="submissions.draft.action.delete">
L&ouml;schen
</button>
</div>
<p className="submission-draft-savestatus" id="submission-draft-savestatus" />
<div className="submission-draft-variables" id="submission-draft-variables" />
</aside>
{/* Preview pane — read-only HTML render of the merged
document body. Re-renders on autosave round-trip. */}
<section className="submission-draft-preview-wrap">
<header className="submission-draft-preview-header">
<h2 data-i18n="submissions.draft.preview.title">Vorschau</h2>
<span
className="submission-draft-preview-hint"
data-i18n="submissions.draft.preview.hint">
Read-only Vorschau &mdash; finale Bearbeitung in Word.
</span>
</header>
<div className="submission-draft-preview" id="submission-draft-preview" />
</section>
</div>
</div>
</div>
</section>
</main>
<Footer />
<PaliadinWidget />
<script src="/assets/submission-draft.js"></script>
</body>
</html>
);
}

View File

@@ -0,0 +1,84 @@
import { h } from "./jsx";
import { Sidebar } from "./components/Sidebar";
import { PaliadinWidget } from "./components/PaliadinWidget";
import { BottomNav } from "./components/BottomNav";
import { Footer } from "./components/Footer";
import { PWAHead } from "./components/PWAHead";
// t-paliad-240 — global Schriftsätze drafts index. Top-level sidebar
// entry that lists every draft the caller owns across visible projects.
// Per-project editor stays at /projects/{id}/submissions/{code}/draft —
// this page only adds a discovery surface and click-through to it.
export function renderSubmissionsIndex(): string {
return "<!DOCTYPE html>" + (
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#BFF355" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<PWAHead />
<title data-i18n="submissions.index.title">Schriftsätze &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar">
<Sidebar currentPath="/submissions" />
<BottomNav currentPath="/submissions" />
<main>
<section className="tool-page">
<div className="container">
<div className="tool-header">
<div className="submissions-index-headline">
<div>
<h1 data-i18n="submissions.index.heading">Schriftsätze</h1>
<p className="tool-subtitle" data-i18n="submissions.index.subtitle">
Ihre Schriftsatz-Entw&uuml;rfe &uuml;ber alle sichtbaren Projekte.
</p>
</div>
<a href="/submissions/new" className="btn-primary btn-cta-lime"
data-i18n="submissions.index.action.new">+ Neuer Entwurf</a>
</div>
</div>
<p className="entity-events-empty" id="submissions-index-loading"
data-i18n="submissions.index.loading">L&auml;dt&hellip;</p>
<div className="entity-empty" id="submissions-index-empty" style="display:none">
<p data-i18n="submissions.index.empty">
Noch keine Entw&uuml;rfe. Beginnen Sie mit einem neuen Entwurf &mdash; mit oder ohne Projekt.
</p>
<a href="/submissions/new" className="btn-primary btn-cta-lime"
data-i18n="submissions.index.empty.cta">+ Neuer Entwurf</a>
</div>
<div className="entity-empty" id="submissions-index-error" style="display:none">
<p data-i18n="submissions.index.error">Schrifts&auml;tze konnten nicht geladen werden.</p>
</div>
<div className="entity-table-wrap" id="submissions-index-tablewrap" style="display:none">
<table className="entity-table">
<thead>
<tr>
<th data-i18n="submissions.index.col.project">Projekt</th>
<th data-i18n="submissions.index.col.submission">Schriftsatz</th>
<th data-i18n="submissions.index.col.draft">Entwurf</th>
<th data-i18n="submissions.index.col.updated">Zuletzt ge&auml;ndert</th>
</tr>
</thead>
<tbody id="submissions-index-body" />
</table>
</div>
</div>
</section>
</main>
<Footer />
<PaliadinWidget />
<script src="/assets/submissions-index.js"></script>
</body>
</html>
);
}

View File

@@ -0,0 +1,118 @@
import { h } from "./jsx";
import { Sidebar } from "./components/Sidebar";
import { PaliadinWidget } from "./components/PaliadinWidget";
import { BottomNav } from "./components/BottomNav";
import { Footer } from "./components/Footer";
import { PWAHead } from "./components/PWAHead";
// t-paliad-243 — global Schriftsatz picker. Lists the full
// cross-proceeding submission catalog (grouped by proceeding,
// filterable) and lets the lawyer start a draft with or without
// binding a project. Picking "Ohne Projekt" jumps straight to
// /submissions/draft/{id}; picking "Mit Projekt verknüpfen" opens an
// autocomplete project picker, then redirects to the project-scoped
// editor.
export function renderSubmissionsNew(): string {
return "<!DOCTYPE html>" + (
<html lang="de">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#BFF355" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="default" />
<PWAHead />
<title data-i18n="submissions.new.title">Neuer Schriftsatz &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar">
<Sidebar currentPath="/submissions" />
<BottomNav currentPath="/submissions" />
<main>
<section className="tool-page submissions-new-page">
<div className="container">
<a href="/submissions" className="back-link"
data-i18n="submissions.new.back">&larr; Zur&uuml;ck zur &Uuml;bersicht</a>
<div className="tool-header">
<h1 data-i18n="submissions.new.heading">Neuer Schriftsatz</h1>
<p className="tool-subtitle" data-i18n="submissions.new.subtitle">
W&auml;hlen Sie eine Vorlage. Optional verkn&uuml;pfen Sie den
Entwurf mit einem Projekt &mdash; sonst f&uuml;llen Sie alle
Variablen manuell.
</p>
</div>
<div className="submissions-new-toolbar">
<input
type="search"
id="submissions-new-search"
className="entity-form-input"
data-i18n-placeholder="submissions.new.search.placeholder"
placeholder="Suche nach Schriftsatz, Code oder Norm…" />
<div id="submissions-new-proceeding-chips" className="submissions-new-chips" />
</div>
<p className="entity-events-empty" id="submissions-new-loading"
data-i18n="submissions.new.loading">L&auml;dt&hellip;</p>
<div className="entity-empty" id="submissions-new-error" style="display:none">
<p data-i18n="submissions.new.error">Katalog konnte nicht geladen werden.</p>
</div>
<div className="entity-table-wrap" id="submissions-new-tablewrap" style="display:none">
<table className="entity-table entity-table--readonly">
<thead>
<tr>
<th data-i18n="submissions.new.col.name">Schriftsatz</th>
<th data-i18n="submissions.new.col.party">Partei</th>
<th data-i18n="submissions.new.col.source">Rechtsgrundlage</th>
<th data-i18n="submissions.new.col.actions">Entwurf starten</th>
</tr>
</thead>
<tbody id="submissions-new-body" />
</table>
</div>
<p className="entity-empty" id="submissions-new-empty" style="display:none">
<span data-i18n="submissions.new.empty.filtered">
Keine passenden Schrifts&auml;tze. Filter zur&uuml;cksetzen.
</span>
</p>
</div>
</section>
{/* Project picker modal — opened by "Mit Projekt verknüpfen". */}
<div id="submissions-new-project-modal" className="modal-overlay" style="display:none" role="dialog" aria-modal="true">
<div className="modal-card">
<header className="modal-header">
<h2 data-i18n="submissions.new.picker.title">Projekt w&auml;hlen</h2>
<button type="button" id="submissions-new-project-modal-close"
className="modal-close" aria-label="Close">&times;</button>
</header>
<div className="modal-body">
<input
type="search"
id="submissions-new-project-search"
className="entity-form-input"
data-i18n-placeholder="submissions.new.picker.placeholder"
placeholder="Projekt suchen (Titel oder Aktenzeichen)…" />
<ul id="submissions-new-project-list" className="submissions-new-project-list" />
<p id="submissions-new-project-loading" className="entity-events-empty" style="display:none"
data-i18n="submissions.new.picker.loading">L&auml;dt Projekte&hellip;</p>
<p id="submissions-new-project-empty" className="entity-empty" style="display:none"
data-i18n="submissions.new.picker.empty">Keine sichtbaren Projekte.</p>
</div>
</div>
</div>
</main>
<Footer />
<PaliadinWidget />
<script src="/assets/submissions-new.js"></script>
</body>
</html>
);
}

View File

@@ -84,7 +84,7 @@ export function renderVerfahrensablauf(): string {
<title data-i18n="tools.verfahrensablauf.title">Verfahrensablauf &mdash; Paliad</title>
<link rel="stylesheet" href="/assets/global.css" />
</head>
<body className="has-sidebar">
<body className="has-sidebar page-verfahrensablauf">
<Sidebar currentPath="/tools/verfahrensablauf" />
<BottomNav currentPath="/tools/verfahrensablauf" />
@@ -210,6 +210,53 @@ export function renderVerfahrensablauf(): string {
Fristen berechnen
</button>
</div>
{/* Perspective strip (t-paliad-250 / m/paliad#81). Side
swaps the column LABELS so the user's own side is
proactive (= "your filings"). Appellant collapses
party=both rows to a single column when set — only
relevant for role-swap proceedings (Appeal etc.);
the row hides itself when the picked proceeding has
no appellant axis (see hasAppellantAxis() in the
client). Both selectors are URL-driven (?side= +
?appellant=) so the perspective survives reload
and is shareable. */}
<div className="verfahrensablauf-perspective" id="verfahrensablauf-perspective">
<div className="verfahrensablauf-perspective-row" id="side-row">
<span className="date-label" data-i18n="deadlines.side.label">Seite:</span>
<div className="fristen-view-toggle" role="radiogroup" aria-label="Side">
<label className="fristen-view-option">
<input type="radio" name="side" value="claimant" />
<span data-i18n="deadlines.side.claimant">Klägerseite</span>
</label>
<label className="fristen-view-option">
<input type="radio" name="side" value="defendant" />
<span data-i18n="deadlines.side.defendant">Beklagtenseite</span>
</label>
<label className="fristen-view-option">
<input type="radio" name="side" value="" checked />
<span data-i18n="deadlines.side.both">Beide</span>
</label>
</div>
</div>
<div className="verfahrensablauf-perspective-row" id="appellant-row" style="display:none">
<span className="date-label" data-i18n="deadlines.appellant.label">Berufung durch:</span>
<div className="fristen-view-toggle" role="radiogroup" aria-label="Appellant">
<label className="fristen-view-option">
<input type="radio" name="appellant" value="claimant" />
<span data-i18n="deadlines.appellant.claimant">Klägerseite</span>
</label>
<label className="fristen-view-option">
<input type="radio" name="appellant" value="defendant" />
<span data-i18n="deadlines.appellant.defendant">Beklagtenseite</span>
</label>
<label className="fristen-view-option">
<input type="radio" name="appellant" value="" checked />
<span data-i18n="deadlines.appellant.none"></span>
</label>
</div>
</div>
</div>
</div>
<div className="wizard-step" id="step-3" style="display:none">

View File

@@ -30,6 +30,78 @@ type Entry struct {
// Entries lists everything shipped so far, newest first. Append new rows
// at the top.
var Entries = []Entry{
{
Date: "2026-05-21",
Tag: TagFeature,
TitleDE: "Konfigurierbares Dashboard",
TitleEN: "Configurable dashboard",
BodyDE: "Das Dashboard lässt sich jetzt frei zusammenstellen: Widgets per Drag-and-drop verschieben, in der Größe ändern und einzeln konfigurieren. Der Katalog umfasst Fristen-Ampel, Termine, Agenda, Inbox-Übersicht, angepinnte Projekte und Schnellaktionen. Admins können eine kanzleiweite Standardanordnung festlegen, von der jeder Nutzer startet und sie nach Wunsch anpasst.",
BodyEN: "The dashboard can now be assembled freely: drag-and-drop widgets, resize them and configure each one individually. The catalog covers the deadline traffic-light, appointments, agenda, inbox summary, pinned projects and quick actions. Admins can set a firm-wide default layout that every user starts from and then tweaks to taste.",
},
{
Date: "2026-05-20",
Tag: TagFeature,
TitleDE: "Eigene Einreichungs-Checklisten",
TitleEN: "User-authored checklists",
BodyDE: "Eigene Checklisten lassen sich per Wizard anlegen und gezielt mit einzelnen Kolleg:innen, einem Büro, einer Partnereinheit oder einem Projekt teilen. Admins können besonders gute Vorlagen kanzleiweit unter „Geteilte Vorlagen\" freigeben. Wird eine Vorlage später überarbeitet, erscheint an laufenden Instanzen ein Hinweis-Badge auf die neuere Version.",
BodyEN: "Build your own filing checklists through a wizard and share them explicitly with individual colleagues, an office, a partner unit or a project. Admins can promote the best templates firm-wide under „Shared templates\". When a template is later revised, running instances surface a notice badge pointing at the newer version.",
},
{
Date: "2026-05-20",
Tag: TagFeature,
TitleDE: "Genehmigungen: Änderungen vorschlagen",
TitleEN: "Approvals: suggest changes",
BodyDE: "Im Inbox gibt es eine dritte Aktion neben „Genehmigen\" und „Ablehnen\": „Änderungen vorschlagen\". Ein Modal zeigt den ursprünglichen Wert, der Gegenvorschlag wandert mit einem Kommentar zurück an die Antragsteller:in. Der gesamte Austausch erscheint im Verlauf des Eintrags.",
BodyEN: "Inbox now offers a third action alongside „Approve\" and „Reject\": „Suggest changes\". A modal shows the original value, the counter-proposal travels back to the requester together with a comment. The full exchange shows up in the entry's Verlauf.",
},
{
Date: "2026-05-20",
Tag: TagFeature,
TitleDE: "Mandant:innen-Rolle und automatische Projekt-Codes",
TitleEN: "Client role and auto-derived project codes",
BodyDE: "Mandant:innen lassen sich jetzt als eigene Rolle in das Team eines Projekts aufnehmen — separat von HLC-Mitgliedern und mit eigenem Sichtbarkeitsumfang. Außerdem leitet Paliad pro Projekt einen kompakten Code aus dem Baum ab (etwa /9999-1-EP123-CFI) und zeigt ihn als zweites Badge im Header und in jedem Projekt-Picker.",
BodyEN: "Clients can now be added to a project's team as their own role — separate from HLC members and with their own visibility scope. In addition, Paliad derives a compact code per project from the ancestor tree (e.g. /9999-1-EP123-CFI) and shows it as a second badge in the header and in every project picker.",
},
{
Date: "2026-05-19",
Tag: TagFeature,
TitleDE: "Datenexport — Excel, CSV, JSON",
TitleEN: "Data export — Excel, CSV, JSON",
BodyDE: "Unter Einstellungen → Datenexport lassen sich alle sichtbaren Projekte, Fristen, Termine, Notizen und Checklisten als Excel-, CSV- oder JSON-Datei herunterladen. Auf jeder Projekt-Seite gibt es zusätzlich einen „Daten exportieren\"-Button, der nur den jeweiligen Teilbaum mitnimmt.",
BodyEN: "Settings → Data export lets you download every project, deadline, appointment, note and checklist you can see as an Excel, CSV or JSON file. Each project page additionally offers a „Daten exportieren\" button that exports just that subtree.",
},
{
Date: "2026-05-15",
Tag: TagFeature,
TitleDE: "Eigene Sichten — Liste, Karten, Kalender, Timeline",
TitleEN: "Custom views — list, cards, calendar, timeline",
BodyDE: "Eigene Filter über Fristen, Termine und Projekte lassen sich speichern und als Liste, Karten, Kalender oder Timeline rendern. Jede Sicht erhält einen permanenten Link, lässt sich als SVG, PNG, CSV, JSON oder iCal exportieren und erscheint in der Seitenleiste unter „Meine Sichten\".",
BodyEN: "Custom filters over deadlines, appointments and projects can be saved and rendered as list, cards, calendar or timeline. Each view gets a permalink, can be exported as SVG, PNG, CSV, JSON or iCal and shows up in the sidebar under „Meine Sichten\".",
},
{
Date: "2026-05-07",
Tag: TagFeature,
TitleDE: "Projekte-Seite mit Baum, Pinnungen und Karten-Ansicht",
TitleEN: "Projects page with tree, pins and cards view",
BodyDE: "Die Projekte-Seite öffnet jetzt mit einem zusammenklappbaren Baum, Volltextsuche und Chips für Mandant, Ort und Status. Häufig genutzte Projekte lassen sich oben anpinnen; die alternative Karten-Ansicht erlaubt frei per Drag-and-drop sortierbare Layouts pro Nutzer.",
BodyEN: "The Projects page now opens with a collapsible tree, full-text search and chips for client, location and status. Frequently used projects can be pinned to the top; the alternative cards view supports per-user drag-and-drop layouts.",
},
{
Date: "2026-05-06",
Tag: TagFeature,
TitleDE: "Vier-Augen-Prinzip für Fristen und Termine",
TitleEN: "Four-eyes principle for deadlines and appointments",
BodyDE: "Pro Projekt lässt sich festlegen, dass Anlegen, Ändern, Abhaken und Löschen von Fristen oder Terminen durch eine zweite Person freigegeben werden müssen. Anfragen erscheinen im Inbox, am Eintrag selbst und mit „PENDING\"-Vermerk im CalDAV-Kalender. Admins pflegen die Regeln zentral unter /admin/approval-policies.",
BodyEN: "Per project you can require that creating, editing, completing or deleting a deadline or appointment must be cleared by a second person. Requests show up in the inbox, on the entry itself and as a „PENDING\" marker in the CalDAV calendar. Admins maintain the rules centrally under /admin/approval-policies.",
},
{
Date: "2026-05-05",
Tag: TagFeature,
TitleDE: "Fristenrechner v3 — Entscheidungsbaum, Begriffe, DE/EPA/DPMA",
TitleEN: "Deadline calculator v3 — decision tree, concepts, DE/EPA/DPMA",
BodyDE: "Der Fristenrechner wurde grundlegend überarbeitet: ein Entscheidungsbaum führt durch Verfahren und Fristart, eine neue Begriffsebene fasst Wiedereinsetzung, Säumnis, Schriftsatznachreichung und Weiterbehandlung als wiederverwendbare Konzepte zusammen. Der Regelbestand wurde um deutsche Verfahren (PatG, BPatG, BGH), EPA- und DPMA-Strecken erweitert, mit aktuellen Werten und Querverweisen.",
BodyEN: "The deadline calculator has been overhauled from the ground up: a decision tree walks you through proceeding and deadline type, and a new concept layer treats Wiedereinsetzung, default, post-filing and further processing as reusable cross-cutting building blocks. The rule corpus has been extended with German proceedings (PatG, BPatG, BGH), EPO and DPMA tracks, with current values and cross-references.",
},
{
Date: "2026-04-30",
Tag: TagFeature,

View File

@@ -0,0 +1,2 @@
ALTER TABLE paliad.paliadin_turns
DROP COLUMN IF EXISTS aichat_conversation_id;

View File

@@ -0,0 +1,14 @@
-- t-paliad-235: track aichat conversation id on each paliadin turn so the
-- recovery endpoint can ask aichat for the late-arriving response when
-- paliad's stream connection drops mid-turn.
--
-- The PALIADIN_BACKEND=aichat path persists this from the upstream
-- /chat/turn/stream `done` frame's conversation_id. PALIADIN_BACKEND=legacy
-- turns leave it NULL — the filesystem janitor is still the recovery path
-- there.
ALTER TABLE paliad.paliadin_turns
ADD COLUMN IF NOT EXISTS aichat_conversation_id uuid;
COMMENT ON COLUMN paliad.paliadin_turns.aichat_conversation_id IS
'Aichat backend conversation id (t-paliad-235). Set when the streaming /chat/turn/stream done frame arrives, or when the recovery endpoint asks aichat to disambiguate which conversation this turn lives in. NULL for legacy backend turns and for aichat turns that errored before the conversation id was resolved.';

View File

@@ -0,0 +1,7 @@
-- t-paliad-238: revert submission_drafts table.
--
-- The shared paliad.tg_set_updated_at trigger function is intentionally
-- left in place — it may be in use by other tables. DROP TABLE cascades
-- to the trigger that references it on this table only.
DROP TABLE IF EXISTS paliad.submission_drafts;

View File

@@ -0,0 +1,88 @@
-- t-paliad-238: dedicated Submissions/Schriftsätze page.
--
-- paliad.submission_drafts holds the lawyer's per-(project, submission_code)
-- draft state for the new editor at /projects/{id}/submissions/{code}/draft.
-- Each row is one named draft owned by one user; multiple drafts per
-- (project, submission_code, user_id) are supported via the `name` field
-- (auto-generated "Entwurf 1", "Entwurf 2", … and lawyer-renameable).
--
-- `variables` carries the lawyer's overrides for the placeholder map
-- assembled at export time by SubmissionVarsService — empty string forces
-- the [KEIN WERT: …] marker; absent key falls back to the resolved bag.
--
-- `last_exported_at` / `last_exported_sha` record provenance of the most
-- recent .docx export (template SHA pinned for audit). Audit rows live
-- in paliad.system_audit_log + paliad.project_events; this table is the
-- lawyer's working state, not the audit log.
--
-- Visibility: per project CLAUDE.md, every project-scoped resource gates
-- on paliad.can_see_project. UPDATE / DELETE additionally require the
-- draft's user_id to match auth.uid() so two co-team-members don't stomp
-- on each other's drafts (head-confirmed Q-E4 owner-scoped pick).
CREATE TABLE IF NOT EXISTS paliad.submission_drafts (
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
project_id uuid NOT NULL REFERENCES paliad.projects(id) ON DELETE CASCADE,
submission_code text NOT NULL,
user_id uuid NOT NULL REFERENCES paliad.users(id) ON DELETE CASCADE,
name text NOT NULL,
variables jsonb NOT NULL DEFAULT '{}'::jsonb,
last_exported_at timestamptz,
last_exported_sha text,
created_at timestamptz NOT NULL DEFAULT now(),
updated_at timestamptz NOT NULL DEFAULT now(),
CONSTRAINT submission_drafts_unique_per_user
UNIQUE (project_id, submission_code, user_id, name)
);
CREATE INDEX IF NOT EXISTS submission_drafts_project_user_idx
ON paliad.submission_drafts (project_id, user_id, submission_code, updated_at DESC);
ALTER TABLE paliad.submission_drafts ENABLE ROW LEVEL SECURITY;
DROP POLICY IF EXISTS submission_drafts_select ON paliad.submission_drafts;
CREATE POLICY submission_drafts_select
ON paliad.submission_drafts FOR SELECT TO authenticated
USING (paliad.can_see_project(project_id));
DROP POLICY IF EXISTS submission_drafts_insert ON paliad.submission_drafts;
CREATE POLICY submission_drafts_insert
ON paliad.submission_drafts FOR INSERT TO authenticated
WITH CHECK (
user_id = auth.uid()
AND paliad.can_see_project(project_id)
);
DROP POLICY IF EXISTS submission_drafts_update ON paliad.submission_drafts;
CREATE POLICY submission_drafts_update
ON paliad.submission_drafts FOR UPDATE TO authenticated
USING (user_id = auth.uid() AND paliad.can_see_project(project_id))
WITH CHECK (user_id = auth.uid() AND paliad.can_see_project(project_id));
DROP POLICY IF EXISTS submission_drafts_delete ON paliad.submission_drafts;
CREATE POLICY submission_drafts_delete
ON paliad.submission_drafts FOR DELETE TO authenticated
USING (user_id = auth.uid() AND paliad.can_see_project(project_id));
-- updated_at maintenance: trigger function lives once per schema; reuse if
-- it already exists, otherwise create the standard shape.
CREATE OR REPLACE FUNCTION paliad.tg_set_updated_at()
RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
NEW.updated_at = now();
RETURN NEW;
END;
$$;
DROP TRIGGER IF EXISTS submission_drafts_set_updated_at ON paliad.submission_drafts;
CREATE TRIGGER submission_drafts_set_updated_at
BEFORE UPDATE ON paliad.submission_drafts
FOR EACH ROW EXECUTE FUNCTION paliad.tg_set_updated_at();
COMMENT ON TABLE paliad.submission_drafts IS
't-paliad-238: per-(project, submission_code, user) named drafts for the dedicated Submissions/Schriftsätze page. Each row holds the lawyer-edited variable overrides for the .docx export. Audit rows live in paliad.system_audit_log + paliad.project_events.';

View File

@@ -0,0 +1,46 @@
-- t-paliad-243 revert: restore NOT NULL on project_id.
--
-- The revert refuses to run if any project-less draft exists — those
-- rows would silently fail the NOT NULL re-imposition and corrupt the
-- migration runner's state. The safe revert path is to surface the
-- conflict to the operator who can decide whether to attach the rows
-- to a project or delete them before retrying the down.
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM paliad.submission_drafts WHERE project_id IS NULL
) THEN
RAISE EXCEPTION
'cannot re-impose NOT NULL on paliad.submission_drafts.project_id: '
'project-less drafts exist. Attach them to a project or delete '
'them, then re-run the down migration.';
END IF;
END $$;
ALTER TABLE paliad.submission_drafts
ALTER COLUMN project_id SET NOT NULL;
DROP POLICY IF EXISTS submission_drafts_select ON paliad.submission_drafts;
CREATE POLICY submission_drafts_select
ON paliad.submission_drafts FOR SELECT TO authenticated
USING (paliad.can_see_project(project_id));
DROP POLICY IF EXISTS submission_drafts_insert ON paliad.submission_drafts;
CREATE POLICY submission_drafts_insert
ON paliad.submission_drafts FOR INSERT TO authenticated
WITH CHECK (
user_id = auth.uid()
AND paliad.can_see_project(project_id)
);
DROP POLICY IF EXISTS submission_drafts_update ON paliad.submission_drafts;
CREATE POLICY submission_drafts_update
ON paliad.submission_drafts FOR UPDATE TO authenticated
USING (user_id = auth.uid() AND paliad.can_see_project(project_id))
WITH CHECK (user_id = auth.uid() AND paliad.can_see_project(project_id));
DROP POLICY IF EXISTS submission_drafts_delete ON paliad.submission_drafts;
CREATE POLICY submission_drafts_delete
ON paliad.submission_drafts FOR DELETE TO authenticated
USING (user_id = auth.uid() AND paliad.can_see_project(project_id));

View File

@@ -0,0 +1,70 @@
-- t-paliad-243: drafts may exist without a project attached.
--
-- The global /submissions/new picker lets a lawyer start a Schriftsatz
-- draft straight from the top-level Schriftsätze sidebar, with or
-- without binding it to a project. project_id therefore becomes
-- optional. Existing rows are unaffected; new rows may insert NULL.
--
-- RLS rewrite: every policy splits on (project_id IS NULL):
--
-- project_id IS NOT NULL → gate on paliad.can_see_project (existing
-- inheritance-aware visibility).
-- project_id IS NULL → owner-only (user_id = auth.uid()). A
-- project-less draft is a personal scratch
-- space — never shared, never visible to
-- other team members.
--
-- INSERT enforces the same shape via WITH CHECK: a project-less insert
-- only writes user_id = auth.uid(); a project-scoped insert additionally
-- requires can_see_project.
ALTER TABLE paliad.submission_drafts
ALTER COLUMN project_id DROP NOT NULL;
DROP POLICY IF EXISTS submission_drafts_select ON paliad.submission_drafts;
CREATE POLICY submission_drafts_select
ON paliad.submission_drafts FOR SELECT TO authenticated
USING (
(project_id IS NULL AND user_id = auth.uid())
OR (project_id IS NOT NULL AND paliad.can_see_project(project_id))
);
DROP POLICY IF EXISTS submission_drafts_insert ON paliad.submission_drafts;
CREATE POLICY submission_drafts_insert
ON paliad.submission_drafts FOR INSERT TO authenticated
WITH CHECK (
user_id = auth.uid()
AND (
project_id IS NULL
OR paliad.can_see_project(project_id)
)
);
DROP POLICY IF EXISTS submission_drafts_update ON paliad.submission_drafts;
CREATE POLICY submission_drafts_update
ON paliad.submission_drafts FOR UPDATE TO authenticated
USING (
user_id = auth.uid()
AND (
project_id IS NULL
OR paliad.can_see_project(project_id)
)
)
WITH CHECK (
user_id = auth.uid()
AND (
project_id IS NULL
OR paliad.can_see_project(project_id)
)
);
DROP POLICY IF EXISTS submission_drafts_delete ON paliad.submission_drafts;
CREATE POLICY submission_drafts_delete
ON paliad.submission_drafts FOR DELETE TO authenticated
USING (
user_id = auth.uid()
AND (
project_id IS NULL
OR paliad.can_see_project(project_id)
)
);

View File

@@ -0,0 +1,7 @@
-- Drop the optional trigger-event label columns added in
-- 121_proceeding_trigger_event_label.up.sql. Any populated rows lose
-- their override; the frontend falls back to proceedingName.
ALTER TABLE paliad.proceeding_types
DROP COLUMN IF EXISTS trigger_event_label_en,
DROP COLUMN IF EXISTS trigger_event_label_de;

View File

@@ -0,0 +1,27 @@
-- t-paliad-250 / m/paliad#81 — Concern B: UPC Appeal trigger-event label.
--
-- The /tools/verfahrensablauf "Auslösendes Ereignis" caption falls back
-- to `paliad.proceeding_types.name` whenever the calculator finds no
-- root rule (duration_value=0 + parent_id=NULL + !is_court_set). For
-- UPC Appeal (upc.apl.merits) all rules carry a non-zero duration off
-- the trigger date, so the caption reads "Berufungsverfahren" /
-- "Appeal" — the proceeding itself — instead of the appealable
-- decision that actually starts the clock.
--
-- Fix: add an optional `trigger_event_label_de` / `trigger_event_label_en`
-- pair on proceeding_types. When set, the calculator surfaces it on the
-- response (TriggerEventLabel{,EN}) and the frontend prefers it over
-- proceedingName. No deadline-rule additions, no slug changes; existing
-- proceeding_type.code stays stable (hard rule from the issue).
ALTER TABLE paliad.proceeding_types
ADD COLUMN IF NOT EXISTS trigger_event_label_de text,
ADD COLUMN IF NOT EXISTS trigger_event_label_en text;
-- UPC Appeal: the trigger date is the date of the appealable first-instance
-- decision (per UPC RoP R.224(1)(a) the 2-month appeal clock runs from
-- service of the decision per R.220.1(a)/(b)).
UPDATE paliad.proceeding_types
SET trigger_event_label_de = 'Anfechtbare Entscheidung',
trigger_event_label_en = 'Appealable Decision'
WHERE code = 'upc.apl.merits';

View File

@@ -0,0 +1,6 @@
-- t-paliad-258: revert the additive custom_rule_text column.
-- Drop the column; rows that used the Custom path lose their free-text
-- label and read as "no rule".
ALTER TABLE paliad.deadlines
DROP COLUMN IF EXISTS custom_rule_text;

View File

@@ -0,0 +1,26 @@
-- t-paliad-258 / m/paliad#89 — binary Auto/Custom Rule model on the
-- deadline form.
--
-- t-paliad-251 shipped the form with a full deadline_rules catalog
-- dropdown. m's verdict: too noisy (4 "Oral hearings" across UPC CFI,
-- UPC CoA, DPMA, EPO etc.). Replace with a binary model:
--
-- 1. Auto — rule_id derived from the chosen event_type, displayed
-- read-only.
-- 2. Custom — rule_id is NULL and the lawyer's free-text label is
-- stored here.
--
-- The column is additive + nullable: existing rows keep their
-- deadline_rule_id and read as Auto-equivalent. A future row with both
-- columns NULL renders as "keine Regel" (matches today's no-rule state).
ALTER TABLE paliad.deadlines
ADD COLUMN IF NOT EXISTS custom_rule_text text;
COMMENT ON COLUMN paliad.deadlines.custom_rule_text IS
'Free-text rule label entered when the lawyer chose Custom on the '
'deadline form (t-paliad-258). Mutually exclusive with rule_id at '
'the application layer: Auto path sets rule_id and leaves this '
'NULL; Custom path sets this and leaves rule_id NULL. Display '
'surfaces prefer the rule_id-joined deadline_rules.name when '
'present, else fall back to custom_rule_text + a "Custom" badge.';

View File

@@ -326,6 +326,56 @@ func handleRevokeApprovalRequest(w http.ResponseWriter, r *http.Request) {
handleApprovalDecision(w, r, "revoke")
}
// POST /api/approval-requests/{id}/edit-entity — t-paliad-252 / m/paliad#83.
//
// Lets the requester revise the in-flight entity (e.g. tweak the title on a
// pending create) without withdrawing the request. The non-destructive
// sibling of /revoke that m asked for after noticing that withdraw silently
// deletes the underlying event.
//
// Body: {"fields": {<entity-shape>}}
// 200: {"status": "ok"}
//
// Status mapping (mapApprovalError):
//
// 400 suggestion_requires_change — payload has no allowlisted fields
// 403 not_authorized — caller isn't the requested_by
// 404 — request not found / not visible
// 409 request_not_pending — request already decided / revoked
type editPendingEntityBody struct {
Fields map[string]any `json:"fields"`
}
func handleEditPendingEntity(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
requestID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request id"})
return
}
var body editPendingEntityBody
if r.Body != nil && r.ContentLength > 0 {
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{
"code": "invalid_body",
"message": "Ungültiger Body.",
})
return
}
}
if err := dbSvc.approval.EditPendingEntity(r.Context(), requestID, uid, body.Fields); err != nil {
writeApprovalError(w, err)
return
}
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
// suggestChangesBody is the JSON body for POST /api/approval-requests/{id}/suggest-changes.
// counter_payload is an entity-shaped jsonb of the approver's edited
// values (allowlist enforced server-side); note is the optional free-text

View File

@@ -33,11 +33,29 @@ func handleChecklistsAuthorPage(w http.ResponseWriter, r *http.Request) {
func handleChecklistDetailPage(w http.ResponseWriter, r *http.Request) {
slug := r.PathValue("slug")
if _, ok := checklists.Find(slug); !ok {
http.NotFound(w, r)
// Static catalog match → serve unconditionally; the static templates
// are always visible.
if _, ok := checklists.Find(slug); ok {
http.ServeFile(w, r, "dist/checklists-detail.html")
return
}
http.ServeFile(w, r, "dist/checklists-detail.html")
// Otherwise fall back to the DB-backed catalog (authored templates,
// slug shape "u-a-..." from t-paliad-225). The catalog enforces
// visibility per-user; a slug the caller can't see returns
// ErrNotVisible and the user gets the same 404 they'd see for an
// unknown slug. Without this branch authored checklists 404'd at the
// page level even though they showed up in the overview, which is
// exactly m's 2026-05-22 report.
if dbSvc != nil && dbSvc.checklistCatalog != nil {
uid, ok := auth.UserIDFromContext(r.Context())
if ok {
if _, err := dbSvc.checklistCatalog.Find(r.Context(), uid, slug); err == nil {
http.ServeFile(w, r, "dist/checklists-detail.html")
return
}
}
}
http.NotFound(w, r)
}
func handleChecklistInstancePage(w http.ResponseWriter, r *http.Request) {

View File

@@ -11,8 +11,15 @@ import "net/http"
// to the canonical /events?type=deadline (t-paliad-115). Detail page
// /deadlines/{id} stays type-specific. Drop this redirect once we're
// confident no caches / bookmarks / external links still hit the old URL.
//
// Preserves the incoming query string so filter params (e.g. status=this_week
// from the dashboard summary cards) survive the redirect.
func handleDeadlinesListRedirect(w http.ResponseWriter, r *http.Request) {
http.Redirect(w, r, "/events?type=deadline", http.StatusMovedPermanently)
target := "/events?type=deadline"
if r.URL.RawQuery != "" {
target += "&" + r.URL.RawQuery
}
http.Redirect(w, r, target, http.StatusMovedPermanently)
}
func handleDeadlinesNewPage(w http.ResponseWriter, r *http.Request) {

View File

@@ -1,6 +1,7 @@
package handlers
import (
"context"
"encoding/json"
"fmt"
"io"
@@ -36,6 +37,11 @@ type fileEntry struct {
//
// The URL slug ("hl-patents-style.dotm") is preserved as a stable public
// identifier so existing bookmarks keep working post-rebrand.
//
// Per-submission templates (slug `submission/<code>.docx`) are server-only:
// only the submission-draft editor reaches them via fetchSubmissionTemplateBytes.
// handleFileDownload serves any slug that lands here, but the public URL
// surface for submission templates is the export endpoint, not /files.
var fileRegistry = map[string]fileEntry{
"hl-patents-style.dotm": {
RawURL: "https://mgit.msbls.de/m/mWorkRepo/raw/branch/main/6%20-%20material/Templates/Word/HL%20Patents%20Style.dotm",
@@ -45,6 +51,92 @@ var fileRegistry = map[string]fileEntry{
RepoName: "mWorkRepo",
FilePath: "6 - material/Templates/Word/HL Patents Style.dotm",
},
// Per-submission demo template (t-paliad-241). Exercises every
// placeholder SubmissionVarsService resolves so the
// /projects/{id}/submissions/{code}/draft editor has variables to
// substitute. One file per submission_code; future codes register
// the same way — slug shape "submission/<code>.docx" so the
// namespace stays separate from the universal style template.
"submission/de.inf.lg.erwidg.docx": {
RawURL: "https://mgit.msbls.de/m/mWorkRepo/raw/branch/main/6%20-%20material/Templates/Word/Paliad/" + branding.Name + "/de.inf.lg.erwidg.docx",
DownloadName: "Klageerwiderung — " + branding.Name + ".docx",
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
RepoOwner: "m",
RepoName: "mWorkRepo",
FilePath: "6 - material/Templates/Word/Paliad/" + branding.Name + "/de.inf.lg.erwidg.docx",
},
// Universal skeleton (t-paliad-259). Code-agnostic Schriftsatz starter
// that carries every placeholder SubmissionVarsService resolves but no
// submission_code-specific body structure. Slot between the per-firm
// per-code template and the bare HL Patents Style .dotm fallback: every
// submission_code without a dedicated template still renders with
// variables substituted instead of the macro-only letterhead.
skeletonSubmissionSlug: {
RawURL: "https://mgit.msbls.de/m/mWorkRepo/raw/branch/main/6%20-%20material/Templates/Word/Paliad/" + branding.Name + "/_skeleton.docx",
DownloadName: branding.Name + " — Schriftsatz-Skelett.docx",
ContentType: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
RepoOwner: "m",
RepoName: "mWorkRepo",
FilePath: "6 - material/Templates/Word/Paliad/" + branding.Name + "/_skeleton.docx",
},
}
// skeletonSubmissionSlug names the universal skeleton template inside
// the shared fileRegistry cache. Exported via a const so handler code
// (resolveSubmissionTemplate, hlPatentsStyleSHA's sibling) refers to
// the same string the registry uses.
const skeletonSubmissionSlug = "submission/_skeleton.docx"
// submissionTemplateRegistry maps a deadline-rule submission_code to a
// fileRegistry slug. Lookup order matches the cronus design fallback
// chain §8: per-firm `templates/{FIRM_NAME}/{code}.docx` first, then
// universal HL Patents Style as the global fallback.
//
// Add new entries here as the firm authors per-submission templates;
// the file itself lives in mWorkRepo and is served through the shared
// Gitea proxy cache so refreshes are visible to all consumers in one
// place.
var submissionTemplateRegistry = map[string]string{
"de.inf.lg.erwidg": "submission/de.inf.lg.erwidg.docx",
}
// fetchSubmissionTemplateBytes returns the per-submission_code template
// bytes (and provenance SHA) when one is registered. The bool result
// distinguishes "no per-code template registered" (callers fall back to
// HL Patents Style) from an upstream fetch error.
func fetchSubmissionTemplateBytes(ctx context.Context, submissionCode string) ([]byte, string, bool, error) {
slug, ok := submissionTemplateRegistry[submissionCode]
if !ok {
return nil, "", false, nil
}
entry, ok := fileRegistry[slug]
if !ok {
return nil, "", false, fmt.Errorf("file proxy: submission template slug %q not registered", slug)
}
ce := getCacheEntry(slug)
ce.mu.RLock()
hasData := len(ce.data) > 0
needsCheck := time.Since(ce.lastChecked) >= checkInterval
ce.mu.RUnlock()
if !hasData {
if err := fileFetch(ce, entry); err != nil {
return nil, "", false, err
}
} else if needsCheck {
go fileCheckAndRefresh(ce, entry)
}
ce.mu.RLock()
defer ce.mu.RUnlock()
if len(ce.data) == 0 {
return nil, "", false, fmt.Errorf("file proxy: %s cache empty after fetch", slug)
}
out := make([]byte, len(ce.data))
copy(out, ce.data)
_ = ctx
return out, ce.sha, true, nil
}
type cacheEntry struct {
@@ -117,6 +209,85 @@ func handleFileRefresh(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]string{"ok": "true", "message": "Cache cleared"})
}
// fetchSubmissionSkeletonBytes returns the cached universal skeleton
// template bytes plus its provenance SHA. Sits between the per-firm
// per-submission_code template (fetchSubmissionTemplateBytes) and the
// bare universal HL Patents Style .dotm (fetchHLPatentsStyleBytes) in
// resolveSubmissionTemplate's fallback chain — used for every
// submission_code that has no dedicated template registered. Same
// stale-while-revalidate semantics as the rest of the file proxy: first
// call warms the cache synchronously from mWorkRepo via Gitea; later
// calls return immediately while a background refresh runs.
func fetchSubmissionSkeletonBytes(ctx context.Context) ([]byte, string, error) {
entry, ok := fileRegistry[skeletonSubmissionSlug]
if !ok {
return nil, "", fmt.Errorf("file proxy: %s not registered", skeletonSubmissionSlug)
}
ce := getCacheEntry(skeletonSubmissionSlug)
ce.mu.RLock()
hasData := len(ce.data) > 0
needsCheck := time.Since(ce.lastChecked) >= checkInterval
ce.mu.RUnlock()
if !hasData {
if err := fileFetch(ce, entry); err != nil {
return nil, "", err
}
} else if needsCheck {
go fileCheckAndRefresh(ce, entry)
}
ce.mu.RLock()
defer ce.mu.RUnlock()
if len(ce.data) == 0 {
return nil, "", fmt.Errorf("file proxy: %s cache empty after fetch", skeletonSubmissionSlug)
}
out := make([]byte, len(ce.data))
copy(out, ce.data)
_ = ctx
return out, ce.sha, nil
}
// fetchHLPatentsStyleBytes returns the cached HL Patents Style .dotm
// bytes. Shared accessor used by both the /files/{slug} download path
// (Word auto-update channel) and the submission generator
// (handlers/submissions.go) so a refresh through one path is visible to
// the other. First call warms the cache from Gitea synchronously;
// subsequent calls are sub-millisecond. A stale-but-present cache is
// returned immediately while a background refresh runs.
func fetchHLPatentsStyleBytes(ctx context.Context) ([]byte, error) {
entry, ok := fileRegistry[hlPatentsStyleSlug]
if !ok {
return nil, fmt.Errorf("file proxy: %s not registered", hlPatentsStyleSlug)
}
ce := getCacheEntry(hlPatentsStyleSlug)
ce.mu.RLock()
hasData := len(ce.data) > 0
needsCheck := time.Since(ce.lastChecked) >= checkInterval
ce.mu.RUnlock()
if !hasData {
if err := fileFetch(ce, entry); err != nil {
return nil, err
}
} else if needsCheck {
go fileCheckAndRefresh(ce, entry)
}
ce.mu.RLock()
defer ce.mu.RUnlock()
if len(ce.data) == 0 {
return nil, fmt.Errorf("file proxy: %s cache empty after fetch", hlPatentsStyleSlug)
}
out := make([]byte, len(ce.data))
copy(out, ce.data)
_ = ctx // ctx reserved for future timeout pass-through; fileFetch
// uses the package httpClient timeout today.
return out, nil
}
// fileFetch downloads the file synchronously (first request).
func fileFetch(ce *cacheEntry, entry fileEntry) error {
sha, _ := giteaLatestSHA(entry)

View File

@@ -98,14 +98,8 @@ type Services struct {
Projection *services.ProjectionService
Export *services.ExportService
// Submission generator (t-paliad-215) — Klageerwiderung &
// friends. Three coordinated services: registry fetches templates
// from Gitea; vars builds the placeholder map from project +
// parties + rule; renderer merges the .docx. Wired together in
// cmd/server/main.go; nil here when DATABASE_URL is unset.
SubmissionRegistry *services.TemplateRegistry
SubmissionVars *services.SubmissionVarsService
SubmissionRenderer *services.SubmissionRenderer
// t-paliad-238 — dedicated Submissions/Schriftsätze editor.
SubmissionDraft *services.SubmissionDraftService
// Paliadin is wired when DATABASE_URL is set. The concrete backend
// is picked in cmd/server/main.go based on PALIADIN_REMOTE_HOST
@@ -123,14 +117,6 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
paliadinSvc = svc.Paliadin
}
// Submission generator singletons (t-paliad-215). All three or
// none — the handler short-circuits with 503 when any is nil.
if svc != nil {
submissionRegistry = svc.SubmissionRegistry
submissionVars = svc.SubmissionVars
submissionRenderer = svc.SubmissionRenderer
}
if svc != nil {
dbSvc = &dbServices{
projects: svc.Project,
@@ -176,6 +162,7 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
firmDashboardDefault: svc.FirmDashboardDefault,
projection: svc.Projection,
export: svc.Export,
submissionDraft: svc.SubmissionDraft,
}
}
@@ -289,6 +276,11 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("POST /api/checklist-instances/{id}/reset", handleResetChecklistInstance)
protected.HandleFunc("DELETE /api/checklist-instances/{id}", handleDeleteChecklistInstance)
protected.HandleFunc("GET /api/projects/{id}/checklists", handleListChecklistInstancesForProject)
// t-paliad-240 — global Schriftsätze drafts index (top-level sidebar
// entry). Lists every draft the caller owns across visible projects.
// The per-project Schriftsätze tab keeps the editor itself project-
// scoped; this index is the cross-project landing.
protected.HandleFunc("GET /submissions", gateOnboarded(handleSubmissionsIndexPage))
protected.HandleFunc("GET /courts", handleCourtsPage)
protected.HandleFunc("GET /api/courts", handleCourtsAPI)
protected.HandleFunc("POST /api/courts/feedback", handleCourtsFeedback)
@@ -323,11 +315,40 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("POST /api/projects/{id}/timeline/milestone", handleCreateProjectTimelineMilestone)
protected.HandleFunc("POST /api/projects/{id}/timeline/anchor", handleProjectTimelineAnchor)
protected.HandleFunc("POST /api/projects/{id}/timeline/skip", handleProjectTimelineSkip)
// t-paliad-215 Slice 1 — submission generator. /submissions lists
// the project's filing-type rules with template-availability flags;
// /submissions/{code}/generate streams the rendered .docx.
// t-paliad-230 — submission generator (format-only). /submissions
// lists the project's published filing rules; /generate fetches the
// universal HL Patents Style .dotm, strips the macro project, and
// streams a clean .docx attachment. POST because each generation
// writes an audit row.
protected.HandleFunc("GET /api/projects/{id}/submissions", handleListProjectSubmissions)
protected.HandleFunc("GET /api/projects/{id}/submissions/{code}/generate", handleGenerateProjectSubmission)
protected.HandleFunc("POST /api/projects/{id}/submissions/{code}/generate", handleGenerateProjectSubmission)
// t-paliad-238 — dedicated Submissions/Schriftsätze draft editor.
// Per (project, submission_code, user) named drafts with autosaved
// variable overrides; export merges the bag with the universal HL
// Patents Style template (Slice A) or the per-code template
// (Slice B, future).
protected.HandleFunc("GET /api/projects/{id}/submissions/{code}/drafts", handleListSubmissionDrafts)
protected.HandleFunc("POST /api/projects/{id}/submissions/{code}/drafts", handleCreateSubmissionDraft)
protected.HandleFunc("GET /api/projects/{id}/submissions/{code}/drafts/{draft_id}", handleGetSubmissionDraft)
protected.HandleFunc("PATCH /api/projects/{id}/submissions/{code}/drafts/{draft_id}", handlePatchSubmissionDraft)
protected.HandleFunc("DELETE /api/projects/{id}/submissions/{code}/drafts/{draft_id}", handleDeleteSubmissionDraft)
protected.HandleFunc("GET /api/projects/{id}/submissions/{code}/drafts/{draft_id}/preview", handlePreviewSubmissionDraft)
protected.HandleFunc("POST /api/projects/{id}/submissions/{code}/drafts/{draft_id}/export", handleExportSubmissionDraft)
// t-paliad-240 — global drafts index (across visible projects).
protected.HandleFunc("GET /api/user/submission-drafts", handleListUserSubmissionDrafts)
// t-paliad-243 — global Schriftsätze drafts with optional project
// binding. The picker page at /submissions/new lists the full
// cross-proceeding catalog (without a project context) and posts to
// POST /api/submission-drafts to spawn a draft. The
// /api/submission-drafts/{draft_id}* endpoints back the project-less
// editor and ALSO accept project-scoped drafts (the draft row
// carries its own project_id so the project segment is redundant).
protected.HandleFunc("GET /api/submissions/catalog", handleListSubmissionCatalog)
protected.HandleFunc("POST /api/submission-drafts", handleCreateGlobalSubmissionDraft)
protected.HandleFunc("GET /api/submission-drafts/{draft_id}", handleGetGlobalSubmissionDraft)
protected.HandleFunc("PATCH /api/submission-drafts/{draft_id}", handleGlobalPatchSubmissionDraft)
protected.HandleFunc("DELETE /api/submission-drafts/{draft_id}", handleGlobalDeleteSubmissionDraft)
protected.HandleFunc("POST /api/submission-drafts/{draft_id}/export", handleGlobalExportSubmissionDraft)
// /counterclaim creates a CCR sub-project linked via the new
// paliad.projects.counterclaim_of FK (t-paliad-174 Slice 3).
protected.HandleFunc("POST /api/projects/{id}/counterclaim", handleCreateProjectCounterclaim)
@@ -481,6 +502,20 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("GET /projects/{id}/notes", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/checklists", gateOnboarded(handleProjectsDetailPage))
protected.HandleFunc("GET /projects/{id}/team", gateOnboarded(handleProjectsDetailPage))
// t-paliad-230 Schriftsätze tab — same shape as every other tab above.
// Without this route the deep-link 404s; the tab still works via
// in-page click since it just toggles a panel.
protected.HandleFunc("GET /projects/{id}/submissions", gateOnboarded(handleProjectsDetailPage))
// t-paliad-238 — dedicated submission draft editor. Both routes
// render the project detail page; the actual editor mounts
// client-side based on the URL path.
protected.HandleFunc("GET /projects/{id}/submissions/{code}/draft", gateOnboarded(handleSubmissionDraftPage))
protected.HandleFunc("GET /projects/{id}/submissions/{code}/draft/{draft_id}", gateOnboarded(handleSubmissionDraftPage))
// t-paliad-243 — global Schriftsätze pages: picker + project-less
// editor. Both render dist/* files; client bundles parse the URL
// and branch on whether a project segment is present.
protected.HandleFunc("GET /submissions/new", gateOnboarded(handleSubmissionsNewPage))
protected.HandleFunc("GET /submissions/draft/{draft_id}", gateOnboarded(handleSubmissionDraftGlobalPage))
// t-paliad-177 — standalone Project Timeline / Chart page (Slice 1).
// Horizontal SVG renderer mounted client-side; reuses the existing
// /api/projects/{id}/timeline JSON endpoint for data.
@@ -623,6 +658,9 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("POST /api/approval-requests/{id}/approve", handleApproveApprovalRequest)
protected.HandleFunc("POST /api/approval-requests/{id}/reject", handleRejectApprovalRequest)
protected.HandleFunc("POST /api/approval-requests/{id}/revoke", handleRevokeApprovalRequest)
// t-paliad-252 — non-destructive sibling of /revoke: lets the
// requester revise the in-flight entity without withdrawing.
protected.HandleFunc("POST /api/approval-requests/{id}/edit-entity", handleEditPendingEntity)
protected.HandleFunc("POST /api/approval-requests/{id}/suggest-changes", handleSuggestChangesApprovalRequest)
// t-paliad-154 — form-time effective policy lookup. Reachable by
@@ -664,6 +702,11 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
protected.HandleFunc("POST /api/paliadin/turn", handlePaliadinTurn)
protected.HandleFunc("GET /api/paliadin/stream/{id}", handlePaliadinStream)
protected.HandleFunc("GET /api/paliadin/turns/{id}", handlePaliadinTurnGet)
// Recovery endpoint (t-paliad-235): when the SSE stream drops mid-turn,
// the frontend hits this to ask whether aichat actually finished the
// turn upstream. Dispatches per backend — aichat hits the conversation
// API; legacy backends fall through to the local row read + janitor.
protected.HandleFunc("GET /api/paliadin/turns/{id}/recover", handlePaliadinTurnRecover)
// Crash-resistant history hydrate (t-paliad-161 follow-up): both
// Paliadin surfaces use this to seed their UI from the DB before
// consulting localStorage.

View File

@@ -185,16 +185,21 @@ func handlePaliadinTurn(w http.ResponseWriter, r *http.Request) {
}
// runPaliadinTurnAsync executes the turn and writes events into ch.
// Uses a 150 s hard timeout independently of the originating request,
// which leaves headroom over the shim's 120 s run-turn cap + SSH
// overhead (t-paliad-155: cold-start safety for skill + MCP discovery).
//
// Backend dispatch:
// - StreamingPaliadin (aichat) → drives runStreamingTurn which relays
// incremental chunks + upstream heartbeats. No hard ceiling on
// stream duration; falls back to silence_timeout (silenceTimeout)
// if the upstream goes dark.
// - Plain Paliadin (legacy local/remote) → one-shot RunTurn with the
// original 150 s ceiling (matches the shim's 120 s run-turn cap +
// SSH overhead per t-paliad-155).
func runPaliadinTurnAsync(turnID uuid.UUID, req services.TurnRequest, ch chan<- turnEvent) {
defer func() {
// Drain + close. The SSE handler reads until the channel closes.
close(ch)
}()
// Send a meta event so the client can show "Paliadin denkt nach …"
send(ch, turnEvent{
Kind: "meta",
Data: map[string]any{
@@ -203,6 +208,16 @@ func runPaliadinTurnAsync(turnID uuid.UUID, req services.TurnRequest, ch chan<-
},
})
if streamer, ok := paliadinSvc.(services.StreamingPaliadin); ok {
runStreamingTurn(turnID, req, ch, streamer)
return
}
runOneShotTurn(turnID, req, ch)
}
// runOneShotTurn drives the legacy synchronous backends (local-tmux PoC,
// remote ssh+paliadin-shim). Preserves the original 150 s ceiling.
func runOneShotTurn(turnID uuid.UUID, req services.TurnRequest, ch chan<- turnEvent) {
ctx, cancel := newDetachedContext(150 * time.Second)
defer cancel()
@@ -220,9 +235,7 @@ func runPaliadinTurnAsync(turnID uuid.UUID, req services.TurnRequest, ch chan<-
}
// One-shot content event with the full body. The frontend simulates
// streaming with a typewriter effect (cf. design §0.5.5: real
// chunked streaming would require Claude to write the response file
// progressively — out of PoC scope).
// streaming with a typewriter effect.
send(ch, turnEvent{
Kind: "content",
Data: map[string]any{"text": result.Response},
@@ -241,6 +254,224 @@ func runPaliadinTurnAsync(turnID uuid.UUID, req services.TurnRequest, ch chan<-
})
}
// silenceTimeout is the longest the aichat upstream may stay silent
// (no chunk, no heartbeat) before runStreamingTurn gives up and fires
// an error frame. 90 s comfortably exceeds aichat's 5 s heartbeat
// cadence so a transient stall (model wedge, GC pause) doesn't kill
// the turn, while still catching a hard upstream drop.
const silenceTimeout = 90 * time.Second
// streamingThinkingInterval is the cadence at which we emit a synthetic
// `thinking` event when the upstream has gone quiet but the connection
// is still alive. 5 s matches aichat's own heartbeat tick so the UI
// pulse never falls more than 5 s out of date.
const streamingThinkingInterval = 5 * time.Second
// streamingTurnDeadline is the upper bound for a single streaming turn.
// Far above any realistic Claude turn but finite so a runaway upstream
// (or a paliad bug that never closes the channel) can't leak forever.
const streamingTurnDeadline = 30 * time.Minute
// runStreamingTurn drives an incremental turn against the StreamingPaliadin
// backend. Relays chunks → content events, upstream heartbeats →
// thinking events, errors → error events. Adds its own silence-watch:
// if the upstream emits no event for silenceTimeout, fire an error
// frame so the client doesn't sit on a dead stream forever.
func runStreamingTurn(turnID uuid.UUID, req services.TurnRequest, ch chan<- turnEvent, streamer services.StreamingPaliadin) {
ctx, cancel := context.WithTimeout(context.Background(), streamingTurnDeadline)
defer cancel()
events := make(chan services.StreamEvent, 32)
startedAt := time.Now()
// streamerDone closes when the backend's RunTurnStream returns. We
// race the silence watcher and the event pump against it so the
// goroutine exit is clean either way.
type runResult struct {
result *services.TurnResult
err error
}
runCh := make(chan runResult, 1)
go func() {
res, err := streamer.RunTurnStream(ctx, req, events)
runCh <- runResult{res, err}
}()
var (
lastEventAt = time.Now()
usedTools []string
rowsSeen []int
classifierTag string
convID string
gotChunk bool
errorEmitted bool
)
silenceTicker := time.NewTicker(streamingThinkingInterval)
defer silenceTicker.Stop()
emitThinking := func(elapsedSeconds int) {
// Don't emit `thinking` after the first real chunk arrives —
// the frontend hides the pulse once content starts flowing
// anyway, but we save bandwidth by stopping emission.
send(ch, turnEvent{
Kind: "thinking",
Data: map[string]any{
"elapsed_seconds": elapsedSeconds,
"since_first": gotChunk,
},
})
}
for {
select {
case ev, more := <-events:
if !more {
events = nil // disable case
continue
}
lastEventAt = time.Now()
switch ev.Kind {
case services.StreamChunk:
gotChunk = true
send(ch, turnEvent{
Kind: "content",
Data: map[string]any{
"delta": ev.Content,
"streamed": true,
},
})
case services.StreamHeartbeat:
// Upstream is alive but no chunks yet (or a mid-stream
// stall). Pass through with our own thinking shape.
send(ch, turnEvent{
Kind: "thinking",
Data: map[string]any{
"elapsed_seconds": ev.ElapsedSeconds,
"since_first": gotChunk,
"upstream": true,
},
})
case services.StreamMeta:
usedTools = ev.UsedTools
rowsSeen = ev.RowsSeen
classifierTag = ev.ClassifierTag
case services.StreamConversation:
convID = ev.ConversationID
case services.StreamError:
errorEmitted = true
send(ch, turnEvent{
Kind: "error",
Data: map[string]any{
"code": ev.Code,
"message": ev.Message,
"retryable": ev.Retryable,
},
})
}
case <-silenceTicker.C:
elapsed := time.Since(lastEventAt)
if elapsed >= silenceTimeout {
send(ch, turnEvent{
Kind: "error",
Data: map[string]any{
"code": "upstream_silence",
"message": "aichat upstream went silent for over " + silenceTimeout.String(),
},
})
// Cancel the backend so it doesn't keep running.
cancel()
continue
}
emitThinking(int(time.Since(startedAt).Seconds()))
case res := <-runCh:
// Drain any remaining events the backend pushed before
// closing the channel.
if events != nil {
for ev := range events {
switch ev.Kind {
case services.StreamChunk:
gotChunk = true
send(ch, turnEvent{
Kind: "content",
Data: map[string]any{
"delta": ev.Content,
"streamed": true,
},
})
case services.StreamMeta:
usedTools = ev.UsedTools
rowsSeen = ev.RowsSeen
classifierTag = ev.ClassifierTag
case services.StreamConversation:
convID = ev.ConversationID
case services.StreamError:
errorEmitted = true
send(ch, turnEvent{
Kind: "error",
Data: map[string]any{
"code": ev.Code,
"message": ev.Message,
"retryable": ev.Retryable,
},
})
}
}
}
if res.err != nil {
if !errorEmitted {
send(ch, turnEvent{
Kind: "error",
Data: map[string]any{
"code": "upstream_error",
"message": res.err.Error(),
},
})
}
return
}
result := res.result
if result == nil {
// Shouldn't happen — backend contract returns either err
// or a result. Defensive bail.
if !errorEmitted {
send(ch, turnEvent{
Kind: "error",
Data: map[string]any{
"code": "upstream_error",
"message": "stream closed without result",
},
})
}
return
}
if result.UsedTools != nil {
usedTools = result.UsedTools
}
if result.RowsSeen != nil {
rowsSeen = result.RowsSeen
}
if classifierTag == "" && result.ClassifierTag != "" {
classifierTag = result.ClassifierTag
}
endData := map[string]any{
"turn_id": turnID.String(),
"used_tools": usedTools,
"rows_seen": rowsSeen,
"chip_count": result.ChipCount,
"classifier_tag": classifierTag,
"duration_ms": result.DurationMS,
"streamed": true,
}
if convID != "" {
endData["aichat_conversation_id"] = convID
}
send(ch, turnEvent{Kind: "end", Data: endData})
return
}
}
}
// handlePaliadinStream is the SSE endpoint the EventSource subscribes
// to. Reads from the per-turn channel + writes SSE-framed events.
func handlePaliadinStream(w http.ResponseWriter, r *http.Request) {
@@ -354,6 +585,114 @@ func handlePaliadinTurnGet(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, resp)
}
// handlePaliadinTurnRecover is the dispatching late-recovery endpoint
// (t-paliad-235). Replaces the legacy direct-row-read for the aichat
// backend. When the backend implements services.AichatRecoverer (the
// PALIADIN_BACKEND=aichat path), we ask aichat directly via its
// conversation API whether the turn actually completed upstream after
// our stream connection dropped. When it doesn't implement it (legacy
// local/remote backends), we fall back to reading the local row —
// services.LocalPaliadinService.runJanitor is still the recovery path
// there.
//
// Response shape mirrors handlePaliadinTurnGet so the frontend
// late-poll module doesn't need a backend-specific code path.
// Additional field `recovery_state` distinguishes:
//
// "recovered" — the response is in the row (already there, or freshly
// written from the upstream check)
// "pending" — still no response; caller should keep polling
// "lost" — backend confirms the turn is gone (aichat doesn't
// have it either). UI should degrade to "verloren".
func handlePaliadinTurnRecover(w http.ResponseWriter, r *http.Request) {
if !requirePaliadinOwner(w, r) {
return
}
uid, _ := requireUser(w, r)
turnID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
http.Error(w, "invalid turn_id", http.StatusBadRequest)
return
}
// Quick read first — gives us the row regardless of backend.
row, err := paliadinSvc.GetTurn(r.Context(), uid, turnID)
if err != nil {
if errors.Is(err, sql.ErrNoRows) {
http.Error(w, "not found", http.StatusNotFound)
return
}
http.Error(w, "lookup failed", http.StatusInternalServerError)
return
}
state := recoveryStateFor(row)
// Aichat backend: when the row still has no response, ask aichat
// whether the turn actually finished upstream.
if state == "pending" {
if rec, ok := paliadinSvc.(services.AichatRecoverer); ok {
ctx, cancel := context.WithTimeout(r.Context(), 8*time.Second)
defer cancel()
recovered, recErr := rec.RecoverTurn(ctx, uid, turnID)
if recErr != nil {
// Log + fall through to a plain pending response — a
// transient aichat hiccup shouldn't flip the UI to
// "lost".
_ = recErr
} else if recovered != nil {
row = recovered
state = recoveryStateFor(row)
} else {
// Aichat returned a clean "no, I don't have it either".
// Only mark as lost when the turn is older than the
// upstream's plausible turn budget — otherwise the
// recovery just hit the window between paliad's stream
// dropping and aichat finishing the run.
if recoveryShouldGiveUp(row) {
state = "lost"
}
}
} else if recoveryShouldGiveUp(row) {
// Legacy backends: rely on the janitor. If we're past the
// give-up threshold and still no response, surface "lost".
state = "lost"
}
}
resp := map[string]any{
"turn_id": row.TurnID.String(),
"started_at": row.StartedAt.Format(time.RFC3339),
"response": row.Response,
"error_code": row.ErrorCode,
"finished_at": row.FinishedAt,
"duration_ms": row.DurationMS,
"used_tools": []string(row.UsedTools),
"rows_seen": []int64(row.RowsSeen),
"chip_count": row.ChipCount,
"classifier_tag": row.ClassifierTag,
"recovery_state": state,
}
writeJSON(w, http.StatusOK, resp)
}
// recoveryStateFor returns the lifecycle state of a paliadin turn from
// the recovery endpoint's perspective.
func recoveryStateFor(row *services.PaliadinTurn) string {
if row.Response != nil && *row.Response != "" {
return "recovered"
}
return "pending"
}
// recoveryShouldGiveUp returns true when a turn has been pending long
// enough that we should surface "lost" rather than asking the user to
// keep waiting. 12 minutes is comfortably beyond the longest realistic
// Claude turn (cold-start + reasoning + tool calls all bundled).
func recoveryShouldGiveUp(row *services.PaliadinTurn) bool {
return time.Since(row.StartedAt) > 12*time.Minute
}
// handlePaliadinHistory returns the caller's prior turns for a given
// browser session id, oldest → newest. Both Paliadin surfaces (the
// inline drawer and the standalone /paliadin page) hit this on mount

View File

@@ -251,6 +251,23 @@ func handleProjectTimelineAnchor(w http.ResponseWriter, r *http.Request) {
})
return
}
if cpe, ok := services.IsCrossProceedingAnchor(err); ok {
parentURL := "/projects/" + cpe.ParentProjectID.String()
writeJSON(w, http.StatusConflict, map[string]any{
"error": "cross_proceeding_anchor",
"requested_rule_code": cpe.RequestedRuleCode,
"requested_rule_name_de": cpe.RequestedRuleNameDE,
"requested_rule_name_en": cpe.RequestedRuleNameEN,
"parent_project_id": cpe.ParentProjectID.String(),
"parent_project_title": cpe.ParentProjectTitle,
"parent_project_url": parentURL,
"message_de": "Diese Frist gehört zum Verletzungsverfahren „" +
cpe.ParentProjectTitle + "“. Bitte den Anker dort setzen, nicht auf der Widerklage.",
"message_en": "This deadline belongs to the infringement proceeding „" +
cpe.ParentProjectTitle + "“. Anchor it on the parent project, not the counterclaim.",
})
return
}
writeServiceError(w, err)
return
}

View File

@@ -61,6 +61,9 @@ type dbServices struct {
firmDashboardDefault *services.FirmDashboardDefaultService
projection *services.ProjectionService
export *services.ExportService
// t-paliad-238 — submission draft editor.
submissionDraft *services.SubmissionDraftService
}
var dbSvc *dbServices

View File

@@ -57,3 +57,29 @@ func TestStandaloneCalendarHandlers_RedirectToEventsKalender(t *testing.T) {
}
}
}
// /deadlines list redirect must forward the incoming query string so legacy
// dashboard cards and external bookmarks like /deadlines?status=this_week
// land at /events?type=deadline&status=this_week instead of losing the
// filter. Regression for m's 2026-05-21 14:20 report.
func TestDeadlinesListRedirect_PreservesQueryString(t *testing.T) {
cases := []struct {
path string
want string
}{
{"/deadlines", "/events?type=deadline"},
{"/deadlines?status=this_week", "/events?type=deadline&status=this_week"},
{"/deadlines?status=overdue&project_id=abc", "/events?type=deadline&status=overdue&project_id=abc"},
}
for _, tc := range cases {
req := httptest.NewRequest(http.MethodGet, tc.path, nil)
w := httptest.NewRecorder()
handleDeadlinesListRedirect(w, req)
if w.Code != http.StatusMovedPermanently {
t.Fatalf("%s: status = %d, want 301", tc.path, w.Code)
}
if got := w.Header().Get("Location"); got != tc.want {
t.Fatalf("%s: Location = %q, want %q", tc.path, got, tc.want)
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -1,24 +1,37 @@
package handlers
// Submission generator HTTP layer (t-paliad-215 Slice 1).
// Submission generator HTTP layer (t-paliad-230 — format-only scope
// reduction of t-paliad-215; t-paliad-242 broadened the list endpoint
// to the full cross-proceeding catalog; t-paliad-253 promoted /generate
// from format-only to the same merge engine the draft editor uses).
//
// Endpoints:
//
// GET /api/projects/{id}/submissions
// Lists the project's proceeding-relevant submission codes
// and reports template availability for each. Powers the
// SubmissionsPanel on the project detail page.
// Lists every published filing rule across every active
// proceeding the platform knows about, joined with its
// proceeding_type so the frontend can group by proceeding.
// has_template flips per-row: true when a per-submission .docx
// is wired in submissionTemplateRegistry, false when the
// editor falls back to the universal HL Patents Style.
//
// GET /api/projects/{id}/submissions/{code}/generate
// Renders the .docx and streams it as an attachment download.
// Writes one paliad.system_audit_log row and one
// paliad.project_events row per generation. No server-side
// binary persistence (design §3, m's Q3 pick).
// POST /api/projects/{id}/submissions/{code}/generate
// Resolves the template through the cronus fallback chain
// (per-firm `submissionTemplateRegistry[code]` first, HL
// Patents Style as the universal fallback), builds a fresh
// variable bag via SubmissionVarsService.Build, and runs the
// SubmissionRenderer merge so every {{placeholder}} resolves
// to project state (or `[KEIN WERT: key]` for empties). Writes
// one paliad.system_audit_log row and streams the .docx as an
// attachment download. The HL Patents Style fallback has no
// placeholders today, so for codes without a per-firm template
// the renderer is a no-op on substitution but still runs the
// .dotm→.docx pre-pass.
//
// Visibility: every endpoint runs through ProjectService.GetByID
// (paliad.can_see_project gate). Unauthorised callers get 404, never
// 403 — same convention as the rest of the project surfaces (avoids
// project-existence enumeration).
// (paliad.can_see_project gate). Unauthorised callers get 404 — same
// convention as the rest of the project surfaces (no project-existence
// enumeration).
import (
"context"
@@ -33,48 +46,69 @@ import (
"github.com/google/uuid"
"mgit.msbls.de/m/paliad/internal/branding"
"mgit.msbls.de/m/paliad/internal/models"
"mgit.msbls.de/m/paliad/internal/services"
)
// submissionRenderer + registry + vars are package-level singletons
// wired by Register() once at boot. Stateless rendering + thread-safe
// caches inside the registry mean no per-request construction.
var (
submissionRenderer *services.SubmissionRenderer
submissionRegistry *services.TemplateRegistry
submissionVars *services.SubmissionVarsService
)
// submissionRenderTimeout caps a single generate request. Template
// fetch (cache-miss) + rendering of a typical pleading takes well
// under a second; the timeout exists to surface "Gitea is unreachable"
// quickly rather than letting the browser spin.
// submissionRenderTimeout caps a single generate request. .dotm fetch
// is from the in-process cache (sub-millisecond) and the convert step
// is a single zip round-trip; the timeout exists so a cold cache miss
// against Gitea surfaces quickly rather than letting the browser spin.
const submissionRenderTimeout = 30 * time.Second
// docxMime is the .docx Content-Type per the OOXML spec.
const docxMime = "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
// submissionListEntry is one row in the SubmissionsPanel.
// hlPatentsStyleSlug names the universal style template inside the
// fileRegistry in files.go. Both surfaces (the /files download for
// Word's auto-update channel and this generator) share the same
// cache entry so a refresh through one path is visible to the other.
const hlPatentsStyleSlug = "hl-patents-style.dotm"
// submissionListEntry is one row in the Schriftsätze panel.
type submissionListEntry struct {
SubmissionCode string `json:"submission_code"`
Name string `json:"name"`
NameEN string `json:"name_en"`
EventType string `json:"event_type,omitempty"`
PrimaryParty string `json:"primary_party,omitempty"`
LegalSource string `json:"legal_source,omitempty"`
HasTemplate bool `json:"has_template"`
SubmissionCode string `json:"submission_code"`
Name string `json:"name"`
NameEN string `json:"name_en"`
EventType string `json:"event_type,omitempty"`
PrimaryParty string `json:"primary_party,omitempty"`
LegalSource string `json:"legal_source,omitempty"`
HasTemplate bool `json:"has_template"`
ProceedingCode string `json:"proceeding_code"`
ProceedingName string `json:"proceeding_name"`
ProceedingNameEN string `json:"proceeding_name_en"`
}
// submissionListResponse wraps the list with a project-level header.
//
// ProjectProceedingCode names the project's own proceeding so the
// frontend can pin its group to the top of the grouped catalog
// (t-paliad-242). nil when the project hasn't bound a proceeding yet.
type submissionListResponse struct {
ProjectID uuid.UUID `json:"project_id"`
ProceedingTypeID *int `json:"proceeding_type_id,omitempty"`
Entries []submissionListEntry `json:"entries"`
ProjectID uuid.UUID `json:"project_id"`
ProceedingTypeID *int `json:"proceeding_type_id,omitempty"`
ProjectProceedingCode *string `json:"project_proceeding_code,omitempty"`
Entries []submissionListEntry `json:"entries"`
}
// handleListProjectSubmissions returns the filing-type rules for the
// project's proceeding, annotated with template availability.
// handleListProjectSubmissions returns every published filing rule
// across every active proceeding the platform knows about, joined with
// its proceeding_type so the Schriftsätze tab can group rows by
// proceeding (t-paliad-242 — m wants to see the entire catalog from any
// project, not just the rules for the project's own proceeding).
//
// Visibility is gated on the PROJECT (paliad.can_see_project via
// ProjectService.GetByID); the rules themselves are static reference
// data shared across the firm.
//
// has_template flips when a per-submission .docx is wired into
// submissionTemplateRegistry (files.go). When false, the universal HL
// Patents Style .dotm is the fallback — the editor (t-paliad-238)
// resolves both flavours transparently, so every row remains
// generatable and editable from the UI.
//
// Rows are sorted by (proceeding_code, submission_code) so the
// frontend's groupBy stays cheap and the order is stable.
func handleListProjectSubmissions(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
return
@@ -83,9 +117,6 @@ func handleListProjectSubmissions(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if !requireSubmissionsWired(w) {
return
}
projectID, err := uuid.Parse(r.PathValue("id"))
if err != nil {
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid project id"})
@@ -106,54 +137,145 @@ func handleListProjectSubmissions(w http.ResponseWriter, r *http.Request) {
Entries: []submissionListEntry{},
}
if project.ProceedingTypeID == nil {
writeJSON(w, http.StatusOK, resp)
return
}
rules, err := dbSvc.rules.List(ctx, project.ProceedingTypeID)
entries, ownCode, err := loadSubmissionCatalog(ctx, project.ProceedingTypeID)
if err != nil {
log.Printf("submissions: list rules for proceeding %d: %v", *project.ProceedingTypeID, err)
log.Printf("submissions: list submission catalog: %v", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "rule lookup failed"})
return
}
for _, rule := range rules {
if rule.SubmissionCode == nil || *rule.SubmissionCode == "" {
continue
}
if rule.EventType == nil || *rule.EventType != "filing" {
// Hearings + decisions don't generate submissions. The
// "Schriftsätze" panel only lists filings.
continue
}
if rule.LifecycleState != "published" {
continue
}
entry := submissionListEntry{
SubmissionCode: *rule.SubmissionCode,
Name: rule.Name,
NameEN: rule.NameEN,
HasTemplate: submissionRegistry.HasTemplate(ctx, *rule.SubmissionCode),
}
if rule.EventType != nil {
entry.EventType = *rule.EventType
}
if rule.PrimaryParty != nil {
entry.PrimaryParty = *rule.PrimaryParty
}
if rule.LegalSource != nil {
entry.LegalSource = *rule.LegalSource
}
resp.Entries = append(resp.Entries, entry)
}
resp.Entries = entries
resp.ProjectProceedingCode = ownCode
writeJSON(w, http.StatusOK, resp)
}
// handleGenerateProjectSubmission renders the .docx and streams it
// back to the browser. Audits the generation; never persists the
// rendered bytes server-side.
// handleListSubmissionCatalog returns the same cross-proceeding catalog
// without a project context — used by the global /submissions/new
// picker (t-paliad-243). No project_proceeding_code is returned since
// the picker isn't pinned to one project.
func handleListSubmissionCatalog(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
return
}
if _, ok := requireUser(w, r); !ok {
return
}
entries, _, err := loadSubmissionCatalog(r.Context(), nil)
if err != nil {
log.Printf("submissions: list global submission catalog: %v", err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "rule lookup failed"})
return
}
writeJSON(w, http.StatusOK, map[string]any{"entries": entries})
}
// loadSubmissionCatalog runs the shared catalog query. When
// projectProceedingTypeID is non-nil, the returned ownCode points at
// that proceeding's code so the frontend can pin its group to the top;
// otherwise ownCode is nil.
func loadSubmissionCatalog(ctx context.Context, projectProceedingTypeID *int) ([]submissionListEntry, *string, error) {
type catalogRow struct {
SubmissionCode string `db:"submission_code"`
Name string `db:"name"`
NameEN string `db:"name_en"`
EventType *string `db:"event_type"`
PrimaryParty *string `db:"primary_party"`
LegalSource *string `db:"legal_source"`
ProceedingID int `db:"proceeding_type_id"`
ProceedingCode string `db:"proceeding_code"`
ProceedingName string `db:"proceeding_name"`
ProceedingNameEN string `db:"proceeding_name_en"`
}
var rows []catalogRow
err := dbSvc.projects.DB().SelectContext(ctx, &rows,
`SELECT dr.submission_code AS submission_code,
dr.name AS name,
dr.name_en AS name_en,
dr.event_type AS event_type,
dr.primary_party AS primary_party,
dr.legal_source AS legal_source,
dr.proceeding_type_id AS proceeding_type_id,
pt.code AS proceeding_code,
pt.name AS proceeding_name,
pt.name_en AS proceeding_name_en
FROM paliad.deadline_rules dr
JOIN paliad.proceeding_types pt ON pt.id = dr.proceeding_type_id
WHERE dr.is_active = true
AND dr.lifecycle_state = 'published'
AND dr.event_type = 'filing'
AND dr.submission_code IS NOT NULL
AND dr.submission_code <> ''
AND pt.is_active = true
ORDER BY pt.code ASC, dr.submission_code ASC`)
if err != nil {
return nil, nil, err
}
entries := make([]submissionListEntry, 0, len(rows))
var ownCode *string
for _, row := range rows {
entry := submissionListEntry{
SubmissionCode: row.SubmissionCode,
Name: row.Name,
NameEN: row.NameEN,
HasTemplate: hasPerSubmissionTemplate(row.SubmissionCode),
ProceedingCode: row.ProceedingCode,
ProceedingName: row.ProceedingName,
ProceedingNameEN: row.ProceedingNameEN,
}
if row.EventType != nil {
entry.EventType = *row.EventType
}
if row.PrimaryParty != nil {
entry.PrimaryParty = *row.PrimaryParty
}
if row.LegalSource != nil {
entry.LegalSource = *row.LegalSource
}
entries = append(entries, entry)
if projectProceedingTypeID != nil && row.ProceedingID == *projectProceedingTypeID && ownCode == nil {
code := row.ProceedingCode
ownCode = &code
}
}
// If the project's proceeding has no filing rules of its own, fall
// back to a direct proceeding_types lookup so the frontend can still
// pin the right group even when the catalog ordering wouldn't have
// surfaced the code via a row.
if projectProceedingTypeID != nil && ownCode == nil {
var code string
if err := dbSvc.projects.DB().GetContext(ctx, &code,
`SELECT code FROM paliad.proceeding_types WHERE id = $1`, *projectProceedingTypeID); err == nil && code != "" {
ownCode = &code
}
}
return entries, ownCode, nil
}
// hasPerSubmissionTemplate reports whether a per-submission .docx is
// wired in the fileRegistry (files.go). false means the editor falls
// back to the universal HL Patents Style — still renderable, still
// editable, but the UI may want to surface a "universal Vorlage"
// indicator. Read-only — no I/O, just a map lookup.
func hasPerSubmissionTemplate(submissionCode string) bool {
_, ok := submissionTemplateRegistry[submissionCode]
return ok
}
// handleGenerateProjectSubmission resolves the per-submission template
// (per-firm first, HL Patents Style fallback), builds a fresh variable
// bag from project state via SubmissionVarsService, runs the merge
// engine so every {{placeholder}} substitutes, writes one audit row,
// and streams the result. Pre-t-paliad-253 this handler ignored the
// per-firm registry and returned the bare HL Patents Style .dotm with
// no substitution — the "Generieren" button on the Schriftsätze tab
// therefore produced a generic firm-style .docx instead of a
// project-merged Klageerwiderung, which is what m noticed in
// m/paliad#84.
func handleGenerateProjectSubmission(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
return
@@ -162,7 +284,10 @@ func handleGenerateProjectSubmission(w http.ResponseWriter, r *http.Request) {
if !ok {
return
}
if !requireSubmissionsWired(w) {
if dbSvc.submissionDraft == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "submissions not configured",
})
return
}
projectID, err := uuid.Parse(r.PathValue("id"))
@@ -179,11 +304,14 @@ func handleGenerateProjectSubmission(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), submissionRenderTimeout)
defer cancel()
varsResult, err := submissionVars.Build(ctx, services.SubmissionVarsContext{
UserID: uid,
ProjectID: projectID,
SubmissionCode: submissionCode,
})
tplBytes, _, err := resolveSubmissionTemplate(ctx, submissionCode)
if err != nil {
log.Printf("submissions: template fetch (project=%s code=%s): %v", projectID, submissionCode, err)
writeJSON(w, http.StatusBadGateway, map[string]string{"error": "template upstream unreachable"})
return
}
docx, resolved, err := dbSvc.submissionDraft.RenderProjectSubmission(ctx, uid, projectID, submissionCode, tplBytes)
if err != nil {
if errors.Is(err, services.ErrSubmissionRuleNotFound) {
writeJSON(w, http.StatusNotFound, map[string]string{
@@ -191,197 +319,89 @@ func handleGenerateProjectSubmission(w http.ResponseWriter, r *http.Request) {
})
return
}
// ErrNotVisible / project ErrNotFound from the visibility gate
// surface through writeServiceError as 404, matching the rest
// of the project surfaces.
log.Printf("submissions: render (project=%s code=%s): %v", projectID, submissionCode, err)
writeServiceError(w, err)
return
}
tmpl, err := submissionRegistry.Resolve(ctx, submissionCode)
if err != nil {
if errors.Is(err, services.ErrNoTemplate) {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "no template available for this submission",
"hint": "ask an admin to upload a .docx template under templates/_base/ in mWorkRepo",
})
return
}
log.Printf("submissions: template resolve for %s: %v", submissionCode, err)
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "template repository unreachable",
})
return
}
filename := submissionFileName(resolved.Rule, resolved.Project, resolved.Lang)
missing := services.DefaultMissingMarker(varsResult.Lang)
rendered, err := submissionRenderer.Render(tmpl.Bytes, varsResult.Placeholders, missing)
if err != nil {
log.Printf("submissions: render %s for project %s: %v", submissionCode, projectID, err)
writeJSON(w, http.StatusInternalServerError, map[string]string{
"error": "render failed",
})
return
}
filename := submissionFileName(varsResult, projectID)
// Audit + Verlauf writes. Best-effort with a background context so
// the user still receives the download even if the audit insert
// races a slow DB.
// Audit write is best-effort with a background context so the
// download still succeeds if the DB races. Audit failure here only
// affects the system_audit_log feed — never the user's response.
bgCtx, cancelBG := context.WithTimeout(context.Background(), 10*time.Second)
defer cancelBG()
if err := writeSubmissionAuditRow(bgCtx, varsResult, tmpl, submissionCode); err != nil {
if err := writeSubmissionAuditRow(bgCtx, resolved.User, projectID, submissionCode, resolved.Rule.Name, filename); err != nil {
log.Printf("submissions: audit insert failed (project=%s code=%s): %v", projectID, submissionCode, err)
}
if err := writeSubmissionProjectEvent(bgCtx, varsResult, tmpl, submissionCode); err != nil {
log.Printf("submissions: project_events insert failed (project=%s code=%s): %v", projectID, submissionCode, err)
}
if err := writeSubmissionDocumentRow(bgCtx, varsResult, tmpl, submissionCode); err != nil {
log.Printf("submissions: documents insert failed (project=%s code=%s): %v", projectID, submissionCode, err)
}
w.Header().Set("Content-Type", docxMime)
w.Header().Set("Content-Disposition", fmt.Sprintf(`attachment; filename=%q`, filename))
w.Header().Set("Content-Length", strconv.Itoa(len(rendered)))
w.Header().Set("X-Paliad-Template-Sha", tmpl.SHA)
w.Header().Set("X-Paliad-Template-Tier", tmpl.FirmTier)
if _, err := w.Write(rendered); err != nil {
w.Header().Set("Content-Length", strconv.Itoa(len(docx)))
if _, err := w.Write(docx); err != nil {
log.Printf("submissions: response write failed (project=%s code=%s): %v", projectID, submissionCode, err)
}
}
// requireSubmissionsWired returns false (and writes 503) when the
// generator wasn't constructed at boot. Happens in DATABASE_URL-less
// deployments — knowledge-platform-only stacks don't ship the
// submission engine.
func requireSubmissionsWired(w http.ResponseWriter) bool {
if submissionRenderer == nil || submissionRegistry == nil || submissionVars == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
"error": "submission generator not configured",
})
return false
}
return true
}
// submissionFileName builds the user-facing filename per design §7:
//
// {rule.name}-{project.case_number}-{YYYY-MM-DD}.docx
//
// Slashes and backslashes in case_number sanitise to underscores so
// the file saves cleanly across Windows + macOS + Linux. Missing
// case_number falls back to an 8-hex-char stable id from the project
// UUID so the file still has a deterministic handle.
func submissionFileName(vars *services.SubmissionVarsResult, projectID uuid.UUID) string {
// submissionFileName produces the user-facing download name per
// design §7: {rule.name}-{project.case_number}-{YYYY-MM-DD}.docx.
// Empty case_number drops the segment entirely (no fallback hash —
// the lawyer can rename if the project lacks an Aktenzeichen).
// Umlauts in the rule name are ASCII-folded by SanitiseSubmissionFileName
// so the file lands cleanly on legacy SMB shares.
func submissionFileName(rule *models.DeadlineRule, project *models.Project, lang string) string {
day := time.Now()
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
day = day.In(loc)
}
ruleName := strings.TrimSpace(vars.Rule.Name)
if strings.EqualFold(vars.Lang, "en") {
ruleName = strings.TrimSpace(vars.Rule.NameEN)
ruleName := strings.TrimSpace(rule.Name)
if strings.EqualFold(lang, "en") && strings.TrimSpace(rule.NameEN) != "" {
ruleName = strings.TrimSpace(rule.NameEN)
}
if ruleName == "" {
ruleName = "submission"
}
parts := []string{services.SanitiseSubmissionFileName(ruleName)}
caseNo := ""
if vars.Project != nil && vars.Project.CaseNumber != nil {
caseNo = strings.TrimSpace(*vars.Project.CaseNumber)
if project != nil && project.CaseNumber != nil {
caseNo = strings.TrimSpace(*project.CaseNumber)
}
if caseNo == "" {
caseNo = projectID.String()[:8]
if caseNo != "" {
parts = append(parts, services.SanitiseSubmissionFileName(caseNo))
}
caseNo = strings.ReplaceAll(caseNo, "/", "_")
caseNo = strings.ReplaceAll(caseNo, `\`, "_")
return fmt.Sprintf("%s-%s-%s.docx", ruleName, caseNo, day.Format("2006-01-02"))
parts = append(parts, day.Format("2006-01-02"))
return strings.Join(parts, "-") + ".docx"
}
// writeSubmissionAuditRow files the org-wide audit entry. Reuses the
// system_audit_log convention (event_type='submission.generated')
// established in t-paliad-214's mig 102.
func writeSubmissionAuditRow(ctx context.Context, vars *services.SubmissionVarsResult, tmpl *services.ResolvedTemplate, code string) error {
// writeSubmissionAuditRow files one row in paliad.system_audit_log per
// generation. event_type='submission.generated', scope='project',
// scope_root=project_id. Metadata is intentionally small per Slice 1:
// {submission_code, rule_name, filename} — enough for a reviewer to
// reconstruct which template was offered to which project without
// over-baking the audit shape.
func writeSubmissionAuditRow(ctx context.Context, user *models.User, projectID uuid.UUID, submissionCode, ruleName, filename string) error {
meta := map[string]any{
"submission_code": code,
"template_path": tmpl.Path,
"template_sha": tmpl.SHA,
"template_tier": tmpl.FirmTier,
"project_id": vars.Project.ID.String(),
"rule_id": vars.Rule.ID.String(),
"firm": branding.Name,
"submission_code": submissionCode,
"rule_name": ruleName,
"filename": filename,
}
body, _ := json.Marshal(meta)
var (
actorID any
actorEmail string
)
if user != nil {
actorID = user.ID
actorEmail = user.Email
}
_, err := dbSvc.projects.DB().ExecContext(ctx,
`INSERT INTO paliad.system_audit_log
(event_type, actor_id, actor_email, scope, scope_root, metadata)
VALUES ('submission.generated', $1, $2, 'project', $3, $4::jsonb)`,
vars.User.ID, vars.User.Email, vars.Project.ID.String(), string(body),
)
return err
}
// writeSubmissionProjectEvent surfaces the generation in the project
// Verlauf / SmartTimeline. event_type stays free-text (no CHECK on
// paliad.project_events.event_type per Slice 2 of SmartTimeline) so we
// don't need a migration to introduce 'submission_generated'.
func writeSubmissionProjectEvent(ctx context.Context, vars *services.SubmissionVarsResult, tmpl *services.ResolvedTemplate, code string) error {
ruleName := strings.TrimSpace(vars.Rule.Name)
if strings.EqualFold(vars.Lang, "en") {
ruleName = strings.TrimSpace(vars.Rule.NameEN)
}
title := fmt.Sprintf("%s generiert", ruleName)
if strings.EqualFold(vars.Lang, "en") {
title = fmt.Sprintf("%s generated", ruleName)
}
meta := map[string]any{
"submission_code": code,
"template_path": tmpl.Path,
"template_sha": tmpl.SHA,
"template_tier": tmpl.FirmTier,
"rule_id": vars.Rule.ID.String(),
}
body, _ := json.Marshal(meta)
now := time.Now().UTC()
_, err := dbSvc.projects.DB().ExecContext(ctx,
`INSERT INTO paliad.project_events
(id, project_id, event_type, title, description, event_date,
created_by, metadata, created_at, updated_at)
VALUES ($1, $2, 'submission_generated', $3, NULL, $4, $5, $6::jsonb, $4, $4)`,
uuid.New(), vars.Project.ID, title, now, vars.User.ID, string(body),
)
return err
}
// writeSubmissionDocumentRow files the audit-only paliad.documents
// row. file_path stays NULL — the bytes are regenerable from inputs
// (m's Q3 pick: no server-side binary). doc_type='generated_submission'
// is the additive marker; no CHECK constraint exists on doc_type, so
// this requires no migration.
func writeSubmissionDocumentRow(ctx context.Context, vars *services.SubmissionVarsResult, tmpl *services.ResolvedTemplate, code string) error {
ruleName := strings.TrimSpace(vars.Rule.Name)
if strings.EqualFold(vars.Lang, "en") {
ruleName = strings.TrimSpace(vars.Rule.NameEN)
}
day := time.Now()
if loc, err := time.LoadLocation("Europe/Berlin"); err == nil {
day = day.In(loc)
}
title := fmt.Sprintf("%s (generiert %s)", ruleName, day.Format("2006-01-02"))
if strings.EqualFold(vars.Lang, "en") {
title = fmt.Sprintf("%s (generated %s)", ruleName, day.Format("2006-01-02"))
}
provenance := map[string]any{
"submission_code": code,
"template_path": tmpl.Path,
"template_sha": tmpl.SHA,
"template_tier": tmpl.FirmTier,
"firm": branding.Name,
"rule_id": vars.Rule.ID.String(),
}
body, _ := json.Marshal(provenance)
_, err := dbSvc.projects.DB().ExecContext(ctx,
`INSERT INTO paliad.documents
(id, project_id, title, doc_type, file_path, file_size, mime_type,
ai_extracted, uploaded_by, created_at, updated_at)
VALUES ($1, $2, $3, 'generated_submission', NULL, NULL, $4, $5::jsonb, $6, now(), now())`,
uuid.New(), vars.Project.ID, title, docxMime, string(body), vars.User.ID,
actorID, actorEmail, projectID.String(), string(body),
)
return err
}

View File

@@ -313,6 +313,14 @@ type Deadline struct {
// changes to paliad.deadline_rules and accepts citations from
// outside that table.
RuleCode *string `db:"rule_code" json:"rule_code,omitempty"`
// CustomRuleText holds the lawyer's free-text rule label when the
// deadline form is in Custom mode (t-paliad-258 / m/paliad#89).
// Mutually exclusive with RuleID at the application layer: the Auto
// path sets RuleID and leaves this NULL; the Custom path sets this
// and leaves RuleID NULL. Display surfaces prefer the joined
// deadline_rules.name when RuleID is set, else fall back to this
// text + a "Custom" badge.
CustomRuleText *string `db:"custom_rule_text" json:"custom_rule_text,omitempty"`
Status string `db:"status" json:"status"`
CompletedAt *time.Time `db:"completed_at" json:"completed_at,omitempty"`
CalDAVUID *string `db:"caldav_uid" json:"caldav_uid,omitempty"`
@@ -721,6 +729,14 @@ type ProceedingType struct {
DefaultColor string `db:"default_color" json:"default_color"`
SortOrder int `db:"sort_order" json:"sort_order"`
IsActive bool `db:"is_active" json:"is_active"`
// TriggerEventLabel{DE,EN}: optional caption for /tools/verfahrensablauf
// "Auslösendes Ereignis". When set, overrides the proceedingName fallback
// that fires when no rule has IsRootEvent=true. Populated for UPC Appeal
// (mig 121) so the caption reads "Anfechtbare Entscheidung" /
// "Appealable Decision" instead of "Berufungsverfahren" / "Appeal".
// NULL on most proceedings — they already carry a root rule.
TriggerEventLabelDE *string `db:"trigger_event_label_de" json:"trigger_event_label_de,omitempty"`
TriggerEventLabelEN *string `db:"trigger_event_label_en" json:"trigger_event_label_en,omitempty"`
}
// TriggerEvent is a UPC procedural event that can start one or more deadlines

View File

@@ -112,6 +112,11 @@ type AichatPaliadinService struct {
// Hook for tests — when non-nil, callHTTP delegates here instead
// of hitting the wire. Production code never sets this.
httpHook func(ctx context.Context, method, path string, body any, out any) error
// Hook for tests — when non-nil, callStreamingHTTP delegates here
// instead of opening a real SSE connection. Production code never
// sets this.
streamHook func(ctx context.Context, path string, body any, emit func(streamFrame)) error
}
// ErrAichatAuthFailed signals the aichat service rejected the bearer
@@ -217,6 +222,7 @@ func (s *AichatPaliadinService) RunTurn(ctx context.Context, req TurnRequest) (*
body := aichatTurnRequest{
Persona: s.cfg.Persona,
Username: username,
UserID: req.UserID.String(),
SessionID: req.SessionID,
Message: sanitiseForTmux(req.UserMessage),
JWT: jwt,
@@ -611,8 +617,13 @@ func (s *AichatPaliadinService) clearPrimed(session string) {
// =============================================================================
type aichatTurnRequest struct {
Persona string `json:"persona"`
Username string `json:"username"`
Persona string `json:"persona"`
Username string `json:"username"`
// UserID is the paliad user UUID, required by aichat now that a
// tenant DB is configured ("user_id is required when a tenant DB
// is configured"). Without it /chat/turn 400s and the SSE relay
// closes empty → "Verbindung verloren" on the frontend.
UserID string `json:"user_id"`
SessionID string `json:"session_id,omitempty"`
Message string `json:"message"`
JWT string `json:"jwt,omitempty"`

View File

@@ -0,0 +1,654 @@
package services
// Streaming + recovery support for AichatPaliadinService (t-paliad-235).
//
// =============================================================================
// Upstream contract — /chat/turn/stream
// =============================================================================
//
// Source of truth: m/mAi internal/aichat/api/stream.go. Captured here as
// inline doc so future debugging doesn't require chasing across repos:
//
// Request body: same shape as POST /chat/turn (TurnRequest mirror in
// aichat_paliadin.go). Persona must support streaming; paliad's
// "paliadin" persona does.
//
// Response: text/event-stream. Two SSE event flavours:
//
// 1. The default unnamed `data:` event carries a discriminated-union
// JSON object keyed by `"type"`:
//
// {"type":"chunk","content":"…"}
// {"type":"meta","used_tools":[…],"rows_seen":[…],"classifier_tag":"…"}
// {"type":"done","turn_id":"…","conversation_id":"…",
// "duration_ms":1234,"pane_spawned":false,"resumed":false}
// {"type":"error","code":"…","message":"…","retryable":true}
//
// 2. The named `event: heartbeat` event carries:
//
// {"elapsed_seconds": N}
//
// Emitted every 5 s by the upstream while the runner has been
// silent (no content). aichat keeps emitting these for the lifetime
// of the runner so the client can render "Paliadin denkt nach
// (N s)" without conflating with actual content.
//
// Errors before the stream starts (auth failure, persona unknown,
// validation) come back as a normal JSON envelope with the appropriate
// HTTP status — not SSE. Those land in callHTTP via decodeAichatError.
//
// =============================================================================
// Conversation-based late recovery
// =============================================================================
//
// Aichat exposes:
//
// GET /chat/conversations?persona=…&username=…&user_id=…
// → list of ConversationSummary, ordered last_turn_at DESC
// GET /chat/conversations/{id}/turns
// → list of TurnRow (role=user|assistant, body, created_at)
//
// When paliad's stream drops mid-turn we:
// 1. Look up paliad.paliadin_turns.aichat_conversation_id for the row.
// 2. If unset (stream dropped before the `done` frame): list the user's
// conversations and take the most recent one for the persona —
// that's the pane our turn ran against (aichat owns one active
// conversation per persona+user, see m/mAi#243).
// 3. GET that conversation's turns. Find the latest assistant turn
// whose preceding user-role turn body matches our user_message.
// 4. Persist the response (completeTurnLate) and return it.
//
// If aichat returns no matching assistant turn → the turn is truly lost
// (transport drop + upstream crash). Recovery returns (nil, nil) and
// the handler degrades the UI to "verloren".
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"time"
"github.com/google/uuid"
)
// =============================================================================
// Streaming RunTurnStream
// =============================================================================
// RunTurnStream drives one /chat/turn/stream turn against aichat and
// relays incremental events onto `events`. Closes `events` before
// returning. Implements StreamingPaliadin.
func (s *AichatPaliadinService) RunTurnStream(ctx context.Context, req TurnRequest, events chan<- StreamEvent) (*TurnResult, error) {
defer close(events)
s.turnMu.Lock()
defer s.turnMu.Unlock()
turnID := uuid.New()
startedAt := time.Now().UTC()
if err := s.insertTurnRow(ctx, &PaliadinTurn{
TurnID: turnID,
UserID: req.UserID,
SessionID: req.SessionID,
StartedAt: startedAt,
UserMessage: req.UserMessage,
PageOrigin: optionalString(req.PageOrigin),
}, req.Context); err != nil {
return nil, fmt.Errorf("paliadin: insert turn row: %w", err)
}
if err := s.healthGate(ctx); err != nil {
_ = s.markTurnError(ctx, turnID, "mriver_unreachable")
safeSendStream(ctx, events, StreamEvent{
Kind: StreamError,
Code: "mriver_unreachable",
Message: err.Error(),
})
return nil, err
}
username := s.usernameFor(ctx, req.UserID)
session := s.cfg.Persona + ":" + username
primer := s.buildPrimerExchanges(ctx, session, req)
jwt, err := s.mintJWTIfConfigured(req.UserID)
if err != nil {
_ = s.markTurnError(ctx, turnID, "jwt_mint_failed")
safeSendStream(ctx, events, StreamEvent{
Kind: StreamError,
Code: "shim_error",
Message: fmt.Sprintf("mint turn jwt: %v", err),
})
return nil, fmt.Errorf("paliadin: mint turn jwt: %w", err)
}
body := aichatTurnRequest{
Persona: s.cfg.Persona,
Username: username,
UserID: req.UserID.String(),
SessionID: req.SessionID,
Message: sanitiseForTmux(req.UserMessage),
JWT: jwt,
Primer: primer,
Meta: buildAichatMeta(req),
}
// Stream the upstream call. acc accumulates the full text so we can
// persist the row + return a TurnResult on success.
var (
acc strings.Builder
streamMeta trailerMeta
convID string
paneSpawned bool
upstreamDoneMs int64
)
streamErr := s.callStreamingHTTP(ctx, "/chat/turn/stream", body, func(frame streamFrame) {
switch {
case frame.event == "heartbeat":
safeSendStream(ctx, events, StreamEvent{
Kind: StreamHeartbeat,
ElapsedSeconds: frame.heartbeat.ElapsedSeconds,
})
case frame.data.Type == "chunk":
if frame.data.Content == "" {
return
}
acc.WriteString(frame.data.Content)
safeSendStream(ctx, events, StreamEvent{
Kind: StreamChunk,
Content: frame.data.Content,
})
case frame.data.Type == "meta":
streamMeta = trailerMeta{
UsedTools: append([]string(nil), frame.data.UsedTools...),
RowsSeen: coerceAichatRowsSeen(frame.data.RowsSeen),
ClassifierTag: frame.data.ClassifierTag,
}
safeSendStream(ctx, events, StreamEvent{
Kind: StreamMeta,
UsedTools: streamMeta.UsedTools,
RowsSeen: streamMeta.RowsSeen,
ClassifierTag: streamMeta.ClassifierTag,
})
case frame.data.Type == "done":
if frame.data.ConversationID != "" {
convID = frame.data.ConversationID
safeSendStream(ctx, events, StreamEvent{
Kind: StreamConversation,
ConversationID: convID,
})
}
paneSpawned = frame.data.PaneSpawned
upstreamDoneMs = frame.data.DurationMs
case frame.data.Type == "error":
// Forward as a stream error AND mark for non-nil err
// propagation via the streamErr captured below.
safeSendStream(ctx, events, StreamEvent{
Kind: StreamError,
Code: frame.data.Code,
Message: frame.data.Message,
Retryable: frame.data.Retryable,
})
}
})
cleanBody := acc.String()
tokens := approxTokenCount(cleanBody)
chipCount := countChips(cleanBody)
finished := time.Now().UTC()
durationMS := int(finished.Sub(startedAt) / time.Millisecond)
if upstreamDoneMs > 0 {
durationMS = int(upstreamDoneMs)
}
// Persist the conversation id we learned (best-effort — failure here
// just means recovery for THIS turn will have to list conversations
// rather than fast-path to a single id).
if convID != "" {
if err := s.setAichatConversationID(ctx, turnID, convID); err != nil {
log.Printf("paliadin: persist aichat conversation id %s: %v", convID, err)
}
}
if streamErr != nil {
// Don't overwrite an existing error_code we may have set above.
_ = s.markTurnError(ctx, turnID, classifyAichatError(streamErr))
return nil, streamErr
}
// Aichat is stateless on user content; the client owns the primer.
if paneSpawned {
s.clearPrimed(session)
} else {
s.markPrimed(session)
}
if cleanBody == "" {
// Upstream closed cleanly with no error event but no content
// either (unexpected — log + treat as upstream_error so the
// handler doesn't ship an empty bubble).
_ = s.markTurnError(ctx, turnID, "shim_error")
return nil, errors.New("aichat: stream closed with no content and no error")
}
if err := s.completeTurn(ctx, turnID, finished, durationMS, cleanBody, tokens, streamMeta, chipCount); err != nil {
log.Printf("paliadin: complete turn %s: %v", turnID, err)
}
return &TurnResult{
TurnID: turnID,
Response: cleanBody,
UsedTools: streamMeta.UsedTools,
RowsSeen: streamMeta.RowsSeen,
ChipCount: chipCount,
ClassifierTag: streamMeta.ClassifierTag,
DurationMS: durationMS,
}, nil
}
// streamFrame is one decoded SSE event.
type streamFrame struct {
event string // "" → default (data:) event
data streamDataFrame
heartbeat streamHeartbeatFrame
}
type streamDataFrame struct {
Type string `json:"type"`
Content string `json:"content,omitempty"`
UsedTools []string `json:"used_tools,omitempty"`
RowsSeen []string `json:"rows_seen,omitempty"`
ClassifierTag string `json:"classifier_tag,omitempty"`
TurnID string `json:"turn_id,omitempty"`
ConversationID string `json:"conversation_id,omitempty"`
DurationMs int64 `json:"duration_ms,omitempty"`
PaneSpawned bool `json:"pane_spawned,omitempty"`
Resumed bool `json:"resumed,omitempty"`
Code string `json:"code,omitempty"`
Message string `json:"message,omitempty"`
Retryable bool `json:"retryable,omitempty"`
}
type streamHeartbeatFrame struct {
ElapsedSeconds int `json:"elapsed_seconds"`
}
// callStreamingHTTP opens a streaming POST to aichat and invokes `emit`
// for each parsed SSE frame. Returns once the stream closes; surfaces
// non-2xx responses via decodeAichatError, transport errors via the
// underlying http.Client error.
//
// Tests can override the parsing path by setting streamHook (kept null
// in production).
func (s *AichatPaliadinService) callStreamingHTTP(ctx context.Context, path string, body any, emit func(streamFrame)) error {
if s.streamHook != nil {
return s.streamHook(ctx, path, body, emit)
}
buf, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("aichat: encode %s body: %w", path, err)
}
httpReq, err := http.NewRequestWithContext(ctx, http.MethodPost, s.cfg.BaseURL+path, strings.NewReader(string(buf)))
if err != nil {
return fmt.Errorf("aichat: build %s request: %w", path, err)
}
httpReq.Header.Set("Content-Type", "application/json")
httpReq.Header.Set("Accept", "text/event-stream")
if s.cfg.BearerToken != "" {
httpReq.Header.Set("Authorization", "Bearer "+s.cfg.BearerToken)
}
// Use a dedicated client without the short Timeout — for streaming
// we rely on the silence_timeout watch (no events for > 90 s ⇒ fail)
// rather than a hard ceiling on the whole turn. The aichat upstream
// keeps emitting heartbeats while it's alive, so a true upstream
// stall is observable here.
client := s.streamingClient()
resp, err := client.Do(httpReq)
if err != nil {
return fmt.Errorf("aichat: POST %s: %w", path, err)
}
defer resp.Body.Close()
if resp.StatusCode < 200 || resp.StatusCode >= 300 {
respBytes, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<10))
return decodeAichatError(resp.StatusCode, respBytes)
}
return parseSSEStream(ctx, resp.Body, emit)
}
// streamingClient returns an HTTP client tuned for streaming — no
// per-request Timeout (kills mid-stream), but a long IdleConnTimeout so
// the connection stays usable for multi-minute turns.
func (s *AichatPaliadinService) streamingClient() *http.Client {
if s.cfg.HTTPClient == nil {
return &http.Client{Timeout: 0}
}
c := *s.cfg.HTTPClient
c.Timeout = 0
return &c
}
// parseSSEStream tokenises an SSE byte stream into streamFrame events
// and calls emit for each. Returns nil on clean EOF; returns the read
// error otherwise.
//
// Frame format (per https://html.spec.whatwg.org/multipage/server-sent-events.html):
//
// event: <name>\n
// data: <payload>\n
// <blank line>\n
//
// Multiple `data:` lines per event are concatenated with `\n`. Lines
// starting with `:` are comments and ignored.
func parseSSEStream(ctx context.Context, r io.Reader, emit func(streamFrame)) error {
br := bufio.NewReaderSize(r, 64<<10)
var (
eventName string
dataLines []string
)
flush := func() {
if len(dataLines) == 0 && eventName == "" {
return
}
payload := strings.Join(dataLines, "\n")
eventName = strings.TrimSpace(eventName)
dataLines = nil
eventOut := eventName
eventName = ""
if eventOut == "heartbeat" {
var hb streamHeartbeatFrame
if err := json.Unmarshal([]byte(payload), &hb); err != nil {
return
}
emit(streamFrame{event: "heartbeat", heartbeat: hb})
return
}
// Default event (unnamed) — discriminated by `type` field.
var d streamDataFrame
if err := json.Unmarshal([]byte(payload), &d); err != nil {
return
}
emit(streamFrame{event: "", data: d})
}
for {
if err := ctx.Err(); err != nil {
return err
}
line, err := br.ReadString('\n')
if err != nil {
if errors.Is(err, io.EOF) {
// Final frame may not be terminated by a blank line on
// abrupt close — flush whatever we accumulated.
if line != "" {
processSSELine(line, &eventName, &dataLines)
}
flush()
return nil
}
return fmt.Errorf("aichat: read sse: %w", err)
}
// Normalise line endings (some intermediaries send \r\n).
line = strings.TrimRight(line, "\r\n")
if line == "" {
flush()
continue
}
processSSELine(line, &eventName, &dataLines)
}
}
// processSSELine handles one line of the SSE wire format.
func processSSELine(line string, eventName *string, dataLines *[]string) {
if strings.HasPrefix(line, ":") {
return // comment / keep-alive
}
if idx := strings.IndexByte(line, ':'); idx >= 0 {
field := line[:idx]
value := line[idx+1:]
if strings.HasPrefix(value, " ") {
value = value[1:]
}
switch field {
case "event":
*eventName = value
case "data":
*dataLines = append(*dataLines, value)
}
return
}
// Field with no value (rare). Treat the whole line as field name
// per spec.
}
// =============================================================================
// AichatRecoverer — late recovery via the conversation API
// =============================================================================
// RecoverTurn asks aichat whether the given paliad turn has a response.
// Returns the up-to-date row on success (including a freshly persisted
// response when aichat had one), nil + nil when aichat doesn't know
// either, or an error on transport / DB failures.
func (s *AichatPaliadinService) RecoverTurn(ctx context.Context, callerID, turnID uuid.UUID) (*PaliadinTurn, error) {
row, err := s.GetTurn(ctx, callerID, turnID)
if err != nil {
return nil, err
}
// Fast path: the row already has a response (the janitor or a
// concurrent stream finished writing). Return it as-is.
if row.Response != nil && *row.Response != "" {
return row, nil
}
convID, err := s.resolveAichatConversationID(ctx, row)
if err != nil {
log.Printf("paliadin: recover %s: resolve conversation: %v", turnID, err)
return nil, nil
}
if convID == "" {
return nil, nil
}
turns, err := s.fetchAichatConversationTurns(ctx, convID)
if err != nil {
log.Printf("paliadin: recover %s: fetch turns: %v", turnID, err)
return nil, nil
}
assistantBody := matchAssistantResponse(turns, row.UserMessage)
if assistantBody == "" {
return nil, nil
}
finished := time.Now().UTC()
durationMS := int(finished.Sub(row.StartedAt) / time.Millisecond)
tokens := approxTokenCount(assistantBody)
chipCount := countChips(assistantBody)
if err := s.completeTurnLate(ctx, turnID, finished, durationMS, assistantBody, tokens, trailerMeta{}, chipCount); err != nil {
log.Printf("paliadin: recover %s: complete late: %v", turnID, err)
return nil, err
}
// Re-read so the caller gets a row that reflects the late-write.
return s.GetTurn(ctx, callerID, turnID)
}
// resolveAichatConversationID returns the conversation the turn lived
// in. Fast path: read the column on the row. Fallback: list aichat
// conversations for the user+persona and take the most recent.
func (s *AichatPaliadinService) resolveAichatConversationID(ctx context.Context, row *PaliadinTurn) (string, error) {
stored, err := s.getAichatConversationID(ctx, row.TurnID)
if err != nil {
return "", err
}
if stored != "" {
return stored, nil
}
username := s.usernameFor(ctx, row.UserID)
convs, err := s.listAichatConversations(ctx, username, row.UserID.String())
if err != nil {
return "", err
}
if len(convs) == 0 {
return "", nil
}
// Aichat orders by last_turn_at DESC; the head is the most recently
// active conversation, which is the pane the lost turn ran against.
return convs[0].ID, nil
}
// matchAssistantResponse walks the aichat turn list and returns the
// body of the latest assistant turn whose preceding user-role turn body
// matches `userMessage` (verbatim — aichat persists the raw message
// the same way paliad does).
//
// Falls back to "the last assistant body in the conversation" when no
// match is found but the conversation has assistant content. This
// covers cases where aichat persisted the user turn with envelope
// prefixes that don't exactly match our user_message (e.g. an embedded
// [ctx …] block).
func matchAssistantResponse(turns []aichatConversationTurn, userMessage string) string {
wantedNorm := normaliseForMatch(userMessage)
for i := 0; i < len(turns)-1; i++ {
t := turns[i]
if t.Role != "user" {
continue
}
if normaliseForMatch(t.Body) != wantedNorm {
continue
}
next := turns[i+1]
if next.Role == "assistant" && next.Body != "" {
return next.Body
}
}
for i := len(turns) - 1; i >= 0; i-- {
t := turns[i]
if t.Role == "assistant" && t.Body != "" {
return t.Body
}
}
return ""
}
// normaliseForMatch lowercases, strips surrounding whitespace, and
// collapses internal whitespace runs. Comparison only — no semantic
// meaning beyond "did aichat persist the same prompt we sent".
func normaliseForMatch(s string) string {
s = strings.TrimSpace(strings.ToLower(s))
for strings.Contains(s, " ") {
s = strings.ReplaceAll(s, " ", " ")
}
return s
}
// =============================================================================
// aichat conversation API client helpers
// =============================================================================
type aichatConversationSummary struct {
ID string `json:"id"`
Persona string `json:"persona"`
LastTurnAt string `json:"last_turn_at"`
}
type aichatListConversationsResponse struct {
Conversations []aichatConversationSummary `json:"conversations"`
}
type aichatConversationTurn struct {
ID string `json:"id"`
Seq int `json:"seq"`
Role string `json:"role"`
Body string `json:"body"`
CreatedAt string `json:"created_at"`
}
type aichatGetConversationTurnsResponse struct {
ConversationID string `json:"conversation_id"`
Turns []aichatConversationTurn `json:"turns"`
HasMore bool `json:"has_more"`
}
// listAichatConversations calls GET /chat/conversations for the user.
func (s *AichatPaliadinService) listAichatConversations(ctx context.Context, username, userID string) ([]aichatConversationSummary, error) {
q := url.Values{}
q.Set("persona", s.cfg.Persona)
q.Set("username", username)
q.Set("user_id", userID)
q.Set("limit", "5")
path := "/chat/conversations?" + q.Encode()
var resp aichatListConversationsResponse
if err := s.callHTTP(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, err
}
return resp.Conversations, nil
}
// fetchAichatConversationTurns calls GET /chat/conversations/{id}/turns.
func (s *AichatPaliadinService) fetchAichatConversationTurns(ctx context.Context, convID string) ([]aichatConversationTurn, error) {
q := url.Values{}
q.Set("persona", s.cfg.Persona)
q.Set("limit", "20")
path := "/chat/conversations/" + url.PathEscape(convID) + "/turns?" + q.Encode()
var resp aichatGetConversationTurnsResponse
if err := s.callHTTP(ctx, http.MethodGet, path, nil, &resp); err != nil {
return nil, err
}
return resp.Turns, nil
}
// =============================================================================
// DB helpers for paliadin_turns.aichat_conversation_id (migration 118)
// =============================================================================
func (s *AichatPaliadinService) setAichatConversationID(ctx context.Context, turnID uuid.UUID, convID string) error {
if convID == "" {
return nil
}
convUUID, err := uuid.Parse(convID)
if err != nil {
return fmt.Errorf("invalid conversation id %q: %w", convID, err)
}
_, err = s.db.ExecContext(ctx, `
UPDATE paliad.paliadin_turns
SET aichat_conversation_id = $2
WHERE turn_id = $1
AND aichat_conversation_id IS DISTINCT FROM $2
`, turnID, convUUID)
return err
}
func (s *AichatPaliadinService) getAichatConversationID(ctx context.Context, turnID uuid.UUID) (string, error) {
var convID *uuid.UUID
err := s.db.QueryRowxContext(ctx,
`SELECT aichat_conversation_id FROM paliad.paliadin_turns WHERE turn_id = $1`,
turnID).Scan(&convID)
if err != nil {
return "", err
}
if convID == nil {
return "", nil
}
return convID.String(), nil
}
// Compile-time interface conformance — fail the build if a streaming
// method drifts off this backend.
var _ StreamingPaliadin = (*AichatPaliadinService)(nil)
var _ AichatRecoverer = (*AichatPaliadinService)(nil)

View File

@@ -0,0 +1,259 @@
package services
// Streaming + recovery tests for AichatPaliadinService (t-paliad-235).
//
// Like the sync-path tests next door, every test bypasses the HTTP wire
// (streamHook / httpHook). DB-write paths in RunTurnStream are out of
// scope here for the same reason — paliad has no sqlx mock. We focus
// on the SSE parser, the conversation-API client, and the
// match-assistant-response helper.
import (
"context"
"strings"
"testing"
)
// =============================================================================
// SSE parser
// =============================================================================
func TestParseSSEStream_DefaultEvents(t *testing.T) {
body := `data: {"type":"chunk","content":"Hello "}
data: {"type":"chunk","content":"world"}
data: {"type":"meta","used_tools":["search"],"rows_seen":["3"],"classifier_tag":"howto"}
data: {"type":"done","turn_id":"abc","conversation_id":"11111111-1111-1111-1111-111111111111","duration_ms":1234,"pane_spawned":false,"resumed":false}
`
var frames []streamFrame
err := parseSSEStream(context.Background(), strings.NewReader(body), func(f streamFrame) {
frames = append(frames, f)
})
if err != nil {
t.Fatalf("parseSSEStream: %v", err)
}
if len(frames) != 4 {
t.Fatalf("got %d frames; want 4 (%+v)", len(frames), frames)
}
if frames[0].data.Type != "chunk" || frames[0].data.Content != "Hello " {
t.Errorf("frame 0 = %+v; want chunk Hello ", frames[0])
}
if frames[1].data.Type != "chunk" || frames[1].data.Content != "world" {
t.Errorf("frame 1 = %+v; want chunk world", frames[1])
}
if frames[2].data.Type != "meta" || frames[2].data.ClassifierTag != "howto" {
t.Errorf("frame 2 = %+v; want meta howto", frames[2])
}
if frames[3].data.Type != "done" || frames[3].data.ConversationID == "" {
t.Errorf("frame 3 = %+v; want done with conversation_id", frames[3])
}
}
func TestParseSSEStream_HeartbeatEvent(t *testing.T) {
body := `event: heartbeat
data: {"elapsed_seconds": 5}
event: heartbeat
data: {"elapsed_seconds": 10}
data: {"type":"chunk","content":"Hi"}
`
var frames []streamFrame
err := parseSSEStream(context.Background(), strings.NewReader(body), func(f streamFrame) {
frames = append(frames, f)
})
if err != nil {
t.Fatalf("parseSSEStream: %v", err)
}
if len(frames) != 3 {
t.Fatalf("got %d frames; want 3", len(frames))
}
if frames[0].event != "heartbeat" || frames[0].heartbeat.ElapsedSeconds != 5 {
t.Errorf("frame 0 = %+v; want heartbeat 5s", frames[0])
}
if frames[1].event != "heartbeat" || frames[1].heartbeat.ElapsedSeconds != 10 {
t.Errorf("frame 1 = %+v; want heartbeat 10s", frames[1])
}
if frames[2].data.Type != "chunk" || frames[2].data.Content != "Hi" {
t.Errorf("frame 2 = %+v; want chunk Hi", frames[2])
}
}
func TestParseSSEStream_IgnoresComments(t *testing.T) {
body := `: keep-alive comment line
data: {"type":"chunk","content":"x"}
`
var frames []streamFrame
err := parseSSEStream(context.Background(), strings.NewReader(body), func(f streamFrame) {
frames = append(frames, f)
})
if err != nil {
t.Fatalf("parseSSEStream: %v", err)
}
if len(frames) != 1 || frames[0].data.Content != "x" {
t.Errorf("frames = %+v; want 1 chunk", frames)
}
}
func TestParseSSEStream_HandlesCRLF(t *testing.T) {
body := "data: {\"type\":\"chunk\",\"content\":\"crlf\"}\r\n\r\n"
var frames []streamFrame
err := parseSSEStream(context.Background(), strings.NewReader(body), func(f streamFrame) {
frames = append(frames, f)
})
if err != nil {
t.Fatalf("parseSSEStream: %v", err)
}
if len(frames) != 1 || frames[0].data.Content != "crlf" {
t.Errorf("frames = %+v; want crlf chunk", frames)
}
}
func TestParseSSEStream_MultilineData(t *testing.T) {
// Two data: lines for the same event must concatenate with \n.
body := `data: {"type":"chunk",
data: "content":"x"}
`
var frames []streamFrame
err := parseSSEStream(context.Background(), strings.NewReader(body), func(f streamFrame) {
frames = append(frames, f)
})
if err != nil {
t.Fatalf("parseSSEStream: %v", err)
}
if len(frames) != 1 || frames[0].data.Content != "x" {
t.Errorf("frames = %+v; want 1 chunk x", frames)
}
}
// =============================================================================
// matchAssistantResponse
// =============================================================================
func TestMatchAssistantResponse_PrefersUserPrecededAssistant(t *testing.T) {
turns := []aichatConversationTurn{
{Role: "user", Body: "first question"},
{Role: "assistant", Body: "first answer"},
{Role: "user", Body: "second question"},
{Role: "assistant", Body: "second answer"},
}
got := matchAssistantResponse(turns, "second question")
if got != "second answer" {
t.Errorf("got %q; want %q", got, "second answer")
}
}
func TestMatchAssistantResponse_NormaliseCase(t *testing.T) {
turns := []aichatConversationTurn{
{Role: "user", Body: "Hello World"},
{Role: "assistant", Body: "hi back"},
}
got := matchAssistantResponse(turns, " hello world ")
if got != "hi back" {
t.Errorf("got %q; want %q", got, "hi back")
}
}
func TestMatchAssistantResponse_FallbackToLastAssistant(t *testing.T) {
// User message doesn't match (aichat persisted with a different
// envelope or wrapper). Fallback: take the last assistant turn.
turns := []aichatConversationTurn{
{Role: "user", Body: "[ctx route=x] my question"},
{Role: "assistant", Body: "the answer"},
}
got := matchAssistantResponse(turns, "my question")
if got != "the answer" {
t.Errorf("got %q; want %q", got, "the answer")
}
}
func TestMatchAssistantResponse_NoAssistantTurns(t *testing.T) {
turns := []aichatConversationTurn{
{Role: "user", Body: "lonely"},
}
got := matchAssistantResponse(turns, "lonely")
if got != "" {
t.Errorf("got %q; want empty", got)
}
}
func TestMatchAssistantResponse_EmptyAssistantSkipped(t *testing.T) {
turns := []aichatConversationTurn{
{Role: "user", Body: "q1"},
{Role: "assistant", Body: ""},
{Role: "user", Body: "q2"},
{Role: "assistant", Body: "a2"},
}
got := matchAssistantResponse(turns, "q1")
if got != "a2" {
// q1's immediate next is the empty-body assistant — we skip it
// and fall back to the last non-empty assistant body.
t.Errorf("got %q; want %q (fallback)", got, "a2")
}
}
// =============================================================================
// Conversation-API HTTP client
// =============================================================================
func TestListAichatConversations_BuildsExpectedQuery(t *testing.T) {
var seenPath string
s := newAichatService(t, nil, func(ctx context.Context, method, path string, body any, out any) error {
seenPath = path
if dst, ok := out.(*aichatListConversationsResponse); ok {
dst.Conversations = []aichatConversationSummary{{ID: "11111111-1111-1111-1111-111111111111"}}
}
return nil
})
got, err := s.listAichatConversations(context.Background(), "alice", "00000000-0000-0000-0000-000000000001")
if err != nil {
t.Fatalf("listAichatConversations: %v", err)
}
if len(got) != 1 || got[0].ID == "" {
t.Errorf("got = %+v; want one conversation", got)
}
for _, want := range []string{"/chat/conversations?", "persona=paliadin", "username=alice", "user_id=00000000-0000-0000-0000-000000000001", "limit=5"} {
if !strings.Contains(seenPath, want) {
t.Errorf("path %q missing %q", seenPath, want)
}
}
}
func TestFetchAichatConversationTurns_BuildsPath(t *testing.T) {
var seenPath string
s := newAichatService(t, nil, func(ctx context.Context, method, path string, body any, out any) error {
seenPath = path
if dst, ok := out.(*aichatGetConversationTurnsResponse); ok {
dst.Turns = []aichatConversationTurn{{Role: "assistant", Body: "answer"}}
}
return nil
})
turns, err := s.fetchAichatConversationTurns(context.Background(), "11111111-1111-1111-1111-111111111111")
if err != nil {
t.Fatalf("fetchAichatConversationTurns: %v", err)
}
if len(turns) != 1 || turns[0].Body != "answer" {
t.Errorf("turns = %+v; want one assistant", turns)
}
for _, want := range []string{"/chat/conversations/11111111-1111-1111-1111-111111111111/turns", "persona=paliadin", "limit=20"} {
if !strings.Contains(seenPath, want) {
t.Errorf("path %q missing %q", seenPath, want)
}
}
}
// =============================================================================
// Interface conformance
// =============================================================================
func TestAichatPaliadinService_ImplementsStreaming(t *testing.T) {
var _ StreamingPaliadin = (*AichatPaliadinService)(nil)
var _ AichatRecoverer = (*AichatPaliadinService)(nil)
}

View File

@@ -501,6 +501,7 @@ func TestRunTurn_HappyPath_ViaCallHTTP(t *testing.T) {
body := aichatTurnRequest{
Persona: s.cfg.Persona,
Username: s.usernameFor(context.Background(), uid),
UserID: uid.String(),
Message: "Hello",
JWT: jwtTok,
Meta: buildAichatMeta(TurnRequest{PageOrigin: "/dashboard"}),
@@ -516,6 +517,12 @@ func TestRunTurn_HappyPath_ViaCallHTTP(t *testing.T) {
if captured.Username != "user-aaaaaaaa" {
t.Errorf("username = %q; want user-aaaaaaaa (nil DB fallback)", captured.Username)
}
// Regression for the 2026-05-21 outage: aichat now requires user_id
// when a tenant DB is configured; missing → 400 → SSE drop on the
// frontend ("Verbindung verloren"). The struct must carry it.
if captured.UserID != uid.String() {
t.Errorf("user_id = %q; want %q", captured.UserID, uid.String())
}
if captured.Message != "Hello" {
t.Errorf("message = %q; want Hello", captured.Message)
}

View File

@@ -41,6 +41,7 @@ import (
"encoding/json"
"errors"
"fmt"
"maps"
"strings"
"time"
@@ -364,6 +365,135 @@ func (s *ApprovalService) Revoke(ctx context.Context, requestID, callerID uuid.U
return s.decide(ctx, requestID, callerID, RequestStatusRevoked, "")
}
// EditPendingEntity lets the REQUESTER of a pending approval_request revise
// the in-flight entity (e.g. tweak the title or due_date on a pending
// create) without withdrawing the request. t-paliad-252 / m/paliad#83 added
// this as the non-destructive sibling of Revoke — m's mental model is
// "withdraw deletes the event; let me edit the event instead, keep the
// approval request alive".
//
// Authorization: caller MUST be the original requested_by (no approver can
// edit on the requester's behalf — that would collapse into SuggestChanges).
// Request status MUST be pending.
//
// Allowlist: uses the WIDER counter-allowlist already maintained for
// SuggestChanges (buildCounterSetClauses) — every editable field on the
// entity, not just the date-bearing approval triggers. Unknown keys are
// silently dropped. Returns ErrSuggestionRequiresChange when fields carries
// no allowlisted key for the entity_type (would be a no-op write).
//
// Side effects in one tx: entity columns updated (and event_type_ids junction
// rewritten for deadlines), approval_request.payload merged with the new
// values so the approver sees what was revised, and a distinct
// `<entity>_approval_edited_by_requester` project_event emitted so the
// Verlauf shows the revision separately from the original *_requested row.
//
// The approval_request stays pending; entity.approval_status stays pending.
// The approver inbox sees a fresh updated_at + the merged payload.
func (s *ApprovalService) EditPendingEntity(ctx context.Context, requestID, callerID uuid.UUID, fields map[string]any) error {
tx, err := s.db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer tx.Rollback() //nolint:errcheck
req, err := s.getRequestForUpdate(ctx, tx, requestID)
if err != nil {
return err
}
if req.Status != RequestStatusPending {
return fmt.Errorf("%w: status=%s", ErrRequestNotPending, req.Status)
}
if callerID != req.RequestedBy {
return ErrNotApprover
}
// Validate the counter-allowlist intersect produces at least one
// settable column. applyEntityUpdate also wraps this check; pre-checking
// here lets us emit a cleaner error before opening the entity-write.
if _, _, err := buildCounterSetClauses(req.EntityType, fields); err != nil {
// Already wraps ErrSuggestionRequiresChange for empty / title-cleared
// cases. Propagate verbatim.
return err
}
// Apply the field updates to the entity row via the shared
// counter-allowlist path (same as SuggestChanges).
if err := s.applyEntityUpdate(ctx, tx, req.EntityType, req.EntityID, fields); err != nil {
return err
}
// Merge new fields into the request payload so the approver's inbox
// reflects what the requester revised to. Keys overwrite; event_type_ids
// is replaced wholesale per the same semantics applyEntityUpdate uses
// for the junction rewrite.
var existing map[string]any
if len(req.Payload) > 0 {
if err := json.Unmarshal(req.Payload, &existing); err != nil {
return fmt.Errorf("unmarshal payload: %w", err)
}
}
if existing == nil {
existing = map[string]any{}
}
maps.Copy(existing, fields)
merged, err := json.Marshal(existing)
if err != nil {
return fmt.Errorf("marshal merged payload: %w", err)
}
now := time.Now().UTC()
if _, err := tx.ExecContext(ctx,
`UPDATE paliad.approval_requests
SET payload = $1, updated_at = $2
WHERE id = $3`,
merged, now, requestID); err != nil {
return fmt.Errorf("update payload: %w", err)
}
// Audit emit. Distinct event_type so the Verlauf surfaces the revision
// separately from the original *_requested or any decision row.
verlaufKind := "edited_by_requester"
eventType := approvalEventType(req.EntityType, verlaufKind)
descPtr := approvalDescription(verlaufKind, req.RequiredRole, req.LifecycleEvent)
editedKeys := sortedKeys(fields)
meta := map[string]any{
"approval_request_id": req.ID.String(),
"lifecycle_event": req.LifecycleEvent,
req.EntityType + "_id": req.EntityID.String(),
"edited_fields": editedKeys,
}
if err := insertProjectEventWithMeta(ctx, tx, req.ProjectID, callerID, eventType, eventType, descPtr, meta); err != nil {
return err
}
return tx.Commit()
}
// sortedKeys returns m's keys in stable alphabetical order so the audit-log
// metadata is byte-for-byte stable across calls (helps when diffing audit
// logs or asserting on them in tests).
func sortedKeys(m map[string]any) []string {
out := make([]string, 0, len(m))
for k := range m {
out = append(out, k)
}
// Use the stdlib sort; the slice is small (≤ counter-allowlist size).
sortStrings(out)
return out
}
// sortStrings: indirection so we don't add a new top-level import group.
// In Go 1.21+ slices.Sort exists; this package is currently importing
// strings + standard libs and adding "sort" would re-fan the imports.
// Kept as a one-line wrapper to localise the dependency if a later move
// to slices.Sort feels right.
func sortStrings(s []string) {
for i := 1; i < len(s); i++ {
for j := i; j > 0 && s[j-1] > s[j]; j-- {
s[j-1], s[j] = s[j], s[j-1]
}
}
}
// SuggestChanges is the fourth approval action (t-paliad-216). The caller
// proposes a counter-payload + optional free-text note; in one transaction
// we close the old request as 'changes_requested', revert the entity from

View File

@@ -226,10 +226,12 @@ func validatePosition(i int, w DashboardWidgetRef, def WidgetDef) error {
}
// SanitizeForRead applies the forgiving read-path rules: drop entries whose
// keys are not in the catalog (catalog has shrunk) and bump the version to
// the current one if missing. Settings on surviving entries pass through
// unchanged — invalid settings on read are not worth aborting over and the
// next write will reject them anyway.
// keys are not in the catalog (catalog has shrunk), bump the version to
// the current one if missing, and clamp w/h/x against the catalog's
// MinW/MaxW/MinH/MaxH/grid bounds so a stale row with out-of-range sizes
// can't strand the user with unrenderable widgets (m/paliad#73). Settings
// on surviving entries pass through unchanged — invalid settings on read
// are not worth aborting over and the next write will reject them anyway.
//
// Returns true if anything was changed; callers can use that to decide
// whether to PUT the cleaned spec back.
@@ -244,16 +246,88 @@ func (s *DashboardLayoutSpec) SanitizeForRead() bool {
}
out := make([]DashboardWidgetRef, 0, len(s.Widgets))
for _, w := range s.Widgets {
if _, ok := LookupWidgetDef(w.Key); !ok {
def, ok := LookupWidgetDef(w.Key)
if !ok {
changed = true
continue
}
if normalizePosition(&w, def) {
changed = true
}
out = append(out, w)
}
s.Widgets = out
return changed
}
// normalizePosition clamps a widget's W/H/X to the catalog bounds and the
// grid extent. Returns true if any field was modified. Zero W/H stay zero
// (auto-flow / default sentinel — the placer fills them in). Negative X
// snaps to 0; X+W overflowing the grid snaps X down.
func normalizePosition(w *DashboardWidgetRef, def WidgetDef) bool {
changed := false
if w.W < 0 {
w.W = 0
changed = true
}
if w.W > DashboardGridColumns {
w.W = DashboardGridColumns
changed = true
}
// W == 0 is the "auto / default" sentinel — leave it untouched so
// downstream renderers can substitute DefaultW. Only clamp non-zero
// values against the per-widget Min/Max.
if w.W > 0 {
if def.MinW > 0 && w.W < def.MinW {
w.W = def.MinW
changed = true
}
if def.MaxW > 0 && w.W > def.MaxW {
w.W = def.MaxW
changed = true
}
}
if w.H < 0 {
w.H = 0
changed = true
}
if w.H > MaxGridRowSpan {
w.H = MaxGridRowSpan
changed = true
}
if w.H > 0 {
if def.MinH > 0 && w.H < def.MinH {
w.H = def.MinH
changed = true
}
if def.MaxH > 0 && w.H > def.MaxH {
w.H = def.MaxH
changed = true
}
}
if w.X < 0 {
w.X = 0
changed = true
}
if w.X >= DashboardGridColumns {
w.X = DashboardGridColumns - 1
changed = true
}
if w.W > 0 && w.X+w.W > DashboardGridColumns {
w.X = DashboardGridColumns - w.W
changed = true
}
if w.Y < 0 {
w.Y = 0
changed = true
}
return changed
}
// ParseDashboardLayoutSpec decodes JSON bytes and validates. Used by the
// HTTP handler on incoming request bodies.
func ParseDashboardLayoutSpec(b []byte) (DashboardLayoutSpec, error) {

View File

@@ -279,6 +279,128 @@ func TestDashboardLayoutSpec_SanitizeForRead_DropsUnknownKeys(t *testing.T) {
}
}
// TestDashboardLayoutSpec_SanitizeForRead_ClampsOutOfRange covers the
// m/paliad#73 recovery path: a stale row in user_dashboard_layouts
// carrying a W below MinW (or above MaxW) must be normalised on load so
// the user doesn't get stranded with super-slim columns. Pre-fix the
// sanitizer only dropped unknown keys; sizes passed through verbatim.
func TestDashboardLayoutSpec_SanitizeForRead_ClampsOutOfRange(t *testing.T) {
// upcoming-deadlines: MinW=4, MaxW=12, MinH=1, MaxH=4 (per catalog).
def, ok := LookupWidgetDef(WidgetUpcomingDeadlines)
if !ok {
t.Fatal("LookupWidgetDef(WidgetUpcomingDeadlines) = !ok")
}
cases := []struct {
name string
in DashboardWidgetRef
wantW int
wantH int
wantX int
wantY int
wantOK bool // expected SanitizeForRead-returns-true
}{
{
name: "W below MinW snaps to MinW",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 1, H: 1},
wantW: def.MinW,
wantH: 1,
wantOK: true,
},
{
name: "W above MaxW snaps to MaxW",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 99, H: 1},
wantW: DashboardGridColumns,
wantH: 1,
wantOK: true,
},
{
name: "W above grid width snaps to grid width",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 50, H: 1},
wantW: DashboardGridColumns,
wantH: 1,
wantOK: true,
},
{
name: "H above MaxGridRowSpan snaps to MaxGridRowSpan",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 6, H: 99},
wantW: 6,
wantH: def.MaxH, // upcoming-deadlines MaxH=4 < MaxGridRowSpan=5
wantOK: true,
},
{
name: "X+W overflowing grid snaps X down",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 10, Y: 0, W: 6, H: 1},
wantW: 6,
wantH: 1,
wantX: 6, // 12 - 6 = 6
wantOK: true,
},
{
name: "W=0 stays 0 (auto / default sentinel)",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 0, H: 0},
wantW: 0,
wantH: 0,
wantOK: false,
},
{
name: "negative X snaps to 0",
in: DashboardWidgetRef{Key: WidgetUpcomingDeadlines, Visible: true, X: -3, Y: 0, W: 6, H: 1},
wantW: 6,
wantH: 1,
wantX: 0,
wantOK: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
s := DashboardLayoutSpec{Version: LayoutSpecVersion, Widgets: []DashboardWidgetRef{tc.in}}
changed := s.SanitizeForRead()
if changed != tc.wantOK {
t.Errorf("SanitizeForRead returned %v; want %v", changed, tc.wantOK)
}
if len(s.Widgets) != 1 {
t.Fatalf("expected 1 widget after sanitize, got %d", len(s.Widgets))
}
got := s.Widgets[0]
if got.W != tc.wantW {
t.Errorf("W = %d; want %d", got.W, tc.wantW)
}
if got.H != tc.wantH {
t.Errorf("H = %d; want %d", got.H, tc.wantH)
}
if got.X != tc.wantX {
t.Errorf("X = %d; want %d", got.X, tc.wantX)
}
if got.Y != tc.wantY {
t.Errorf("Y = %d; want %d", got.Y, tc.wantY)
}
})
}
}
// TestDashboardLayoutSpec_SanitizeForRead_ClampedSpecPassesValidate is
// the round-trip guarantee — after the sanitiser heals a stale row, the
// result must be acceptable to Validate so the next PUT doesn't reject
// the user's layout. Without this guarantee, sanitizing on read could
// produce a layout the validator won't accept on the autosave path.
func TestDashboardLayoutSpec_SanitizeForRead_ClampedSpecPassesValidate(t *testing.T) {
s := DashboardLayoutSpec{
Version: LayoutSpecVersion,
Widgets: []DashboardWidgetRef{
{Key: WidgetUpcomingDeadlines, Visible: true, X: 0, Y: 0, W: 1, H: 1},
{Key: WidgetUpcomingDeadlines, Visible: true, X: 50, Y: 0, W: 99, H: 99}, // duplicate key — Validate will reject; this case checks size clamp at least
},
}
// Trim to one widget for the validate assertion (duplicates are a
// separate concern).
s.Widgets = s.Widgets[:1]
s.SanitizeForRead()
if err := s.Validate(); err != nil {
t.Errorf("Validate after SanitizeForRead returned %v; want nil", err)
}
}
func TestDashboardLayoutSpec_SanitizeForRead_NoopOnClean(t *testing.T) {
s := FactoryDefaultLayout()
if s.SanitizeForRead() {

View File

@@ -66,7 +66,7 @@ func (s *DeadlineService) pendingApprovalErr(ctx context.Context, deadlineID uui
}
const deadlineColumns = `id, project_id, title, description, due_date, original_due_date,
warning_date, source, rule_id, rule_code, status, completed_at, caldav_uid, caldav_etag,
warning_date, source, rule_id, rule_code, custom_rule_text, status, completed_at, caldav_uid, caldav_etag,
notes, created_by, created_at, updated_at,
approval_status, pending_request_id, approved_by, approved_at`
@@ -81,6 +81,11 @@ type CreateDeadlineInput struct {
// Sent by the Fristenrechner save flow so the title can stay clean
// instead of carrying the citation as a prefix.
RuleCode *string `json:"rule_code,omitempty"`
// CustomRuleText is the lawyer's free-text rule label when the
// deadline form is in Custom mode (t-paliad-258). Mutually exclusive
// with RuleID at the application layer; the service trims and treats
// an all-whitespace value as nil.
CustomRuleText *string `json:"custom_rule_text,omitempty"`
Source string `json:"source,omitempty"` // default "manual"
Notes *string `json:"notes,omitempty"`
EventTypeIDs []uuid.UUID `json:"event_type_ids,omitempty"`
@@ -108,6 +113,20 @@ type UpdateDeadlineInput struct {
Status *string `json:"status,omitempty"`
ProjectID *uuid.UUID `json:"project_id,omitempty"`
EventTypeIDs *[]uuid.UUID `json:"event_type_ids,omitempty"`
// Rule pointer pair (t-paliad-258 / m/paliad#89). Three valid
// shapes; the service rejects "both set":
// - RuleSet=true, RuleID non-nil, CustomRuleText nil → Auto:
// bind to the catalog rule, clear custom_rule_text.
// - RuleSet=true, RuleID nil, CustomRuleText non-nil → Custom:
// store free text, clear rule_id.
// - RuleSet=true, RuleID nil, CustomRuleText nil → No rule:
// clear both columns.
// RuleSet=false leaves both columns untouched (the rest of the
// PATCH body doesn't carry rule changes).
RuleSet bool `json:"rule_set,omitempty"`
RuleID *uuid.UUID `json:"rule_id,omitempty"`
CustomRuleText *string `json:"custom_rule_text,omitempty"`
}
// DeadlineStatusFilter is a server-side bucket for ListVisibleForUser.
@@ -197,7 +216,16 @@ func (s *DeadlineService) ListVisibleForUser(ctx context.Context, userID uuid.UU
conds = append(conds, `f.status = 'pending' AND f.due_date < :today`)
args["today"] = b.today
case DeadlineFilterToday:
conds = append(conds, `f.status = 'pending' AND f.due_date = :today`)
// "Heute" includes pending due today AND items that were completed
// today (rendered strikethrough/green client-side). m, 2026-05-22:
// previously filtered out the moment a row was checked off, so a
// user couldn't see their own progress on the day's deadlines.
// Items completed on earlier days still drop out — the bucket
// stays scoped to "today's work".
// date(...) cast instead of `::date` — sqlx's named-parameter parser
// reads `::date` as `::` + `:date` placeholder and rewrites it into
// a syntax error against Postgres.
conds = append(conds, `f.due_date = :today AND (f.status = 'pending' OR date(f.completed_at) = :today)`)
args["today"] = b.today
case DeadlineFilterThisWeek:
conds = append(conds, `f.status = 'pending' AND f.due_date > :today AND f.due_date < :next_monday`)
@@ -232,7 +260,7 @@ func (s *DeadlineService) ListVisibleForUser(ctx context.Context, userID uuid.UU
query := `
SELECT f.id, f.project_id, f.title, f.description, f.due_date, f.original_due_date,
f.warning_date, f.source, f.rule_id, f.rule_code, f.status, f.completed_at,
f.warning_date, f.source, f.rule_id, f.rule_code, f.custom_rule_text, f.status, f.completed_at,
f.caldav_uid, f.caldav_etag, f.notes, f.created_by,
f.created_at, f.updated_at,
f.approval_status, f.pending_request_id, f.approved_by, f.approved_at,
@@ -505,6 +533,23 @@ func (s *DeadlineService) Update(ctx context.Context, userID, deadlineID uuid.UU
}
}
// Auto/Custom rule swap (t-paliad-258). Mutually exclusive at the
// persistence boundary: setting one column NULLs the other.
if input.RuleSet {
if input.RuleID != nil && input.CustomRuleText != nil {
return nil, fmt.Errorf("%w: rule_id and custom_rule_text are mutually exclusive", ErrInvalidInput)
}
appendSet("rule_id", input.RuleID)
var customText *string
if input.CustomRuleText != nil {
trimmed := strings.TrimSpace(*input.CustomRuleText)
if trimmed != "" {
customText = &trimmed
}
}
appendSet("custom_rule_text", customText)
}
// Project move (t-paliad-140). Visibility on the destination is enforced
// the same way as on Create — a GetByID round-trip through ProjectService
// returns ErrNotVisible if the user can't see the target. Same-project
@@ -578,7 +623,7 @@ func (s *DeadlineService) Update(ctx context.Context, userID, deadlineID uuid.UU
// Did the PATCH touch anything beyond the project move?
otherFieldsTouched := input.Title != nil || input.Description != nil ||
input.DueDate != nil || input.Notes != nil || input.Status != nil ||
input.EventTypeIDs != nil
input.EventTypeIDs != nil || input.RuleSet
if otherFieldsTouched {
auditProject := current.ProjectID
if movedFromProject != nil {
@@ -1003,15 +1048,27 @@ func (s *DeadlineService) insertTx(ctx context.Context, tx *sqlx.Tx, userID, pro
}
}
// Auto vs Custom (t-paliad-258): RuleID and CustomRuleText are
// mutually exclusive. If the caller passes both, the catalog rule
// wins and the free-text is dropped — keeps the invariant simple at
// the persistence boundary.
var customRuleText *string
if input.CustomRuleText != nil && input.RuleID == nil {
trimmed := strings.TrimSpace(*input.CustomRuleText)
if trimmed != "" {
customRuleText = &trimmed
}
}
id := uuid.New()
now := time.Now().UTC()
if _, err := tx.ExecContext(ctx,
`INSERT INTO paliad.deadlines
(id, project_id, title, description, due_date, original_due_date,
source, rule_id, rule_code, status, notes, created_by, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, 'pending', $10, $11, $12, $12)`,
source, rule_id, rule_code, custom_rule_text, status, notes, created_by, created_at, updated_at)
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, 'pending', $11, $12, $13, $13)`,
id, projectID, title, input.Description, due, orig,
source, input.RuleID, ruleCode, input.Notes, userID, now,
source, input.RuleID, ruleCode, customRuleText, input.Notes, userID, now,
); err != nil {
return uuid.Nil, fmt.Errorf("insert deadline: %w", err)
}

View File

@@ -42,12 +42,15 @@ func NewDerivationService(db *sqlx.DB, projects *ProjectService, partnerUnit *Pa
// the configured derive_unit_roles. The frontend renders this on the
// /projects/{id}/settings/team Partner Units section.
type AttachedUnit struct {
ProjectID uuid.UUID `db:"project_id" json:"project_id"`
PartnerUnitID uuid.UUID `db:"partner_unit_id" json:"partner_unit_id"`
UnitName string `db:"unit_name" json:"unit_name"`
DeriveUnitRoles []string `db:"derive_unit_roles" json:"derive_unit_roles"`
DeriveGrantsAuthority bool `db:"derive_grants_authority" json:"derive_grants_authority"`
DerivedMemberCount int `db:"derived_member_count" json:"derived_member_count"`
ProjectID uuid.UUID `db:"project_id" json:"project_id"`
PartnerUnitID uuid.UUID `db:"partner_unit_id" json:"partner_unit_id"`
UnitName string `db:"unit_name" json:"unit_name"`
// derive_unit_roles is a Postgres text[]; sqlx returns it as []byte
// without an array adapter, so we use pq.StringArray for the scan
// and convert to []string in JSON via a tiny ergonomics wrapper.
DeriveUnitRoles pq.StringArray `db:"derive_unit_roles" json:"derive_unit_roles"`
DeriveGrantsAuthority bool `db:"derive_grants_authority" json:"derive_grants_authority"`
DerivedMemberCount int `db:"derived_member_count" json:"derived_member_count"`
}
// DerivedMembership is one (unit, role) pair through which a user currently

View File

@@ -107,11 +107,15 @@ type EventListItem struct {
Status *string `json:"status,omitempty"`
CompletedAt *time.Time `json:"completed_at,omitempty"`
Source *string `json:"source,omitempty"`
RuleID *uuid.UUID `json:"rule_id,omitempty"`
RuleCode *string `json:"rule_code,omitempty"`
RuleName *string `json:"rule_name,omitempty"`
RuleNameEN *string `json:"rule_name_en,omitempty"`
EventTypeIDs []uuid.UUID `json:"event_type_ids,omitempty"`
RuleID *uuid.UUID `json:"rule_id,omitempty"`
RuleCode *string `json:"rule_code,omitempty"`
RuleName *string `json:"rule_name,omitempty"`
RuleNameEN *string `json:"rule_name_en,omitempty"`
// CustomRuleText surfaces the lawyer's free-text rule label when the
// deadline was created via the Custom rule path (t-paliad-258).
// Display surfaces fall back to it when RuleName is absent.
CustomRuleText *string `json:"custom_rule_text,omitempty"`
EventTypeIDs []uuid.UUID `json:"event_type_ids,omitempty"`
// Appointment-only.
StartAt *time.Time `json:"start_at,omitempty"`
@@ -236,6 +240,7 @@ func projectDeadline(d models.DeadlineWithProject) EventListItem {
RuleCode: d.RuleCode,
RuleName: d.RuleName,
RuleNameEN: d.RuleNameEN,
CustomRuleText: d.CustomRuleText,
EventTypeIDs: d.EventTypeIDs,
}
}

View File

@@ -115,6 +115,16 @@ type UIResponse struct {
// note explaining the framing.
ContextualNote string `json:"contextualNote,omitempty"`
ContextualNoteEN string `json:"contextualNoteEN,omitempty"`
// TriggerEventLabel / TriggerEventLabelEN: optional caption for the
// /tools/verfahrensablauf "Auslösendes Ereignis" field. Populated
// from paliad.proceeding_types.trigger_event_label_{de,en} (mig 121).
// The frontend prefers this over the proceedingName fallback that
// fires when no rule has IsRootEvent=true — UPC Appeal needed it
// because all its rules carry a non-zero duration off the trigger
// date so no rule is the "anchor". The trigger event for UPC Appeal
// is the appealable first-instance decision (m/paliad#81).
TriggerEventLabel string `json:"triggerEventLabel,omitempty"`
TriggerEventLabelEN string `json:"triggerEventLabelEN,omitempty"`
}
// ErrUnknownProceedingType is returned when the UI sends an unrecognised code.
@@ -237,14 +247,17 @@ func (s *FristenrechnerService) Calculate(ctx context.Context, proceedingCode, t
// Look up proceeding type metadata.
var pt struct {
ID int `db:"id"`
Code string `db:"code"`
Name string `db:"name"`
NameEN string `db:"name_en"`
Jurisdiction *string `db:"jurisdiction"`
ID int `db:"id"`
Code string `db:"code"`
Name string `db:"name"`
NameEN string `db:"name_en"`
Jurisdiction *string `db:"jurisdiction"`
TriggerEventLabelDE *string `db:"trigger_event_label_de"`
TriggerEventLabelEN *string `db:"trigger_event_label_en"`
}
err = s.rules.db.GetContext(ctx, &pt,
`SELECT id, code, name, name_en, jurisdiction
`SELECT id, code, name, name_en, jurisdiction,
trigger_event_label_de, trigger_event_label_en
FROM paliad.proceeding_types
WHERE code = $1 AND is_active = true`, proceedingCode)
if errors.Is(err, sql.ErrNoRows) {
@@ -271,7 +284,8 @@ func (s *FristenrechnerService) Calculate(ctx context.Context, proceedingCode, t
hasSubTrackNote = true
// Re-resolve to the parent proceeding for rule lookup.
err = s.rules.db.GetContext(ctx, &pt,
`SELECT id, code, name, name_en, jurisdiction
`SELECT id, code, name, name_en, jurisdiction,
trigger_event_label_de, trigger_event_label_en
FROM paliad.proceeding_types
WHERE code = $1 AND is_active = true`, route.ParentCode)
if errors.Is(err, sql.ErrNoRows) {
@@ -604,6 +618,17 @@ func (s *FristenrechnerService) Calculate(ctx context.Context, proceedingCode, t
TriggerDate: triggerDateStr,
Deadlines: deadlines,
}
// Sub-track routing keeps the user-picked proceeding's identity,
// so the trigger-event label rides on `pickedProceeding` (e.g.
// upc.ccr.cfi inherits whatever upc.inf.cfi's caption is, not
// upc.ccr.cfi's own — which is fine: the sub-track note already
// explains the framing).
if pickedProceeding.TriggerEventLabelDE != nil {
resp.TriggerEventLabel = *pickedProceeding.TriggerEventLabelDE
}
if pickedProceeding.TriggerEventLabelEN != nil {
resp.TriggerEventLabelEN = *pickedProceeding.TriggerEventLabelEN
}
if hasSubTrackNote {
resp.ContextualNote = subTrackNote.NoteDE
resp.ContextualNoteEN = subTrackNote.NoteEN

View File

@@ -0,0 +1,127 @@
package services
// Streaming support for the Paliadin chat surface (t-paliad-235).
//
// The legacy LocalPaliadinService.RunTurn returns the full response in
// one shot — the chat UI gets one `content` blob and the typewriter
// simulates streaming. That falls apart on long turns: the HTTP client
// hits its 130 s ceiling, paliad's SSE stream closes, the bubble shows
// "Verbindung verloren" and the response is lost.
//
// The aichat backend exposes a real streaming variant at
// /chat/turn/stream that emits incremental chunks + named heartbeat
// events while claude is thinking. AichatPaliadinService implements
// the StreamingPaliadin interface defined here; the handler probes
// for it via a type assertion and falls back to the one-shot RunTurn
// when the backend doesn't support streaming (legacy path).
//
// Recovery (a separate axis): when the transport drops mid-turn,
// the AichatRecoverer interface lets the handler ask the backend to
// look up the late response via aichat's conversation API rather than
// rely on the legacy filesystem janitor — which only knows about
// LocalPaliadinService's per-turn response files.
import (
"context"
"github.com/google/uuid"
)
// StreamEvent is one increment of a streaming turn. The handler
// receives these via the channel passed to RunTurnStream and forwards
// them as SSE frames to the browser.
//
// Exactly one of Kind's payloads is meaningful per event:
//
// StreamChunk → Content holds the next slice of assistant text
// StreamHeartbeat → ElapsedSeconds holds upstream "still thinking" tick
// StreamMeta → UsedTools / RowsSeen / ClassifierTag populated
// StreamError → Code / Message / Retryable populated
//
// StreamDone is implicit: when the channel closes without an error
// event, the turn completed. The accompanying *TurnResult returned by
// RunTurnStream carries the final accumulated body + meta + conversation
// id for persistence and recovery.
type StreamEvent struct {
Kind StreamEventKind
// StreamChunk
Content string
// StreamHeartbeat
ElapsedSeconds int
// StreamMeta (terminal-side; may also be merged into final TurnResult)
UsedTools []string
RowsSeen []int
ClassifierTag string
// StreamError
Code string
Message string
Retryable bool
// StreamConversation — aichat sometimes resolves the conversation id
// before the first chunk arrives. We surface it as soon as we have
// it so the handler can persist it for recovery, even if the stream
// is later interrupted.
ConversationID string
}
// StreamEventKind enumerates the meaningful flavours.
type StreamEventKind string
const (
StreamChunk StreamEventKind = "chunk"
StreamHeartbeat StreamEventKind = "heartbeat"
StreamMeta StreamEventKind = "meta"
StreamError StreamEventKind = "error"
StreamConversation StreamEventKind = "conversation"
)
// StreamingPaliadin is the optional extension the AichatPaliadinService
// implements. Handlers detect it via type assertion; backends that don't
// implement it (the legacy local + remote paths) fall back to the
// one-shot Paliadin.RunTurn.
//
// Contract:
// - RunTurnStream MUST close `events` before returning, so the handler
// loop terminates cleanly.
// - Returning a non-nil error implies the audit row was already
// stamped with an error_code; the handler does not double-stamp.
// - The *TurnResult is populated even on partial failure when the
// upstream produced any meaningful body — handlers may render it as
// a salvaged best-effort result instead of an error.
type StreamingPaliadin interface {
Paliadin
// RunTurnStream drives one turn against the streaming upstream and
// pushes StreamEvents onto `events` as they arrive. Blocks until the
// upstream finishes or the context cancels. `events` is closed by
// the implementation before this method returns.
RunTurnStream(ctx context.Context, req TurnRequest, events chan<- StreamEvent) (*TurnResult, error)
}
// AichatRecoverer is the optional extension that knows how to ask the
// aichat backend "did this turn actually complete?" when paliad's local
// audit row never got a response (because the transport dropped mid
// turn). Implementations look up the persisted aichat_conversation_id,
// query aichat's GET /chat/conversations/{id}/turns, find the matching
// assistant turn, and write the response back to paliad's row.
//
// Returns (nil, nil) when aichat doesn't have the response either —
// i.e. the turn is truly lost and the UI must degrade to "verloren"
// copy rather than "wird nachgereicht".
type AichatRecoverer interface {
RecoverTurn(ctx context.Context, callerID, turnID uuid.UUID) (*PaliadinTurn, error)
}
// safeSendStream pushes an event onto the channel, dropping on context
// cancel. Mirrors the handler-side `send` helper but works against a
// generic chan StreamEvent.
func safeSendStream(ctx context.Context, ch chan<- StreamEvent, ev StreamEvent) {
select {
case ch <- ev:
case <-ctx.Done():
}
}

View File

@@ -59,10 +59,16 @@ type projectChainRow struct {
ProceedingCode *string `db:"proceeding_code"`
}
// BuildProjectCode walks the ancestor chain via the existing
// paliad.projects.path ltree and returns the assembled code. One DB
// round-trip per call; suitable for per-row use in single-project
// projection paths.
// BuildProjectCode walks the ancestor chain via paliad.projects.path
// and returns the assembled code. One DB round-trip per call; suitable
// for per-row use in single-project projection paths.
//
// paliad.projects.path is stored as TEXT (dot-separated UUIDs), not as
// the ltree extension type — see export_service.go comment "ltree as
// text" and can_see_project's string_to_array decomposition. Ancestor
// walks use the same string_to_array(path, '.')::uuid[] pattern as the
// canonical visibility predicate; ltree operators (@>, nlevel) would
// raise "operator does not exist: text @> text" at runtime.
//
// For list endpoints with many rows, the call still scales fine for
// firm-scale datasets (order-of-100s); if profiling later flags it as
@@ -72,10 +78,12 @@ func BuildProjectCode(ctx context.Context, db sqlx.QueryerContext, projectID uui
SELECT p.id, p.type, p.title, p.reference, p.opponent_code,
p.patent_number, p.proceeding_type_id,
pt.code AS proceeding_code
FROM paliad.projects p
FROM paliad.projects target
JOIN paliad.projects p
ON p.id = ANY(string_to_array(target.path, '.')::uuid[])
LEFT JOIN paliad.proceeding_types pt ON pt.id = p.proceeding_type_id
WHERE p.path @> (SELECT path FROM paliad.projects WHERE id = $1)
ORDER BY nlevel(p.path)
WHERE target.id = $1
ORDER BY array_position(string_to_array(target.path, '.')::uuid[], p.id)
`
rows := []projectChainRow{}
if err := sqlx.SelectContext(ctx, db, &rows, query, projectID); err != nil {
@@ -102,8 +110,13 @@ func PopulateProjectCodes(ctx context.Context, db sqlx.QueryerContext, targets [
ids[i] = t.ID.String()
}
// One CTE-based query: for each target id, fetch the full ancestor
// chain joined to proceeding_types, ordered so we can group in Go.
// One query: for each target id, fetch the full ancestor chain
// joined to proceeding_types, ordered so we can group in Go.
//
// Ancestor walk uses string_to_array(path, '.')::uuid[] — same shape
// as can_see_project. paliad.projects.path is TEXT, so ltree
// operators (@>, nlevel) would fail with "operator does not exist:
// text @> text". See BuildProjectCode doc comment for context.
const query = `
WITH targets AS (
SELECT id, path
@@ -114,9 +127,10 @@ func PopulateProjectCodes(ctx context.Context, db sqlx.QueryerContext, targets [
p.id, p.type, p.title, p.reference, p.opponent_code,
p.patent_number, p.proceeding_type_id,
pt.code AS proceeding_code,
nlevel(p.path) AS chain_level
array_position(string_to_array(t.path, '.')::uuid[], p.id) AS chain_level
FROM targets t
JOIN paliad.projects p ON p.path @> t.path
JOIN paliad.projects p
ON p.id = ANY(string_to_array(t.path, '.')::uuid[])
LEFT JOIN paliad.proceeding_types pt ON pt.id = p.proceeding_type_id
ORDER BY t.id, chain_level
`

View File

@@ -924,7 +924,7 @@ func (s *ProjectService) Create(ctx context.Context, userID uuid.UUID, input Cre
input.Title, input.Reference, input.Description, status,
userID,
input.Industry, input.Country, input.BillingReference,
input.ClientNumber, input.MatterNumber, input.NetDocumentsURL,
nullableTrimmed(input.ClientNumber), nullableTrimmed(input.MatterNumber), input.NetDocumentsURL,
input.PatentNumber, input.FilingDate, input.GrantDate,
input.Court, input.CaseNumber, input.ProceedingTypeID,
nullableOurSide(input.OurSide),
@@ -1038,10 +1038,13 @@ func (s *ProjectService) Update(ctx context.Context, userID, id uuid.UUID, input
appendSet("billing_reference", *input.BillingReference)
}
if input.ClientNumber != nil {
appendSetSkippable("client_number", *input.ClientNumber)
// Coerce empty string → NULL so the
// projekte_client_number_check ('^[0-9]{6}$' OR NULL) accepts a
// blanked field (m, 2026-05-22 — "I cant add a project").
appendSetSkippable("client_number", nullableTrimmed(input.ClientNumber))
}
if input.MatterNumber != nil {
appendSet("matter_number", *input.MatterNumber)
appendSet("matter_number", nullableTrimmed(input.MatterNumber))
}
if input.NetDocumentsURL != nil {
appendSet("netdocuments_url", *input.NetDocumentsURL)
@@ -2033,6 +2036,23 @@ func nullableInstanceLevel(p *string) any {
return s
}
// nullableTrimmed returns nil for an empty / whitespace value so the SQL
// driver writes NULL, otherwise the trimmed string. Used for nullable
// text columns whose constraints reject the empty string (e.g.
// projekte_client_number_check requires NULL or 6 digits — a blank
// client_number field on the project form would otherwise fail the
// constraint instead of being treated as "not set").
func nullableTrimmed(p *string) any {
if p == nil {
return nil
}
s := strings.TrimSpace(*p)
if s == "" {
return nil
}
return s
}
// nullableOurSide returns nil for an empty / whitespace value so the
// SQL driver writes NULL, otherwise the trimmed string. Mirrors the
// Update payload contract: empty string from the form clears the

View File

@@ -253,3 +253,95 @@ func TestProjectService_InstanceLevel_Roundtrip(t *testing.T) {
t.Errorf("want ErrInvalidInput, got %v", err)
}
}
// TestProjectService_CaseProceedingTypePicker covers the t-paliad-232
// data path for the new project-form Verfahrenstyp picker:
//
// 1. Creating a `case`-typed project with a fristenrechner-category
// proceeding_type_id round-trips the column.
// 2. The same code path rejects a non-fristenrechner-category id with
// ErrInvalidProceedingTypeCategory (mirror of the guard test above,
// this time exercised through a 'case' shape).
//
// Skipped when TEST_DATABASE_URL is unset.
func TestProjectService_CaseProceedingTypePicker(t *testing.T) {
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL not set — skipping live DB test")
}
if err := db.ApplyMigrations(url); err != nil {
t.Fatalf("apply migrations: %v", err)
}
pool, err := sqlx.Connect("postgres", url)
if err != nil {
t.Fatalf("connect: %v", err)
}
defer pool.Close()
ctx := context.Background()
var fristenrechnerID int
if err := pool.GetContext(ctx, &fristenrechnerID,
`SELECT id FROM paliad.proceeding_types
WHERE category = 'fristenrechner' AND code = $1 AND is_active = true`,
CodeUPCInfringement); err != nil {
t.Fatalf("look up %s id: %v", CodeUPCInfringement, err)
}
var nonFristenrechnerID int
if err := pool.GetContext(ctx, &nonFristenrechnerID,
`SELECT id FROM paliad.proceeding_types
WHERE category <> 'fristenrechner'
ORDER BY id
LIMIT 1`); err != nil {
t.Fatalf("look up non-fristenrechner id: %v", err)
}
users := NewUserService(pool)
svc := NewProjectService(pool, users)
userID := uuid.New()
cleanup := func() {
pool.ExecContext(ctx, `DELETE FROM paliad.projects WHERE created_by = $1`, userID)
pool.ExecContext(ctx, `DELETE FROM paliad.users WHERE id = $1`, userID)
pool.ExecContext(ctx, `DELETE FROM auth.users WHERE id = $1`, userID)
}
cleanup()
defer cleanup()
if _, err := pool.ExecContext(ctx,
`INSERT INTO auth.users (id, email) VALUES ($1, 't-paliad-232-test@hlc.com')`,
userID); err != nil {
t.Fatalf("seed auth.users: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.users (id, email, display_name, office, role, lang)
VALUES ($1, 't-paliad-232-test@hlc.com', 'Picker Test', 'munich', 'associate', 'de')`,
userID); err != nil {
t.Fatalf("seed paliad.users: %v", err)
}
// 1. Case-typed create with a fristenrechner id succeeds.
created, err := svc.Create(ctx, userID, CreateProjectInput{
Type: ProjectTypeCase,
Title: "t-paliad-232 — case with proceeding_type_id",
ProceedingTypeID: &fristenrechnerID,
})
if err != nil {
t.Fatalf("Create case with fristenrechner id: %v", err)
}
if created.ProceedingTypeID == nil || *created.ProceedingTypeID != fristenrechnerID {
t.Errorf("created proceeding_type_id = %v, want %d", created.ProceedingTypeID, fristenrechnerID)
}
// 2. Case-typed create with a non-fristenrechner id is rejected.
_, err = svc.Create(ctx, userID, CreateProjectInput{
Type: ProjectTypeCase,
Title: "t-paliad-232 — case with non-fristenrechner id",
ProceedingTypeID: &nonFristenrechnerID,
})
if err == nil {
t.Error("Create case with non-fristenrechner proceeding_type_id should fail, but succeeded")
} else if !errors.Is(err, ErrInvalidProceedingTypeCategory) {
t.Errorf("expected ErrInvalidProceedingTypeCategory, got %v", err)
}
}

View File

@@ -0,0 +1,211 @@
package services
// Live-DB integration test for the CCR-anchors-inf-rule path
// (t-paliad-237). The SmartTimeline on a CCR project surfaces parent
// inf rules in the parent_context lane; clicking "Datum setzen" on
// those rows used to bubble up as a generic 500 because the anchor
// lookup was scoped to the CCR's own proceeding_type_id. The service
// now detects the cross-proceeding case and rejects with a structured
// error pointing at the parent project — verified end-to-end here.
import (
"context"
"errors"
"os"
"testing"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"mgit.msbls.de/m/paliad/internal/db"
)
func TestRecordAnchor_CrossProceeding_RejectsWithParentPointer_Live(t *testing.T) {
url := os.Getenv("TEST_DATABASE_URL")
if url == "" {
t.Skip("TEST_DATABASE_URL not set — skipping live DB test")
}
if err := db.ApplyMigrations(url); err != nil {
t.Fatalf("apply migrations: %v", err)
}
pool, err := sqlx.Connect("postgres", url)
if err != nil {
t.Fatalf("connect: %v", err)
}
defer pool.Close()
ctx := context.Background()
userID := uuid.New()
patentID := uuid.New()
parentCaseID := uuid.New()
// Resolve upc.inf.cfi + upc.rev.cfi ids.
var upcInf, upcRev int
if err := pool.GetContext(ctx, &upcInf,
`SELECT id FROM paliad.proceeding_types WHERE code = $1`,
CodeUPCInfringement); err != nil {
t.Fatalf("resolve %s: %v", CodeUPCInfringement, err)
}
if err := pool.GetContext(ctx, &upcRev,
`SELECT id FROM paliad.proceeding_types WHERE code = $1`,
CodeUPCRevocation); err != nil {
t.Fatalf("resolve %s: %v", CodeUPCRevocation, err)
}
// Seed a unique inf-only rule for this test so the assertion does
// not couple to the live seed corpus.
infRuleID := uuid.New()
infRuleCode := "test.t237.infonly." + uuid.NewString()[:8]
cleanup := func() {
pool.ExecContext(ctx, `DELETE FROM paliad.deadline_rules WHERE id = $1`, infRuleID)
pool.ExecContext(ctx, `DELETE FROM paliad.project_events WHERE project_id IN (
SELECT id FROM paliad.projects WHERE counterclaim_of = $1)`, parentCaseID)
pool.ExecContext(ctx, `DELETE FROM paliad.project_teams WHERE project_id IN (
SELECT id FROM paliad.projects WHERE counterclaim_of = $1)`, parentCaseID)
pool.ExecContext(ctx, `DELETE FROM paliad.projects WHERE counterclaim_of = $1`, parentCaseID)
pool.ExecContext(ctx, `DELETE FROM paliad.project_events WHERE project_id IN ($1, $2)`, parentCaseID, patentID)
pool.ExecContext(ctx, `DELETE FROM paliad.project_teams WHERE project_id IN ($1, $2)`, parentCaseID, patentID)
pool.ExecContext(ctx, `DELETE FROM paliad.projects WHERE id IN ($1, $2)`, parentCaseID, patentID)
pool.ExecContext(ctx, `DELETE FROM paliad.users WHERE id = $1`, userID)
pool.ExecContext(ctx, `DELETE FROM auth.users WHERE id = $1`, userID)
}
cleanup()
defer cleanup()
if _, err := pool.ExecContext(ctx,
`INSERT INTO auth.users (id, email) VALUES ($1, 'cross-anchor-test@hlc.com')`,
userID); err != nil {
t.Fatalf("seed auth.users: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.users (id, email, display_name, office, global_role, lang)
VALUES ($1, 'cross-anchor-test@hlc.com', 'Cross-Anchor Test', 'munich', 'global_admin', 'de')`,
userID); err != nil {
t.Fatalf("seed paliad.users: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.projects (id, type, path, title, patent_number, status, created_by)
VALUES ($1, 'patent', $1::text, 'EP-T237 — Test Patent', 'EP-T237', 'active', $2)`,
patentID, userID); err != nil {
t.Fatalf("seed patent: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.project_teams (project_id, user_id, role, responsibility, inherited, added_by)
VALUES ($1, $2, 'lead', 'lead', false, $2)`,
patentID, userID); err != nil {
t.Fatalf("seed patent team: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.projects
(id, type, parent_id, path, title, status, created_by,
proceeding_type_id, our_side)
VALUES ($1, 'case', $2, $2::text || '.' || $1::text,
'UPC-CFI München — Klage (T237)', 'active', $3, $4, 'claimant')`,
parentCaseID, patentID, userID, upcInf); err != nil {
t.Fatalf("seed parent case: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.project_teams (project_id, user_id, role, responsibility, inherited, added_by)
VALUES ($1, $2, 'lead', 'lead', false, $2)`,
parentCaseID, userID); err != nil {
t.Fatalf("seed parent team: %v", err)
}
// Inf-only rule. Lives under upc.inf.cfi (upcInf), NOT upc.rev.cfi.
if _, err := pool.ExecContext(ctx,
`SELECT set_config('paliad.audit_reason', $1, true)`,
"t-paliad-237 cross-anchor test seed"); err != nil {
t.Fatalf("set audit_reason: %v", err)
}
if _, err := pool.ExecContext(ctx,
`INSERT INTO paliad.deadline_rules
(id, proceeding_type_id, submission_code, name, name_en,
duration_value, duration_unit, timing, is_court_set, is_spawn,
sequence_order, is_active, priority,
lifecycle_state, created_at, updated_at)
VALUES ($1, $2, $3, 'Klageschrift (T237)', 'Statement of Claim (T237)',
0, 'days', 'after', false, false,
0, true, 'mandatory', 'published', now(), now())`,
infRuleID, upcInf, infRuleCode); err != nil {
t.Fatalf("seed inf rule: %v", err)
}
users := NewUserService(pool)
projects := NewProjectService(pool, users)
eventTypes := NewEventTypeService(pool, users)
deadlines := NewDeadlineService(pool, projects, eventTypes)
appointments := NewAppointmentService(pool, projects)
rules := NewDeadlineRuleService(pool)
holidays := NewHolidayService(pool)
courts := NewCourtService(pool)
fristen := NewFristenrechnerService(rules, holidays, courts)
projection := NewProjectionService(pool, projects, deadlines, appointments, fristen, rules)
// Create the CCR child. Default proceeding_type → upc.rev.cfi.
child, err := projects.CreateCounterclaim(ctx, userID, parentCaseID, CounterclaimOpts{})
if err != nil {
t.Fatalf("CreateCounterclaim: %v", err)
}
if child.ProceedingTypeID == nil || *child.ProceedingTypeID != upcRev {
t.Fatalf("CCR child proceeding_type_id = %v, want upcRev (%d)", child.ProceedingTypeID, upcRev)
}
// Anchor attempt #1: rule lives in the parent's proceeding type, not
// the CCR's. Must reject with CrossProceedingAnchorError.
_, err = projection.RecordAnchor(ctx, userID, child.ID, AnchorInput{
RuleCode: infRuleCode,
ActualDate: time.Date(2026, 5, 22, 0, 0, 0, 0, time.UTC),
})
if err == nil {
t.Fatal("expected cross-proceeding rejection, got nil")
}
cpe, ok := IsCrossProceedingAnchor(err)
if !ok {
t.Fatalf("expected CrossProceedingAnchorError, got %T: %v", err, err)
}
if cpe.RequestedRuleCode != infRuleCode {
t.Errorf("RequestedRuleCode = %q, want %q", cpe.RequestedRuleCode, infRuleCode)
}
if cpe.ParentProjectID != parentCaseID {
t.Errorf("ParentProjectID = %v, want %v", cpe.ParentProjectID, parentCaseID)
}
if cpe.RequestedRuleNameDE != "Klageschrift (T237)" {
t.Errorf("RequestedRuleNameDE = %q", cpe.RequestedRuleNameDE)
}
if cpe.RequestedRuleNameEN != "Statement of Claim (T237)" {
t.Errorf("RequestedRuleNameEN = %q", cpe.RequestedRuleNameEN)
}
// Anchor attempt #2: same rule code, anchored on the PARENT inf
// project. Must succeed — the legitimate happy path stays intact.
res, err := projection.RecordAnchor(ctx, userID, parentCaseID, AnchorInput{
RuleCode: infRuleCode,
ActualDate: time.Date(2026, 5, 22, 0, 0, 0, 0, time.UTC),
})
if err != nil {
t.Fatalf("anchor on parent inf project failed: %v", err)
}
if res == nil || res.DeadlineID == nil {
t.Fatalf("expected DeadlineID set on anchor result, got %+v", res)
}
// Anchor attempt #3: rule code that exists in NEITHER project — must
// still return the legacy "unknown submission_code" error, not the
// cross-proceeding error.
_, err = projection.RecordAnchor(ctx, userID, child.ID, AnchorInput{
RuleCode: "test.t237.nonexistent." + uuid.NewString()[:8],
ActualDate: time.Date(2026, 5, 22, 0, 0, 0, 0, time.UTC),
})
if err == nil {
t.Fatal("expected error for unknown rule, got nil")
}
if _, ok := IsCrossProceedingAnchor(err); ok {
t.Errorf("unknown rule should NOT surface as cross-proceeding error: %v", err)
}
if !errors.Is(err, ErrInvalidInput) {
t.Errorf("unknown rule should wrap ErrInvalidInput, got %v", err)
}
}

View File

@@ -181,6 +181,42 @@ func TestRuleNameInLang(t *testing.T) {
}
}
func TestCrossProceedingAnchorError(t *testing.T) {
parentID := uuid.New()
cpe := &CrossProceedingAnchorError{
RequestedRuleCode: "upc.inf.cfi.soc",
RequestedRuleNameDE: "Klageschrift",
RequestedRuleNameEN: "Statement of Claim",
ParentProjectID: parentID,
ParentProjectTitle: "UPC-CFI München — Klage",
}
got, ok := IsCrossProceedingAnchor(cpe)
if !ok {
t.Fatal("IsCrossProceedingAnchor on direct error should return ok")
}
if got != cpe {
t.Errorf("unwrapped pointer mismatch")
}
wrapped := wrap(cpe, "context")
got2, ok2 := IsCrossProceedingAnchor(wrapped)
if !ok2 {
t.Fatal("IsCrossProceedingAnchor on wrapped error should return ok")
}
if got2 != cpe {
t.Errorf("unwrapped wrapped pointer mismatch")
}
if _, ok := IsCrossProceedingAnchor(errOther{}); ok {
t.Error("non-CPE should not unwrap as CPE")
}
// And the inverse: a PredecessorMissingError must NOT match the
// cross-proceeding helper (the two coexist on the 409 response and a
// mistaken unwrap would render the wrong UI).
pme := &PredecessorMissingError{RequestedRuleCode: "x"}
if _, ok := IsCrossProceedingAnchor(pme); ok {
t.Error("PredecessorMissingError must not unwrap as CrossProceedingAnchorError")
}
}
func TestPredecessorMissingError(t *testing.T) {
pme := &PredecessorMissingError{
MissingRuleCode: "upc.inf.cfi.soc",

View File

@@ -1544,6 +1544,35 @@ func IsPredecessorMissing(err error) (*PredecessorMissingError, bool) {
return nil, false
}
// CrossProceedingAnchorError is returned when a user tries to anchor a
// rule on a CCR sub-project, but the rule belongs to the parent
// infringement project's proceeding type (t-paliad-237). The
// SmartTimeline on a CCR project surfaces the parent's track in the
// parent_context lane — clicking "Datum setzen" on a parent-track rule
// would silently corrupt the inf project's actuals if written onto the
// CCR. Reject with a clear pointer to the parent project.
type CrossProceedingAnchorError struct {
RequestedRuleCode string
RequestedRuleNameDE string
RequestedRuleNameEN string
ParentProjectID uuid.UUID
ParentProjectTitle string
}
func (e *CrossProceedingAnchorError) Error() string {
return fmt.Sprintf("rule %q belongs to parent project %s, not this CCR",
e.RequestedRuleCode, e.ParentProjectID)
}
// IsCrossProceedingAnchor unwraps a CrossProceedingAnchorError if present.
func IsCrossProceedingAnchor(err error) (*CrossProceedingAnchorError, bool) {
var cpe *CrossProceedingAnchorError
if errors.As(err, &cpe) {
return cpe, true
}
return nil, false
}
// RecordAnchor writes (or PATCHes) the actual occurrence of a rule for
// the given project. Implements the §6 click-to-anchor + #31 layer 3
// sequence guard:
@@ -1579,6 +1608,31 @@ func (s *ProjectionService) RecordAnchor(ctx context.Context, userID, projectID
}
rule, err := s.lookupRuleBySubmissionCode(ctx, *proj.ProceedingTypeID, in.RuleCode)
if errors.Is(err, sql.ErrNoRows) {
// Cross-proceeding fallback (t-paliad-237). On a CCR project,
// the SmartTimeline renders the parent infringement project's
// rules in the parent_context lane. The user can click "Datum
// setzen" on those rows; writing the anchor onto the CCR
// would corrupt the inf project's actuals. Detect this and
// reject with a pointer to the parent project so the frontend
// can guide the user to anchor there instead.
if proj.CounterclaimOf != nil {
parent, perr := s.projects.GetByID(ctx, userID, *proj.CounterclaimOf)
if perr == nil && parent != nil && parent.ProceedingTypeID != nil {
parentRule, plookErr := s.lookupRuleBySubmissionCode(ctx, *parent.ProceedingTypeID, in.RuleCode)
if plookErr == nil && parentRule != nil {
return nil, &CrossProceedingAnchorError{
RequestedRuleCode: in.RuleCode,
RequestedRuleNameDE: parentRule.Name,
RequestedRuleNameEN: parentRule.NameEN,
ParentProjectID: parent.ID,
ParentProjectTitle: parent.Title,
}
}
}
}
return nil, fmt.Errorf("%w: unknown submission_code %q", ErrInvalidInput, in.RuleCode)
}
if err != nil {
return nil, err
}
@@ -1663,7 +1717,9 @@ func (s *ProjectionService) RecordRuleSkipped(ctx context.Context, userID, proje
}
// lookupRuleBySubmissionCode resolves (proceeding_type_id, submission_code)
// → DeadlineRule.
// → DeadlineRule. Returns sql.ErrNoRows when the rule is not present so
// callers can implement cross-proceeding fallback logic (t-paliad-237);
// other DB errors are wrapped.
func (s *ProjectionService) lookupRuleBySubmissionCode(ctx context.Context, ptID int, code string) (*models.DeadlineRule, error) {
var rule models.DeadlineRule
err := s.db.GetContext(ctx, &rule,
@@ -1672,7 +1728,7 @@ func (s *ProjectionService) lookupRuleBySubmissionCode(ctx context.Context, ptID
WHERE proceeding_type_id = $1 AND submission_code = $2 AND is_active = true`,
ptID, code)
if errors.Is(err, sql.ErrNoRows) {
return nil, fmt.Errorf("%w: unknown submission_code %q", ErrInvalidInput, code)
return nil, err
}
if err != nil {
return nil, fmt.Errorf("lookup rule by submission_code: %w", err)

View File

@@ -0,0 +1,570 @@
package services
// Submission draft service — CRUD over paliad.submission_drafts plus
// the render+export entry points that combine the variable bag, lawyer
// overrides, and template fetch into a .docx or HTML preview
// (t-paliad-238 Slice A, design doc
// docs/design-submission-page-2026-05-22.md §5.2).
//
// Each draft is owned by one user; multiple drafts per (project,
// submission_code, user_id) are supported via the `name` column. The
// override semantics are explicit:
//
// variables = {"project.case_number": "2 O 999/25"} → use this value
// variables = {"project.case_number": ""} → force [KEIN WERT: …]
// key absent → fall back to bag
//
// Visibility flows through ProjectService.GetByID — every read and
// write gates on paliad.can_see_project. RLS in the DB enforces the
// owner-scoped UPDATE/DELETE constraint independently of the Go layer.
import (
"context"
"database/sql"
"encoding/json"
"errors"
"fmt"
"maps"
"strings"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"mgit.msbls.de/m/paliad/internal/models"
)
// SubmissionDraft mirrors a row in paliad.submission_drafts.
//
// ProjectID is nullable since t-paliad-243 — a draft started from the
// global /submissions/new picker without picking a project is private
// to its creator and carries an empty variable bag (no project /
// parties / deadline state to resolve). All callers must check for nil
// before treating it as a uuid.
type SubmissionDraft struct {
ID uuid.UUID `db:"id" json:"id"`
ProjectID *uuid.UUID `db:"project_id" json:"project_id,omitempty"`
SubmissionCode string `db:"submission_code" json:"submission_code"`
UserID uuid.UUID `db:"user_id" json:"user_id"`
Name string `db:"name" json:"name"`
VariablesRaw []byte `db:"variables" json:"-"`
LastExportedAt *time.Time `db:"last_exported_at" json:"last_exported_at,omitempty"`
LastExportedSHA *string `db:"last_exported_sha" json:"last_exported_sha,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
// Variables is the decoded overrides map; populated on read by the
// service so callers don't have to unmarshal manually.
Variables PlaceholderMap `json:"variables"`
}
// SubmissionDraftService handles CRUD on submission_drafts and exposes
// the render/preview/export entry points the handler layer calls.
type SubmissionDraftService struct {
db *sqlx.DB
projects *ProjectService
vars *SubmissionVarsService
renderer *SubmissionRenderer
}
// NewSubmissionDraftService wires the service.
func NewSubmissionDraftService(db *sqlx.DB, projects *ProjectService, vars *SubmissionVarsService, renderer *SubmissionRenderer) *SubmissionDraftService {
return &SubmissionDraftService{
db: db,
projects: projects,
vars: vars,
renderer: renderer,
}
}
// DraftPatch carries optional fields for Update. nil pointer = "no
// change"; non-nil = "set to this". Variables is replace-semantics —
// the lawyer's sidebar sends the full map every save.
//
// ProjectID uses a two-level pointer (t-paliad-243) so we can encode
// the three operations the global drafts flow needs:
//
// patch.ProjectID == nil → no change
// *patch.ProjectID == nil → detach (re-set to NULL)
// **patch.ProjectID → attach (assign a project)
//
// The detach path stays as scope for symmetry with attach even though
// the current frontend only exposes attach.
type DraftPatch struct {
Name *string
Variables *PlaceholderMap
ProjectID **uuid.UUID
}
// ErrSubmissionDraftNotFound is the sentinel for "no draft with that id
// visible to this user". Maps to 404 in the handler.
var ErrSubmissionDraftNotFound = errors.New("submission draft: not found")
// ErrSubmissionDraftNameTaken is the sentinel for duplicate names per
// (project, submission_code, user). Maps to 409 in the handler.
var ErrSubmissionDraftNameTaken = errors.New("submission draft: name already taken")
// draftColumns is the canonical select list — kept in one place so
// every fetch stays in sync.
const draftColumns = `id, project_id, submission_code, user_id, name,
variables, last_exported_at, last_exported_sha,
created_at, updated_at`
// List returns every draft for (project, submission_code, user)
// ordered by updated_at DESC. Visibility flows through projects.GetByID.
func (s *SubmissionDraftService) List(ctx context.Context, userID, projectID uuid.UUID, submissionCode string) ([]SubmissionDraft, error) {
if _, err := s.projects.GetByID(ctx, userID, projectID); err != nil {
return nil, err
}
var rows []SubmissionDraft
err := s.db.SelectContext(ctx, &rows,
`SELECT `+draftColumns+`
FROM paliad.submission_drafts
WHERE project_id = $1 AND submission_code = $2 AND user_id = $3
ORDER BY updated_at DESC`,
projectID, submissionCode, userID)
if err != nil {
return nil, fmt.Errorf("list submission drafts: %w", err)
}
for i := range rows {
if err := rows[i].decodeVariables(); err != nil {
return nil, err
}
}
return rows, nil
}
// DraftWithProject is the row shape for the global /submissions index —
// a draft joined with the minimal project metadata the table needs.
// Visibility is gated by paliad.can_see_project in the SELECT itself.
//
// ProjectTitle / ProjectReference are pointer-nullable since
// t-paliad-243 — project-less drafts surface in the same list with a
// NULL project ref, and the frontend renders them with a dedicated
// "kein Projekt" label.
type DraftWithProject struct {
SubmissionDraft
ProjectTitle *string `db:"project_title" json:"project_title,omitempty"`
ProjectReference *string `db:"project_reference" json:"project_reference,omitempty"`
}
// ListAllForUser returns every draft the user owns across visible
// projects PLUS every project-less draft the user owns, ordered by
// updated_at DESC. LEFT JOIN on paliad.projects keeps project-less rows
// in the result set; the WHERE clause permits project_id IS NULL or a
// visible can_see_project hit, so a draft on a project the user no
// longer has access to is silently dropped.
func (s *SubmissionDraftService) ListAllForUser(ctx context.Context, userID uuid.UUID) ([]DraftWithProject, error) {
var rows []DraftWithProject
err := s.db.SelectContext(ctx, &rows,
`SELECT d.id, d.project_id, d.submission_code, d.user_id, d.name,
d.variables, d.last_exported_at, d.last_exported_sha,
d.created_at, d.updated_at,
p.title AS project_title,
p.reference AS project_reference
FROM paliad.submission_drafts d
LEFT JOIN paliad.projects p ON p.id = d.project_id
WHERE d.user_id = $1
AND (
d.project_id IS NULL
OR paliad.can_see_project(d.project_id)
)
ORDER BY d.updated_at DESC`,
userID)
if err != nil {
return nil, fmt.Errorf("list all submission drafts for user: %w", err)
}
for i := range rows {
if err := rows[i].decodeVariables(); err != nil {
return nil, err
}
}
return rows, nil
}
// Get returns a single draft by id, gated on project visibility AND
// owner-only — the caller can only fetch drafts they own. RLS in the
// DB enforces this independently; the Go check makes the 404 semantics
// explicit at the service boundary.
//
// A project-less draft (ProjectID == nil) skips the can_see_project
// gate — the owner-only constraint is the entire visibility check.
func (s *SubmissionDraftService) Get(ctx context.Context, userID, draftID uuid.UUID) (*SubmissionDraft, error) {
var d SubmissionDraft
err := s.db.GetContext(ctx, &d,
`SELECT `+draftColumns+`
FROM paliad.submission_drafts
WHERE id = $1 AND user_id = $2`,
draftID, userID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrSubmissionDraftNotFound
}
if err != nil {
return nil, fmt.Errorf("get submission draft: %w", err)
}
if d.ProjectID != nil {
if _, err := s.projects.GetByID(ctx, userID, *d.ProjectID); err != nil {
// Project no longer visible → behave as not-found rather than
// leaking the draft's existence. ON DELETE CASCADE keeps this
// rare in practice.
if errors.Is(err, ErrNotVisible) {
return nil, ErrSubmissionDraftNotFound
}
return nil, err
}
}
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
}
// EnsureLatest returns the user's most-recently-updated draft for
// (project, submission_code). Creates "Entwurf 1" / "Draft 1" if none
// exists. Idempotent on repeat calls — once a draft exists, EnsureLatest
// always returns the freshest one rather than spawning new rows.
func (s *SubmissionDraftService) EnsureLatest(ctx context.Context, userID, projectID uuid.UUID, submissionCode, lang string) (*SubmissionDraft, error) {
if _, err := s.projects.GetByID(ctx, userID, projectID); err != nil {
return nil, err
}
var d SubmissionDraft
err := s.db.GetContext(ctx, &d,
`SELECT `+draftColumns+`
FROM paliad.submission_drafts
WHERE project_id = $1 AND submission_code = $2 AND user_id = $3
ORDER BY updated_at DESC
LIMIT 1`,
projectID, submissionCode, userID)
if errors.Is(err, sql.ErrNoRows) {
return s.Create(ctx, userID, &projectID, submissionCode, lang)
}
if err != nil {
return nil, fmt.Errorf("ensure latest submission draft: %w", err)
}
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
}
// Create makes a new draft with an auto-incremented "Entwurf N" name
// ("Draft N" for English locale). Lawyer can rename via Update.
//
// A nil projectID creates a project-less draft (t-paliad-243); the
// visibility check is skipped — the caller is the owner and the row is
// private to them.
func (s *SubmissionDraftService) Create(ctx context.Context, userID uuid.UUID, projectID *uuid.UUID, submissionCode, lang string) (*SubmissionDraft, error) {
if projectID != nil {
if _, err := s.projects.GetByID(ctx, userID, *projectID); err != nil {
return nil, err
}
}
name, err := s.nextDraftName(ctx, projectID, submissionCode, userID, lang)
if err != nil {
return nil, err
}
var d SubmissionDraft
err = s.db.GetContext(ctx, &d,
`INSERT INTO paliad.submission_drafts
(project_id, submission_code, user_id, name)
VALUES ($1, $2, $3, $4)
RETURNING `+draftColumns,
projectID, submissionCode, userID, name)
if err != nil {
return nil, fmt.Errorf("create submission draft: %w", err)
}
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
}
// nextDraftName returns "Entwurf N" / "Draft N" with N = (highest
// existing N + 1), or N=1 if no draft yet. Falls back to a unique
// suffix if two callers race; the unique constraint on the table is
// the final guard.
//
// A nil projectID scopes the search to the user's project-less drafts
// for this submission_code — matches the row-uniqueness contract on
// the DB side (project_id, submission_code, user_id, name) where
// project_id IS NULL is its own equivalence class.
func (s *SubmissionDraftService) nextDraftName(ctx context.Context, projectID *uuid.UUID, submissionCode string, userID uuid.UUID, lang string) (string, error) {
prefix := "Entwurf"
if strings.EqualFold(lang, "en") {
prefix = "Draft"
}
var names []string
var err error
if projectID == nil {
err = s.db.SelectContext(ctx, &names,
`SELECT name FROM paliad.submission_drafts
WHERE project_id IS NULL AND submission_code = $1 AND user_id = $2`,
submissionCode, userID)
} else {
err = s.db.SelectContext(ctx, &names,
`SELECT name FROM paliad.submission_drafts
WHERE project_id = $1 AND submission_code = $2 AND user_id = $3`,
*projectID, submissionCode, userID)
}
if err != nil {
return "", fmt.Errorf("scan existing draft names: %w", err)
}
highest := 0
for _, n := range names {
var idx int
if _, scanErr := fmt.Sscanf(n, prefix+" %d", &idx); scanErr == nil && idx > highest {
highest = idx
}
}
return fmt.Sprintf("%s %d", prefix, highest+1), nil
}
// Update patches the draft. Variables is replace-semantics — pass the
// full map. Name patches go through a uniqueness check to surface
// ErrSubmissionDraftNameTaken cleanly instead of a raw constraint
// violation.
func (s *SubmissionDraftService) Update(ctx context.Context, userID, draftID uuid.UUID, patch DraftPatch) (*SubmissionDraft, error) {
existing, err := s.Get(ctx, userID, draftID)
if err != nil {
return nil, err
}
setParts := []string{}
args := []any{}
idx := 1
if patch.Name != nil {
newName := strings.TrimSpace(*patch.Name)
if newName == "" {
return nil, ErrInvalidInput
}
if newName != existing.Name {
// Pre-check for the unique constraint so we can return a
// typed error instead of a raw PG conflict. NULL project_id
// is its own equivalence class in the unique index (NULLs
// don't collide), so the no-project flow checks `IS NULL`.
var dup int
var qErr error
if existing.ProjectID == nil {
qErr = s.db.GetContext(ctx, &dup,
`SELECT COUNT(*) FROM paliad.submission_drafts
WHERE project_id IS NULL AND submission_code = $1
AND user_id = $2 AND name = $3 AND id <> $4`,
existing.SubmissionCode, userID, newName, draftID)
} else {
qErr = s.db.GetContext(ctx, &dup,
`SELECT COUNT(*) FROM paliad.submission_drafts
WHERE project_id = $1 AND submission_code = $2
AND user_id = $3 AND name = $4 AND id <> $5`,
*existing.ProjectID, existing.SubmissionCode, userID, newName, draftID)
}
if qErr != nil {
return nil, fmt.Errorf("check name uniqueness: %w", qErr)
}
if dup > 0 {
return nil, ErrSubmissionDraftNameTaken
}
}
setParts = append(setParts, fmt.Sprintf("name = $%d", idx))
args = append(args, newName)
idx++
}
if patch.Variables != nil {
raw, err := json.Marshal(*patch.Variables)
if err != nil {
return nil, fmt.Errorf("marshal variables: %w", err)
}
setParts = append(setParts, fmt.Sprintf("variables = $%d::jsonb", idx))
args = append(args, string(raw))
idx++
}
if patch.ProjectID != nil {
newPID := *patch.ProjectID // *uuid.UUID — nil means detach
if newPID != nil {
// Caller must be able to see the project they're attaching
// the draft to; same gate as Create.
if _, err := s.projects.GetByID(ctx, userID, *newPID); err != nil {
return nil, err
}
}
setParts = append(setParts, fmt.Sprintf("project_id = $%d", idx))
args = append(args, newPID)
idx++
}
if len(setParts) == 0 {
return existing, nil
}
args = append(args, draftID, userID)
q := fmt.Sprintf(
`UPDATE paliad.submission_drafts
SET %s
WHERE id = $%d AND user_id = $%d
RETURNING %s`,
strings.Join(setParts, ", "), idx, idx+1, draftColumns,
)
var d SubmissionDraft
err = s.db.GetContext(ctx, &d, q, args...)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrSubmissionDraftNotFound
}
if err != nil {
return nil, fmt.Errorf("update submission draft: %w", err)
}
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
}
// Delete removes the draft. Visibility-gated via Get; the DELETE itself
// is owner-scoped (user_id = caller).
func (s *SubmissionDraftService) Delete(ctx context.Context, userID, draftID uuid.UUID) error {
if _, err := s.Get(ctx, userID, draftID); err != nil {
return err
}
_, err := s.db.ExecContext(ctx,
`DELETE FROM paliad.submission_drafts WHERE id = $1 AND user_id = $2`,
draftID, userID)
if err != nil {
return fmt.Errorf("delete submission draft: %w", err)
}
return nil
}
// MarkExported updates the last_exported_* columns after a successful
// export. Background-context safe.
func (s *SubmissionDraftService) MarkExported(ctx context.Context, draftID uuid.UUID, templateSHA string) error {
var sha any
if templateSHA != "" {
sha = templateSHA
}
_, err := s.db.ExecContext(ctx,
`UPDATE paliad.submission_drafts
SET last_exported_at = now(),
last_exported_sha = $1
WHERE id = $2`,
sha, draftID)
if err != nil {
return fmt.Errorf("mark submission draft exported: %w", err)
}
return nil
}
// BuildRenderBag composes the placeholder map for a draft — pulls
// project/parties/rule/deadline state from SubmissionVarsService, then
// layers the lawyer's overrides on top.
//
// Override semantics:
//
// variables[key] = "" → delete the key (force [KEIN WERT: key])
// variables[key] = "X" → bag[key] = "X"
// key absent → bag[key] unchanged (falls back to resolved value)
//
// Returns the final PlaceholderMap along with the SubmissionVarsResult
// so callers (export, file naming) get the resolved entities too. A
// project-less draft (ProjectID == nil, t-paliad-243) skips project /
// parties / deadline lookups — the resolved bag carries only the
// user-independent variables (firm, today) plus the user.* group; the
// lawyer's overrides fill the rest.
func (s *SubmissionDraftService) BuildRenderBag(ctx context.Context, draft *SubmissionDraft) (PlaceholderMap, *SubmissionVarsResult, error) {
resolved, err := s.vars.Build(ctx, SubmissionVarsContext{
UserID: draft.UserID,
ProjectID: draft.ProjectID,
SubmissionCode: draft.SubmissionCode,
})
if err != nil {
return nil, nil, err
}
bag := PlaceholderMap{}
maps.Copy(bag, resolved.Placeholders)
for k, v := range draft.Variables {
if v == "" {
delete(bag, k)
continue
}
bag[k] = v
}
return bag, resolved, nil
}
// RenderPreview returns the HTML preview of the merged document body
// for the draft-editor preview pane. Read-only; emits one <p> per <w:p>
// with <strong>/<em> spans for runs flagged bold/italic.
func (s *SubmissionDraftService) RenderPreview(ctx context.Context, draft *SubmissionDraft, templateBytes []byte) (string, error) {
bag, resolved, err := s.BuildRenderBag(ctx, draft)
if err != nil {
return "", err
}
return s.renderer.RenderHTML(templateBytes, bag, DefaultMissingMarker(resolved.Lang))
}
// Export renders the merged .docx for download. Returns the bytes, the
// resolved bag (for audit row + file naming), and the variables result
// (lang, rule.Name, project.case_number). Callers wire MarkExported and
// the audit writes.
func (s *SubmissionDraftService) Export(ctx context.Context, draft *SubmissionDraft, templateBytes []byte) ([]byte, *SubmissionVarsResult, error) {
bag, resolved, err := s.BuildRenderBag(ctx, draft)
if err != nil {
return nil, nil, err
}
out, err := s.renderer.Render(templateBytes, bag, DefaultMissingMarker(resolved.Lang))
if err != nil {
return nil, nil, err
}
return out, resolved, nil
}
// RenderProjectSubmission renders the given .docx template with a fresh
// variable bag for (user, project, submissionCode). No lawyer overrides
// — the output reflects exactly what SubmissionVarsService resolves
// from project state. Used by the one-click /api/projects/{id}/
// submissions/{code}/generate path which has no saved draft row.
//
// Returns the merged bytes plus the resolved bag (for audit row + file
// naming). Visibility is enforced by SubmissionVarsService.Build via
// ProjectService.GetByID — callers get ErrNotFound on no-access.
// ErrSubmissionRuleNotFound surfaces when no published rule matches the
// requested submission_code.
func (s *SubmissionDraftService) RenderProjectSubmission(ctx context.Context, userID, projectID uuid.UUID, submissionCode string, templateBytes []byte) ([]byte, *SubmissionVarsResult, error) {
pid := projectID
resolved, err := s.vars.Build(ctx, SubmissionVarsContext{
UserID: userID,
ProjectID: &pid,
SubmissionCode: submissionCode,
})
if err != nil {
return nil, nil, err
}
out, err := s.renderer.Render(templateBytes, resolved.Placeholders, DefaultMissingMarker(resolved.Lang))
if err != nil {
return nil, nil, err
}
return out, resolved, nil
}
// decodeVariables turns the raw jsonb bytes into the PlaceholderMap.
// Called by every fetch path so the caller sees a populated Variables.
func (d *SubmissionDraft) decodeVariables() error {
if len(d.VariablesRaw) == 0 {
d.Variables = PlaceholderMap{}
return nil
}
out := PlaceholderMap{}
if err := json.Unmarshal(d.VariablesRaw, &out); err != nil {
return fmt.Errorf("decode submission draft variables: %w", err)
}
d.Variables = out
return nil
}
// Compile-time guard: ensure the *models.User reference in the import
// graph doesn't get optimised away by linters. The service doesn't
// dereference User directly — that happens in SubmissionVarsService —
// but the import keeps the package compile-time-aware of the dependency
// chain that wires us into the bundle.
var _ = (*models.User)(nil)

View File

@@ -0,0 +1,531 @@
package services
// Submission template renderer — in-house engine for the submission
// draft editor (t-paliad-238, design doc
// docs/design-submission-page-2026-05-22.md §3 / §6.2).
//
// Resurrected from commit 8ea3509 (the original t-paliad-215 Slice 1
// "in-house .docx render engine"). Kept in a separate file from the
// format-only converter (submission_render.go) so the t-paliad-230
// /generate one-click path stays unchanged and the merge engine doesn't
// have to share zip-helper names with it.
//
// Why not lukasjarosch/go-docx: the library's "nested placeholder" guard
// treats sibling placeholders inside the same <w:t> run (e.g.
// "{{a}} ./. {{b}}") as nested and refuses to replace either. Patent
// submissions routinely have multiple placeholders per paragraph (party
// blocks especially), so the library is a non-starter. This renderer
// handles single-run placeholders (preserving run-level formatting) AND
// cross-run placeholders (rewriting the paragraph as one run when Word
// has fragmented the placeholder across runs).
//
// Placeholder grammar: {{[A-Za-z][A-Za-z0-9_.]*}} with optional
// whitespace inside braces ({{ project.case_number }} ≡
// {{project.case_number}}).
//
// Missing-value behaviour: when a placeholder has no binding in the
// PlaceholderMap, the renderer emits a marker token so the lawyer sees
// the gap in Word rather than failing the request.
import (
"archive/zip"
"bytes"
"fmt"
"io"
"regexp"
"strings"
)
// PlaceholderMap is the variable bag built by SubmissionVarsService.
// Keys are dotted paths without braces (e.g. "project.case_number").
// Values are the substituted text — already locale-aware, pretty-
// printed, and sanitised by the caller.
type PlaceholderMap map[string]string
// MissingPlaceholderFn translates an unbound placeholder key into the
// in-document marker token. The default in DefaultMissingMarker is
// "[KEIN WERT: <key>]" / "[NO VALUE: <key>]" depending on lang.
type MissingPlaceholderFn func(key string) string
// valueWrapperFn wraps a substituted value with a marker the HTML
// preview emitter can recognise — used by RenderHTML to turn each
// substituted value into a clickable <span class="draft-var" …>
// (t-paliad-261, click-variable-in-preview → jump-to-field). nil means
// no wrapping; the .docx export path uses nil so its output is
// byte-identical to the wrapper-free build. The wrapper is invoked for
// both resolved values and missing-marker text so clicking a missing
// placeholder still jumps to the corresponding sidebar input.
type valueWrapperFn func(key, value string) string
// Private-Use-Area sentinels for the HTML preview wrap. PUA characters
// are valid in XML 1.0 content, never appear in legitimate template
// text, pass unchanged through xmlEncode/xmlDecode/htmlEscape, and are
// stripped by emitTextWithDraftVars when the preview HTML is assembled.
const (
previewVarBegin = ""
previewVarMid = ""
previewVarEnd = ""
)
// htmlPreviewWrapper wraps a substituted value with the PUA sentinels
// emitTextWithDraftVars recognises. Used only by RenderHTML; the .docx
// Render path uses nil so its output is identical to the pre-261 build.
func htmlPreviewWrapper(key, value string) string {
return previewVarBegin + key + previewVarMid + value + previewVarEnd
}
// DefaultMissingMarker returns the standard missing-value marker for
// the given UI language.
func DefaultMissingMarker(lang string) MissingPlaceholderFn {
prefix := "KEIN WERT"
if strings.EqualFold(lang, "en") {
prefix = "NO VALUE"
}
return func(key string) string {
return "[" + prefix + ": " + key + "]"
}
}
// placeholderRegex matches a single placeholder. The capture group
// extracts the key name without braces or surrounding whitespace.
//
// Restricted to [A-Za-z][A-Za-z0-9_.]* so that stray "{{" sequences in
// legal prose don't get mistaken for placeholders. A genuine placeholder
// always starts with an ASCII letter.
var placeholderRegex = regexp.MustCompile(`\{\{\s*([A-Za-z][A-Za-z0-9_.]*)\s*\}\}`)
// SubmissionRenderer renders a .docx template into a .docx output by
// substituting {{placeholder}} tokens with values from a PlaceholderMap.
// Stateless; safe for concurrent use.
type SubmissionRenderer struct{}
// NewSubmissionRenderer constructs the renderer.
func NewSubmissionRenderer() *SubmissionRenderer {
return &SubmissionRenderer{}
}
// Render reads the .docx template at templateBytes, substitutes every
// placeholder from vars (or emits the missing-marker token), and returns
// the merged .docx bytes. Unknown placeholders never fail the render —
// the lawyer sees the marker in Word and fixes it.
//
// Pre-pass: ConvertDotmToDocx is called on the input so a .dotm
// template (macro-bearing) is downgraded to a plain .docx before the
// merge step runs. Idempotent on inputs that are already plain .docx.
func (r *SubmissionRenderer) Render(templateBytes []byte, vars PlaceholderMap, missing MissingPlaceholderFn) ([]byte, error) {
if missing == nil {
missing = DefaultMissingMarker("de")
}
cleanBytes, err := ConvertDotmToDocx(templateBytes)
if err != nil {
return nil, fmt.Errorf("submission render: pre-pass convert: %w", err)
}
zr, err := zip.NewReader(bytes.NewReader(cleanBytes), int64(len(cleanBytes)))
if err != nil {
return nil, fmt.Errorf("submission render: open zip: %w", err)
}
var out bytes.Buffer
zw := zip.NewWriter(&out)
for _, entry := range zr.File {
body, err := readMergeZipEntry(entry)
if err != nil {
return nil, fmt.Errorf("submission render: read %s: %w", entry.Name, err)
}
if isWordXMLEntry(entry.Name) {
body = substituteInDocumentXML(body, vars, missing, nil)
}
w, err := zw.CreateHeader(&zip.FileHeader{
Name: entry.Name,
Method: entry.Method,
Modified: entry.Modified,
})
if err != nil {
return nil, fmt.Errorf("submission render: write header %s: %w", entry.Name, err)
}
if _, err := w.Write(body); err != nil {
return nil, fmt.Errorf("submission render: write %s: %w", entry.Name, err)
}
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("submission render: finalise zip: %w", err)
}
return out.Bytes(), nil
}
// RenderHTML produces a read-only HTML rendering of the merged document
// body for the draft-editor preview pane. Walks the SAME placeholder
// substitution as Render, then extracts the body text from word/document.xml
// and emits semantic HTML — one <p> per <w:p>, with <strong>/<em> spans
// for runs that carry <w:b>/<w:i> formatting. Tables, lists, and complex
// formatting collapse to plain paragraphs (the preview is a fidelity
// guide, not a WYSIWYG editor — final formatting comes from Word at
// export).
//
// Returns escaped HTML safe to inject into the page via dangerouslySet
// or innerHTML. The caller is responsible for wrapping in an outer
// container; this method emits only the body fragment.
func (r *SubmissionRenderer) RenderHTML(templateBytes []byte, vars PlaceholderMap, missing MissingPlaceholderFn) (string, error) {
if missing == nil {
missing = DefaultMissingMarker("de")
}
cleanBytes, err := ConvertDotmToDocx(templateBytes)
if err != nil {
return "", fmt.Errorf("submission render html: pre-pass convert: %w", err)
}
zr, err := zip.NewReader(bytes.NewReader(cleanBytes), int64(len(cleanBytes)))
if err != nil {
return "", fmt.Errorf("submission render html: open zip: %w", err)
}
var docXML []byte
for _, entry := range zr.File {
if entry.Name != "word/document.xml" {
continue
}
docXML, err = readMergeZipEntry(entry)
if err != nil {
return "", fmt.Errorf("submission render html: read document.xml: %w", err)
}
break
}
if docXML == nil {
return "", fmt.Errorf("submission render html: word/document.xml missing")
}
merged := substituteInDocumentXML(docXML, vars, missing, htmlPreviewWrapper)
return docXMLToHTML(merged), nil
}
// isWordXMLEntry returns true for the .docx parts that contain
// substitutable text. We touch document.xml plus header*.xml and
// footer*.xml (templates may put firm letterhead in a header) but
// skip styles, theme, settings, comments, footnotes — none of which
// should carry merge placeholders in a well-formed template.
func isWordXMLEntry(name string) bool {
switch {
case name == "word/document.xml":
return true
case strings.HasPrefix(name, "word/header") && strings.HasSuffix(name, ".xml"):
return true
case strings.HasPrefix(name, "word/footer") && strings.HasSuffix(name, ".xml"):
return true
}
return false
}
// readMergeZipEntry slurps a zip entry's bytes. Named distinctly from
// the helper in submission_render.go (readZipFile) to keep this file
// self-contained — the two are functionally identical.
func readMergeZipEntry(f *zip.File) ([]byte, error) {
rc, err := f.Open()
if err != nil {
return nil, err
}
defer rc.Close()
return io.ReadAll(rc)
}
// substituteInDocumentXML walks document XML and replaces every
// {{placeholder}} occurrence inside <w:t> text nodes. Handles both
// single-run placeholders (the common case for freshly authored
// templates) and cross-run placeholders (where Word's autocorrect or
// manual editing has split a placeholder across runs).
//
// Two-pass strategy:
//
// 1. Pass 1: replace placeholders that fit entirely within one
// <w:t>…</w:t>. This is the 99% case and preserves all run-level
// formatting (bold, italic, font runs).
// 2. Pass 2: for paragraphs that still contain orphan "{{" or "}}"
// markers after pass 1, merge the text of every <w:t> inside the
// paragraph, run the replacement on the merged text, and rewrite
// the paragraph's runs as a single <w:r><w:t>…</w:t></w:r> using
// the formatting properties of the first run.
func substituteInDocumentXML(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn, wrap valueWrapperFn) []byte {
replaced := substituteInTextNodes(body, vars, missing, wrap)
if !needsCrossRunMerge(replaced) {
return replaced
}
return substituteAcrossRuns(replaced, vars, missing, wrap)
}
// wTextNodeRegex matches one <w:t …>contents</w:t> element, capturing
// the contents.
var wTextNodeRegex = regexp.MustCompile(`<w:t(\s[^>]*)?>([^<]*)</w:t>`)
// substituteInTextNodes runs the placeholder replacement inside each
// <w:t> text node independently. Format-preserving for single-run
// placeholders.
func substituteInTextNodes(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn, wrap valueWrapperFn) []byte {
return wTextNodeRegex.ReplaceAllFunc(body, func(match []byte) []byte {
sub := wTextNodeRegex.FindSubmatch(match)
attrs := string(sub[1])
contents := xmlDecode(string(sub[2]))
replaced := replacePlaceholders(contents, vars, missing, wrap)
if replaced == contents {
return match
}
if !strings.Contains(attrs, "xml:space") &&
(strings.HasPrefix(replaced, " ") || strings.HasSuffix(replaced, " ")) {
attrs += ` xml:space="preserve"`
}
return []byte(`<w:t` + attrs + `>` + xmlEncode(replaced) + `</w:t>`)
})
}
// needsCrossRunMerge returns true when the body still contains an
// unmatched "{{" or "}}" inside any <w:t> after pass 1.
func needsCrossRunMerge(body []byte) bool {
for _, m := range wTextNodeRegex.FindAllSubmatch(body, -1) {
t := string(m[2])
if strings.Contains(t, "{{") || strings.Contains(t, "}}") {
return true
}
}
return false
}
// wParagraphRegex matches one <w:p>…</w:p> paragraph block. Greedy
// inner-content match is safe — <w:p> elements do not nest.
var wParagraphRegex = regexp.MustCompile(`(?s)<w:p\b[^>]*>.*?</w:p>`)
// wRunPropsRegex pulls the first <w:rPr>…</w:rPr> block from a paragraph.
var wRunPropsRegex = regexp.MustCompile(`(?s)<w:rPr>.*?</w:rPr>`)
// wParagraphPropsRegex pulls the optional <w:pPr>…</w:pPr>.
var wParagraphPropsRegex = regexp.MustCompile(`(?s)<w:pPr>.*?</w:pPr>`)
// substituteAcrossRuns is pass 2: concatenate every text node in a
// fragmented-placeholder paragraph, run replacement, rewrite as one run.
func substituteAcrossRuns(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn, wrap valueWrapperFn) []byte {
return wParagraphRegex.ReplaceAllFunc(body, func(para []byte) []byte {
textNodes := wTextNodeRegex.FindAllSubmatch(para, -1)
if len(textNodes) == 0 {
return para
}
var merged strings.Builder
for _, m := range textNodes {
merged.WriteString(xmlDecode(string(m[2])))
}
original := merged.String()
if !strings.Contains(original, "{{") {
return para
}
replaced := replacePlaceholders(original, vars, missing, wrap)
if replaced == original {
return para
}
pPr := wParagraphPropsRegex.Find(para)
rPr := wRunPropsRegex.Find(para)
var rebuilt bytes.Buffer
rebuilt.WriteString(`<w:p>`)
if pPr != nil {
rebuilt.Write(pPr)
}
rebuilt.WriteString(`<w:r>`)
if rPr != nil {
rebuilt.Write(rPr)
}
rebuilt.WriteString(`<w:t xml:space="preserve">`)
rebuilt.WriteString(xmlEncode(replaced))
rebuilt.WriteString(`</w:t></w:r></w:p>`)
return rebuilt.Bytes()
})
}
// replacePlaceholders performs the actual substitution on a plain
// string. Unbound placeholders render the missing marker. When wrap is
// non-nil, both the resolved value AND the missing-marker text are
// passed through wrap(key, value) — the HTML preview path uses this to
// emit clickable spans around every substituted placeholder, including
// missing ones (clicking a missing marker jumps to the corresponding
// sidebar input).
func replacePlaceholders(s string, vars PlaceholderMap, missing MissingPlaceholderFn, wrap valueWrapperFn) string {
return placeholderRegex.ReplaceAllStringFunc(s, func(match string) string {
sub := placeholderRegex.FindStringSubmatch(match)
if len(sub) < 2 {
return match
}
key := sub[1]
var value string
if v, ok := vars[key]; ok {
value = v
} else {
value = missing(key)
}
if wrap != nil {
return wrap(key, value)
}
return value
})
}
// xmlDecode reverses the five standard XML entities Word emits in
// <w:t> content.
func xmlDecode(s string) string {
s = strings.ReplaceAll(s, "&lt;", "<")
s = strings.ReplaceAll(s, "&gt;", ">")
s = strings.ReplaceAll(s, "&quot;", `"`)
s = strings.ReplaceAll(s, "&apos;", "'")
s = strings.ReplaceAll(s, "&amp;", "&")
return s
}
// xmlEncode escapes for safe insertion back into <w:t> content. & first
// to avoid double-encoding the entity prefixes.
func xmlEncode(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, `"`, "&quot;")
s = strings.ReplaceAll(s, "'", "&apos;")
return s
}
// docXMLToHTML walks the post-merge document XML and emits HTML for
// the preview pane. One <p> per <w:p>; <strong>/<em> spans for runs
// carrying <w:b>/<w:i>. Tables/lists/images collapse to text. Output
// is HTML-escaped except for the structural <p>/<strong>/<em> tags
// this function emits.
func docXMLToHTML(docXML []byte) string {
paragraphs := wParagraphRegex.FindAll(docXML, -1)
var out bytes.Buffer
for _, para := range paragraphs {
out.WriteString("<p>")
out.WriteString(paragraphToHTML(para))
out.WriteString("</p>\n")
}
if out.Len() == 0 {
return "<p></p>"
}
return out.String()
}
// wRunRegex matches one <w:r>…</w:r> run. Greedy match safe — <w:r>
// elements do not nest.
var wRunRegex = regexp.MustCompile(`(?s)<w:r\b[^>]*>.*?</w:r>`)
// wBoldRegex / wItalicRegex detect the bold/italic flags inside a run's
// <w:rPr>. Word emits <w:b/> or <w:b w:val="true"/>; matching the open
// tag covers both forms.
var (
wBoldRegex = regexp.MustCompile(`<w:b\b[^>]*/?>`)
wItalicRegex = regexp.MustCompile(`<w:i\b[^>]*/?>`)
)
// paragraphToHTML extracts the text from each <w:r> inside a paragraph,
// wraps runs flagged bold/italic with the corresponding HTML tags, and
// HTML-escapes the text content.
func paragraphToHTML(para []byte) string {
runs := wRunRegex.FindAll(para, -1)
if len(runs) == 0 {
// Empty paragraph (line break).
return ""
}
var out bytes.Buffer
for _, run := range runs {
text := extractRunText(run)
if text == "" {
continue
}
// Check for bold/italic on the run's <w:rPr>.
rPr := wRunPropsRegex.Find(run)
bold := rPr != nil && wBoldRegex.Match(rPr) && !isFalseFlag(rPr, wBoldRegex)
italic := rPr != nil && wItalicRegex.Match(rPr) && !isFalseFlag(rPr, wItalicRegex)
if bold {
out.WriteString("<strong>")
}
if italic {
out.WriteString("<em>")
}
out.WriteString(emitTextWithDraftVars(text))
if italic {
out.WriteString("</em>")
}
if bold {
out.WriteString("</strong>")
}
}
return out.String()
}
// emitTextWithDraftVars HTML-escapes run text while converting any
// preview-only sentinels emitted by htmlPreviewWrapper into
// <span class="draft-var" data-var="<key>">…</span>. The key is
// restricted to [A-Za-z][A-Za-z0-9_.]* by placeholderRegex, so no
// attribute-escaping is needed on the key; the value is HTML-escaped
// normally. Sentinel-free text (the Render path output, or template
// text outside placeholders) is passed straight through htmlEscape, so
// callers that never invoked wrap see byte-identical HTML.
//
// t-paliad-261: makes substituted variables clickable in the preview
// pane so the user can jump to the matching input in the sidebar.
func emitTextWithDraftVars(text string) string {
if !strings.Contains(text, previewVarBegin) {
return htmlEscape(text)
}
var out strings.Builder
rest := text
for {
i := strings.Index(rest, previewVarBegin)
if i < 0 {
out.WriteString(htmlEscape(rest))
return out.String()
}
out.WriteString(htmlEscape(rest[:i]))
body := rest[i+len(previewVarBegin):]
mid := strings.Index(body, previewVarMid)
end := strings.Index(body, previewVarEnd)
if mid < 0 || end < 0 || mid > end {
// Malformed sentinel — emit the marker as plain escaped
// text and continue past it so the rest of the run still
// renders.
out.WriteString(htmlEscape(previewVarBegin))
rest = body
continue
}
key := body[:mid]
value := body[mid+len(previewVarMid) : end]
out.WriteString(`<span class="draft-var" data-var="`)
out.WriteString(key)
out.WriteString(`">`)
out.WriteString(htmlEscape(value))
out.WriteString(`</span>`)
rest = body[end+len(previewVarEnd):]
}
}
// extractRunText concatenates every <w:t> inside a run, XML-decoding
// the content as it goes.
func extractRunText(run []byte) string {
var out strings.Builder
for _, m := range wTextNodeRegex.FindAllSubmatch(run, -1) {
out.WriteString(xmlDecode(string(m[2])))
}
return out.String()
}
// isFalseFlag returns true if the matched tag explicitly carries
// w:val="false" or w:val="0" — Word's way of turning off an inherited
// format. The default match (just `<w:b/>` or `<w:b w:val="true"/>`)
// is "on".
func isFalseFlag(rPr []byte, rx *regexp.Regexp) bool {
match := rx.Find(rPr)
if match == nil {
return false
}
s := string(match)
return strings.Contains(s, `w:val="false"`) || strings.Contains(s, `w:val="0"`)
}
// htmlEscape escapes the five HTML-significant characters for safe
// insertion into the preview pane.
func htmlEscape(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, `"`, "&quot;")
s = strings.ReplaceAll(s, "'", "&#39;")
return s
}

View File

@@ -0,0 +1,353 @@
package services
// Submission merge-engine tests — resurrected from the original
// t-paliad-215 Slice 1 (commit 8ea3509) + Slice 2 (commit 1765d5e).
// Adapted: helper names suffixed with "Merge" so they don't collide
// with the convert tests in submission_render_test.go (minimalDOTM,
// unzipEntries) that test the format-only ConvertDotmToDocx path.
import (
"archive/zip"
"bytes"
"io"
"strings"
"testing"
)
// minimalMergeDOCX builds a tiny .docx zip with one document.xml that
// contains the given body. Just enough to exercise the merge engine.
func minimalMergeDOCX(t *testing.T, documentBody string) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, err := zw.Create("word/document.xml")
if err != nil {
t.Fatalf("create document.xml: %v", err)
}
if _, err := io.WriteString(w, documentBody); err != nil {
t.Fatalf("write document.xml: %v", err)
}
w2, err := zw.Create("[Content_Types].xml")
if err != nil {
t.Fatalf("create content types: %v", err)
}
// Use a docx-compatible content type so the convert pre-pass treats
// the input as already-clean (no .dotm rewrites needed).
body := `<?xml version="1.0"?><Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">` +
`<Override PartName="/word/document.xml" ContentType="` + docxMainContentType + `"/></Types>`
if _, err := io.WriteString(w2, body); err != nil {
t.Fatalf("write content types: %v", err)
}
if err := zw.Close(); err != nil {
t.Fatalf("close zip: %v", err)
}
return buf.Bytes()
}
// readMergeDocumentXML pulls word/document.xml out of a rendered .docx.
func readMergeDocumentXML(t *testing.T, b []byte) string {
t.Helper()
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
if err != nil {
t.Fatalf("open rendered zip: %v", err)
}
for _, f := range zr.File {
if f.Name != "word/document.xml" {
continue
}
rc, err := f.Open()
if err != nil {
t.Fatalf("open document.xml: %v", err)
}
defer rc.Close()
body, err := io.ReadAll(rc)
if err != nil {
t.Fatalf("read document.xml: %v", err)
}
return string(body)
}
t.Fatal("rendered .docx had no word/document.xml")
return ""
}
func TestRender_SingleRunPlaceholder(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{firm.name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"firm.name": "HLC"}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, ">HLC<") {
t.Errorf("expected HLC in body, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("unreplaced placeholder marker in body: %q", body)
}
}
func TestRender_MultiplePlaceholdersPerRun(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{parties.claimant.name}}, vertreten durch {{parties.claimant.representative}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{
"parties.claimant.name": "Acme Inc.",
"parties.claimant.representative": "Kanzlei Müller",
}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, "Acme Inc.") || !strings.Contains(body, "Kanzlei Müller") {
t.Errorf("expected both party values, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("unreplaced placeholder marker in body: %q", body)
}
}
func TestRender_MissingMarker(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{project.case_number}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{}, DefaultMissingMarker("de"))
if err != nil {
t.Fatalf("render: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, "[KEIN WERT: project.case_number]") {
t.Errorf("expected KEIN WERT marker, got %q", body)
}
outEN, err := r.Render(tmpl, PlaceholderMap{}, DefaultMissingMarker("en"))
if err != nil {
t.Fatalf("render en: %v", err)
}
bodyEN := readMergeDocumentXML(t, outEN)
if !strings.Contains(bodyEN, "[NO VALUE: project.case_number]") {
t.Errorf("expected NO VALUE marker, got %q", bodyEN)
}
}
func TestRender_CrossRunPlaceholder(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>Hello {{</w:t></w:r><w:r><w:t>project</w:t></w:r><w:r><w:t>.case_number}}!</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"project.case_number": "7 O 1234/26"}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, "7 O 1234/26") {
t.Errorf("expected case number after cross-run merge, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("orphan placeholder marker remained: %q", body)
}
}
func TestRender_XMLEscaping(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{user.display_name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{
"user.display_name": `Müller & Söhne <GmbH> "Special"`,
}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, "Müller &amp; Söhne &lt;GmbH&gt; &quot;Special&quot;") {
t.Errorf("expected escaped value, got %q", body)
}
}
func TestPlaceholderRegex_Boundaries(t *testing.T) {
tests := []struct {
in string
matches []string
}{
{"plain text", nil},
{"{{foo}}", []string{"{{foo}}"}},
{"{{ foo }}", []string{"{{ foo }}"}},
{"{{foo.bar}}", []string{"{{foo.bar}}"}},
{"{{ foo.bar_baz }}", []string{"{{ foo.bar_baz }}"}},
{"{{1bad}}", nil},
{"{{ foo }} and {{ bar }}", []string{"{{ foo }}", "{{ bar }}"}},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
got := placeholderRegex.FindAllString(tc.in, -1)
if len(got) != len(tc.matches) {
t.Fatalf("got %d matches, want %d (in=%q)", len(got), len(tc.matches), tc.in)
}
for i := range got {
if got[i] != tc.matches[i] {
t.Errorf("match %d: got %q, want %q", i, got[i], tc.matches[i])
}
}
})
}
}
func TestLegalSourcePretty(t *testing.T) {
tests := []struct {
src, lang, want string
}{
{"DE.ZPO.276.1", "de", "§ 276 Abs. 1 ZPO"},
{"DE.ZPO.276.1", "en", "Section 276(1) ZPO"},
{"DE.ZPO.253", "de", "§ 253 ZPO"},
{"DE.ZPO.253", "en", "Section 253 ZPO"},
{"UPC.RoP.23.1", "de", "Regel 23.1 VerfO UPC"},
{"UPC.RoP.23.1", "en", "Rule 23.1 RoP UPC"},
{"UPC.RoP.198", "de", "Regel 198 VerfO UPC"},
{"DE.PatG.83", "de", "§ 83 PatG"},
{"EPC.123", "de", "Art. 123 EPÜ"},
{"EPC.123", "en", "Art. 123 EPC"},
{"FOO.BAR.123", "de", "FOO.BAR.123"},
{"", "de", ""},
}
for _, tc := range tests {
t.Run(tc.src+"/"+tc.lang, func(t *testing.T) {
got := legalSourcePretty(tc.src, tc.lang)
if got != tc.want {
t.Errorf("legalSourcePretty(%q, %q) = %q, want %q", tc.src, tc.lang, got, tc.want)
}
})
}
}
func TestOurSideTranslations(t *testing.T) {
cases := []struct {
in, wantDE, wantEN string
}{
{"claimant", "Klägerin", "Claimant"},
{"defendant", "Beklagte", "Defendant"},
{"court", "Gericht", "Court"},
{"both", "Klägerin und Beklagte", "Claimant and Defendant"},
{"", "", ""},
{"unknown", "", ""},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
if got := ourSideDE(tc.in); got != tc.wantDE {
t.Errorf("ourSideDE(%q) = %q, want %q", tc.in, got, tc.wantDE)
}
if got := ourSideEN(tc.in); got != tc.wantEN {
t.Errorf("ourSideEN(%q) = %q, want %q", tc.in, got, tc.wantEN)
}
})
}
}
func TestPatentNumberUPC(t *testing.T) {
tests := []struct {
in, want string
}{
{"EP 1 234 567 B1", "EP 1 234 567 (B1)"},
{"EP 4 056 049 A1", "EP 4 056 049 (A1)"},
{"DE 10 2020 123 456 A1", "DE 10 2020 123 456 (A1)"},
{"EP 1 234 567", "EP 1 234 567"},
{" EP 1 234 567 B1 ", "EP 1 234 567 (B1)"},
{"", ""},
{"WO/2023/123456", "WO/2023/123456"},
{"EP 1 234 567 B12", "EP 1 234 567 B12"},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
got := patentNumberUPC(tc.in)
if got != tc.want {
t.Errorf("patentNumberUPC(%q) = %q, want %q", tc.in, got, tc.want)
}
})
}
}
// TestRenderHTML_ExtractsParagraphsAndFormatting verifies the preview
// HTML emitter walks <w:p> / <w:r> / <w:t> correctly and carries
// bold/italic through to <strong>/<em>. Substituted placeholders are
// wrapped in <span class="draft-var" data-var="…"> so the client can
// make them clickable (t-paliad-261).
func TestRenderHTML_ExtractsParagraphsAndFormatting(t *testing.T) {
doc := `<w:document><w:body>` +
`<w:p><w:r><w:t>Hello {{firm.name}}</w:t></w:r></w:p>` +
`<w:p><w:r><w:rPr><w:b/></w:rPr><w:t>Bold line</w:t></w:r></w:p>` +
`<w:p><w:r><w:rPr><w:i/></w:rPr><w:t>Italic line</w:t></w:r></w:p>` +
`</w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
html, err := r.RenderHTML(tmpl, PlaceholderMap{"firm.name": "HLC"}, nil)
if err != nil {
t.Fatalf("render html: %v", err)
}
if !strings.Contains(html, `<p>Hello <span class="draft-var" data-var="firm.name">HLC</span></p>`) {
t.Errorf("expected merged paragraph with draft-var span, got %q", html)
}
if !strings.Contains(html, "<strong>Bold line</strong>") {
t.Errorf("expected bold span, got %q", html)
}
if !strings.Contains(html, "<em>Italic line</em>") {
t.Errorf("expected italic span, got %q", html)
}
}
// TestRenderHTML_EscapesContent confirms the preview emitter HTML-escapes
// special characters in placeholder values even inside the draft-var
// span wrapper.
func TestRenderHTML_EscapesContent(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{user.display_name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
html, err := r.RenderHTML(tmpl, PlaceholderMap{
"user.display_name": `M&S <Inc> "X"`,
}, nil)
if err != nil {
t.Fatalf("render html: %v", err)
}
want := `<span class="draft-var" data-var="user.display_name">M&amp;S &lt;Inc&gt; &quot;X&quot;</span>`
if !strings.Contains(html, want) {
t.Errorf("expected escaped value inside draft-var span, got %q", html)
}
}
// TestRenderHTML_WrapsMissingMarker confirms that an unbound placeholder
// is still rendered as a clickable draft-var span so the user can click
// the [KEIN WERT: …] marker in the preview and jump to the field.
func TestRenderHTML_WrapsMissingMarker(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{project.case_number}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
html, err := r.RenderHTML(tmpl, PlaceholderMap{}, nil)
if err != nil {
t.Fatalf("render html: %v", err)
}
want := `<span class="draft-var" data-var="project.case_number">[KEIN WERT: project.case_number]</span>`
if !strings.Contains(html, want) {
t.Errorf("expected missing marker wrapped in draft-var span, got %q", html)
}
}
// TestRender_DocxOutputUnchangedByPreviewWrap asserts the hard rule from
// t-paliad-261: the .docx export path must NOT carry the preview-only
// draft-var sentinels or any draft-var span markup. Renders the same
// template through Render (.docx) and asserts the merged document.xml
// has only the resolved value, not a wrapped one.
func TestRender_DocxOutputUnchangedByPreviewWrap(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{firm.name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"firm.name": "HLC"}, nil)
if err != nil {
t.Fatalf("render docx: %v", err)
}
body := readMergeDocumentXML(t, out)
if !strings.Contains(body, `<w:t>HLC</w:t>`) {
t.Errorf("expected raw resolved value in .docx, got %q", body)
}
// PUA sentinels and any span markup must NOT appear in the .docx.
for _, forbidden := range []string{"draft-var", "data-var", previewVarBegin, previewVarMid, previewVarEnd} {
if strings.Contains(body, forbidden) {
t.Errorf("docx output unexpectedly contains %q: %q", forbidden, body)
}
}
}

View File

@@ -1,27 +1,33 @@
package services
// Submission template renderer — in-house engine for the submission
// generator (t-paliad-215, design doc
// docs/design-submission-generator-2026-05-19.md §6).
// Submission .dotm → .docx converter (t-paliad-230, "format-only" scope
// reduction of the original t-paliad-215 submission generator).
//
// Design choice — why not lukasjarosch/go-docx:
// The library's "nested placeholder" guard treats sibling placeholders
// inside the same <w:t> run (e.g. "{{a}} ./. {{b}}") as nested and
// refuses to replace either. Patent submissions routinely have multiple
// placeholders per paragraph (party blocks especially), so the library
// is a non-starter without a custom fork. The in-house renderer below
// is ~150 LoC and handles both the single-run common case and the
// cross-run case (where Word may split a placeholder across runs after
// editing).
// Word .dotm (macro-enabled template), .docm (macro-enabled document),
// .dotx (template, no macros), and .docx (document, no macros) are all
// OOXML zip containers. The macro-bearing variants carry an extra set
// of parts:
//
// Placeholder grammar: {{[A-Za-z][A-Za-z0-9_.]*}} with optional
// whitespace inside braces ({{ project.case_number }} ≡
// {{project.case_number}}).
// word/vbaProject.bin — the VBA project binary
// word/_rels/vbaProject.bin.rels — auxiliary relationships
// word/vbaData.xml — VBA support data
// word/customizations.xml — keyMapCustomizations
//
// Missing-value behaviour: when a placeholder has no binding in the
// PlaceholderMap, the renderer emits a marker token so the lawyer sees
// the gap in Word rather than failing the request. See §6.3 of the
// design doc.
// plus a Content-Types override for each of those, a Default extension
// declaring all .bin files as vbaProject, and a different "main" content
// type for word/document.xml itself.
//
// ConvertDotmToDocx walks the zip, drops the macro parts, rewrites
// [Content_Types].xml and word/_rels/document.xml.rels to remove every
// reference to them, and switches the main document content type to
// the plain .docx form. Every other part — styles, fonts, theme,
// settings, document body, header/footer/numbering, glossary, custom
// XML — passes through bit-for-bit at the original compression method
// and modification time.
//
// No variable substitution. Today's slice hands the lawyer the firm
// style template as a clean .docx so they can edit and save under
// their own filename. The merge-engine slice is deferred.
import (
"archive/zip"
@@ -32,110 +38,132 @@ import (
"strings"
)
// PlaceholderMap is the variable bag built by SubmissionVarsService.
// Keys are dotted paths without braces (e.g. "project.case_number").
// Values are the substituted text — already locale-aware, pretty-
// printed, and sanitised by the caller.
type PlaceholderMap map[string]string
// The four OOXML "main" content types we may see on word/document.xml.
// Anything other than docxMainContentType gets rewritten so the output
// reads as a plain document.
const (
dotmMainContentType = "application/vnd.ms-word.template.macroEnabledTemplate.main+xml"
docmMainContentType = "application/vnd.ms-word.document.macroEnabled.main+xml"
dotxMainContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.template.main+xml"
docxMainContentType = "application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"
)
// MissingPlaceholderFn translates an unbound placeholder key into the
// in-document marker token. The default in DefaultMissingMarker is
// "[KEIN WERT: <key>]" / "[NO VALUE: <key>]" depending on lang.
type MissingPlaceholderFn func(key string) string
// DefaultMissingMarker returns the standard missing-value marker for
// the given UI language.
func DefaultMissingMarker(lang string) MissingPlaceholderFn {
prefix := "KEIN WERT"
if strings.EqualFold(lang, "en") {
prefix = "NO VALUE"
}
return func(key string) string {
return "[" + prefix + ": " + key + "]"
}
// Macro-related parts dropped wholesale from the output zip.
var macroParts = map[string]bool{
"word/vbaProject.bin": true,
"word/_rels/vbaProject.bin.rels": true,
"word/vbaData.xml": true,
"word/customizations.xml": true,
}
// placeholderRegex matches a single placeholder. The capture group
// extracts the key name without braces or surrounding whitespace.
//
// Restricted to [A-Za-z][A-Za-z0-9_.]* so that stray "{{" sequences in
// legal prose (extremely rare in DE/EN court briefs but possible)
// don't get mistaken for placeholders. A genuine placeholder always
// starts with an ASCII letter.
var placeholderRegex = regexp.MustCompile(`\{\{\s*([A-Za-z][A-Za-z0-9_.]*)\s*\}\}`)
const (
contentTypesPath = "[Content_Types].xml"
documentRelsPath = "word/_rels/document.xml.rels"
)
// SubmissionRenderer renders a .docx template into a .docx output by
// substituting {{placeholder}} tokens with values from a PlaceholderMap.
// Stateless; safe for concurrent use.
type SubmissionRenderer struct{}
// vbaDefaultExtensionRegex matches the `<Default Extension="bin"
// ContentType=".../vbaProject"/>` row in [Content_Types].xml. After
// vbaProject.bin is dropped, the Default is dead weight (and Word will
// flag the file as macro-bearing if it survives).
var vbaDefaultExtensionRegex = regexp.MustCompile(
`\s*<Default\b[^>]*\bExtension\s*=\s*"bin"[^>]*\bContentType\s*=\s*"application/vnd\.ms-office\.vbaProject"[^>]*/>`,
)
// NewSubmissionRenderer constructs the renderer.
func NewSubmissionRenderer() *SubmissionRenderer {
return &SubmissionRenderer{}
}
// macroOverridePartRegex matches any <Override PartName="…"/> element
// whose PartName is one of the dropped macro parts. The /word/
// prefix is the OOXML convention for the absolute part path in
// [Content_Types].xml — file paths in the zip itself omit the leading
// slash.
var macroOverridePartRegex = regexp.MustCompile(
`\s*<Override\b[^>]*\bPartName\s*=\s*"/word/(?:vbaProject\.bin|vbaData\.xml|customizations\.xml)"[^>]*/>`,
)
// Render reads the .docx template at templateBytes, substitutes every
// placeholder from vars (or emits the missing-marker token), and writes
// the result to the returned byte slice. Unknown placeholders never
// fail the render — the lawyer sees the marker in Word and fixes it.
func (r *SubmissionRenderer) Render(templateBytes []byte, vars PlaceholderMap, missing MissingPlaceholderFn) ([]byte, error) {
if missing == nil {
missing = DefaultMissingMarker("de")
}
zr, err := zip.NewReader(bytes.NewReader(templateBytes), int64(len(templateBytes)))
// macroRelTypeRegex matches the two macro-related relationship Types
// in word/_rels/document.xml.rels: vbaProject (binds to vbaProject.bin)
// and keyMapCustomizations (binds to customizations.xml). After both
// targets are dropped, leaving the relationships in would make Word
// flag the file as corrupt.
var macroRelTypeRegex = regexp.MustCompile(
`\s*<Relationship\b[^>]*\bType\s*=\s*"http://schemas\.microsoft\.com/office/2006/relationships/(?:vbaProject|keyMapCustomizations)"[^>]*/>`,
)
// ConvertDotmToDocx rewrites a .dotm (or .docm, or .dotx) zip into a
// clean .docx zip. Idempotent on a zip that is already a plain .docx.
// Returns an error if the input is not a valid zip.
func ConvertDotmToDocx(dotmBytes []byte) ([]byte, error) {
zr, err := zip.NewReader(bytes.NewReader(dotmBytes), int64(len(dotmBytes)))
if err != nil {
return nil, fmt.Errorf("submission template: open zip: %w", err)
return nil, fmt.Errorf("dotm→docx: open zip: %w", err)
}
var out bytes.Buffer
zw := zip.NewWriter(&out)
defer zw.Close()
for _, entry := range zr.File {
body, err := readZipEntry(entry)
if macroParts[entry.Name] {
continue
}
body, err := readZipFile(entry)
if err != nil {
return nil, fmt.Errorf("submission template: read %s: %w", entry.Name, err)
return nil, fmt.Errorf("dotm→docx: read %s: %w", entry.Name, err)
}
if isWordXMLEntry(entry.Name) {
body = substituteInDocumentXML(body, vars, missing)
switch entry.Name {
case contentTypesPath:
body = rewriteContentTypes(body)
case documentRelsPath:
body = rewriteDocumentRels(body)
}
w, err := zw.CreateHeader(&zip.FileHeader{
Name: entry.Name,
Method: entry.Method,
Modified: entry.Modified,
})
if err != nil {
return nil, fmt.Errorf("submission template: write header %s: %w", entry.Name, err)
return nil, fmt.Errorf("dotm→docx: write header %s: %w", entry.Name, err)
}
if _, err := w.Write(body); err != nil {
return nil, fmt.Errorf("submission template: write %s: %w", entry.Name, err)
return nil, fmt.Errorf("dotm→docx: write body %s: %w", entry.Name, err)
}
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("submission template: finalise zip: %w", err)
return nil, fmt.Errorf("dotm→docx: finalise zip: %w", err)
}
return out.Bytes(), nil
}
// isWordXMLEntry returns true for the .docx parts that contain
// substitutable text. We touch document.xml plus header*.xml and
// footer*.xml (templates may put firm letterhead in a header) but
// skip styles, theme, settings, comments, footnotes — none of which
// should carry merge placeholders in a well-formed template.
func isWordXMLEntry(name string) bool {
switch {
case name == "word/document.xml":
return true
case strings.HasPrefix(name, "word/header") && strings.HasSuffix(name, ".xml"):
return true
case strings.HasPrefix(name, "word/footer") && strings.HasSuffix(name, ".xml"):
return true
}
return false
// rewriteContentTypes demotes any of the three non-docx "main" content
// types to plain docx, drops the bin Default-Extension entry, and
// drops every Override that targeted a dropped macro part.
//
// String-level substitution rather than encoding/xml: round-tripping
// through Go's XML marshaller would re-emit the document with
// canonical namespace declarations on every child, which Word reads
// but which makes the binary diff unnecessarily large. Direct
// substitution preserves the file's original shape.
func rewriteContentTypes(body []byte) []byte {
body = bytes.ReplaceAll(body, []byte(dotmMainContentType), []byte(docxMainContentType))
body = bytes.ReplaceAll(body, []byte(docmMainContentType), []byte(docxMainContentType))
body = bytes.ReplaceAll(body, []byte(dotxMainContentType), []byte(docxMainContentType))
body = vbaDefaultExtensionRegex.ReplaceAll(body, nil)
body = macroOverridePartRegex.ReplaceAll(body, nil)
return body
}
// readZipEntry slurps a zip entry's bytes.
func readZipEntry(f *zip.File) ([]byte, error) {
// rewriteDocumentRels drops the two macro-related relationships from
// word/_rels/document.xml.rels (vbaProject + keyMapCustomizations) so
// the manifest no longer points at parts the zip no longer carries.
// Every other relationship — styles, settings, numbering, theme,
// headers/footers, customXml — passes through untouched.
func rewriteDocumentRels(body []byte) []byte {
return macroRelTypeRegex.ReplaceAll(body, nil)
}
// readZipFile slurps a zip entry's bytes.
func readZipFile(f *zip.File) ([]byte, error) {
rc, err := f.Open()
if err != nil {
return nil, err
@@ -144,172 +172,33 @@ func readZipEntry(f *zip.File) ([]byte, error) {
return io.ReadAll(rc)
}
// substituteInDocumentXML walks document XML and replaces every
// {{placeholder}} occurrence inside <w:t> text nodes. Handles both
// single-run placeholders (the common case for freshly authored
// templates) and cross-run placeholders (where Word's autocorrect or
// manual editing has split a placeholder across runs).
//
// Two-pass strategy:
//
// 1. Pass 1: replace placeholders that fit entirely within one
// <w:t>…</w:t>. This is the 99% case and preserves all run-level
// formatting (bold, italic, font runs).
// 2. Pass 2: for paragraphs that still contain orphan "{{" or "}}"
// markers after pass 1, merge the text of every <w:t> inside the
// paragraph, run the replacement on the merged text, and rewrite
// the paragraph's runs as a single <w:r><w:t>…</w:t></w:r> using
// the formatting properties of the first run. Loses intra-paragraph
// formatting on the affected paragraph — but only on paragraphs
// where Word genuinely fragmented a placeholder.
func substituteInDocumentXML(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn) []byte {
replaced := substituteInTextNodes(body, vars, missing)
if !needsCrossRunMerge(replaced) {
return replaced
}
return substituteAcrossRuns(replaced, vars, missing)
}
// wTextNodeRegex matches one <w:t …>contents</w:t> element, capturing
// the contents. Attributes on <w:t> (xml:space="preserve") are preserved
// because the entire match is rewritten.
var wTextNodeRegex = regexp.MustCompile(`<w:t(\s[^>]*)?>([^<]*)</w:t>`)
// substituteInTextNodes runs the placeholder replacement inside each
// <w:t> text node independently. Format-preserving for single-run
// placeholders.
func substituteInTextNodes(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn) []byte {
return wTextNodeRegex.ReplaceAllFunc(body, func(match []byte) []byte {
sub := wTextNodeRegex.FindSubmatch(match)
attrs := string(sub[1])
contents := xmlDecode(string(sub[2]))
replaced := replacePlaceholders(contents, vars, missing)
if replaced == contents {
return match
// SanitiseSubmissionFileName cleans a string for use inside a download
// filename — strips path separators and quote characters that would
// break Content-Disposition or confuse browsers across OSes. ASCII-folds
// the small set of German umlaut letters that show up in submission
// names today (Klageerwiderung, Berufungsbegründung, …) so the file
// lands cleanly on legacy SMB shares whose layer is still cp1252.
// Other Unicode is preserved so non-DE/EN names still produce a
// recognisable file.
func SanitiseSubmissionFileName(s string) string {
s = strings.TrimSpace(s)
s = umlautFolder.Replace(s)
s = strings.Map(func(r rune) rune {
switch r {
case '/', '\\':
return '_'
case '"', '\'':
return -1
}
// xml:space="preserve" stays attached whenever the original
// content had leading/trailing whitespace; ensure it's still
// declared after replacement to avoid Word collapsing spaces.
if !strings.Contains(attrs, "xml:space") &&
(strings.HasPrefix(replaced, " ") || strings.HasSuffix(replaced, " ")) {
attrs += ` xml:space="preserve"`
}
return []byte(`<w:t` + attrs + `>` + xmlEncode(replaced) + `</w:t>`)
})
}
// needsCrossRunMerge returns true when the body still contains an
// unmatched "{{" or "}}" after pass 1 — a sign that Word fragmented
// the placeholder across runs and pass 1 couldn't touch it.
func needsCrossRunMerge(body []byte) bool {
// Cheap heuristic: count "{{" vs "}}" inside <w:t> nodes. If we have
// either marker present in the text-node space, pass 2 will handle
// it. (Inside attributes or other XML, the markers don't matter.)
for _, m := range wTextNodeRegex.FindAllSubmatch(body, -1) {
t := string(m[2])
if strings.Contains(t, "{{") || strings.Contains(t, "}}") {
return true
}
}
return false
}
// wParagraphRegex matches one <w:p>…</w:p> paragraph block. Greedy
// inner-content match is safe here because <w:p> elements do not nest
// in WordprocessingML — a paragraph is the leaf container for text.
var wParagraphRegex = regexp.MustCompile(`(?s)<w:p\b[^>]*>.*?</w:p>`)
// wRunPropsRegex pulls the first <w:rPr>…</w:rPr> block from a
// paragraph so we can reuse it as the formatting of the merged run.
var wRunPropsRegex = regexp.MustCompile(`(?s)<w:rPr>.*?</w:rPr>`)
// wParagraphPropsRegex pulls the optional <w:pPr>…</w:pPr> that sits
// at the top of a paragraph (alignment, spacing, etc.). Preserved.
var wParagraphPropsRegex = regexp.MustCompile(`(?s)<w:pPr>.*?</w:pPr>`)
// substituteAcrossRuns is pass 2: for any paragraph that still has a
// split placeholder, concatenate every text node, run replacement, and
// rewrite the paragraph as a single run using the first run's
// properties. Paragraphs without orphan markers are left untouched so
// run-level formatting survives wherever pass 1 already resolved the
// placeholders.
func substituteAcrossRuns(body []byte, vars PlaceholderMap, missing MissingPlaceholderFn) []byte {
return wParagraphRegex.ReplaceAllFunc(body, func(para []byte) []byte {
textNodes := wTextNodeRegex.FindAllSubmatch(para, -1)
if len(textNodes) == 0 {
return para
}
var merged strings.Builder
for _, m := range textNodes {
merged.WriteString(xmlDecode(string(m[2])))
}
original := merged.String()
if !strings.Contains(original, "{{") {
// No fragmented placeholder in this paragraph; leave it
// alone so pass 1's run-level edits survive.
return para
}
replaced := replacePlaceholders(original, vars, missing)
if replaced == original {
return para
}
// Preserve paragraph properties (alignment, spacing) and the
// first run's properties (font, bold/italic).
pPr := wParagraphPropsRegex.Find(para)
rPr := wRunPropsRegex.Find(para)
var rebuilt bytes.Buffer
rebuilt.WriteString(`<w:p>`)
if pPr != nil {
rebuilt.Write(pPr)
}
rebuilt.WriteString(`<w:r>`)
if rPr != nil {
rebuilt.Write(rPr)
}
rebuilt.WriteString(`<w:t xml:space="preserve">`)
rebuilt.WriteString(xmlEncode(replaced))
rebuilt.WriteString(`</w:t></w:r></w:p>`)
return rebuilt.Bytes()
})
}
// replacePlaceholders performs the actual substitution on a plain
// string. Unbound placeholders render the missing marker.
func replacePlaceholders(s string, vars PlaceholderMap, missing MissingPlaceholderFn) string {
return placeholderRegex.ReplaceAllStringFunc(s, func(match string) string {
sub := placeholderRegex.FindStringSubmatch(match)
if len(sub) < 2 {
return match
}
key := sub[1]
if value, ok := vars[key]; ok {
return value
}
return missing(key)
})
}
// xmlDecode reverses the small set of escapes used in WordprocessingML
// text content. We don't need a full XML parser — text nodes carry only
// the standard five entities, and Word never emits numeric-character
// references inside <w:t> for printable content.
func xmlDecode(s string) string {
s = strings.ReplaceAll(s, "&lt;", "<")
s = strings.ReplaceAll(s, "&gt;", ">")
s = strings.ReplaceAll(s, "&quot;", `"`)
s = strings.ReplaceAll(s, "&apos;", "'")
s = strings.ReplaceAll(s, "&amp;", "&")
return r
}, s)
return s
}
// xmlEncode escapes a substituted value for safe insertion back into a
// WordprocessingML text node. & must be replaced first to avoid double
// encoding the entity prefixes we introduce on the other characters.
func xmlEncode(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, `"`, "&quot;")
s = strings.ReplaceAll(s, "'", "&apos;")
return s
}
// umlautFolder turns the four DE umlaut letters (both cases) into ASCII
// digraphs; ß → ss.
var umlautFolder = strings.NewReplacer(
"ä", "ae", "ö", "oe", "ü", "ue",
"Ä", "Ae", "Ö", "Oe", "Ü", "Ue",
"ß", "ss",
)

View File

@@ -6,392 +6,249 @@ import (
"io"
"strings"
"testing"
"time"
)
// minimalDOCX builds a tiny .docx zip with one document.xml that
// contains the given body. Just enough to exercise the renderer
// without depending on Word's full OOXML scaffolding.
func minimalDOCX(t *testing.T, documentBody string) []byte {
// minimalDOTM builds a small .dotm zip whose shape mirrors the real
// HL Patents Style template: macro-enabled main content type, Default
// extension declaring .bin as vbaProject, Overrides for vbaData.xml +
// customizations.xml, document.xml.rels with vbaProject +
// keyMapCustomizations relationships, and the four macro parts on
// disk (vbaProject.bin + auxiliary rels + vbaData.xml +
// customizations.xml).
//
// In-memory so the test is self-contained (no checked-in binary).
// Word and LibreOffice would reject this minimal file as incomplete
// (no _rels/.rels root manifest); the tests work at the byte level
// and assert structural properties of the converted output.
func minimalDOTM(t *testing.T) []byte {
t.Helper()
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
w, err := zw.Create("word/document.xml")
if err != nil {
t.Fatalf("create document.xml: %v", err)
}
if _, err := io.WriteString(w, documentBody); err != nil {
t.Fatalf("write document.xml: %v", err)
}
// Drop in a stub Content-Types so the bytes look more like a real
// .docx for any downstream sanity checks; Word doesn't care about
// the content during our unit tests but the shape stays honest.
w2, err := zw.Create("[Content_Types].xml")
if err != nil {
t.Fatalf("create content types: %v", err)
}
if _, err := io.WriteString(w2, `<?xml version="1.0"?><Types/>`); err != nil {
t.Fatalf("write content types: %v", err)
add := func(name, body string) {
t.Helper()
w, err := zw.CreateHeader(&zip.FileHeader{
Name: name,
Method: zip.Deflate,
Modified: time.Date(2026, 5, 21, 12, 0, 0, 0, time.UTC),
})
if err != nil {
t.Fatalf("zip header %s: %v", name, err)
}
if _, err := io.WriteString(w, body); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
add(contentTypesPath, `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+
`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`+
`<Default Extension="bin" ContentType="application/vnd.ms-office.vbaProject"/>`+
`<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>`+
`<Default Extension="xml" ContentType="application/xml"/>`+
`<Override PartName="/word/document.xml" ContentType="`+dotmMainContentType+`"/>`+
`<Override PartName="/word/customizations.xml" ContentType="application/vnd.ms-word.keyMapCustomizations+xml"/>`+
`<Override PartName="/word/vbaData.xml" ContentType="application/vnd.ms-word.vbaData+xml"/>`+
`<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>`+
`</Types>`)
add("word/document.xml",
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+
`<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`+
`<w:body><w:p><w:r><w:t>Hello Paliad</w:t></w:r></w:p></w:body></w:document>`)
add(documentRelsPath,
`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`+
`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">`+
`<Relationship Id="rId1" Type="http://schemas.microsoft.com/office/2006/relationships/vbaProject" Target="vbaProject.bin"/>`+
`<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>`+
`<Relationship Id="rId3" Type="http://schemas.microsoft.com/office/2006/relationships/keyMapCustomizations" Target="customizations.xml"/>`+
`</Relationships>`)
add("word/styles.xml", `<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main"/>`)
add("word/vbaProject.bin", "PRETEND-VBA-BINARY-PAYLOAD")
add("word/_rels/vbaProject.bin.rels", `<?xml version="1.0"?><Relationships/>`)
add("word/vbaData.xml", `<?xml version="1.0"?><wne:vbaSuppData xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"/>`)
add("word/customizations.xml", `<?xml version="1.0"?><wne:tcg xmlns:wne="http://schemas.microsoft.com/office/word/2006/wordml"/>`)
if err := zw.Close(); err != nil {
t.Fatalf("close zip: %v", err)
}
return buf.Bytes()
}
// readDocumentXML pulls word/document.xml out of a rendered .docx.
func readDocumentXML(t *testing.T, b []byte) string {
func unzipEntries(t *testing.T, data []byte) map[string]string {
t.Helper()
zr, err := zip.NewReader(bytes.NewReader(b), int64(len(b)))
zr, err := zip.NewReader(bytes.NewReader(data), int64(len(data)))
if err != nil {
t.Fatalf("open rendered zip: %v", err)
t.Fatalf("open output zip: %v", err)
}
out := make(map[string]string, len(zr.File))
for _, f := range zr.File {
if f.Name != "word/document.xml" {
continue
}
rc, err := f.Open()
if err != nil {
t.Fatalf("open document.xml: %v", err)
t.Fatalf("open %s: %v", f.Name, err)
}
defer rc.Close()
body, err := io.ReadAll(rc)
rc.Close()
if err != nil {
t.Fatalf("read document.xml: %v", err)
t.Fatalf("read %s: %v", f.Name, err)
}
return string(body)
out[f.Name] = string(body)
}
t.Fatal("rendered .docx had no word/document.xml")
return ""
return out
}
// TestRender_SingleRunPlaceholder covers the 99% case: a placeholder
// that sits inside a single <w:t> text node.
func TestRender_SingleRunPlaceholder(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{firm.name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"firm.name": "HLC"}, nil)
func TestConvertDotmToDocx_StripsMacroParts(t *testing.T) {
dotm := minimalDOTM(t)
out, err := ConvertDotmToDocx(dotm)
if err != nil {
t.Fatalf("render: %v", err)
t.Fatalf("ConvertDotmToDocx: %v", err)
}
body := readDocumentXML(t, out)
if !strings.Contains(body, ">HLC<") {
t.Errorf("expected HLC in body, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("unreplaced placeholder marker in body: %q", body)
}
}
// TestRender_MultiplePlaceholdersPerRun is the case go-docx fails on
// — sibling placeholders inside the same <w:t> run. The in-house
// renderer must handle them.
func TestRender_MultiplePlaceholdersPerRun(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{parties.claimant.name}}, vertreten durch {{parties.claimant.representative}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{
"parties.claimant.name": "Acme Inc.",
"parties.claimant.representative": "Kanzlei Müller",
}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readDocumentXML(t, out)
if !strings.Contains(body, "Acme Inc.") || !strings.Contains(body, "Kanzlei Müller") {
t.Errorf("expected both party values, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("unreplaced placeholder marker in body: %q", body)
}
}
entries := unzipEntries(t, out)
// TestRender_MissingMarker confirms unbound placeholders render the
// missing-value marker instead of failing the request.
func TestRender_MissingMarker(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{project.case_number}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{}, DefaultMissingMarker("de"))
if err != nil {
t.Fatalf("render: %v", err)
}
body := readDocumentXML(t, out)
if !strings.Contains(body, "[KEIN WERT: project.case_number]") {
t.Errorf("expected KEIN WERT marker, got %q", body)
}
outEN, err := r.Render(tmpl, PlaceholderMap{}, DefaultMissingMarker("en"))
if err != nil {
t.Fatalf("render en: %v", err)
}
bodyEN := readDocumentXML(t, outEN)
if !strings.Contains(bodyEN, "[NO VALUE: project.case_number]") {
t.Errorf("expected NO VALUE marker, got %q", bodyEN)
}
}
// TestRender_CrossRunPlaceholder simulates Word fragmenting a
// placeholder across runs (autocorrect or post-edit run-split).
// Pass 2 must catch it.
func TestRender_CrossRunPlaceholder(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>Hello {{</w:t></w:r><w:r><w:t>project</w:t></w:r><w:r><w:t>.case_number}}!</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"project.case_number": "7 O 1234/26"}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readDocumentXML(t, out)
if !strings.Contains(body, "7 O 1234/26") {
t.Errorf("expected case number after cross-run merge, got %q", body)
}
if strings.Contains(body, "{{") {
t.Errorf("orphan placeholder marker remained: %q", body)
}
}
// TestRender_XMLEscaping verifies special characters in placeholder
// values are escaped so they don't corrupt the document XML.
func TestRender_XMLEscaping(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{user.display_name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{
"user.display_name": `Müller & Söhne <GmbH> "Special"`,
}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
body := readDocumentXML(t, out)
if !strings.Contains(body, "Müller &amp; Söhne &lt;GmbH&gt; &quot;Special&quot;") {
t.Errorf("expected escaped value, got %q", body)
}
}
// TestRender_PreservesNonWordEntries leaves the rest of the .docx
// untouched so any styles / theme / settings parts come through bit-
// for-bit.
func TestRender_PreservesNonWordEntries(t *testing.T) {
doc := `<w:document><w:body><w:p><w:r><w:t>{{firm.name}}</w:t></w:r></w:p></w:body></w:document>`
tmpl := minimalDOCX(t, doc)
r := NewSubmissionRenderer()
out, err := r.Render(tmpl, PlaceholderMap{"firm.name": "HLC"}, nil)
if err != nil {
t.Fatalf("render: %v", err)
}
zr, err := zip.NewReader(bytes.NewReader(out), int64(len(out)))
if err != nil {
t.Fatalf("open rendered: %v", err)
}
var sawTypes bool
for _, f := range zr.File {
if f.Name == "[Content_Types].xml" {
sawTypes = true
for _, name := range []string{
"word/vbaProject.bin",
"word/_rels/vbaProject.bin.rels",
"word/vbaData.xml",
"word/customizations.xml",
} {
if _, ok := entries[name]; ok {
t.Errorf("output still contains %s", name)
}
}
if !sawTypes {
t.Error("rendered .docx lost [Content_Types].xml")
if doc, ok := entries["word/document.xml"]; !ok {
t.Error("output is missing word/document.xml")
} else if !strings.Contains(doc, "Hello Paliad") {
t.Errorf("document body lost during conversion: %q", doc)
}
if _, ok := entries["word/styles.xml"]; !ok {
t.Error("output lost unrelated word/styles.xml")
}
ctypes, ok := entries[contentTypesPath]
if !ok {
t.Fatal("output is missing [Content_Types].xml")
}
if strings.Contains(ctypes, "macroEnabled") {
t.Errorf("output [Content_Types].xml still references a macro-enabled type: %q", ctypes)
}
if !strings.Contains(ctypes, docxMainContentType) {
t.Errorf("output is missing plain docx main content type: %q", ctypes)
}
if strings.Contains(ctypes, "vbaProject") {
t.Errorf("output [Content_Types].xml still references vbaProject: %q", ctypes)
}
if strings.Contains(ctypes, "vbaData") {
t.Errorf("output [Content_Types].xml still overrides vbaData: %q", ctypes)
}
if strings.Contains(ctypes, "keyMapCustomizations") {
t.Errorf("output [Content_Types].xml still overrides customizations: %q", ctypes)
}
if !strings.Contains(ctypes, "wordprocessingml.styles") {
t.Errorf("output lost unrelated styles Override: %q", ctypes)
}
rels, ok := entries[documentRelsPath]
if !ok {
t.Fatal("output is missing word/_rels/document.xml.rels")
}
if strings.Contains(rels, "vbaProject") {
t.Errorf("output rels still references vbaProject: %q", rels)
}
if strings.Contains(rels, "keyMapCustomizations") {
t.Errorf("output rels still references keyMapCustomizations: %q", rels)
}
if !strings.Contains(rels, "styles.xml") {
t.Errorf("output rels lost unrelated styles relationship: %q", rels)
}
}
// TestPlaceholderRegex_Boundaries pins the placeholder grammar.
func TestPlaceholderRegex_Boundaries(t *testing.T) {
tests := []struct {
in string
matches []string
}{
{"plain text", nil},
{"{{foo}}", []string{"{{foo}}"}},
{"{{ foo }}", []string{"{{ foo }}"}},
{"{{foo.bar}}", []string{"{{foo.bar}}"}},
{"{{ foo.bar_baz }}", []string{"{{ foo.bar_baz }}"}},
{"{{1bad}}", nil}, // must start with a letter
{"{{ foo }} and {{ bar }}", []string{"{{ foo }}", "{{ bar }}"}},
func TestConvertDotmToDocx_IdempotentOnPlainDocx(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
add := func(name, body string) {
w, err := zw.Create(name)
if err != nil {
t.Fatalf("create %s: %v", name, err)
}
if _, err := io.WriteString(w, body); err != nil {
t.Fatalf("write %s: %v", name, err)
}
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
got := placeholderRegex.FindAllString(tc.in, -1)
if len(got) != len(tc.matches) {
t.Fatalf("got %d matches, want %d (in=%q)", len(got), len(tc.matches), tc.in)
add(contentTypesPath, `<?xml version="1.0"?>`+
`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`+
`<Override PartName="/word/document.xml" ContentType="`+docxMainContentType+`"/>`+
`</Types>`)
add("word/document.xml", `<w:document/>`)
if err := zw.Close(); err != nil {
t.Fatalf("close: %v", err)
}
out, err := ConvertDotmToDocx(buf.Bytes())
if err != nil {
t.Fatalf("ConvertDotmToDocx: %v", err)
}
entries := unzipEntries(t, out)
if _, ok := entries["word/vbaProject.bin"]; ok {
t.Error("plain docx grew a vbaProject during conversion")
}
if ctypes := entries[contentTypesPath]; !strings.Contains(ctypes, docxMainContentType) {
t.Errorf("plain docx lost its content type: %q", ctypes)
}
}
func TestConvertDotmToDocx_AcceptsDocmAndDotx(t *testing.T) {
for _, mainType := range []string{docmMainContentType, dotxMainContentType} {
t.Run(mainType, func(t *testing.T) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
add := func(name, body string) {
w, _ := zw.Create(name)
_, _ = io.WriteString(w, body)
}
for i := range got {
if got[i] != tc.matches[i] {
t.Errorf("match %d: got %q, want %q", i, got[i], tc.matches[i])
}
add(contentTypesPath, `<?xml version="1.0"?>`+
`<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">`+
`<Override PartName="/word/document.xml" ContentType="`+mainType+`"/>`+
`</Types>`)
add("word/document.xml", `<w:document/>`)
zw.Close()
out, err := ConvertDotmToDocx(buf.Bytes())
if err != nil {
t.Fatalf("ConvertDotmToDocx: %v", err)
}
ctypes := unzipEntries(t, out)[contentTypesPath]
if strings.Contains(ctypes, mainType) {
t.Errorf("non-docx main type survived conversion: %q", ctypes)
}
if !strings.Contains(ctypes, docxMainContentType) {
t.Errorf("docx main type not present: %q", ctypes)
}
})
}
}
// TestFamilyOf covers the proceeding-family extraction used by the
// template registry's fallback chain.
func TestFamilyOf(t *testing.T) {
tests := map[string]string{
"de.inf.lg.erwidg": "de.inf.lg",
"upc.inf.cfi.soc": "upc.inf.cfi",
"dpma.opp.dpma": "", // only three segments → no family
"de.inf.lg": "",
"": "",
func TestConvertDotmToDocx_RejectsNonZip(t *testing.T) {
_, err := ConvertDotmToDocx([]byte("not a zip file"))
if err == nil {
t.Fatal("expected error for non-zip input, got nil")
}
for in, want := range tests {
}
func TestSanitiseSubmissionFileName(t *testing.T) {
cases := map[string]string{
"Klageerwiderung": "Klageerwiderung",
"Berufungsbegründung": "Berufungsbegruendung",
"Schriftsatz/Anlage": "Schriftsatz_Anlage",
`Statement of "Defence"`: "Statement of Defence",
` Klage `: "Klage",
"Größe": "Groesse",
}
for in, want := range cases {
t.Run(in, func(t *testing.T) {
got := familyOf(in)
if got != want {
t.Errorf("familyOf(%q) = %q, want %q", in, got, want)
}
})
}
}
// TestLegalSourcePretty covers the prefix table.
func TestLegalSourcePretty(t *testing.T) {
tests := []struct {
src, lang, want string
}{
{"DE.ZPO.276.1", "de", "§ 276 Abs. 1 ZPO"},
{"DE.ZPO.276.1", "en", "Section 276(1) ZPO"},
{"DE.ZPO.253", "de", "§ 253 ZPO"},
{"DE.ZPO.253", "en", "Section 253 ZPO"},
{"UPC.RoP.23.1", "de", "Regel 23.1 VerfO UPC"},
{"UPC.RoP.23.1", "en", "Rule 23.1 RoP UPC"},
{"UPC.RoP.198", "de", "Regel 198 VerfO UPC"},
{"DE.PatG.83", "de", "§ 83 PatG"},
{"EPC.123", "de", "Art. 123 EPÜ"},
{"EPC.123", "en", "Art. 123 EPC"},
// Unknown prefix → pass-through unchanged.
{"FOO.BAR.123", "de", "FOO.BAR.123"},
{"", "de", ""},
}
for _, tc := range tests {
t.Run(tc.src+"/"+tc.lang, func(t *testing.T) {
got := legalSourcePretty(tc.src, tc.lang)
if got != tc.want {
t.Errorf("legalSourcePretty(%q, %q) = %q, want %q", tc.src, tc.lang, got, tc.want)
}
})
}
}
// TestOurSideTranslations pins the our_side enum → DE/EN prose
// mapping used by addProjectVars. Post t-paliad-222: seven sub-role
// values + the gender-neutral "-Seite" / "-Partei" suffix shape on
// DE. Legacy 'court' / 'both' yield "" (the column no longer accepts
// them after mig 112, but the function defensively handles stale
// in-memory values from older callers).
func TestOurSideTranslations(t *testing.T) {
cases := []struct {
in, wantDE, wantEN string
}{
{"claimant", "Klägerseite", "Claimant"},
{"defendant", "Beklagtenseite", "Defendant"},
{"applicant", "Antragstellerseite", "Applicant"},
{"appellant", "Berufungsklägerseite", "Appellant"},
{"respondent", "Antragsgegnerseite", "Respondent"},
{"third_party", "Drittpartei", "Third Party"},
{"other", "sonstige Verfahrensbeteiligte", "other party"},
{"court", "", ""},
{"both", "", ""},
{"", "", ""},
{"unknown", "", ""},
}
for _, tc := range cases {
t.Run(tc.in, func(t *testing.T) {
if got := ourSideDE(tc.in); got != tc.wantDE {
t.Errorf("ourSideDE(%q) = %q, want %q", tc.in, got, tc.wantDE)
}
if got := ourSideEN(tc.in); got != tc.wantEN {
t.Errorf("ourSideEN(%q) = %q, want %q", tc.in, got, tc.wantEN)
}
})
}
}
// TestTemplateRegistry_Candidates verifies the fallback-chain order
// matches the m-locked Q4 decision (firm → base/code → base/family →
// skeleton).
func TestTemplateRegistry_Candidates(t *testing.T) {
r := NewTemplateRegistry("", "HLC")
got := r.candidates("de.inf.lg.erwidg")
want := []string{
"templates/HLC/de.inf.lg.erwidg.docx",
"templates/_base/de.inf.lg.erwidg.docx",
"templates/_base/de.inf.lg.docx",
"templates/_base/_skeleton.docx",
}
if len(got) != len(want) {
t.Fatalf("candidates = %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Errorf("candidate[%d] = %q, want %q", i, got[i], want[i])
}
}
}
// TestTemplateRegistry_Candidates_NoFamily covers submission codes
// without a family suffix (only three dot-segments).
func TestTemplateRegistry_Candidates_NoFamily(t *testing.T) {
r := NewTemplateRegistry("", "HLC")
got := r.candidates("dpma.opp.dpma")
want := []string{
"templates/HLC/dpma.opp.dpma.docx",
"templates/_base/dpma.opp.dpma.docx",
"templates/_base/_skeleton.docx",
}
if len(got) != len(want) {
t.Fatalf("candidates = %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Errorf("candidate[%d] = %q, want %q", i, got[i], want[i])
}
}
}
// TestTemplateRegistry_Tiers labels each candidate slot. Must stay
// 1:1 with candidates().
func TestTemplateRegistry_Tiers(t *testing.T) {
r := NewTemplateRegistry("", "HLC")
codes := []string{"de.inf.lg.erwidg", "dpma.opp.dpma"}
for _, code := range codes {
c := r.candidates(code)
ts := r.tiers(code)
if len(c) != len(ts) {
t.Fatalf("candidate/tier mismatch for %q: %d vs %d", code, len(c), len(ts))
}
}
}
// TestPatentNumberUPC covers the kind-code parenthesisation that UPC
// briefs use (t-paliad-215 Slice 2, design §22 Q-S2-4).
func TestPatentNumberUPC(t *testing.T) {
tests := []struct {
in, want string
}{
// EP variants — the common case.
{"EP 1 234 567 B1", "EP 1 234 567 (B1)"},
{"EP 4 056 049 A1", "EP 4 056 049 (A1)"},
// DE national number with kind code.
{"DE 10 2020 123 456 A1", "DE 10 2020 123 456 (A1)"},
// No kind code → pass-through unchanged.
{"EP 1 234 567", "EP 1 234 567"},
// Leading + trailing whitespace trimmed.
{" EP 1 234 567 B1 ", "EP 1 234 567 (B1)"},
// Empty input.
{"", ""},
// Slash-separated forms (WO publication numbers) don't match
// the kind-code shape → pass through.
{"WO/2023/123456", "WO/2023/123456"},
// Two-digit kind code (e.g. B12) doesn't match the single-digit
// pattern; pass through. This is intentional — real EP kind
// codes are single-letter + single-digit.
{"EP 1 234 567 B12", "EP 1 234 567 B12"},
}
for _, tc := range tests {
t.Run(tc.in, func(t *testing.T) {
got := patentNumberUPC(tc.in)
if got != tc.want {
t.Errorf("patentNumberUPC(%q) = %q, want %q", tc.in, got, tc.want)
if got := SanitiseSubmissionFileName(in); got != want {
t.Errorf("SanitiseSubmissionFileName(%q) = %q, want %q", in, got, want)
}
})
}

View File

@@ -1,442 +0,0 @@
package services
// Submission template registry — Gitea-backed .docx template loader for
// the submission generator (t-paliad-215, design doc
// docs/design-submission-generator-2026-05-19.md §5).
//
// Layout in mWorkRepo:
//
// templates/{FIRM_NAME}/{submission_code}.docx firm-specific override
// templates/_base/{submission_code}.docx cross-firm baseline
// templates/_base/{family}.docx proceeding-family fallback
// templates/_base/_skeleton.docx ultra-generic fallback
//
// Lookup is first-match-wins down the chain; this is the m-locked Q4
// decision. Templates fetched via Gitea's raw URL endpoint, cached
// in-process with a 5-minute SHA refresh check — identical pattern to
// the HL Patents Style proxy in internal/handlers/files.go (which the
// design doc §1 verified is in production and works).
//
// Slice 1 ships one template at templates/_base/de.inf.lg.erwidg.docx
// (committed to HL/mWorkRepo at SHA 7f97b7f9, the bootstrap demo
// authored by the engine for end-to-end testing — HLC ships the
// polished version per §14 follow-up).
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"net/http"
"net/url"
"strings"
"sync"
"time"
)
const (
templatesGiteaBaseURL = "https://mgit.msbls.de"
templatesGiteaRepoOwn = "HL"
templatesGiteaRepoName = "mWorkRepo"
templatesGiteaBranch = "main"
templatesCheckInterval = 5 * time.Minute
templatesSkeleton = "_skeleton"
)
// ErrNoTemplate is returned when no template resolves anywhere in the
// fallback chain (firm/code → base/code → base/family → skeleton).
// Caller maps to 503 + a clear UI hint.
var ErrNoTemplate = errors.New("submission template: no template resolved in fallback chain")
// ErrTemplateUpstream wraps Gitea-side failures (network, 5xx).
// Distinct from ErrNoTemplate so the handler can render different UI:
// "no template configured" vs "template repo unreachable".
var ErrTemplateUpstream = errors.New("submission template: upstream Gitea unreachable")
// ResolvedTemplate is the result of a fallback-chain lookup: the
// template bytes plus the metadata the audit row + UI need.
type ResolvedTemplate struct {
// Path is the Gitea-relative path that resolved (e.g.
// "templates/HLC/de.inf.lg.erwidg.docx"). Persisted in the
// system_audit_log row so an admin can trace which template was
// used for a given generation.
Path string
// SHA is the commit SHA the template was fetched at. Pinning this
// lets audit consumers reproduce the exact bytes that went into
// the lawyer's download.
SHA string
// FirmTier reports which level of the fallback chain fired:
// "firm", "base_code", "base_family", or "skeleton". Useful for
// the variable-contract sidebar (Slice 3) and for ops monitoring
// of how often each firm is actually overriding.
FirmTier string
// Bytes is the .docx content; only populated for callers that
// need to render (i.e. SubmissionRenderer.Render). Resolve()
// returns it populated; Probe() leaves it nil.
Bytes []byte
}
// templateCacheEntry mirrors the per-file cache shape used by
// internal/handlers/files.go. Each cached entry tracks its bytes, the
// commit SHA, the last upstream check, and a checking flag so two
// concurrent refresh goroutines don't double-fetch.
type templateCacheEntry struct {
mu sync.RWMutex
data []byte
sha string
lastChecked time.Time
checking bool
missing bool // true when Gitea returned 404 — short-circuits subsequent lookups
}
// TemplateRegistry resolves submission templates from Gitea using the
// fallback chain. Process-wide cache; single-replica deployment (per
// docs/design-submission-generator-2026-05-19.md §1) makes in-process
// caching sufficient — a future multi-replica rollout would swap this
// for a shared cache. Same trade-off the HL Patents Style proxy makes.
type TemplateRegistry struct {
cache map[string]*templateCacheEntry
cacheMu sync.Mutex
giteaToken string
httpClient *http.Client
firmName string
}
// NewTemplateRegistry constructs the registry. firmName is read once
// at process start from internal/branding.Name so a runtime FIRM_NAME
// rebrand cuts in on the next deploy, not mid-request.
func NewTemplateRegistry(giteaToken, firmName string) *TemplateRegistry {
return &TemplateRegistry{
cache: make(map[string]*templateCacheEntry),
giteaToken: giteaToken,
firmName: firmName,
httpClient: &http.Client{Timeout: 30 * time.Second},
}
}
// HasTemplate reports whether any template resolves for the given
// submission code, without fetching the bytes. Used by the
// SubmissionsPanel to decide which "Generate" buttons to enable.
//
// Cheap path: walks the same fallback chain as Resolve, but stops at
// the SHA-probe step (Gitea's contents endpoint, single round-trip per
// candidate). The probe results land in the same cache as Resolve so a
// subsequent Resolve call reuses the SHA.
func (r *TemplateRegistry) HasTemplate(ctx context.Context, submissionCode string) bool {
for _, candidate := range r.candidates(submissionCode) {
if r.probe(ctx, candidate) {
return true
}
}
return false
}
// Resolve walks the fallback chain and returns the first template that
// fetches successfully, with bytes loaded. Returns ErrNoTemplate when
// no candidate (including the ultra-generic skeleton) resolves.
func (r *TemplateRegistry) Resolve(ctx context.Context, submissionCode string) (*ResolvedTemplate, error) {
candidates := r.candidates(submissionCode)
tiers := r.tiers(submissionCode)
if len(candidates) != len(tiers) {
return nil, fmt.Errorf("template registry: candidate/tier mismatch (%d vs %d)", len(candidates), len(tiers))
}
for i, candidate := range candidates {
entry := r.cacheGet(candidate)
entry.mu.RLock()
hasData := !entry.missing && len(entry.data) > 0
needsCheck := time.Since(entry.lastChecked) >= templatesCheckInterval
isMissing := entry.missing
entry.mu.RUnlock()
if isMissing && !needsCheck {
continue
}
if !hasData {
if err := r.fetchInto(ctx, candidate, entry); err != nil {
if errors.Is(err, errTemplate404) {
continue
}
return nil, fmt.Errorf("%w: %v", ErrTemplateUpstream, err)
}
} else if needsCheck {
go r.refresh(context.Background(), candidate, entry)
}
entry.mu.RLock()
out := &ResolvedTemplate{
Path: candidate,
SHA: entry.sha,
FirmTier: tiers[i],
Bytes: append([]byte(nil), entry.data...),
}
entry.mu.RUnlock()
return out, nil
}
return nil, ErrNoTemplate
}
// candidates returns the ordered Gitea-relative paths the registry
// walks for the given submission code. The order is the m-locked Q4
// decision: firm → base/code → base/family → skeleton.
func (r *TemplateRegistry) candidates(submissionCode string) []string {
family := familyOf(submissionCode)
out := []string{
fmt.Sprintf("templates/%s/%s.docx", r.firmName, submissionCode),
fmt.Sprintf("templates/_base/%s.docx", submissionCode),
}
if family != "" && family != submissionCode {
out = append(out, fmt.Sprintf("templates/_base/%s.docx", family))
}
out = append(out, fmt.Sprintf("templates/_base/%s.docx", templatesSkeleton))
return out
}
// tiers labels each candidate with its fallback tier. Order is locked
// to candidates(); both functions evolve together.
func (r *TemplateRegistry) tiers(submissionCode string) []string {
family := familyOf(submissionCode)
out := []string{"firm", "base_code"}
if family != "" && family != submissionCode {
out = append(out, "base_family")
}
out = append(out, "skeleton")
return out
}
// familyOf extracts the proceeding-family prefix from a submission
// code. The convention (docs/design-proceeding-code-taxonomy-2026-05-18.md)
// is jurisdiction.substantive.forum.submission, so the family is the
// first three dot-segments.
//
// de.inf.lg.erwidg → de.inf.lg
// upc.inf.cfi.soc → upc.inf.cfi
// dpma.opp.dpma → "" (only three segments — no submission suffix)
//
// Returns "" when the code doesn't carry a submission segment (no
// family-level fallback is meaningful).
func familyOf(submissionCode string) string {
parts := strings.Split(submissionCode, ".")
if len(parts) < 4 {
return ""
}
return strings.Join(parts[:3], ".")
}
// cacheGet returns the cache entry for a Gitea path, creating an empty
// entry on first lookup.
func (r *TemplateRegistry) cacheGet(path string) *templateCacheEntry {
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
entry, ok := r.cache[path]
if !ok {
entry = &templateCacheEntry{}
r.cache[path] = entry
}
return entry
}
// errTemplate404 is an internal sentinel: candidate doesn't exist in
// Gitea, walk the chain. Distinguished from network/5xx errors so the
// registry doesn't wrap every fallback miss as ErrTemplateUpstream.
var errTemplate404 = errors.New("template not found in gitea")
// fetchInto downloads a candidate and populates the cache entry. On
// 404 it marks the entry missing so subsequent lookups short-circuit
// without hitting the network.
func (r *TemplateRegistry) fetchInto(ctx context.Context, path string, entry *templateCacheEntry) error {
sha, err := r.giteaSHA(ctx, path)
if err != nil {
if errors.Is(err, errTemplate404) {
entry.mu.Lock()
entry.missing = true
entry.lastChecked = time.Now()
entry.mu.Unlock()
}
return err
}
data, err := r.giteaDownload(ctx, path)
if err != nil {
return err
}
entry.mu.Lock()
entry.data = data
entry.sha = sha
entry.lastChecked = time.Now()
entry.missing = false
entry.mu.Unlock()
return nil
}
// refresh runs in the background after a stale-but-present cache hit.
// SHA-checks the candidate; re-downloads on change. Mirrors the same
// goroutine pattern as internal/handlers/files.go.
func (r *TemplateRegistry) refresh(ctx context.Context, path string, entry *templateCacheEntry) {
entry.mu.Lock()
if entry.checking {
entry.mu.Unlock()
return
}
entry.checking = true
entry.mu.Unlock()
defer func() {
entry.mu.Lock()
entry.checking = false
entry.mu.Unlock()
}()
latestSHA, err := r.giteaSHA(ctx, path)
if err != nil {
log.Printf("submission template: SHA check for %s failed: %v", path, err)
entry.mu.Lock()
entry.lastChecked = time.Now()
entry.mu.Unlock()
return
}
entry.mu.RLock()
unchanged := latestSHA == entry.sha && entry.sha != ""
entry.mu.RUnlock()
if unchanged {
entry.mu.Lock()
entry.lastChecked = time.Now()
entry.mu.Unlock()
return
}
data, err := r.giteaDownload(ctx, path)
if err != nil {
log.Printf("submission template: download %s failed: %v", path, err)
entry.mu.Lock()
entry.lastChecked = time.Now()
entry.mu.Unlock()
return
}
entry.mu.Lock()
entry.data = data
entry.sha = latestSHA
entry.lastChecked = time.Now()
entry.mu.Unlock()
log.Printf("submission template: updated %s (SHA: %.8s)", path, latestSHA)
}
// probe is the cheap existence-check used by HasTemplate. Reuses the
// cache but only fetches the SHA (not the bytes), so the
// SubmissionsPanel's per-row HasTemplate calls don't pull a megabyte
// of .docx data the user might never download.
func (r *TemplateRegistry) probe(ctx context.Context, path string) bool {
entry := r.cacheGet(path)
entry.mu.RLock()
hasData := !entry.missing && len(entry.data) > 0
hasSHA := !entry.missing && entry.sha != ""
isMissing := entry.missing
needsCheck := time.Since(entry.lastChecked) >= templatesCheckInterval
entry.mu.RUnlock()
if isMissing && !needsCheck {
return false
}
if hasData || hasSHA {
return true
}
sha, err := r.giteaSHA(ctx, path)
if err != nil {
if errors.Is(err, errTemplate404) {
entry.mu.Lock()
entry.missing = true
entry.lastChecked = time.Now()
entry.mu.Unlock()
}
return false
}
entry.mu.Lock()
entry.sha = sha
entry.lastChecked = time.Now()
entry.missing = false
entry.mu.Unlock()
return true
}
// giteaSHA returns the SHA of the latest commit that touched the
// template path. Returns errTemplate404 when Gitea responds with 404 —
// the registry distinguishes "no such template" from "Gitea is down".
func (r *TemplateRegistry) giteaSHA(ctx context.Context, path string) (string, error) {
apiURL := fmt.Sprintf("%s/api/v1/repos/%s/%s/commits?path=%s&limit=1&sha=%s",
templatesGiteaBaseURL,
templatesGiteaRepoOwn,
templatesGiteaRepoName,
url.QueryEscape(path),
templatesGiteaBranch,
)
req, err := http.NewRequestWithContext(ctx, "GET", apiURL, nil)
if err != nil {
return "", err
}
if r.giteaToken != "" {
req.Header.Set("Authorization", "token "+r.giteaToken)
}
resp, err := r.httpClient.Do(req)
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return "", errTemplate404
}
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("gitea sha lookup returned %d", resp.StatusCode)
}
var commits []struct {
SHA string `json:"sha"`
}
if err := json.NewDecoder(resp.Body).Decode(&commits); err != nil {
return "", err
}
if len(commits) == 0 {
return "", errTemplate404
}
return commits[0].SHA, nil
}
// giteaDownload fetches the raw template bytes.
func (r *TemplateRegistry) giteaDownload(ctx context.Context, path string) ([]byte, error) {
rawURL := fmt.Sprintf("%s/%s/%s/raw/branch/%s/%s",
templatesGiteaBaseURL,
templatesGiteaRepoOwn,
templatesGiteaRepoName,
templatesGiteaBranch,
path,
)
req, err := http.NewRequestWithContext(ctx, "GET", rawURL, nil)
if err != nil {
return nil, err
}
if r.giteaToken != "" {
req.Header.Set("Authorization", "token "+r.giteaToken)
}
resp, err := r.httpClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusNotFound {
return nil, errTemplate404
}
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("gitea raw returned %d", resp.StatusCode)
}
return io.ReadAll(resp.Body)
}
// ClearCache drops every cached entry. Exposed for an admin-side
// "refresh templates" affordance — paliad's existing /api/files/refresh
// has the same shape for the HL Patents Style proxy.
func (r *TemplateRegistry) ClearCache() {
r.cacheMu.Lock()
defer r.cacheMu.Unlock()
for k := range r.cache {
r.cache[k] = &templateCacheEntry{}
}
}

View File

@@ -57,9 +57,13 @@ func NewSubmissionVarsService(db *sqlx.DB, projects *ProjectService, parties *Pa
}
// SubmissionVarsContext is the input bundle that produces a render.
//
// ProjectID is optional since t-paliad-243 — a global Schriftsatz draft
// started from /submissions/new without picking a project carries
// nil here and the project / parties / deadline lookups are skipped.
type SubmissionVarsContext struct {
UserID uuid.UUID
ProjectID uuid.UUID
ProjectID *uuid.UUID
SubmissionCode string
}
@@ -87,7 +91,11 @@ type SubmissionVarsResult struct {
// matches the requested submission_code. Maps to 404 in the handler.
var ErrSubmissionRuleNotFound = errors.New("submission generator: no rule found for submission_code")
// Build resolves every entity and assembles the placeholder map.
// Build resolves every entity and assembles the placeholder map. A nil
// ProjectID skips project / parties / deadline lookups — the resolved
// bag carries only firm.*, today.*, user.* and rule.* in that case;
// every other placeholder falls through to the lawyer's overrides via
// SubmissionDraftService.BuildRenderBag.
func (s *SubmissionVarsService) Build(ctx context.Context, in SubmissionVarsContext) (*SubmissionVarsResult, error) {
if s.projects == nil || s.users == nil {
return nil, fmt.Errorf("submission vars: required services not wired")
@@ -101,34 +109,11 @@ func (s *SubmissionVarsService) Build(ctx context.Context, in SubmissionVarsCont
return nil, ErrNotVisible
}
// Visibility gate — GetByID returns ErrNotFound when the user
// can't see the project, which is exactly the 404 the handler
// wants to propagate.
project, err := s.projects.GetByID(ctx, in.UserID, in.ProjectID)
if err != nil {
return nil, err
}
rule, err := s.loadPublishedRule(ctx, in.SubmissionCode)
if err != nil {
return nil, err
}
pt, err := s.loadProceedingType(ctx, project.ProceedingTypeID)
if err != nil {
return nil, err
}
parties, err := s.parties.ListForProject(ctx, in.UserID, in.ProjectID)
if err != nil {
return nil, err
}
next, err := s.nextOpenDeadline(ctx, in.ProjectID, rule.ID)
if err != nil {
return nil, err
}
lang := user.Lang
if lang == "" {
lang = "de"
@@ -137,21 +122,55 @@ func (s *SubmissionVarsService) Build(ctx context.Context, in SubmissionVarsCont
addFirmVars(bag)
addTodayVars(bag, time.Now())
addUserVars(bag, user)
addRuleVars(bag, rule, lang)
out := &SubmissionVarsResult{
Placeholders: bag,
User: user,
Rule: rule,
Lang: lang,
}
if in.ProjectID == nil {
// Project-less draft (t-paliad-243): no project / parties /
// deadline state to resolve. The lawyer's overrides will fill
// the placeholder map; missing keys render as
// [KEIN WERT: …] / [NO VALUE: …] in the preview.
return out, nil
}
// Visibility gate — GetByID returns ErrNotFound when the user
// can't see the project, which is exactly the 404 the handler
// wants to propagate.
project, err := s.projects.GetByID(ctx, in.UserID, *in.ProjectID)
if err != nil {
return nil, err
}
pt, err := s.loadProceedingType(ctx, project.ProceedingTypeID)
if err != nil {
return nil, err
}
parties, err := s.parties.ListForProject(ctx, in.UserID, *in.ProjectID)
if err != nil {
return nil, err
}
next, err := s.nextOpenDeadline(ctx, *in.ProjectID, rule.ID)
if err != nil {
return nil, err
}
addProjectVars(bag, project, pt, lang)
addPartyVars(bag, parties)
addRuleVars(bag, rule, lang)
addDeadlineVars(bag, next, project, lang)
return &SubmissionVarsResult{
Placeholders: bag,
User: user,
Project: project,
Rule: rule,
ProceedingType: pt,
Parties: parties,
NextDeadline: next,
Lang: lang,
}, nil
out.Project = project
out.ProceedingType = pt
out.Parties = parties
out.NextDeadline = next
return out, nil
}
// loadPublishedRule fetches the deadline_rule that owns the given
@@ -262,11 +281,6 @@ func addUserVars(bag PlaceholderMap, u *models.User) {
func addProjectVars(bag PlaceholderMap, p *models.Project, pt *models.ProceedingType, lang string) {
bag["project.title"] = p.Title
bag["project.reference"] = derefString(p.Reference)
// project.code is the auto-derived (or override) dotted project
// code computed by services.BuildProjectCode. Populated upstream
// by the service projection; templates that want the explicit
// override should read project.reference instead.
bag["project.code"] = p.Code
bag["project.case_number"] = derefString(p.CaseNumber)
bag["project.court"] = derefString(p.Court)
bag["project.patent_number"] = derefString(p.PatentNumber)
@@ -393,29 +407,16 @@ func formatDatePtr(t *time.Time, layout string) string {
}
// ourSideDE returns the German legal-prose form of an our_side value.
//
// t-paliad-222: unified on the gender-neutral "-Seite" / "-Partei"
// suffix shape to match the form labels and to avoid implying the
// firm represents a single (female) natural person — a B2B patent
// practice almost always represents companies. The seven sub-roles
// map onto the post-mig-110 schema; legacy 'court' / 'both' no
// longer exist in the column.
func ourSideDE(side string) string {
switch strings.ToLower(side) {
case "claimant":
return "Klägerseite"
return "Klägerin"
case "defendant":
return "Beklagtenseite"
case "applicant":
return "Antragstellerseite"
case "appellant":
return "Berufungsklägerseite"
case "respondent":
return "Antragsgegnerseite"
case "third_party":
return "Drittpartei"
case "other":
return "sonstige Verfahrensbeteiligte"
return "Beklagte"
case "court":
return "Gericht"
case "both":
return "Klägerin und Beklagte"
}
return ""
}
@@ -427,16 +428,10 @@ func ourSideEN(side string) string {
return "Claimant"
case "defendant":
return "Defendant"
case "applicant":
return "Applicant"
case "appellant":
return "Appellant"
case "respondent":
return "Respondent"
case "third_party":
return "Third Party"
case "other":
return "other party"
case "court":
return "Court"
case "both":
return "Claimant and Defendant"
}
return ""
}

View File

@@ -0,0 +1,346 @@
// Demo submission template generator (t-paliad-241).
//
// One-shot authoring tool that emits a minimal but Word-compatible
// .docx file exercising every placeholder SubmissionVarsService
// resolves. Drop the output into m/mWorkRepo at
//
// 6 - material/Templates/Word/Paliad/HLC/de.inf.lg.erwidg.docx
//
// so paliad's submission-draft editor (t-paliad-238 Slice A) can fetch
// it via the per-submission_code fallback chain wired into
// handlers/files.go. The structure is a fake Klageerwiderung skeleton
// in German — fake legal prose, real placeholder tokens.
//
// Why a generator instead of authoring in Word: the per-placeholder
// docx grammar is `{{[A-Za-z][A-Za-z0-9_.]*}}` and Word's autocorrect
// happily fragments such tokens across <w:r> runs ({{ → "{", "{",
// project.case_number, "}", "}"). A programmatic emitter writes each
// placeholder as a single run so the renderer's pass-1 substitution
// (format-preserving) catches it cleanly. The merge engine handles
// cross-run cases too (pass 2) but pass 1 is the cheaper path.
//
// Run:
//
// go run ./scripts/gen-demo-submission-template -out /tmp/de.inf.lg.erwidg.docx
//
// Output is deterministic so re-generating to the same path produces a
// byte-identical file (modulo zip mtime — we pin those to a fixed UTC
// timestamp so the bytes are reproducible).
package main
import (
"archive/zip"
"bytes"
"flag"
"fmt"
"os"
"strings"
"time"
)
func main() {
out := flag.String("out", "de.inf.lg.erwidg.docx", "output .docx path")
flag.Parse()
docx, err := buildDocx()
if err != nil {
fmt.Fprintln(os.Stderr, "gen-demo-submission-template:", err)
os.Exit(1)
}
if err := os.WriteFile(*out, docx, 0o644); err != nil {
fmt.Fprintln(os.Stderr, "gen-demo-submission-template: write:", err)
os.Exit(1)
}
fmt.Printf("wrote %s (%d bytes)\n", *out, len(docx))
}
// fixedTime is the zip mtime stamp baked into every entry so the output
// is byte-reproducible.
var fixedTime = time.Date(2026, 5, 23, 0, 0, 0, 0, time.UTC)
// buildDocx assembles the four-part .docx zip Word needs to open the
// file cleanly: Content_Types, root rels, document.xml, and document
// rels. Everything else (styles, theme, fonts) is optional — Word
// supplies sane defaults when absent.
func buildDocx() ([]byte, error) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
add := func(name, body string) error {
hdr := &zip.FileHeader{
Name: name,
Method: zip.Deflate,
Modified: fixedTime,
}
w, err := zw.CreateHeader(hdr)
if err != nil {
return fmt.Errorf("create %s: %w", name, err)
}
if _, err := w.Write([]byte(body)); err != nil {
return fmt.Errorf("write %s: %w", name, err)
}
return nil
}
if err := add("[Content_Types].xml", contentTypesXML); err != nil {
return nil, err
}
if err := add("_rels/.rels", rootRelsXML); err != nil {
return nil, err
}
if err := add("word/_rels/document.xml.rels", documentRelsXML); err != nil {
return nil, err
}
if err := add("word/styles.xml", stylesXML); err != nil {
return nil, err
}
if err := add("word/document.xml", buildDocumentXML()); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("finalise zip: %w", err)
}
return buf.Bytes(), nil
}
const contentTypesXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>`
const rootRelsXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`
const documentRelsXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>`
// stylesXML provides minimal Heading1 + Heading2 paragraph styles so
// the section headings render with visual weight. Body text falls
// through to Word's Normal style.
const stylesXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/>
<w:basedOn w:val="Normal"/>
<w:pPr><w:spacing w:before="360" w:after="120"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="28"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading2">
<w:name w:val="heading 2"/>
<w:basedOn w:val="Normal"/>
<w:pPr><w:spacing w:before="240" w:after="80"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="24"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal">
<w:name w:val="Normal"/>
</w:style>
</w:styles>`
// Document body — a fake Klageerwiderung skeleton with every placeholder
// SubmissionVarsService resolves embedded in natural positions. Each
// placeholder is in its own run so pass-1 substitution catches it without
// fragmentation worries. The DEMO marker in the header makes it obvious
// this is not approved firm content.
//
// Structure mirrors a real submission:
//
// 1. Firm letterhead + author block (firm.*, user.*, today.*)
// 2. Court caption (project.*, project.proceeding.*)
// 3. Parties block (parties.*)
// 4. Submission title + legal source (rule.*)
// 5. Deadline (deadline.*)
// 6. Boilerplate body + signature
//
// Order matches what a lawyer drafting a real Klageerwiderung would put
// at the top of the document, so when the lawyer customises this
// template later they don't have to restructure.
func buildDocumentXML() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`)
b.WriteString(`<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
b.WriteString(`<w:body>`)
demoBanner(&b)
heading1(&b, "{{firm.name}} — Patentstreitsachen")
plain(&b, "Bearbeiter: {{user.display_name}}")
plain(&b, "E-Mail: {{user.email}} · Büro: {{user.office}}")
plain(&b, "Datum: {{today.long_de}} ({{today.iso}})")
heading1(&b, "{{project.court}}")
plain(&b, "Aktenzeichen: {{project.case_number}}")
plain(&b, "Verfahrensart: {{project.proceeding.name}} ({{project.proceeding.code}})")
plain(&b, "Instanz: {{project.instance_level}}")
heading2(&b, "In der Patentstreitsache")
plain(&b, "{{parties.claimant.name}}")
plain(&b, "vertreten durch {{parties.claimant.representative}}")
bold(&b, "— Klägerin —")
plain(&b, "")
plain(&b, "gegen")
plain(&b, "")
plain(&b, "{{parties.defendant.name}}")
plain(&b, "vertreten durch {{parties.defendant.representative}}")
bold(&b, "— Beklagte —")
plainOptional(&b, "Weitere Beteiligte: {{parties.other.name}}, vertreten durch {{parties.other.representative}}")
heading2(&b, "Betreff")
plain(&b, "Streitpatent: {{project.patent_number}} (UPC: {{project.patent_number_upc}})")
plain(&b, "Anmeldung: {{project.filing_date}} · Erteilung: {{project.grant_date}}")
plain(&b, "Projekttitel: {{project.title}}")
plain(&b, "Unsere Seite: {{project.our_side_de}} ({{project.our_side}})")
plain(&b, "Mandant: {{project.client_number}} · Matter: {{project.matter_number}}")
plain(&b, "Internes Aktenzeichen: {{project.reference}}")
heading1(&b, "{{rule.name}}")
plain(&b, "(Schriftsatz-Code: {{rule.submission_code}})")
plain(&b, "Rechtsgrundlage: {{rule.legal_source_pretty}} ({{rule.legal_source}})")
plain(&b, "Typische Partei: {{rule.primary_party}} · Schriftsatz-Typ: {{rule.event_type}}")
heading2(&b, "Frist")
plain(&b, "Diese Frist wurde berechnet aus: {{deadline.computed_from}}")
plain(&b, "Fälligkeit: {{deadline.due_date_long_de}} ({{deadline.due_date}})")
plainOptional(&b, "Ursprüngliche Frist: {{deadline.original_due_date}}")
plain(&b, "Frist-Bezeichnung: {{deadline.title}} · Quelle: {{deadline.source}}")
heading2(&b, "I. Anträge")
plain(&b, "Die Beklagte beantragt,")
plain(&b, "")
plain(&b, "1. die Klage abzuweisen;")
plain(&b, "2. der Klägerin die Kosten des Rechtsstreits aufzuerlegen.")
heading2(&b, "II. Sachverhalt")
plain(&b, "[DEMO-Platzhalter] Hier folgt der Sachvortrag der Beklagten zum Streitpatent {{project.patent_number}} und zu den von der Klägerin geltend gemachten Ansprüchen.")
heading2(&b, "III. Rechtsausführungen")
plain(&b, "[DEMO-Platzhalter] Die Beklagte tritt der Klage aus den nachfolgenden Gründen entgegen.")
heading2(&b, "Schlussformel")
plain(&b, "{{today.long_de}}")
plain(&b, "")
plain(&b, "{{user.display_name}}")
plain(&b, "{{firm.name}}")
plainOptional(&b, "{{firm.signature_block}}")
// English-locale exercise — lets the lawyer verify the EN long-form
// date and EN proceeding name resolve correctly when the user's
// preference is en. Also exercises the bare {{today}} alias
// (identical to {{today.iso}}; included so every key the variable
// bag carries appears at least once in this demo template).
heading2(&b, "Locale-aware variants (DEMO)")
plain(&b, "EN long date: {{today.long_en}} · Deadline EN: {{deadline.due_date_long_en}}")
plain(&b, "Project our side (EN): {{project.our_side_en}} · Proceeding (EN): {{project.proceeding.name_en}}")
plain(&b, "Rule name (EN): {{rule.name_en}} · Project our side (DE): {{project.our_side_de}}")
plain(&b, "Proceeding (DE): {{project.proceeding.name_de}} · Rule name (DE): {{rule.name_de}}")
plain(&b, "Today (bare alias): {{today}}")
b.WriteString(`</w:body></w:document>`)
return b.String()
}
// demoBanner writes a clearly-marked DEMO header so the file can't be
// mistaken for approved firm content (HLC branding compliance has not
// reviewed this — it's a developer-authored placeholder fixture).
func demoBanner(b *strings.Builder) {
b.WriteString(`<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t xml:space="preserve">DEMO — interne Vorlage (nicht freigegeben)</w:t></w:r></w:p>`)
}
// heading1 emits a styled "Heading 1" paragraph with placeholder runs
// emitted intact (one run per placeholder so pass-1 substitution works).
func heading1(b *strings.Builder, text string) { paragraph(b, "Heading1", text, false) }
// heading2 emits a "Heading 2" paragraph.
func heading2(b *strings.Builder, text string) { paragraph(b, "Heading2", text, false) }
// plain emits a Normal-style paragraph.
func plain(b *strings.Builder, text string) { paragraph(b, "", text, false) }
// plainOptional is a Normal paragraph rendered as italic so the lawyer
// recognises rows that contain placeholders which may be empty
// (parties.other.*, deadline.original_due_date, firm.signature_block).
// Visual cue only; the merge engine still substitutes the same way.
func plainOptional(b *strings.Builder, text string) { paragraph(b, "", text, true) }
// bold emits a Normal paragraph with bold run formatting.
func bold(b *strings.Builder, text string) {
b.WriteString(`<w:p>`)
b.WriteString(`<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">`)
b.WriteString(xmlEscape(text))
b.WriteString(`</w:t></w:r></w:p>`)
}
// paragraph splits text on placeholder boundaries and emits one <w:r>
// per segment. Each placeholder occupies a dedicated run so the
// renderer's pass-1 substitution (format-preserving, single-run) hits
// the placeholder without the cross-run fallback. Italic runs are
// flagged via the italic argument.
func paragraph(b *strings.Builder, style, text string, italic bool) {
b.WriteString(`<w:p>`)
if style != "" {
b.WriteString(`<w:pPr><w:pStyle w:val="`)
b.WriteString(style)
b.WriteString(`"/></w:pPr>`)
}
for _, seg := range splitOnPlaceholders(text) {
b.WriteString(`<w:r>`)
if italic {
b.WriteString(`<w:rPr><w:i/></w:rPr>`)
}
b.WriteString(`<w:t xml:space="preserve">`)
b.WriteString(xmlEscape(seg))
b.WriteString(`</w:t></w:r>`)
}
b.WriteString(`</w:p>`)
}
// splitOnPlaceholders returns the input split into alternating text /
// placeholder segments while keeping each placeholder intact in its own
// segment. Empty input yields a single empty segment so the paragraph
// still emits a (visible) blank line.
func splitOnPlaceholders(s string) []string {
if s == "" {
return []string{""}
}
var out []string
for {
open := strings.Index(s, "{{")
if open < 0 {
out = append(out, s)
return out
}
close := strings.Index(s[open:], "}}")
if close < 0 {
out = append(out, s)
return out
}
end := open + close + 2
if open > 0 {
out = append(out, s[:open])
}
out = append(out, s[open:end])
s = s[end:]
if s == "" {
return out
}
}
}
// xmlEscape handles the five XML-significant characters for <w:t>
// content. Whitespace is preserved by the xml:space="preserve" attr we
// always emit on text runs.
func xmlEscape(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, `"`, "&quot;")
s = strings.ReplaceAll(s, "'", "&apos;")
return s
}

View File

@@ -0,0 +1,303 @@
// Universal-skeleton submission template generator (t-paliad-259).
//
// One-shot authoring tool that emits a minimal but Word-compatible
// .docx file exercising every placeholder SubmissionVarsService
// resolves — without baking in any submission_code-specific prose.
//
// Drop the output into m/mWorkRepo at
//
// 6 - material/Templates/Word/Paliad/HLC/_skeleton.docx
//
// so paliad's submission generator picks it up via the fallback chain
// slotted between the per-submission_code template and the bare
// universal HL Patents Style .dotm. Any submission_code that has no
// per-firm template still gets a draft populated with variables
// instead of the macro-only letterhead.
//
// Why a separate file from de.inf.lg.erwidg.docx: that one is a
// Klageerwiderung skeleton (DE LG, "I. Anträge / II. Sachverhalt /
// III. Rechtsausführungen"). For a UPC SoC, an EPO opposition, a DPMA
// appeal, that body structure is wrong. The universal skeleton drops
// the structure and leaves a single neutral body block the lawyer
// replaces — every variable still resolves regardless of code.
//
// Run:
//
// go run ./scripts/gen-skeleton-submission-template -out /tmp/_skeleton.docx
//
// Output is byte-reproducible (zip mtimes pinned to a fixed UTC
// timestamp).
package main
import (
"archive/zip"
"bytes"
"flag"
"fmt"
"os"
"strings"
"time"
)
func main() {
out := flag.String("out", "_skeleton.docx", "output .docx path")
flag.Parse()
docx, err := buildDocx()
if err != nil {
fmt.Fprintln(os.Stderr, "gen-skeleton-submission-template:", err)
os.Exit(1)
}
if err := os.WriteFile(*out, docx, 0o644); err != nil {
fmt.Fprintln(os.Stderr, "gen-skeleton-submission-template: write:", err)
os.Exit(1)
}
fmt.Printf("wrote %s (%d bytes)\n", *out, len(docx))
}
var fixedTime = time.Date(2026, 5, 25, 0, 0, 0, 0, time.UTC)
func buildDocx() ([]byte, error) {
var buf bytes.Buffer
zw := zip.NewWriter(&buf)
add := func(name, body string) error {
hdr := &zip.FileHeader{
Name: name,
Method: zip.Deflate,
Modified: fixedTime,
}
w, err := zw.CreateHeader(hdr)
if err != nil {
return fmt.Errorf("create %s: %w", name, err)
}
if _, err := w.Write([]byte(body)); err != nil {
return fmt.Errorf("write %s: %w", name, err)
}
return nil
}
if err := add("[Content_Types].xml", contentTypesXML); err != nil {
return nil, err
}
if err := add("_rels/.rels", rootRelsXML); err != nil {
return nil, err
}
if err := add("word/_rels/document.xml.rels", documentRelsXML); err != nil {
return nil, err
}
if err := add("word/styles.xml", stylesXML); err != nil {
return nil, err
}
if err := add("word/document.xml", buildDocumentXML()); err != nil {
return nil, err
}
if err := zw.Close(); err != nil {
return nil, fmt.Errorf("finalise zip: %w", err)
}
return buf.Bytes(), nil
}
const contentTypesXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>`
const rootRelsXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`
const documentRelsXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
</Relationships>`
const stylesXML = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:style w:type="paragraph" w:styleId="Heading1">
<w:name w:val="heading 1"/>
<w:basedOn w:val="Normal"/>
<w:pPr><w:spacing w:before="360" w:after="120"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="28"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:styleId="Heading2">
<w:name w:val="heading 2"/>
<w:basedOn w:val="Normal"/>
<w:pPr><w:spacing w:before="240" w:after="80"/></w:pPr>
<w:rPr><w:b/><w:sz w:val="24"/></w:rPr>
</w:style>
<w:style w:type="paragraph" w:default="1" w:styleId="Normal">
<w:name w:val="Normal"/>
</w:style>
</w:styles>`
// Document body — a code-agnostic Schriftsatz skeleton: firm letterhead +
// case caption + parties + submission heading + deadline + a single
// neutral body block. Mirrors the variable bag from SubmissionVarsService
// (48 keys across firm.* / today.* / user.* / project.* / parties.* /
// rule.* / deadline.*) without baking in DE-LG-Klageerwiderung-specific
// structure. A lawyer customising this template for a UPC SoC, EPO
// opposition, or DPMA appeal replaces the [Schriftsatztext] block and
// renames the party labels — every placeholder still resolves regardless
// of the submission_code chosen.
//
// Every placeholder occupies its own <w:r> run so the renderer's pass-1
// (format-preserving, single-run) substitution catches it. The
// DEMO/SKELETON banner makes it obvious this is a starter template and
// not approved firm content.
func buildDocumentXML() string {
var b strings.Builder
b.WriteString(`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>`)
b.WriteString(`<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">`)
b.WriteString(`<w:body>`)
skeletonBanner(&b)
heading1(&b, "{{firm.name}}")
plain(&b, "Bearbeiter: {{user.display_name}}")
plain(&b, "E-Mail: {{user.email}} · Büro: {{user.office}}")
plain(&b, "Datum: {{today.long_de}} ({{today.iso}})")
plainOptional(&b, "{{firm.signature_block}}")
heading1(&b, "{{project.court}}")
plain(&b, "Aktenzeichen: {{project.case_number}}")
plain(&b, "Verfahrensart: {{project.proceeding.name}} ({{project.proceeding.code}})")
plain(&b, "Instanz: {{project.instance_level}}")
heading2(&b, "In der Sache")
plain(&b, "{{parties.claimant.name}}")
plain(&b, "vertreten durch {{parties.claimant.representative}}")
bold(&b, "— Klägerin / Patentinhaberin / Anmelderin —")
plain(&b, "")
plain(&b, "gegen")
plain(&b, "")
plain(&b, "{{parties.defendant.name}}")
plain(&b, "vertreten durch {{parties.defendant.representative}}")
bold(&b, "— Beklagte / Einsprechende / Beschwerdegegnerin —")
plainOptional(&b, "Weitere Beteiligte: {{parties.other.name}}, vertreten durch {{parties.other.representative}}")
heading2(&b, "Betreff")
plain(&b, "Streitpatent: {{project.patent_number}} (UPC: {{project.patent_number_upc}})")
plain(&b, "Anmeldung: {{project.filing_date}} · Erteilung: {{project.grant_date}}")
plain(&b, "Projekttitel: {{project.title}}")
plain(&b, "Unsere Seite: {{project.our_side_de}} ({{project.our_side}})")
plain(&b, "Mandant: {{project.client_number}} · Matter: {{project.matter_number}}")
plain(&b, "Internes Aktenzeichen: {{project.reference}}")
heading1(&b, "{{rule.name}}")
plain(&b, "(Schriftsatz-Code: {{rule.submission_code}})")
plain(&b, "Rechtsgrundlage: {{rule.legal_source_pretty}} ({{rule.legal_source}})")
plain(&b, "Typische Partei: {{rule.primary_party}} · Schriftsatz-Typ: {{rule.event_type}}")
heading2(&b, "Frist")
plain(&b, "Diese Frist wurde berechnet aus: {{deadline.computed_from}}")
plain(&b, "Fälligkeit: {{deadline.due_date_long_de}} ({{deadline.due_date}})")
plainOptional(&b, "Ursprüngliche Frist: {{deadline.original_due_date}}")
plain(&b, "Frist-Bezeichnung: {{deadline.title}} · Quelle: {{deadline.source}}")
heading2(&b, "Schriftsatztext")
plain(&b, "[Hier folgt der eigentliche Schriftsatztext. Diese Skelett-Vorlage enthält keine vorgefertigte Struktur — bitte gemäß Schriftsatz-Typ ({{rule.name}}) ergänzen.]")
plain(&b, "")
plain(&b, "[Body of the submission goes here. This skeleton template carries no pre-baked structure — fill in according to submission type ({{rule.name_en}}).]")
heading2(&b, "Schlussformel")
plain(&b, "{{today.long_de}}")
plain(&b, "")
plain(&b, "{{user.display_name}}")
plain(&b, "{{firm.name}}")
// Locale-aware verification block — exercises every EN/DE alias the
// variable bag carries (today.long_en, deadline.due_date_long_en,
// project.our_side_en, project.proceeding.name_en, rule.name_en) and
// the bare {{today}} alias. A lawyer customising the template can
// delete this block; the renderer round-trips it cleanly today.
heading2(&b, "Locale-aware variants (SKELETON)")
plain(&b, "EN long date: {{today.long_en}} · Deadline EN: {{deadline.due_date_long_en}}")
plain(&b, "Project our side (EN): {{project.our_side_en}} · Proceeding (EN): {{project.proceeding.name_en}}")
plain(&b, "Rule name (EN): {{rule.name_en}} · Project our side (DE): {{project.our_side_de}}")
plain(&b, "Proceeding (DE): {{project.proceeding.name_de}} · Rule name (DE): {{rule.name_de}}")
plain(&b, "Today (bare alias): {{today}}")
b.WriteString(`</w:body></w:document>`)
return b.String()
}
func skeletonBanner(b *strings.Builder) {
b.WriteString(`<w:p><w:pPr><w:pStyle w:val="Heading1"/></w:pPr><w:r><w:rPr><w:b/><w:color w:val="C00000"/></w:rPr><w:t xml:space="preserve">SKELETON — universelle Vorlage (Schriftsatz-Typ-unabhängig, nicht freigegeben)</w:t></w:r></w:p>`)
}
func heading1(b *strings.Builder, text string) { paragraph(b, "Heading1", text, false) }
func heading2(b *strings.Builder, text string) { paragraph(b, "Heading2", text, false) }
func plain(b *strings.Builder, text string) { paragraph(b, "", text, false) }
func plainOptional(b *strings.Builder, text string) { paragraph(b, "", text, true) }
func bold(b *strings.Builder, text string) {
b.WriteString(`<w:p>`)
b.WriteString(`<w:r><w:rPr><w:b/></w:rPr><w:t xml:space="preserve">`)
b.WriteString(xmlEscape(text))
b.WriteString(`</w:t></w:r></w:p>`)
}
func paragraph(b *strings.Builder, style, text string, italic bool) {
b.WriteString(`<w:p>`)
if style != "" {
b.WriteString(`<w:pPr><w:pStyle w:val="`)
b.WriteString(style)
b.WriteString(`"/></w:pPr>`)
}
for _, seg := range splitOnPlaceholders(text) {
b.WriteString(`<w:r>`)
if italic {
b.WriteString(`<w:rPr><w:i/></w:rPr>`)
}
b.WriteString(`<w:t xml:space="preserve">`)
b.WriteString(xmlEscape(seg))
b.WriteString(`</w:t></w:r>`)
}
b.WriteString(`</w:p>`)
}
func splitOnPlaceholders(s string) []string {
if s == "" {
return []string{""}
}
var out []string
for {
open := strings.Index(s, "{{")
if open < 0 {
out = append(out, s)
return out
}
close := strings.Index(s[open:], "}}")
if close < 0 {
out = append(out, s)
return out
}
end := open + close + 2
if open > 0 {
out = append(out, s[:open])
}
out = append(out, s[open:end])
s = s[end:]
if s == "" {
return out
}
}
}
func xmlEscape(s string) string {
s = strings.ReplaceAll(s, "&", "&amp;")
s = strings.ReplaceAll(s, "<", "&lt;")
s = strings.ReplaceAll(s, ">", "&gt;")
s = strings.ReplaceAll(s, `"`, "&quot;")
s = strings.ReplaceAll(s, "'", "&apos;")
return s
}

View File

@@ -0,0 +1,568 @@
// Seed Example Projects (t-paliad-256 / m/paliad#87).
//
// Re-runnable test-data reset:
//
// 1. Wipes every row in paliad.projects (FK CASCADE handles the
// dependent rows: deadlines, appointments, parties, notes,
// project_events, project_teams, submission_drafts, approval_*,
// project_partner_units, user_pinned_projects, documents,
// user_calendar_bindings).
//
// 2. Inserts a small but realistic example tree (3 clients, 4
// litigations, 4 patents, 8 cases — 19 projects total) that
// exercises the auto-derived chain code: Client.Litigation.Patent.Case
// → e.g. SIEMENS.HUAW.789.INF.CFI.
//
// 3. Re-reads the projects and prints each row's chain code so the
// operator can eyeball the result without bouncing to SQL.
//
// Reference tables (proceeding_types, deadline_rules, event_types,
// gerichte, checklists templates, firms, profiles) are untouched.
//
// Run:
//
// DATABASE_URL='postgres://...' go run ./scripts/seed-example-projects
//
// One transaction wraps both wipe and seed so the DB is never in a
// half-wiped state. Re-running drops the previous example tree and
// reseeds fresh UUIDs — handy when project-code semantics change.
//
// Owner: m (matthias.siebels@hoganlovells.com). The script looks the
// auth user up by email so it works on any environment where that
// account exists; on a brand-new DB it falls back to NULL created_by.
package main
import (
"context"
"database/sql"
"errors"
"flag"
"fmt"
"os"
"strings"
"text/tabwriter"
"time"
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
_ "github.com/lib/pq"
"mgit.msbls.de/m/paliad/internal/services"
)
// ownerEmail is the auth.users email the seed assigns as created_by.
// Living in code (not a flag) because the example tree is m-owned by
// convention; flip if the example data ever needs a service-account
// owner.
const ownerEmail = "matthias.siebels@hoganlovells.com"
// Proceeding-type IDs used by the seed. Resolved by code (not pinned
// to integer IDs in source) to survive DB renumbering. Loaded once at
// startup; missing codes fail fast with a clear message.
var proceedingCodes = []string{
"upc.inf.cfi",
"upc.ccr.cfi",
"upc.apl.merits",
"de.inf.lg",
"epa.opp.opd",
"de.null.bpatg",
"dpma.opp.dpma",
}
func main() {
dsn := flag.String("dsn", os.Getenv("DATABASE_URL"), "Postgres DSN (defaults to $DATABASE_URL)")
dryRun := flag.Bool("dry-run", false, "print intended actions, roll back transaction")
flag.Parse()
if *dsn == "" {
fmt.Fprintln(os.Stderr, "seed-example-projects: DATABASE_URL not set and -dsn empty")
os.Exit(1)
}
db, err := sqlx.Connect("postgres", *dsn)
if err != nil {
fmt.Fprintln(os.Stderr, "connect:", err)
os.Exit(1)
}
defer db.Close()
ctx := context.Background()
if err := run(ctx, db, *dryRun); err != nil {
fmt.Fprintln(os.Stderr, "seed-example-projects:", err)
os.Exit(1)
}
}
func run(ctx context.Context, db *sqlx.DB, dryRun bool) error {
ownerID, err := lookupOwner(ctx, db, ownerEmail)
if err != nil {
return fmt.Errorf("lookup owner: %w", err)
}
if ownerID == uuid.Nil {
fmt.Printf("note: %s not found in auth.users — created_by will be NULL\n", ownerEmail)
} else {
fmt.Printf("owner resolved: %s = %s\n", ownerEmail, ownerID)
}
procIDs, err := lookupProceedingTypes(ctx, db, proceedingCodes)
if err != nil {
return fmt.Errorf("lookup proceeding_types: %w", err)
}
tx, err := db.BeginTxx(ctx, nil)
if err != nil {
return fmt.Errorf("begin tx: %w", err)
}
defer func() { _ = tx.Rollback() }() // no-op if Commit ran first
if err := wipe(ctx, tx); err != nil {
return fmt.Errorf("wipe: %w", err)
}
tree, err := seed(ctx, tx, ownerID, procIDs)
if err != nil {
return fmt.Errorf("seed: %w", err)
}
if dryRun {
fmt.Println("\n--- DRY RUN — rolling back ---")
return nil
}
if err := tx.Commit(); err != nil {
return fmt.Errorf("commit: %w", err)
}
fmt.Println("seed committed.")
if err := report(ctx, db, tree); err != nil {
return fmt.Errorf("report: %w", err)
}
return nil
}
func lookupOwner(ctx context.Context, db *sqlx.DB, email string) (uuid.UUID, error) {
var id uuid.UUID
err := db.GetContext(ctx, &id, `SELECT id FROM auth.users WHERE email = $1`, email)
if errors.Is(err, sql.ErrNoRows) {
return uuid.Nil, nil
}
if err != nil {
return uuid.Nil, err
}
return id, nil
}
func lookupProceedingTypes(ctx context.Context, db *sqlx.DB, codes []string) (map[string]int, error) {
rows, err := db.QueryxContext(ctx,
`SELECT id, code FROM paliad.proceeding_types WHERE code = ANY($1)`,
pgTextArray(codes))
if err != nil {
return nil, err
}
defer rows.Close()
out := make(map[string]int, len(codes))
for rows.Next() {
var id int
var code string
if err := rows.Scan(&id, &code); err != nil {
return nil, err
}
out[code] = id
}
for _, c := range codes {
if _, ok := out[c]; !ok {
return nil, fmt.Errorf("proceeding_types row missing for code=%q", c)
}
}
return out, nil
}
// pgTextArray is the lib/pq array adapter, repackaged inline so the
// script doesn't need a separate util import.
func pgTextArray(xs []string) any {
type arr = []string
return arr(xs)
}
// wipe deletes every paliad.projects row. FK CASCADE handles the
// dependent tables (verified live 2026-05-25 against information_schema:
// appointments, approval_requests, approval_policies, deadlines,
// documents, notes, parties, project_events, project_partner_units,
// project_teams, submission_drafts, user_pinned_projects,
// user_calendar_bindings, checklist_shares all cascade; projects.
// counterclaim_of and checklist_instances SET NULL; policy_audit_log
// SET NULL).
//
// Reference tables (proceeding_types, deadline_rules, event_types,
// gerichte, checklists, firms, partner_units, profiles) are not
// referenced from this delete.
func wipe(ctx context.Context, tx *sqlx.Tx) error {
res, err := tx.ExecContext(ctx, `DELETE FROM paliad.projects`)
if err != nil {
return err
}
n, _ := res.RowsAffected()
fmt.Printf("wiped: %d project rows (FK CASCADE handled dependents)\n", n)
return nil
}
// seededNode is one row of the seed result, kept so we can print the
// chain code after commit without re-querying for IDs.
type seededNode struct {
id uuid.UUID
title string
}
// seed inserts the example tree. Order matters because parent_id FKs
// must already exist — clients first, then litigations under them, then
// patents, then cases (with the CCR case referencing its sibling
// Klage case via counterclaim_of).
func seed(ctx context.Context, tx *sqlx.Tx, ownerID uuid.UUID, procIDs map[string]int) ([]seededNode, error) {
var nodes []seededNode
insertProject := func(p projectInsert) (uuid.UUID, error) {
id := uuid.New()
var createdBy any
if ownerID != uuid.Nil {
createdBy = ownerID
}
_, err := tx.ExecContext(ctx, `
INSERT INTO paliad.projects (
id, type, parent_id, title, reference, description, status,
created_by, industry, country, client_number, matter_number,
patent_number, filing_date, grant_date,
court, case_number, proceeding_type_id,
our_side, opponent_code, instance_level, counterclaim_of
) VALUES (
$1, $2, $3, $4, $5, $6, 'active',
$7, $8, $9, $10, $11,
$12, $13, $14,
$15, $16, $17,
$18, $19, $20, $21
)`,
id, p.Type, nullUUID(p.ParentID), p.Title, nullStr(p.Reference), nullStr(p.Description),
createdBy, nullStr(p.Industry), nullStr(p.Country), nullStr(p.ClientNumber), nullStr(p.MatterNumber),
nullStr(p.PatentNumber), nullDate(p.FilingDate), nullDate(p.GrantDate),
nullStr(p.Court), nullStr(p.CaseNumber), nullInt(p.ProceedingTypeID),
nullStr(p.OurSide), nullStr(p.OpponentCode), nullStr(p.InstanceLevel), nullUUID(p.CounterclaimOf),
)
if err != nil {
return uuid.Nil, fmt.Errorf("insert %s %q: %w", p.Type, p.Title, err)
}
nodes = append(nodes, seededNode{id: id, title: p.Title})
return id, nil
}
// --- Client 1: Siemens AG ----------------------------------------
siemens, err := insertProject(projectInsert{
Type: "client", Title: "Siemens AG", Reference: "SIEMENS",
Industry: "Telekommunikation / Industrieelektronik", Country: "DE",
Description: "Beispiel-Mandant — Telekommunikation & Halbleiter.",
})
if err != nil {
return nil, err
}
siemensHuawei, err := insertProject(projectInsert{
Type: "litigation", ParentID: siemens,
Title: "Siemens ./. Huawei Technologies", OpponentCode: "HUAW",
Description: "Patentstreit Mobilfunk-Standardpatent.", OurSide: "claimant",
})
if err != nil {
return nil, err
}
siemensHuaweiPatent, err := insertProject(projectInsert{
Type: "patent", ParentID: siemensHuawei,
Title: "EP3456789 — Funkkommunikationssystem mit Mehrfachantenne",
PatentNumber: "EP3456789",
FilingDate: "2018-03-12", GrantDate: "2022-11-09",
})
if err != nil {
return nil, err
}
upcInfCFI, err := insertProject(projectInsert{
Type: "case", ParentID: siemensHuaweiPatent,
Title: "UPC CFI München — Klage Siemens ./. Huawei (EP3456789)",
Court: "UPC Lokalkammer München",
CaseNumber: "UPC_CFI_123/2026",
ProceedingTypeID: procIDs["upc.inf.cfi"],
OurSide: "claimant",
InstanceLevel: "first",
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: siemensHuaweiPatent,
Title: "UPC CFI München — Widerklage Huawei ./. Siemens (EP3456789)",
Court: "UPC Lokalkammer München",
CaseNumber: "UPC_CFI_123/2026 (CCR)",
ProceedingTypeID: procIDs["upc.ccr.cfi"],
OurSide: "defendant", // we're respondent on the CCR
InstanceLevel: "first",
CounterclaimOf: upcInfCFI,
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: siemensHuaweiPatent,
Title: "UPC Berufungsgericht — Berufung Huawei (EP3456789)",
Court: "UPC Court of Appeal",
CaseNumber: "UPC_CoA_45/2027",
ProceedingTypeID: procIDs["upc.apl.merits"],
OurSide: "respondent",
InstanceLevel: "appeal",
})
if err != nil {
return nil, err
}
siemensBosch, err := insertProject(projectInsert{
Type: "litigation", ParentID: siemens,
Title: "Siemens ./. Robert Bosch GmbH", OpponentCode: "BOSCH",
Description: "Sensorik / autonomes Fahren.", OurSide: "claimant",
})
if err != nil {
return nil, err
}
siemensBoschPatent, err := insertProject(projectInsert{
Type: "patent", ParentID: siemensBosch,
Title: "EP1111222 — Sensoreinrichtung für autonomes Fahren",
PatentNumber: "EP1111222",
FilingDate: "2017-06-21", GrantDate: "2021-08-04",
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: siemensBoschPatent,
Title: "LG München I — Klage Siemens ./. Bosch (EP1111222)",
Court: "Landgericht München I",
CaseNumber: "7 O 12345/26",
ProceedingTypeID: procIDs["de.inf.lg"],
OurSide: "claimant",
InstanceLevel: "first",
})
if err != nil {
return nil, err
}
// --- Client 2: Bayer AG ------------------------------------------
bayer, err := insertProject(projectInsert{
Type: "client", Title: "Bayer AG", Reference: "BAYER",
Industry: "Pharma / Life Sciences", Country: "DE",
Description: "Beispiel-Mandant — pharmazeutische Wirkstoffe.",
})
if err != nil {
return nil, err
}
bayerNova, err := insertProject(projectInsert{
Type: "litigation", ParentID: bayer,
Title: "Bayer ./. Novartis Pharma", OpponentCode: "NOVA",
Description: "Wirkstoffverbindung X — Einspruch + Nichtigkeit.", OurSide: "claimant",
})
if err != nil {
return nil, err
}
bayerNovaPatent, err := insertProject(projectInsert{
Type: "patent", ParentID: bayerNova,
Title: "EP2222333 — Wirkstoffverbindung X",
PatentNumber: "EP2222333",
FilingDate: "2015-09-30", GrantDate: "2020-04-22",
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: bayerNovaPatent,
Title: "EPA Einspruch — Novartis ./. EP2222333",
Court: "Europäisches Patentamt — Einspruchsabteilung",
CaseNumber: "OPP-2026-0042",
ProceedingTypeID: procIDs["epa.opp.opd"],
OurSide: "respondent", // Bayer is patent owner defending the patent
InstanceLevel: "first",
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: bayerNovaPatent,
Title: "BPatG — Nichtigkeitsklage Novartis ./. EP2222333",
Court: "Bundespatentgericht",
CaseNumber: "5 Ni 12/26",
ProceedingTypeID: procIDs["de.null.bpatg"],
OurSide: "respondent",
InstanceLevel: "first",
})
if err != nil {
return nil, err
}
// --- Client 3: Beispiel AG (intentionally sparse) ----------------
// Demonstrates the empty-segment skip in BuildProjectCode — the
// case row has a proceeding_type set so the tail is present, but
// no instance_level / our_side, and the patent's number is national
// (DE) so the last-3-digits segment shows DE-style behaviour.
beispiel, err := insertProject(projectInsert{
Type: "client", Title: "Beispiel AG", Reference: "BEISPL",
Industry: "Unspezifiziert", Country: "DE",
Description: "Sparse-Beispiel — zeigt, wie fehlende Segmente übersprungen werden.",
})
if err != nil {
return nil, err
}
beispielWtb, err := insertProject(projectInsert{
Type: "litigation", ParentID: beispiel,
Title: "Beispiel ./. Wettbewerber GmbH", OpponentCode: "WTB",
Description: "Demo-Litigation ohne große Detailtiefe.",
})
if err != nil {
return nil, err
}
beispielWtbPatent, err := insertProject(projectInsert{
Type: "patent", ParentID: beispielWtb,
Title: "DE10987654 — Demo-Erfindung",
PatentNumber: "DE10987654",
})
if err != nil {
return nil, err
}
_, err = insertProject(projectInsert{
Type: "case", ParentID: beispielWtbPatent,
Title: "DPMA Einspruch — Wettbewerber ./. DE10987654",
Court: "Deutsches Patent- und Markenamt",
CaseNumber: "DPMA-EIN-987/26",
ProceedingTypeID: procIDs["dpma.opp.dpma"],
OurSide: "respondent",
InstanceLevel: "first",
})
if err != nil {
return nil, err
}
fmt.Printf("seeded: %d projects\n", len(nodes))
return nodes, nil
}
// projectInsert is the typed input for one insertProject call. Pointer
// fields are kept as plain strings here and converted via nullStr at
// bind time; keeps the call sites readable.
type projectInsert struct {
Type string
ParentID uuid.UUID
Title string
Reference string
Description string
Industry string
Country string
ClientNumber string
MatterNumber string
PatentNumber string
FilingDate string // YYYY-MM-DD
GrantDate string
Court string
CaseNumber string
ProceedingTypeID int
OurSide string
OpponentCode string
InstanceLevel string
CounterclaimOf uuid.UUID
}
func nullStr(s string) any {
if s == "" {
return nil
}
return s
}
func nullInt(i int) any {
if i == 0 {
return nil
}
return i
}
func nullUUID(u uuid.UUID) any {
if u == uuid.Nil {
return nil
}
return u
}
func nullDate(s string) any {
if s == "" {
return nil
}
t, err := time.Parse("2006-01-02", s)
if err != nil {
return nil
}
return t
}
// reportRow is one row of the post-seed report — only the fields the
// printout needs.
type reportRow struct {
ID uuid.UUID `db:"id"`
Type string `db:"type"`
Title string `db:"title"`
Path string `db:"path"`
}
// report prints the seeded tree with the auto-derived chain code for
// each row. Uses services.BuildProjectCode so the script verifies the
// same helper the live app uses (catches drift if the algorithm
// changes).
func report(ctx context.Context, db *sqlx.DB, _ []seededNode) error {
var rows []reportRow
err := db.SelectContext(ctx, &rows, `
SELECT id, type, title, path
FROM paliad.projects
ORDER BY path
`)
if err != nil {
return err
}
fmt.Println("\nresulting chain codes:")
tw := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(tw, "TYPE\tTITLE\tCODE")
for _, r := range rows {
code, err := services.BuildProjectCode(ctx, db, r.ID)
if err != nil {
return fmt.Errorf("build code for %s: %w", r.ID, err)
}
indent := strings.Repeat(" ", pathDepth(r.Path)-1)
fmt.Fprintf(tw, "%s\t%s%s\t%s\n", r.Type, indent, r.Title, code)
}
return tw.Flush()
}
func pathDepth(p string) int {
if p == "" {
return 1
}
d := 1
for _, c := range p {
if c == '.' {
d++
}
}
return d
}