Compare commits

..

1 Commits

Author SHA1 Message Date
mAi
d4df81e374 mAi: #106 - t-paliad-274 — bidirectional draft editor link + click-field-highlights
Extension of #92 (m/paliad/issues/106). Two related polish fixes for the
submission draft editor's preview ↔ sidebar wiring.

Concern A — link persists after fill (regression coverage + UX visibility)

  Audited the Go renderer: substituteInTextNodes / substituteAcrossRuns
  already pass both filled and missing values through htmlPreviewWrapper,
  so the <span class="draft-var" data-var="…"> wrapping is present for
  every substituted placeholder regardless of source (resolved bag,
  lawyer override, missing marker). What looked broken to m was a
  visibility problem: the always-on rgba(198, 244, 28, 0.12) tint is
  imperceptible against the serif preview prose, so a filled value
  reads as plain text and the user concludes "the link is gone".

  Added TestRenderHTML_WrapsOverriddenValueSameAsResolved that pins the
  invariant explicitly — an override (project.case_number = "UPC_CFI_
  42/2026") and a resolved value (firm.name = "HLC") both end up in
  matching draft-var spans. Locks future refactors out of dropping the
  wrap on either path.

  CSS rewrite per m's "prose stays clean when not interacting" guidance
  (issue body): drop the always-on background; on hover of a
  --has-input span, layer a dotted-underline + brighter lime tint so
  the click affordance reveals itself. Missing markers carry their own
  [KEIN WERT: …] / [NO VALUE: …] gap-text and don't need extra visual.

Concern B — sidebar-field-focus → preview-occurrence highlight (new)

  Reverse direction of the click-to-jump from #92. focusin on any
  .submission-draft-var-input applies .draft-var--active to every
  matching span in the preview; focusout (or focus shift via Tab)
  clears them. Sticky-while-focused, not a one-shot flash — the lawyer
  can scan "where does this variable land in my prose?" while the
  field stays focused.

  New CSS class .draft-var--active uses a brighter lime + box-shadow
  ring so all occurrences pop at once. Handlers are wired in
  paintVariables and re-applied at the end of both paintVariables AND
  paintPreview because:
    - paintVariables runs after autosave and re-creates inputs via
      innerHTML, so the focusin listener attached to the old input is
      gone; restoreVarFocus puts focus back programmatically without
      firing focusin again. We re-apply explicitly to bridge.
    - paintPreview blows away the preview HTML on every autosave, so
      any prior --active class is gone too. Re-apply based on the
      currently-focused sidebar input.

Files

  internal/services/submission_merge_test.go — new regression test
  frontend/src/client/submission-draft.ts    — focus handlers + re-apply
  frontend/src/styles/global.css             — draft-var rewrite, --active

Hard rules

  - .docx export path unchanged (Render passes nil wrap, covered by
    existing TestRender_DocxOutputUnchangedByPreviewWrap).
  - Both directions survive autosave-driven preview re-renders (see
    paintPreview re-apply + paintVariables re-apply).
  - go build ./... && go test ./internal/... && bun run build all clean.
2026-05-25 16:32:45 +02:00
13 changed files with 228 additions and 999 deletions

View File

@@ -1473,10 +1473,6 @@ const translations: Record<Lang, Record<string, string>> = {
"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-277 — import-from-project + party-picker.
"submissions.draft.import.button": "Aus Projekt importieren",
"submissions.draft.parties.title": "Parteien",
"submissions.draft.parties.hint": "Wählen Sie aus, welche Parteien im Schriftsatz genannt werden sollen.",
// t-paliad-240 — global Schriftsätze drafts index page.
"submissions.index.title": "Schriftsätze — Paliad",
"submissions.index.heading": "Schriftsätze",
@@ -4525,10 +4521,6 @@ const translations: Record<Lang, Record<string, string>> = {
"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-277 — import-from-project + party-picker.
"submissions.draft.import.button": "Import from project",
"submissions.draft.parties.title": "Parties",
"submissions.draft.parties.hint": "Select which parties to mention in this submission.",
// t-paliad-240 — global submissions drafts index page.
"submissions.index.title": "Submissions — Paliad",
"submissions.index.heading": "Submissions",

View File

@@ -21,21 +21,12 @@ interface SubmissionDraftJSON {
user_id: string;
name: string;
variables: Record<string, string>;
selected_parties: string[];
last_exported_at?: string | null;
last_exported_sha?: string | null;
last_imported_at?: string | null;
created_at: string;
updated_at: string;
}
interface AvailablePartyJSON {
id: string;
name: string;
role?: string;
representative?: string;
}
interface SubmissionRuleSummary {
name: string;
name_en: string;
@@ -55,7 +46,6 @@ interface SubmissionDraftView {
lang: string;
has_template: boolean;
template_missing?: boolean;
available_parties: AvailablePartyJSON[];
}
interface SubmissionDraftListResponse {
@@ -411,7 +401,7 @@ async function fetchGlobalView(draftID: string): Promise<SubmissionDraftView> {
return resp.json();
}
async function patchDraft(payload: { name?: string; variables?: Record<string, string>; project_id?: string | null; selected_parties?: string[] }): Promise<SubmissionDraftView> {
async function patchDraft(payload: { name?: string; variables?: Record<string, string>; project_id?: string | null }): Promise<SubmissionDraftView> {
const p = state.parsed;
if (!p.draftID) throw new Error("no draft id");
if (state.inFlight) {
@@ -461,8 +451,6 @@ function paint(): void {
paintNoProjectBanner();
paintSwitcher();
paintNameRow();
paintImportRow();
paintPartyPicker();
paintVariables();
paintPreview();
}
@@ -574,135 +562,6 @@ function paintNameRow(): void {
if (exportBtn) exportBtn.onclick = () => onExport(exportBtn);
}
// t-paliad-277 — "Aus Projekt importieren" + last-imported-at stamp.
// Hidden when the draft has no project (no project state to import).
function paintImportRow(): void {
const row = document.getElementById("submission-draft-import-row");
const btn = document.getElementById("submission-draft-import-btn") as HTMLButtonElement | null;
const stamp = document.getElementById("submission-draft-import-stamp");
if (!row || !btn || !stamp || !state.view) return;
if (!state.view.draft.project_id) {
row.style.display = "none";
return;
}
row.style.display = "";
const last = state.view.draft.last_imported_at;
if (last) {
stamp.textContent = (isEN() ? "Last imported: " : "Zuletzt importiert: ") + formatStamp(last);
} else {
stamp.textContent = isEN() ? "Never imported" : "Noch nicht importiert";
}
btn.onclick = () => { void onImportFromProject(btn); };
}
// t-paliad-277 — multi-select party picker. Lists every party on the
// draft's project (view.available_parties), grouped by role, with one
// checkbox per party. Checked = include in the variable bag. Empty
// selection falls back to the legacy "include every party" default
// (consistent with the migration default).
function paintPartyPicker(): void {
const block = document.getElementById("submission-draft-parties");
const list = document.getElementById("submission-draft-parties-list");
if (!block || !list || !state.view) return;
const parties = state.view.available_parties ?? [];
if (!state.view.draft.project_id || parties.length === 0) {
block.style.display = "none";
list.innerHTML = "";
return;
}
block.style.display = "";
const selected = new Set(state.view.draft.selected_parties ?? []);
// Empty selection is the implicit "all" default — pre-check every
// party so the lawyer can see what's currently being mentioned and
// then deselect what they want to drop. This matches the issue's
// "default = all parties on the project, lawyer can deselect" line.
const effective = selected.size === 0
? new Set(parties.map((p) => p.id))
: selected;
const grouped = groupPartiesByRole(parties);
let html = "";
for (const group of grouped) {
if (group.parties.length === 0) continue;
html += `<fieldset class="submission-draft-parties-group" data-role-bucket="${group.bucket}">`;
html += `<legend>${escapeHtml(group.label)}</legend>`;
for (const p of group.parties) {
const checked = effective.has(p.id) ? " checked" : "";
const chip = p.role
? `<span class="submission-draft-party-chip">${escapeHtml(p.role)}</span>`
: "";
const rep = p.representative
? `<span class="submission-draft-party-rep">${escapeHtml(
(isEN() ? "Repr.: " : "Vertr.: ") + p.representative,
)}</span>`
: "";
html += `<label class="submission-draft-party-row">`;
html += `<input type="checkbox" class="submission-draft-party-check"`;
html += ` data-party-id="${escapeHtml(p.id)}"${checked} />`;
html += `<span class="submission-draft-party-name">${escapeHtml(p.name)}</span>`;
html += chip;
html += rep;
html += `</label>`;
}
html += `</fieldset>`;
}
list.innerHTML = html;
list.querySelectorAll<HTMLInputElement>(".submission-draft-party-check").forEach((inp) => {
inp.addEventListener("change", () => onPartySelectionChange());
});
}
interface PartyRoleGroup {
bucket: "claimant" | "defendant" | "other";
label: string;
parties: AvailablePartyJSON[];
}
function groupPartiesByRole(parties: AvailablePartyJSON[]): PartyRoleGroup[] {
const claimants: AvailablePartyJSON[] = [];
const defendants: AvailablePartyJSON[] = [];
const others: AvailablePartyJSON[] = [];
for (const p of parties) {
const role = (p.role ?? "").trim().toLowerCase();
if (role === "claimant" || role === "kläger" || role === "klaeger"
|| role === "klägerin" || role === "klaegerin") {
claimants.push(p);
} else if (role === "defendant" || role === "beklagter" || role === "beklagte") {
defendants.push(p);
} else {
others.push(p);
}
}
return [
{
bucket: "claimant",
label: isEN() ? "Claimants" : "Klägerinnen",
parties: claimants,
},
{
bucket: "defendant",
label: isEN() ? "Defendants" : "Beklagte",
parties: defendants,
},
{
bucket: "other",
label: isEN() ? "Other parties" : "Weitere Parteien",
parties: others,
},
];
}
function formatStamp(iso: string): string {
const d = new Date(iso);
if (Number.isNaN(d.getTime())) return iso;
return d.toLocaleString(isEN() ? "en-GB" : "de-DE");
}
function paintVariables(): void {
const host = document.getElementById("submission-draft-variables");
if (!host || !state.view) return;
@@ -751,10 +610,25 @@ function paintVariables(): void {
host.querySelectorAll<HTMLInputElement>(".submission-draft-var-input").forEach((inp) => {
inp.addEventListener("input", () => onVarChange(inp));
// t-paliad-274 (B) — focus into a sidebar field highlights every
// matching .draft-var span in the preview (sticky while focused,
// clears on blur). Survives autosave repaints because paintVariables
// is called by flushAutosave and we re-bind every render.
inp.addEventListener("focusin", () => onVarFocusEnter(inp.dataset.var ?? ""));
inp.addEventListener("focusout", () => onVarFocusLeave(inp.dataset.var ?? ""));
});
host.querySelectorAll<HTMLButtonElement>(".submission-draft-var-reset").forEach((btn) => {
btn.addEventListener("click", () => onVarReset(btn.dataset.resetKey ?? ""));
});
// After repaint, re-apply the active highlight if a field is still
// focused (paintVariables runs after autosave; the same input regains
// focus via restoreVarFocus and would otherwise emit focusin too
// late for our handler — re-apply explicitly).
const active = document.activeElement;
if (isVarField(active)) {
const key = active.dataset.var;
if (key) applyPreviewActiveHighlight(key);
}
}
function paintPreview(): void {
@@ -762,6 +636,16 @@ function paintPreview(): void {
if (!host || !state.view) return;
host.innerHTML = state.view.preview_html ?? "";
wireDraftVars(host);
// t-paliad-274 (B) — preview HTML was just blown away by innerHTML,
// so any prior --active classes are gone. Re-apply for whichever
// sidebar field is currently focused (typing in a field triggers an
// autosave round-trip that ends in paintPreview, and the user should
// see the highlight stay put across that cycle).
const active = document.activeElement;
if (isVarField(active)) {
const key = active.dataset.var;
if (key) applyPreviewActiveHighlight(key);
}
}
// t-paliad-261 (B) — click a substituted variable in the preview to
@@ -836,6 +720,48 @@ function onDraftVarClick(key: string, ev: Event): void {
flashVarRow(input);
}
// t-paliad-274 (B) — sidebar-field-focus → preview-occurrence highlight.
// Reverse direction of the click-to-jump from #92: when the user focuses
// any .submission-draft-var-input, every matching .draft-var span in the
// preview gets the --active modifier; on blur (or focus shift to a
// different field), the previous key's highlights clear and the new
// key's apply. Sticky-while-focused, not a one-shot flash — the lawyer
// can scan the preview for "where does this variable land in my prose?"
// while the field stays focused.
function onVarFocusEnter(key: string): void {
if (!key) return;
// Clear any leftover highlight before applying the new one — covers
// the focus-shift-without-blur case (Tab between fields).
clearPreviewActiveHighlight();
applyPreviewActiveHighlight(key);
}
function onVarFocusLeave(_key: string): void {
// We don't need the key here — if focus moves to a different sidebar
// input, that input's focusin will re-call apply with the new key
// (after our clearPreviewActiveHighlight). If focus leaves the sidebar
// entirely, this clears.
clearPreviewActiveHighlight();
}
function applyPreviewActiveHighlight(key: string): void {
const host = document.getElementById("submission-draft-preview");
if (!host) return;
host.querySelectorAll<HTMLElement>(
`.draft-var[data-var="${cssEscape(key)}"]`,
).forEach((el) => {
el.classList.add("draft-var--active");
});
}
function clearPreviewActiveHighlight(): void {
const host = document.getElementById("submission-draft-preview");
if (!host) return;
host.querySelectorAll<HTMLElement>(".draft-var--active").forEach((el) => {
el.classList.remove("draft-var--active");
});
}
function flashVarRow(input: HTMLElement): void {
const row = input.closest<HTMLElement>(".submission-draft-var-row");
if (!row) return;
@@ -851,69 +777,6 @@ function flashVarRow(input: HTMLElement): void {
// Event handlers
// ─────────────────────────────────────────────────────────────────────
async function onPartySelectionChange(): Promise<void> {
if (!state.view) return;
const host = document.getElementById("submission-draft-parties-list");
if (!host) return;
const checks = host.querySelectorAll<HTMLInputElement>(".submission-draft-party-check");
const selectedIDs: string[] = [];
checks.forEach((c) => {
if (c.checked && c.dataset.partyId) selectedIDs.push(c.dataset.partyId);
});
// If the lawyer has checked every party, persist that as an empty
// array so the row matches the "implicit all" default semantics — a
// future party added to the project will then be picked up
// automatically rather than silently dropped from this submission.
// If they've unchecked some, persist the actual subset.
const available = state.view.available_parties ?? [];
const allChecked = selectedIDs.length === available.length;
const payload = allChecked ? [] : selectedIDs;
setSaveStatus(isEN() ? "Saving…" : "Speichert…");
try {
const view = await patchDraft({ selected_parties: payload });
state.view = view;
paintImportRow();
paintPartyPicker();
paintVariables();
paintPreview();
setSaveStatus(isEN() ? "Saved" : "Gespeichert");
} catch (err) {
if ((err as Error).name === "AbortError") return;
console.error("submission-draft party selection:", err);
setSaveStatus(isEN() ? "Save failed" : "Speichern fehlgeschlagen", true);
}
}
async function onImportFromProject(btn: HTMLButtonElement): Promise<void> {
if (!state.view) return;
const draftID = state.view.draft.id;
const originalLabel = btn.textContent ?? "";
btn.disabled = true;
btn.textContent = isEN() ? "Importing…" : "Importiert…";
setSaveStatus(isEN() ? "Importing from project…" : "Importiere aus Projekt…");
try {
const resp = await fetch(`/api/submission-drafts/${draftID}/import-from-project`, {
method: "POST",
});
if (!resp.ok) throw new Error(`import ${resp.status}`);
const view = (await resp.json()) as SubmissionDraftView;
state.view = view;
paintImportRow();
paintPartyPicker();
paintVariables();
paintPreview();
setSaveStatus(isEN() ? "Imported" : "Importiert");
} catch (err) {
console.error("submission-draft import-from-project:", err);
setSaveStatus(isEN() ? "Import failed" : "Import fehlgeschlagen", true);
} finally {
btn.disabled = false;
btn.textContent = originalLabel;
}
}
function onVarChange(input: HTMLInputElement): void {
const key = input.dataset.var;
if (!key || !state.view) return;

View File

@@ -2599,12 +2599,9 @@ export type I18nKey =
| "submissions.draft.action.export"
| "submissions.draft.action.new"
| "submissions.draft.back"
| "submissions.draft.import.button"
| "submissions.draft.loading"
| "submissions.draft.name.placeholder"
| "submissions.draft.notfound"
| "submissions.draft.parties.hint"
| "submissions.draft.parties.title"
| "submissions.draft.preview.hint"
| "submissions.draft.preview.title"
| "submissions.draft.switcher.label"

View File

@@ -5880,16 +5880,27 @@ dialog.modal::backdrop {
font-style: italic;
}
/* t-paliad-261 (B) — substituted variables in the preview are wrapped
in <span class="draft-var" data-var="…"> by the Go HTML renderer.
.draft-var by itself shows a subtle dotted underline so the lawyer
can SEE which text was filled in from a variable. .draft-var--has-input
(added client-side when a matching sidebar input exists) layers on
the clickable affordance — pointer cursor + brighter hover background.
Non-matching draft-vars (derived variables not exposed in the
sidebar) stay visually distinct but non-interactive. */
/* t-paliad-261 / t-paliad-274 — substituted variables in the preview
are wrapped in <span class="draft-var" data-var="…"> by the Go HTML
renderer for BOTH filled values and missing-marker text. The lawyer
can click any wrapped span and jump to the matching sidebar input;
conversely, focusing a sidebar input lights up every matching span in
the preview via .draft-var--active.
Visual contract:
.draft-var — invisible by default (prose stays clean
per t-paliad-274 m's request).
.draft-var--has-input — pointer cursor; dotted underline on
hover so the click affordance reveals
itself, plus a brighter lime tint.
.draft-var--active — sticky lime highlight applied while the
matching sidebar input is focused
(t-paliad-274 reverse direction).
[KEIN WERT: …] / [NO VALUE: …] markers carry their own warning
style via .submission-draft-var-marker on the sidebar hint; in the
preview they read as obvious gap text, so .draft-var itself doesn't
need an always-on visual to flag them. */
.draft-var {
background-color: rgba(198, 244, 28, 0.12);
border-radius: 2px;
padding: 0 2px;
box-decoration-break: clone;
@@ -5904,9 +5915,21 @@ dialog.modal::backdrop {
.draft-var--has-input:hover,
.draft-var--has-input:focus-visible {
background-color: rgba(198, 244, 28, 0.45);
text-decoration: underline dotted rgba(198, 244, 28, 0.85);
text-underline-offset: 2px;
outline: none;
}
/* t-paliad-274 (B) — sticky highlight while the matching sidebar input
is focused. Brighter than the hover tint so the user's eye lands on
every occurrence at once when they click into a field. Applies to ALL
.draft-var spans for that data-var, not just one. */
.draft-var--active,
.draft-var--has-input.draft-var--active {
background-color: rgba(198, 244, 28, 0.55);
box-shadow: 0 0 0 1px rgba(198, 244, 28, 0.85);
}
/* t-paliad-261 (B) — brief lime flash on the sidebar row after a
click-jump from the preview, so the user's eye lands on the right
input even after the smooth-scroll motion. Animation restarts on
@@ -6049,96 +6072,6 @@ dialog.modal::backdrop {
font-size: 0.92rem;
}
/* t-paliad-277 — "Aus Projekt importieren" row + multi-select party
picker block on the submission draft editor sidebar. */
.submission-draft-import-row {
display: flex;
align-items: center;
justify-content: space-between;
gap: 0.6rem;
flex-wrap: wrap;
padding: 0.5rem 0.6rem;
margin-bottom: 0.75rem;
background: var(--color-surface-alt, #f7f7f0);
border: 1px solid var(--color-border);
border-radius: 6px;
}
.submission-draft-import-stamp {
font-size: 0.8em;
color: var(--color-text-muted);
}
.submission-draft-parties {
border-top: 1px solid var(--color-border);
padding-top: 0.75rem;
margin-bottom: 0.75rem;
}
.submission-draft-parties-hint {
font-size: 0.85em;
color: var(--color-text-muted);
margin: 0 0 0.6rem;
}
.submission-draft-parties-list {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.submission-draft-parties-group {
border: 1px solid var(--color-border);
border-radius: 6px;
padding: 0.4rem 0.6rem 0.5rem;
margin: 0;
}
.submission-draft-parties-group > legend {
padding: 0 0.4rem;
font-size: 0.8em;
text-transform: uppercase;
letter-spacing: 0.05em;
color: var(--color-text-muted);
}
.submission-draft-party-row {
display: flex;
align-items: center;
flex-wrap: wrap;
gap: 0.4rem;
padding: 0.25rem 0;
cursor: pointer;
}
.submission-draft-party-check {
margin: 0;
accent-color: var(--color-accent, #c6f41c);
}
.submission-draft-party-name {
font-size: 0.92em;
color: var(--color-text);
}
.submission-draft-party-chip {
font-size: 0.72em;
text-transform: uppercase;
letter-spacing: 0.04em;
padding: 0.1em 0.5em;
border-radius: 999px;
background: var(--color-bg-lime-tint, #f0fac6);
color: var(--color-text);
border: 1px solid var(--color-border);
}
.submission-draft-party-rep {
font-size: 0.78em;
color: var(--color-text-muted);
margin-left: 0.25rem;
}
.checklist-instance-actions {
display: flex;
gap: 0.35rem;

View File

@@ -111,50 +111,6 @@ export function renderSubmissionDraft(): string {
<p className="submission-draft-savestatus" id="submission-draft-savestatus" />
{/* t-paliad-277: "Aus Projekt importieren" + last-
imported-at timestamp. Only visible when the
draft has a project_id attached. */}
<div
id="submission-draft-import-row"
className="submission-draft-import-row"
style="display:none">
<button
type="button"
id="submission-draft-import-btn"
className="btn-small btn-secondary"
data-i18n="submissions.draft.import.button">
Aus Projekt importieren
</button>
<span
id="submission-draft-import-stamp"
className="submission-draft-import-stamp"
/>
</div>
{/* t-paliad-277: multi-select party picker.
Populated from view.available_parties; checkbox
per party, grouped by role. Hidden when no
project or no parties on the project. */}
<div
id="submission-draft-parties"
className="submission-draft-parties"
style="display:none">
<h3
className="submission-draft-var-group-title"
data-i18n="submissions.draft.parties.title">
Parteien
</h3>
<p
className="submission-draft-parties-hint"
data-i18n="submissions.draft.parties.hint">
Wählen Sie aus, welche Parteien im Schriftsatz genannt werden sollen.
</p>
<div
id="submission-draft-parties-list"
className="submission-draft-parties-list"
/>
</div>
<div className="submission-draft-variables" id="submission-draft-variables" />
</aside>

View File

@@ -1,4 +0,0 @@
-- t-paliad-277 rollback.
ALTER TABLE paliad.submission_drafts
DROP COLUMN IF EXISTS selected_parties,
DROP COLUMN IF EXISTS last_imported_at;

View File

@@ -1,32 +0,0 @@
-- t-paliad-277 / m/paliad#109: per-draft party selection + import provenance.
--
-- Adds two columns to paliad.submission_drafts:
--
-- selected_parties uuid[] — IDs of paliad.parties rows the lawyer
-- has chosen to mention in this specific submission. An empty
-- array (the default) means "include every party on the project"
-- so all existing drafts keep their current rendering. Non-empty
-- restricts the variable bag to the chosen subset, grouped by
-- role in SubmissionVarsService.
--
-- last_imported_at timestamptz — when the lawyer last clicked
-- "Aus Projekt importieren" on the draft editor (or NULL if they
-- never did). The frontend surfaces this timestamp next to the
-- button so a stale draft is obvious at a glance.
--
-- Both columns are purely additive and nullable / default-bearing —
-- the migration is safe to apply with active drafts in the table.
-- No FK on selected_parties: paliad.parties is project-scoped and we
-- prune stale references on read inside SubmissionVarsService rather
-- than chasing FK cascades across two tables (the variable bag silently
-- drops any uuid that no longer matches a row in paliad.parties).
ALTER TABLE paliad.submission_drafts
ADD COLUMN IF NOT EXISTS selected_parties uuid[] NOT NULL DEFAULT '{}'::uuid[],
ADD COLUMN IF NOT EXISTS last_imported_at timestamptz;
COMMENT ON COLUMN paliad.submission_drafts.selected_parties IS
't-paliad-277: party IDs (paliad.parties) the lawyer has chosen to mention in this submission. Empty array = include every party on the project (backward-compat default). Non-empty = restrict to subset, grouped by role.';
COMMENT ON COLUMN paliad.submission_drafts.last_imported_at IS
't-paliad-277: timestamp of the last "Aus Projekt importieren" click — surfaced next to the button so the lawyer can see staleness at a glance. NULL = never imported.';

View File

@@ -355,10 +355,6 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
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)
// t-paliad-277 / m/paliad#109 — refresh project-derived variables on
// the draft. Strips overrides for project.* / parties.* / deadline.*
// / procedural_event.* / rule.* prefixes and bumps last_imported_at.
protected.HandleFunc("POST /api/submission-drafts/{draft_id}/import-from-project", handleImportFromProject)
// /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)

View File

@@ -60,53 +60,38 @@ const submissionDraftExportTimeout = 30 * time.Second
// raw row plus the resolved bag and the rule metadata the sidebar uses
// to label each variable group.
type submissionDraftView struct {
Draft submissionDraftJSON `json:"draft"`
Rule *submissionRuleSummary `json:"rule,omitempty"`
ResolvedBag services.PlaceholderMap `json:"resolved_bag"`
MergedBag services.PlaceholderMap `json:"merged_bag"`
PreviewHTML string `json:"preview_html"`
Lang string `json:"lang"`
HasTemplate bool `json:"has_template"`
TemplateMissing bool `json:"template_missing,omitempty"`
// AvailableParties is the project's full party roster (t-paliad-277)
// so the frontend can render the multi-select picker in one round-
// trip. Empty when the draft has no project attached.
AvailableParties []submissionDraftPartyJSON `json:"available_parties"`
}
// submissionDraftPartyJSON is the minimal party row the editor sidebar
// needs to render a checkbox + role chip per party.
type submissionDraftPartyJSON struct {
ID uuid.UUID `json:"id"`
Name string `json:"name"`
Role string `json:"role,omitempty"`
Representative string `json:"representative,omitempty"`
Draft submissionDraftJSON `json:"draft"`
Rule *submissionRuleSummary `json:"rule,omitempty"`
ResolvedBag services.PlaceholderMap `json:"resolved_bag"`
MergedBag services.PlaceholderMap `json:"merged_bag"`
PreviewHTML string `json:"preview_html"`
Lang string `json:"lang"`
HasTemplate bool `json:"has_template"`
TemplateMissing bool `json:"template_missing,omitempty"`
}
type submissionDraftJSON struct {
ID uuid.UUID `json:"id"`
ProjectID *uuid.UUID `json:"project_id"`
SubmissionCode string `json:"submission_code"`
UserID uuid.UUID `json:"user_id"`
Name string `json:"name"`
Variables services.PlaceholderMap `json:"variables"`
SelectedParties []uuid.UUID `json:"selected_parties"`
LastExportedAt *time.Time `json:"last_exported_at,omitempty"`
LastExportedSHA *string `json:"last_exported_sha,omitempty"`
LastImportedAt *time.Time `json:"last_imported_at,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
ID uuid.UUID `json:"id"`
ProjectID *uuid.UUID `json:"project_id"`
SubmissionCode string `json:"submission_code"`
UserID uuid.UUID `json:"user_id"`
Name string `json:"name"`
Variables services.PlaceholderMap `json:"variables"`
LastExportedAt *time.Time `json:"last_exported_at,omitempty"`
LastExportedSHA *string `json:"last_exported_sha,omitempty"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
type submissionRuleSummary struct {
Name string `json:"name"`
NameEN string `json:"name_en"`
SubmissionCode string `json:"submission_code"`
PrimaryParty string `json:"primary_party,omitempty"`
EventType string `json:"event_type,omitempty"`
LegalSource string `json:"legal_source,omitempty"`
LegalSourcePretty string `json:"legal_source_pretty,omitempty"`
LegalSourcePrettyEN string `json:"legal_source_pretty_en,omitempty"`
Name string `json:"name"`
NameEN string `json:"name_en"`
SubmissionCode string `json:"submission_code"`
PrimaryParty string `json:"primary_party,omitempty"`
EventType string `json:"event_type,omitempty"`
LegalSource string `json:"legal_source,omitempty"`
LegalSourcePretty string `json:"legal_source_pretty,omitempty"`
LegalSourcePrettyEN string `json:"legal_source_pretty_en,omitempty"`
}
type submissionDraftListResponse struct {
@@ -116,9 +101,8 @@ type submissionDraftListResponse struct {
}
type submissionDraftPatchInput struct {
Name *string `json:"name,omitempty"`
Variables *services.PlaceholderMap `json:"variables,omitempty"`
SelectedParties *[]uuid.UUID `json:"selected_parties,omitempty"`
Name *string `json:"name,omitempty"`
Variables *services.PlaceholderMap `json:"variables,omitempty"`
}
// ─────────────────────────────────────────────────────────────────────
@@ -353,7 +337,7 @@ func handlePatchSubmissionDraft(w http.ResponseWriter, r *http.Request) {
return
}
patch := services.DraftPatch{Name: input.Name, Variables: input.Variables, SelectedParties: input.SelectedParties}
patch := services.DraftPatch{Name: input.Name, Variables: input.Variables}
d, err := dbSvc.submissionDraft.Update(r.Context(), uid, draftID, patch)
if err != nil {
writeSubmissionDraftServiceError(w, err)
@@ -691,17 +675,13 @@ type globalDraftPatchInput struct {
// "set to null". Set by the custom UnmarshalJSON below.
ProjectID *uuid.UUID `json:"project_id,omitempty"`
projectIDProvided bool
// SelectedParties: present-but-empty array resets to "all parties",
// present non-empty array restricts to subset, absent = no change.
SelectedParties *[]uuid.UUID `json:"selected_parties,omitempty"`
}
func (g *globalDraftPatchInput) UnmarshalJSON(data []byte) error {
type alias struct {
Name *string `json:"name,omitempty"`
Variables *services.PlaceholderMap `json:"variables,omitempty"`
ProjectID *uuid.UUID `json:"project_id,omitempty"`
SelectedParties *[]uuid.UUID `json:"selected_parties,omitempty"`
Name *string `json:"name,omitempty"`
Variables *services.PlaceholderMap `json:"variables,omitempty"`
ProjectID *uuid.UUID `json:"project_id,omitempty"`
}
var a alias
if err := json.Unmarshal(data, &a); err != nil {
@@ -710,7 +690,6 @@ func (g *globalDraftPatchInput) UnmarshalJSON(data []byte) error {
g.Name = a.Name
g.Variables = a.Variables
g.ProjectID = a.ProjectID
g.SelectedParties = a.SelectedParties
// Detect whether "project_id" was present in the JSON object.
var raw map[string]json.RawMessage
if err := json.Unmarshal(data, &raw); err != nil {
@@ -747,7 +726,7 @@ func handleGlobalPatchSubmissionDraft(w http.ResponseWriter, r *http.Request) {
return
}
patch := services.DraftPatch{Name: in.Name, Variables: in.Variables, SelectedParties: in.SelectedParties}
patch := services.DraftPatch{Name: in.Name, Variables: in.Variables}
if in.projectIDProvided {
pid := in.ProjectID // may be nil → detach
patch.ProjectID = &pid
@@ -769,48 +748,6 @@ func handleGlobalPatchSubmissionDraft(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, view)
}
// handleImportFromProject re-pulls every project-derived variable on
// the draft and bumps last_imported_at (t-paliad-277). The service-
// layer call strips overrides for project.* / parties.* / deadline.* /
// procedural_event.* / rule.* prefixes; firm.* / today.* / user.*
// overrides survive because those values aren't sourced from the
// project record.
//
// Idempotent on repeat clicks. Returns the full editor view so the
// frontend can refresh in one round-trip.
func handleImportFromProject(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
return
}
uid, ok := requireUser(w, r)
if !ok {
return
}
draftID, ok := parseUUIDPath(w, r, "draft_id", "draft id")
if !ok {
return
}
if dbSvc.submissionDraft == nil {
writeJSON(w, http.StatusServiceUnavailable, map[string]string{"error": "submission drafts not configured"})
return
}
d, err := dbSvc.submissionDraft.ImportFromProject(r.Context(), uid, draftID)
if err != nil {
writeSubmissionDraftServiceError(w, err)
return
}
user, _ := dbSvc.users.GetByID(r.Context(), uid)
lang := userLang(user)
view, err := buildSubmissionDraftView(r.Context(), d, lang)
if err != nil {
log.Printf("submission_drafts: build view after import (draft=%s): %v", draftID, err)
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "internal error"})
return
}
writeJSON(w, http.StatusOK, view)
}
// handleGlobalDeleteSubmissionDraft removes a draft by id.
func handleGlobalDeleteSubmissionDraft(w http.ResponseWriter, r *http.Request) {
if !requireDB(w) {
@@ -922,10 +859,9 @@ func serveSubmissionDraftNotFound(w http.ResponseWriter) {
// per-rule heading.
func buildSubmissionDraftView(ctx context.Context, d *services.SubmissionDraft, lang string) (*submissionDraftView, error) {
view := &submissionDraftView{
Draft: draftToJSON(d),
Lang: lang,
HasTemplate: true,
AvailableParties: []submissionDraftPartyJSON{},
Draft: draftToJSON(d),
Lang: lang,
HasTemplate: true,
}
merged, resolved, err := dbSvc.submissionDraft.BuildRenderBag(ctx, d)
@@ -937,27 +873,14 @@ func buildSubmissionDraftView(ctx context.Context, d *services.SubmissionDraft,
if resolved.Lang != "" {
view.Lang = resolved.Lang
}
if len(resolved.Parties) > 0 {
view.AvailableParties = make([]submissionDraftPartyJSON, 0, len(resolved.Parties))
for _, p := range resolved.Parties {
row := submissionDraftPartyJSON{ID: p.ID, Name: p.Name}
if p.Role != nil {
row.Role = *p.Role
}
if p.Representative != nil {
row.Representative = *p.Representative
}
view.AvailableParties = append(view.AvailableParties, row)
}
}
if resolved.Rule != nil {
view.Rule = &submissionRuleSummary{
Name: derefStringHandler(resolved.Rule.SubmissionCode),
SubmissionCode: derefStringHandler(resolved.Rule.SubmissionCode),
NameEN: resolved.Rule.NameEN,
PrimaryParty: derefStringHandler(resolved.Rule.PrimaryParty),
EventType: derefStringHandler(resolved.Rule.EventType),
LegalSource: derefStringHandler(resolved.Rule.LegalSource),
Name: derefStringHandler(resolved.Rule.SubmissionCode),
SubmissionCode: derefStringHandler(resolved.Rule.SubmissionCode),
NameEN: resolved.Rule.NameEN,
PrimaryParty: derefStringHandler(resolved.Rule.PrimaryParty),
EventType: derefStringHandler(resolved.Rule.EventType),
LegalSource: derefStringHandler(resolved.Rule.LegalSource),
}
view.Rule.Name = resolved.Rule.Name
view.Rule.LegalSourcePretty = merged["rule.legal_source_pretty"]
@@ -1035,10 +958,6 @@ func draftToJSON(d *services.SubmissionDraft) submissionDraftJSON {
if vars == nil {
vars = services.PlaceholderMap{}
}
selected := d.SelectedParties
if selected == nil {
selected = []uuid.UUID{}
}
return submissionDraftJSON{
ID: d.ID,
ProjectID: d.ProjectID,
@@ -1046,10 +965,8 @@ func draftToJSON(d *services.SubmissionDraft) submissionDraftJSON {
UserID: d.UserID,
Name: d.Name,
Variables: vars,
SelectedParties: selected,
LastExportedAt: d.LastExportedAt,
LastExportedSHA: d.LastExportedSHA,
LastImportedAt: d.LastImportedAt,
CreatedAt: d.CreatedAt,
UpdatedAt: d.UpdatedAt,
}

View File

@@ -30,7 +30,6 @@ import (
"github.com/google/uuid"
"github.com/jmoiron/sqlx"
"github.com/lib/pq"
"mgit.msbls.de/m/paliad/internal/models"
)
@@ -43,28 +42,20 @@ import (
// 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:"-"`
SelectedPartiesRaw pq.StringArray `db:"selected_parties" json:"-"`
LastExportedAt *time.Time `db:"last_exported_at" json:"last_exported_at,omitempty"`
LastExportedSHA *string `db:"last_exported_sha" json:"last_exported_sha,omitempty"`
LastImportedAt *time.Time `db:"last_imported_at" json:"last_imported_at,omitempty"`
CreatedAt time.Time `db:"created_at" json:"created_at"`
UpdatedAt time.Time `db:"updated_at" json:"updated_at"`
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"`
// SelectedParties is the parsed uuid form of SelectedPartiesRaw —
// populated on read by decodeSelectedParties(). An empty slice keeps
// the backward-compat "include every party" behaviour; a non-empty
// slice restricts the variable bag to the listed paliad.parties rows.
SelectedParties []uuid.UUID `json:"selected_parties"`
}
// SubmissionDraftService handles CRUD on submission_drafts and exposes
@@ -103,11 +94,6 @@ type DraftPatch struct {
Name *string
Variables *PlaceholderMap
ProjectID **uuid.UUID
// SelectedParties: nil = no change. A non-nil pointer always writes
// the column; pass *p = nil or an empty slice to reset to "include
// every party on the project" (the backward-compat default).
SelectedParties *[]uuid.UUID
}
// ErrSubmissionDraftNotFound is the sentinel for "no draft with that id
@@ -121,9 +107,7 @@ var ErrSubmissionDraftNameTaken = errors.New("submission draft: name already tak
// 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, selected_parties,
last_exported_at, last_exported_sha,
last_imported_at,
variables, last_exported_at, last_exported_sha,
created_at, updated_at`
// List returns every draft for (project, submission_code, user)
@@ -143,7 +127,7 @@ func (s *SubmissionDraftService) List(ctx context.Context, userID, projectID uui
return nil, fmt.Errorf("list submission drafts: %w", err)
}
for i := range rows {
if err := rows[i].decode(); err != nil {
if err := rows[i].decodeVariables(); err != nil {
return nil, err
}
}
@@ -174,8 +158,7 @@ func (s *SubmissionDraftService) ListAllForUser(ctx context.Context, userID uuid
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.selected_parties,
d.last_exported_at, d.last_exported_sha, d.last_imported_at,
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
@@ -192,7 +175,7 @@ func (s *SubmissionDraftService) ListAllForUser(ctx context.Context, userID uuid
return nil, fmt.Errorf("list all submission drafts for user: %w", err)
}
for i := range rows {
if err := rows[i].decode(); err != nil {
if err := rows[i].decodeVariables(); err != nil {
return nil, err
}
}
@@ -230,7 +213,7 @@ func (s *SubmissionDraftService) Get(ctx context.Context, userID, draftID uuid.U
return nil, err
}
}
if err := d.decode(); err != nil {
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
@@ -258,7 +241,7 @@ func (s *SubmissionDraftService) EnsureLatest(ctx context.Context, userID, proje
if err != nil {
return nil, fmt.Errorf("ensure latest submission draft: %w", err)
}
if err := d.decode(); err != nil {
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
@@ -290,7 +273,7 @@ func (s *SubmissionDraftService) Create(ctx context.Context, userID uuid.UUID, p
if err != nil {
return nil, fmt.Errorf("create submission draft: %w", err)
}
if err := d.decode(); err != nil {
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
@@ -411,17 +394,6 @@ func (s *SubmissionDraftService) Update(ctx context.Context, userID, draftID uui
idx++
}
if patch.SelectedParties != nil {
ids := *patch.SelectedParties
strs := make([]string, 0, len(ids))
for _, id := range ids {
strs = append(strs, id.String())
}
setParts = append(setParts, fmt.Sprintf("selected_parties = $%d::uuid[]", idx))
args = append(args, pq.StringArray(strs))
idx++
}
if len(setParts) == 0 {
return existing, nil
}
@@ -443,7 +415,7 @@ func (s *SubmissionDraftService) Update(ctx context.Context, userID, draftID uui
if err != nil {
return nil, fmt.Errorf("update submission draft: %w", err)
}
if err := d.decode(); err != nil {
if err := d.decodeVariables(); err != nil {
return nil, err
}
return &d, nil
@@ -464,82 +436,6 @@ func (s *SubmissionDraftService) Delete(ctx context.Context, userID, draftID uui
return nil
}
// ImportFromProject re-pulls every project-derived variable on the
// draft by stripping the lawyer's overrides for those keys and bumping
// `last_imported_at`. Project-derived prefixes today are project.*,
// parties.*, deadline.* and (because the rule is keyed on
// submission_code) procedural_event.* / rule.*; the lawyer's overrides
// for firm.*, today.*, user.* survive because those values aren't
// "imported from the project" in any meaningful sense.
//
// Idempotent on repeat clicks: nothing else mutates on the second
// call apart from the new timestamp. The draft must be owned by the
// caller (Get() applies the same ErrNotFound semantics as the rest of
// the service).
func (s *SubmissionDraftService) ImportFromProject(ctx context.Context, userID, draftID uuid.UUID) (*SubmissionDraft, error) {
existing, err := s.Get(ctx, userID, draftID)
if err != nil {
return nil, err
}
if existing.ProjectID == nil {
// No project to import from — surface as 400 via ErrInvalidInput.
return nil, fmt.Errorf("%w: cannot import from project on a project-less draft", ErrInvalidInput)
}
// Strip overrides that came from project state.
cleaned := PlaceholderMap{}
for k, v := range existing.Variables {
if isProjectDerivedKey(k) {
continue
}
cleaned[k] = v
}
raw, err := json.Marshal(cleaned)
if err != nil {
return nil, fmt.Errorf("marshal variables: %w", err)
}
var d SubmissionDraft
err = s.db.GetContext(ctx, &d,
`UPDATE paliad.submission_drafts
SET variables = $1::jsonb,
last_imported_at = now()
WHERE id = $2 AND user_id = $3
RETURNING `+draftColumns,
string(raw), draftID, userID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrSubmissionDraftNotFound
}
if err != nil {
return nil, fmt.Errorf("import from project: %w", err)
}
if err := d.decode(); err != nil {
return nil, err
}
return &d, nil
}
// isProjectDerivedKey reports whether a placeholder key sources its
// value from the project record (rather than firm-wide or user-wide
// state). The "Aus Projekt importieren" affordance strips overrides
// for exactly these keys so the lawyer's manual edits don't survive
// a re-pull.
func isProjectDerivedKey(key string) bool {
switch {
case strings.HasPrefix(key, "project."):
return true
case strings.HasPrefix(key, "parties."):
return true
case strings.HasPrefix(key, "deadline."):
return true
case strings.HasPrefix(key, "procedural_event."):
return true
case strings.HasPrefix(key, "rule."):
return true
}
return false
}
// 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 {
@@ -565,9 +461,9 @@ func (s *SubmissionDraftService) MarkExported(ctx context.Context, draftID uuid.
//
// 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)
// 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
@@ -577,10 +473,9 @@ func (s *SubmissionDraftService) MarkExported(ctx context.Context, draftID uuid.
// 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,
SelectedParties: draft.SelectedParties,
UserID: draft.UserID,
ProjectID: draft.ProjectID,
SubmissionCode: draft.SubmissionCode,
})
if err != nil {
return nil, nil, err
@@ -652,17 +547,8 @@ func (s *SubmissionDraftService) RenderProjectSubmission(ctx context.Context, us
return out, resolved, nil
}
// decode fills the parsed views (Variables, SelectedParties) from the
// raw scan fields. Called by every fetch path so the caller sees both
// populated together.
func (d *SubmissionDraft) decode() error {
if err := d.decodeVariables(); err != nil {
return err
}
return d.decodeSelectedParties()
}
// 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{}
@@ -676,28 +562,6 @@ func (d *SubmissionDraft) decodeVariables() error {
return nil
}
// decodeSelectedParties parses the uuid[] payload from pq.StringArray
// into []uuid.UUID. Unparseable entries are dropped so a single bad
// row never bricks the fetch — the worst case is one extra party
// silently dropped from the selection, which surfaces as it not being
// rendered in the merged document.
func (d *SubmissionDraft) decodeSelectedParties() error {
if len(d.SelectedPartiesRaw) == 0 {
d.SelectedParties = nil
return nil
}
out := make([]uuid.UUID, 0, len(d.SelectedPartiesRaw))
for _, s := range d.SelectedPartiesRaw {
id, err := uuid.Parse(s)
if err != nil {
continue
}
out = append(out, id)
}
d.SelectedParties = 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 —

View File

@@ -327,6 +327,40 @@ func TestRenderHTML_WrapsMissingMarker(t *testing.T) {
}
}
// TestRenderHTML_WrapsOverriddenValueSameAsResolved is the t-paliad-274
// regression: m's report on m/paliad#106 was that "When filled, the link
// disappears". The preview HTML must wrap an override value with the
// same <span class="draft-var"> as it would an unfilled placeholder, so
// the click-jump from preview→sidebar persists after the user types a
// value. There is no distinction at the renderer level between a value
// that came from the resolved bag (project / parties / deadline lookups)
// and a value the lawyer typed into the sidebar — both arrive in the
// same PlaceholderMap and both must be wrapped.
func TestRenderHTML_WrapsOverriddenValueSameAsResolved(t *testing.T) {
doc := `<w:document><w:body>` +
`<w:p><w:r><w:t>{{project.case_number}} / {{firm.name}}</w:t></w:r></w:p>` +
`</w:body></w:document>`
tmpl := minimalMergeDOCX(t, doc)
r := NewSubmissionRenderer()
// project.case_number is the typed-by-lawyer override.
// firm.name is the always-resolved value from the firm bag.
html, err := r.RenderHTML(tmpl, PlaceholderMap{
"project.case_number": "UPC_CFI_42/2026",
"firm.name": "HLC",
}, nil)
if err != nil {
t.Fatalf("render html: %v", err)
}
wantOverride := `<span class="draft-var" data-var="project.case_number">UPC_CFI_42/2026</span>`
if !strings.Contains(html, wantOverride) {
t.Errorf("expected overridden value wrapped in draft-var span (click-jump must persist after fill, t-paliad-274), got %q", html)
}
wantResolved := `<span class="draft-var" data-var="firm.name">HLC</span>`
if !strings.Contains(html, wantResolved) {
t.Errorf("expected resolved value still wrapped, 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

View File

@@ -72,17 +72,10 @@ func NewSubmissionVarsService(db *sqlx.DB, projects *ProjectService, parties *Pa
// 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.
//
// SelectedParties is the t-paliad-277 multi-party selection: an empty
// or nil slice means "include every party on the project" (the
// backward-compat default that every legacy draft renders with); a
// non-empty slice restricts the variable bag to the listed parties so
// the submission only mentions the chosen subset.
type SubmissionVarsContext struct {
UserID uuid.UUID
ProjectID *uuid.UUID
SubmissionCode string
SelectedParties []uuid.UUID
UserID uuid.UUID
ProjectID *uuid.UUID
SubmissionCode string
}
// SubmissionVarsResult bundles the placeholder map with the lookup
@@ -181,7 +174,7 @@ func (s *SubmissionVarsService) Build(ctx context.Context, in SubmissionVarsCont
}
addProjectVars(bag, project, pt, lang)
addPartyVars(bag, filterPartiesBySelection(parties, in.SelectedParties))
addPartyVars(bag, parties)
addDeadlineVars(bag, next, project, lang)
out.Project = project
@@ -191,30 +184,6 @@ func (s *SubmissionVarsService) Build(ctx context.Context, in SubmissionVarsCont
return out, nil
}
// filterPartiesBySelection returns the subset of parties whose IDs
// appear in selected. An empty or nil `selected` slice is the
// backward-compat default — every party flows through unchanged. A
// non-empty slice preserves the input ordering of `parties` (which is
// stable by name from PartyService.ListForProject) so the bag's
// "first claimant / first defendant / first other" picks remain
// deterministic for a given project state.
func filterPartiesBySelection(parties []models.Party, selected []uuid.UUID) []models.Party {
if len(selected) == 0 {
return parties
}
allowed := make(map[uuid.UUID]struct{}, len(selected))
for _, id := range selected {
allowed[id] = struct{}{}
}
out := make([]models.Party, 0, len(parties))
for _, p := range parties {
if _, ok := allowed[p.ID]; ok {
out = append(out, p)
}
}
return out
}
// loadPublishedRule fetches the published procedural-event template
// (paliad.deadline_rules row) keyed by submission_code. Restricts to
// lifecycle_state='published' so drafts never end up shaping a real
@@ -355,98 +324,42 @@ func addProjectVars(bag PlaceholderMap, p *models.Project, pt *models.Proceeding
}
}
// addPartyVars populates the parties.* namespace from the (already
// filtered) list of parties.
//
// Three forms coexist per role (claimant / defendant / other) so
// templates authored against any of them keep merging correctly:
//
// - Comma-joined list (t-paliad-277, primary form for multi-party
// suits):
//
// {{parties.claimants}} — all claimants' names
// {{parties.claimants.representatives}}
// {{parties.defendants}} / .representatives
// {{parties.others}} / .representatives
//
// - Indexed access (templates that need the primary individually):
//
// {{parties.claimant.0.name}} / .representative
// {{parties.defendant.0.name}} / .representative
// {{parties.other.0.name}} / .representative
//
// - Flat legacy (kept forever per the issue's backward-compat
// contract; resolves to the FIRST selected party of each role):
//
// {{parties.claimant.name}} / .representative
// {{parties.defendant.name}} / .representative
// {{parties.other.name}} / .representative
//
// Role bucketing matches the prior shape: German strings ("Kläger",
// "Beklagte") and their English equivalents fold into claimant /
// defendant; everything else (Streithelfer, Patentinhaberin, …) flows
// into "other".
// addPartyVars populates parties.* using the first row of each role.
// Multi-claimant / multi-defendant suits use the first row in Slice 1
// per design §13.6; expanded grouping is Phase 2.
func addPartyVars(bag PlaceholderMap, parties []models.Party) {
var claimants, defendants, others []models.Party
var claimant, defendant, other *models.Party
for i := range parties {
role := strings.ToLower(strings.TrimSpace(derefString(parties[i].Role)))
switch role {
case "claimant", "kläger", "klaeger", "klägerin", "klaegerin":
claimants = append(claimants, parties[i])
case "claimant", "kläger", "klaeger":
if claimant == nil {
claimant = &parties[i]
}
case "defendant", "beklagter", "beklagte":
defendants = append(defendants, parties[i])
if defendant == nil {
defendant = &parties[i]
}
default:
others = append(others, parties[i])
if other == nil {
other = &parties[i]
}
}
}
emitPartyGroup(bag, "claimant", "claimants", claimants)
emitPartyGroup(bag, "defendant", "defendants", defendants)
emitPartyGroup(bag, "other", "others", others)
}
// emitPartyGroup writes the three forms (joined list, indexed access,
// flat legacy first-of-role) for a single role bucket. `singular` is
// the legacy/indexed prefix (claimant / defendant / other); `plural`
// is the joined-list prefix (claimants / defendants / others).
func emitPartyGroup(bag PlaceholderMap, singular, plural string, group []models.Party) {
names := make([]string, 0, len(group))
reps := make([]string, 0, len(group))
for _, p := range group {
names = append(names, p.Name)
reps = append(reps, derefString(p.Representative))
if claimant != nil {
bag["parties.claimant.name"] = claimant.Name
bag["parties.claimant.representative"] = derefString(claimant.Representative)
}
bag["parties."+plural] = strings.Join(names, ", ")
bag["parties."+plural+".representatives"] = joinNonEmpty(reps, ", ")
for i, p := range group {
idx := fmt.Sprintf("parties.%s.%d", singular, i)
bag[idx+".name"] = p.Name
bag[idx+".representative"] = derefString(p.Representative)
if defendant != nil {
bag["parties.defendant.name"] = defendant.Name
bag["parties.defendant.representative"] = derefString(defendant.Representative)
}
if len(group) > 0 {
first := group[0]
bag["parties."+singular+".name"] = first.Name
bag["parties."+singular+".representative"] = derefString(first.Representative)
if other != nil {
bag["parties.other.name"] = other.Name
bag["parties.other.representative"] = derefString(other.Representative)
}
}
// joinNonEmpty joins a slice with sep but skips empty entries so a
// list of representatives where one party has no representative reads
// as "A, B" instead of "A, , B".
func joinNonEmpty(parts []string, sep string) string {
out := make([]string, 0, len(parts))
for _, p := range parts {
if strings.TrimSpace(p) == "" {
continue
}
out = append(out, p)
}
return strings.Join(out, sep)
}
// addRuleVars populates the procedural-event variable namespace —
// code, name(_en), legal_source (+ pretty form), primary_party, kind.
//

View File

@@ -1,200 +0,0 @@
package services
// Multi-party variable bag tests (t-paliad-277 / m/paliad#109).
//
// Pins the three coexisting forms that addPartyVars emits per role:
//
// - Comma-joined list: parties.claimants / .defendants / .others
// - Indexed access: parties.claimant.0.name, parties.defendant.0.name, …
// - Flat legacy (first-of): parties.claimant.name, parties.defendant.name, …
//
// Also covers filterPartiesBySelection — the empty-selection default
// (every party included) and the non-empty restriction.
import (
"strings"
"testing"
"github.com/google/uuid"
"mgit.msbls.de/m/paliad/internal/models"
)
func mkParty(name, role, rep string) models.Party {
p := models.Party{
ID: uuid.New(),
Name: name,
}
if role != "" {
r := role
p.Role = &r
}
if rep != "" {
r := rep
p.Representative = &r
}
return p
}
func TestAddPartyVars_MultiPartyMixedRoles(t *testing.T) {
t.Parallel()
parties := []models.Party{
mkParty("Acme Inc.", "claimant", "Maria Schmidt"),
mkParty("Globex GmbH", "claimant", ""),
mkParty("Initech", "defendant", "John Doe"),
mkParty("Streithelferin", "intervenor", ""),
}
bag := PlaceholderMap{}
addPartyVars(bag, parties)
wants := map[string]string{
// Comma-joined per role.
"parties.claimants": "Acme Inc., Globex GmbH",
"parties.claimants.representatives": "Maria Schmidt", // Globex has no rep → skipped from join.
"parties.defendants": "Initech",
"parties.defendants.representatives": "John Doe",
"parties.others": "Streithelferin",
"parties.others.representatives": "",
// Indexed access.
"parties.claimant.0.name": "Acme Inc.",
"parties.claimant.0.representative": "Maria Schmidt",
"parties.claimant.1.name": "Globex GmbH",
"parties.claimant.1.representative": "",
"parties.defendant.0.name": "Initech",
"parties.defendant.0.representative": "John Doe",
"parties.other.0.name": "Streithelferin",
// Flat legacy: first-of-role.
"parties.claimant.name": "Acme Inc.",
"parties.claimant.representative": "Maria Schmidt",
"parties.defendant.name": "Initech",
"parties.defendant.representative": "John Doe",
"parties.other.name": "Streithelferin",
}
for key, want := range wants {
got, ok := bag[key]
if !ok {
t.Errorf("missing key %q in bag", key)
continue
}
if got != want {
t.Errorf("bag[%q] = %q, want %q", key, got, want)
}
}
}
func TestAddPartyVars_GermanRoleStrings(t *testing.T) {
t.Parallel()
// German role strings on real-world data must bucket the same as
// the English equivalents — "Kläger" / "Klägerin" → claimants.
parties := []models.Party{
mkParty("Erika Musterfrau", "Klägerin", ""),
mkParty("Max Mustermann", "Beklagter", ""),
}
bag := PlaceholderMap{}
addPartyVars(bag, parties)
if got := bag["parties.claimants"]; got != "Erika Musterfrau" {
t.Errorf("parties.claimants = %q, want %q", got, "Erika Musterfrau")
}
if got := bag["parties.defendants"]; got != "Max Mustermann" {
t.Errorf("parties.defendants = %q, want %q", got, "Max Mustermann")
}
// Backward-compat: legacy flat alias resolves to the first row of
// the German-bucketed group.
if got := bag["parties.claimant.name"]; got != "Erika Musterfrau" {
t.Errorf("parties.claimant.name = %q, want %q", got, "Erika Musterfrau")
}
}
func TestAddPartyVars_BackwardCompatFlatAliasResolvesFirstRow(t *testing.T) {
t.Parallel()
// Critical guarantee from m/paliad#109: templates that say
// {{parties.claimant.name}} (old shape) must keep merging — they
// resolve to the FIRST selected claimant. Pinning this stops a
// future refactor silently dropping the alias and breaking every
// .docx in the repo.
parties := []models.Party{
mkParty("FirstCo", "claimant", "Repr A"),
mkParty("SecondCo", "claimant", "Repr B"),
}
bag := PlaceholderMap{}
addPartyVars(bag, parties)
if got := bag["parties.claimant.name"]; got != "FirstCo" {
t.Errorf("parties.claimant.name (flat alias) = %q, want %q (first selected claimant)",
got, "FirstCo")
}
if got := bag["parties.claimant.representative"]; got != "Repr A" {
t.Errorf("parties.claimant.representative (flat alias) = %q, want %q",
got, "Repr A")
}
}
func TestFilterPartiesBySelection_EmptyMeansAll(t *testing.T) {
t.Parallel()
parties := []models.Party{
mkParty("A", "claimant", ""),
mkParty("B", "defendant", ""),
}
got := filterPartiesBySelection(parties, nil)
if len(got) != 2 {
t.Fatalf("empty selection should include every party, got %d/%d", len(got), len(parties))
}
got = filterPartiesBySelection(parties, []uuid.UUID{})
if len(got) != 2 {
t.Fatalf("empty []uuid selection should include every party, got %d/%d", len(got), len(parties))
}
}
func TestFilterPartiesBySelection_NonEmptyRestricts(t *testing.T) {
t.Parallel()
a := mkParty("Acme", "claimant", "")
b := mkParty("Initech", "defendant", "")
c := mkParty("Globex", "claimant", "")
parties := []models.Party{a, b, c}
got := filterPartiesBySelection(parties, []uuid.UUID{a.ID, c.ID})
if len(got) != 2 {
t.Fatalf("got %d parties, want 2", len(got))
}
// Order must match the input order (PartyService.ListForProject
// returns by name ascending; we preserve that to keep "first
// claimant" deterministic across renders).
if got[0].ID != a.ID || got[1].ID != c.ID {
t.Errorf("selection lost input order: got %v", []string{got[0].Name, got[1].Name})
}
// The "Initech" defendant was deselected; the bag should not list
// it under defendants.
bag := PlaceholderMap{}
addPartyVars(bag, got)
if v, ok := bag["parties.defendants"]; ok && v != "" {
t.Errorf("parties.defendants = %q after deselecting Initech, want empty", v)
}
if !strings.Contains(bag["parties.claimants"], "Acme") || !strings.Contains(bag["parties.claimants"], "Globex") {
t.Errorf("parties.claimants = %q, want both Acme and Globex", bag["parties.claimants"])
}
}
func TestIsProjectDerivedKey(t *testing.T) {
t.Parallel()
derived := []string{
"project.title", "project.proceeding.name",
"parties.claimants", "parties.claimant.0.name",
"deadline.due_date",
"procedural_event.name", "rule.name",
}
for _, k := range derived {
if !isProjectDerivedKey(k) {
t.Errorf("expected %q to be project-derived", k)
}
}
survives := []string{
"firm.name", "today", "today.long_de",
"user.email", "user.display_name",
}
for _, k := range survives {
if isProjectDerivedKey(k) {
t.Errorf("expected %q to survive Import-from-project (firm/today/user namespace)", k)
}
}
}