Compare commits
37 Commits
mai/cronus
...
mai/atlas/
| Author | SHA1 | Date | |
|---|---|---|---|
| 490c8a8c8c | |||
| b1c9e8dd97 | |||
| 9aee9e4101 | |||
| 810b65463e | |||
| 33c5fb2983 | |||
| 76d38c4c84 | |||
| 233547297c | |||
| ba3e0795f8 | |||
| 8dfdd77079 | |||
| 4571bd4980 | |||
| 7584b4f428 | |||
| 70985d88b0 | |||
| 06d6c7540e | |||
| 3e55ff8294 | |||
| 9d688459e3 | |||
| 2a2c5b8033 | |||
| 058a36976b | |||
| 3219bff4d4 | |||
| 081b66ebc8 | |||
| 9ab8dd8e0f | |||
| 4218d9cb52 | |||
| 7ea415145f | |||
| 109946edff | |||
| 528fe35540 | |||
| 9c2788ed8c | |||
| c56859058d | |||
| 6acb1167dd | |||
| 4cd28bc896 | |||
| 568eac0aff | |||
| 733d21c930 | |||
| b05bcf7eeb | |||
| 71e8023784 | |||
| d190fbe0a4 | |||
| e0a82d9f9e | |||
| d326f9aa4a | |||
| 026ad2d5ee | |||
| 13a65a6d6e |
@@ -117,9 +117,13 @@ func run(ctx context.Context, pool *sqlx.DB, output, version, sourceLabel string
|
||||
return fmt.Errorf("mkdir output: %w", err)
|
||||
}
|
||||
|
||||
// 1. Proceeding types — UPC + active only. The unified upc.apl row
|
||||
// 1. Proceeding types — UPC primaries only. The unified upc.apl row
|
||||
// from B1 mig 134 is included; the 3 archived old appeal codes
|
||||
// (is_active=false) are filtered out by the WHERE.
|
||||
// (is_active=false) are filtered out by the is_active predicate.
|
||||
// The kind='proceeding' predicate (mig 153, t-paliad-325) belts the
|
||||
// is_active filter so phase/side_action/meta rows can't slip into
|
||||
// the embedded catalog even if some future deploy re-activates one
|
||||
// for an admin task.
|
||||
var procs []litigationplanner.ProceedingType
|
||||
if err := pool.SelectContext(ctx, &procs, `
|
||||
SELECT id, code, name, name_en, description, jurisdiction,
|
||||
@@ -127,7 +131,9 @@ func run(ctx context.Context, pool *sqlx.DB, output, version, sourceLabel string
|
||||
trigger_event_label_de, trigger_event_label_en,
|
||||
appeal_target
|
||||
FROM paliad.proceeding_types
|
||||
WHERE jurisdiction = 'UPC' AND is_active = true
|
||||
WHERE jurisdiction = 'UPC'
|
||||
AND is_active = true
|
||||
AND kind = 'proceeding'
|
||||
ORDER BY sort_order, id`); err != nil {
|
||||
return fmt.Errorf("select proceeding_types: %w", err)
|
||||
}
|
||||
|
||||
342
cmd/seed-orphan-concept-drafts/main.go
Normal file
342
cmd/seed-orphan-concept-drafts/main.go
Normal file
@@ -0,0 +1,342 @@
|
||||
// Command seed-orphan-concept-drafts stages draft sequencing_rules for
|
||||
// deadline_concepts that have rule_count=0 ("orphans"). It calls the
|
||||
// same services.RuleEditorService.Create that POST
|
||||
// /admin/api/procedural-events runs internally, so the audit trigger
|
||||
// + INSTEAD-OF view trigger fan-out into procedural_events +
|
||||
// sequencing_rules + legal_sources fire identically. No HTTP/auth
|
||||
// shell, no direct SQL writes by this command.
|
||||
//
|
||||
// All rules are created with lifecycle_state='draft' (forced by the
|
||||
// service). The admin still reviews + publishes via
|
||||
// /admin/procedural-events.
|
||||
//
|
||||
// t-paliad-320: editorial backlog from t-paliad-193, four remaining
|
||||
// orphan concepts: counterclaim-for-revocation, versaeumnisurteil-
|
||||
// einspruch, schriftsatznachreichung, weiterbehandlung. The
|
||||
// weiterbehandlung concept gets two drafts (EPC Art. 121 + R. 135
|
||||
// versus DPatG § 123a) since the two regimes have different durations
|
||||
// and jurisdictions.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// DATABASE_URL=postgres://… go run ./cmd/seed-orphan-concept-drafts \
|
||||
// [-dry-run] [-reason "free-text audit reason"]
|
||||
//
|
||||
// Idempotency: the command refuses to insert if any rule for a given
|
||||
// (concept, proceeding_type, rule_code) already exists. Safe to re-run
|
||||
// after a partial failure.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"log"
|
||||
"os"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"mgit.msbls.de/m/paliad/internal/services"
|
||||
)
|
||||
|
||||
// draftSpec captures one CreateRuleInput plus the metadata the command
|
||||
// needs to resolve concept_id + proceeding_type_id from human-readable
|
||||
// slugs/codes. ProceedingCode == "" means event-rooted
|
||||
// (proceeding_type_id = NULL), used for cross-cutting rules whose
|
||||
// jurisdiction has no matching proceeding_type yet.
|
||||
type draftSpec struct {
|
||||
Label string // human label for log output
|
||||
ConceptSlug string
|
||||
ProceedingCode string // "" → NULL proceeding_type_id (event-rooted)
|
||||
SubmissionCode string
|
||||
Name string
|
||||
NameEN string
|
||||
EventKind string
|
||||
PrimaryParty string // "" → omit (NULL)
|
||||
DurationValue int
|
||||
DurationUnit string
|
||||
Timing string
|
||||
Priority string
|
||||
IsCourtSet bool
|
||||
RuleCode string
|
||||
LegalSource string
|
||||
DeadlineNotes string
|
||||
DeadlineNotesEn string
|
||||
}
|
||||
|
||||
func drafts() []draftSpec {
|
||||
return []draftSpec{
|
||||
// ─── 1. counterclaim-for-revocation (UPC R.25.1 ∧ R.23) ───────
|
||||
{
|
||||
Label: "counterclaim-for-revocation → upc.ccr.cfi",
|
||||
ConceptSlug: "counterclaim-for-revocation",
|
||||
ProceedingCode: "upc.ccr.cfi",
|
||||
SubmissionCode: "upc.ccr.cfi.lodge",
|
||||
Name: "Widerklage auf Nichtigkeit (CCR)",
|
||||
NameEN: "Counterclaim for Revocation (CCR)",
|
||||
EventKind: "filing",
|
||||
PrimaryParty: "defendant",
|
||||
DurationValue: 3,
|
||||
DurationUnit: "months",
|
||||
Timing: "after",
|
||||
Priority: "mandatory",
|
||||
IsCourtSet: false,
|
||||
RuleCode: "RoP.025",
|
||||
LegalSource: "UPC.RoP.25.1",
|
||||
DeadlineNotes: "Die Widerklage auf Nichtigkeit (Counterclaim for Revocation, CCR) ist gemeinsam mit der Klageerwiderung (Statement of Defence) einzureichen — d. h. innerhalb von 3 Monaten ab Zustellung der Klageschrift " +
|
||||
"(R. 23 i. V. m. R. 25.1 RoP). Inhaltliche Anforderungen folgen R. 25-30 RoP (insbes. R. 25.1(a)-(c) zu Antrag, Tatsachen und Beweismitteln; R. 27 zu Verfahren nach Einreichung; R. 30 zu einem Antrag auf Änderung des Patents).",
|
||||
DeadlineNotesEn: "The Counterclaim for Revocation (CCR) must be lodged together with the Statement of Defence — i.e. within 3 months of service of the Statement of Claim " +
|
||||
"(Rule 23 in conjunction with Rule 25.1 RoP). Substantive requirements follow Rules 25-30 RoP (in particular R. 25.1(a)-(c) on the application, facts and evidence; R. 27 on post-filing procedure; R. 30 on any application to amend the patent).",
|
||||
},
|
||||
|
||||
// ─── 2. versaeumnisurteil-einspruch (ZPO § 339) ───────────────
|
||||
{
|
||||
Label: "versaeumnisurteil-einspruch → de.inf.lg",
|
||||
ConceptSlug: "versaeumnisurteil-einspruch",
|
||||
ProceedingCode: "de.inf.lg",
|
||||
SubmissionCode: "de.inf.lg.einspruch_vu",
|
||||
Name: "Einspruch gegen Versäumnisurteil",
|
||||
NameEN: "Objection to default judgment",
|
||||
EventKind: "filing",
|
||||
PrimaryParty: "defendant",
|
||||
DurationValue: 2,
|
||||
DurationUnit: "weeks",
|
||||
Timing: "after",
|
||||
Priority: "mandatory",
|
||||
IsCourtSet: false,
|
||||
RuleCode: "§ 339 ZPO",
|
||||
LegalSource: "DE.ZPO.339.1",
|
||||
DeadlineNotes: "Notfrist von 2 Wochen ab Zustellung des Versäumnisurteils (§ 339(1) ZPO). " +
|
||||
"Bei Auslandszustellung oder öffentlicher Bekanntmachung bestimmt das Gericht die Einspruchsfrist gesondert im Versäumnisurteil oder durch nachträglichen Beschluss (§ 339(2) ZPO) — in diesem Fall die gerichtlich festgesetzte Frist mit „Datum setzen“ überschreiben. " +
|
||||
"Form: schriftlich oder zu Protokoll der Geschäftsstelle (§ 340(1) ZPO); die Einspruchsbegründung kann bis zum Verhandlungstermin nachgereicht werden (§ 340(3) ZPO).",
|
||||
DeadlineNotesEn: "Statutory two-week emergency period (Notfrist) from service of the default judgment (§ 339(1) ZPO). " +
|
||||
"If service is abroad or by public notice, the court sets the objection period separately in the default judgment or by a subsequent order (§ 339(2) ZPO) — in that case override with the court-set date. " +
|
||||
"Form: in writing or before the registry clerk (§ 340(1) ZPO); substantive grounds may be filed up to the oral hearing (§ 340(3) ZPO).",
|
||||
},
|
||||
|
||||
// ─── 3. schriftsatznachreichung (ZPO § 283) ───────────────────
|
||||
{
|
||||
Label: "schriftsatznachreichung → de.inf.lg",
|
||||
ConceptSlug: "schriftsatznachreichung",
|
||||
ProceedingCode: "de.inf.lg",
|
||||
SubmissionCode: "de.inf.lg.nachreichung",
|
||||
Name: "Schriftsatznachreichung",
|
||||
NameEN: "Subsequent written submission",
|
||||
EventKind: "filing",
|
||||
PrimaryParty: "", // concept.party = "both" → no default
|
||||
DurationValue: 3,
|
||||
DurationUnit: "weeks",
|
||||
Timing: "after",
|
||||
Priority: "optional",
|
||||
IsCourtSet: true,
|
||||
RuleCode: "§ 283 ZPO",
|
||||
LegalSource: "DE.ZPO.283",
|
||||
DeadlineNotes: "Vom Gericht in der mündlichen Verhandlung gesetzte Schriftsatzfrist gem. § 283 ZPO. " +
|
||||
"Sie wird nur auf Antrag einer Partei bestimmt, die sich auf neues Vorbringen des Gegners nicht erklären konnte. " +
|
||||
"Die konkrete Frist (in der Praxis 2-3 Wochen) und der nachfolgende Verkündungstermin werden im Sitzungsprotokoll bzw. in der prozessleitenden Verfügung festgelegt — Default-Frist hier 3 Wochen, mit „Datum setzen“ überschreiben, sobald die Verfügung vorliegt. " +
|
||||
"Nach Fristablauf darf das Gericht keine weiteren Erklärungen mehr berücksichtigen (§ 283 S. 2, § 296a ZPO).",
|
||||
DeadlineNotesEn: "Court-set written-submission period under § 283 ZPO, granted on a party's application when it could not respond at the oral hearing to the opponent's new submissions. " +
|
||||
"The actual period (in practice 2-3 weeks) and the announcement date are set in the hearing record / case-management order — default 3 weeks here, override via „set date“ once the order is on the file. " +
|
||||
"After expiry, the court will disregard further submissions (§ 283 sent. 2, § 296a ZPO).",
|
||||
},
|
||||
|
||||
// ─── 4. weiterbehandlung — EPC variant (Art. 121 + R. 135) ────
|
||||
{
|
||||
Label: "weiterbehandlung (EPC) → epa.grant.exa",
|
||||
ConceptSlug: "weiterbehandlung",
|
||||
ProceedingCode: "epa.grant.exa",
|
||||
SubmissionCode: "epa.grant.exa.weiterbeh",
|
||||
Name: "Antrag auf Weiterbehandlung",
|
||||
NameEN: "Request for further processing",
|
||||
EventKind: "filing",
|
||||
PrimaryParty: "claimant",
|
||||
DurationValue: 2,
|
||||
DurationUnit: "months",
|
||||
Timing: "after",
|
||||
Priority: "mandatory",
|
||||
IsCourtSet: false,
|
||||
RuleCode: "Art. 121 EPÜ",
|
||||
LegalSource: "EU.EPC-R.135.1",
|
||||
DeadlineNotes: "Antrag auf Weiterbehandlung gem. Art. 121 EPÜ i. V. m. R. 135(1) EPÜ — 2 Monate ab Zustellung der Mitteilung über die Fristversäumung bzw. den eingetretenen Rechtsverlust. " +
|
||||
"Der Antrag wird durch Zahlung der vorgeschriebenen Weiterbehandlungsgebühr gestellt; die versäumte Handlung muss innerhalb derselben 2-Monats-Frist nachgeholt werden (R. 135(1) EPÜ). " +
|
||||
"Die Frist ist nicht verlängerbar. Ausgeschlossen sind insbesondere die Frist für die Weiterbehandlung selbst sowie die in R. 135(2) EPÜ ausdrücklich aufgeführten Fristen (u. a. die Beschwerdefrist nach Art. 108 EPÜ, die Prioritätsfrist nach Art. 87 EPÜ und die Frist zur Wiedereinsetzung).",
|
||||
DeadlineNotesEn: "Request for further processing under Article 121 EPC in conjunction with Rule 135(1) EPC — two months from notification of the communication concerning the missed time limit or the loss of rights. " +
|
||||
"The request is made by payment of the further-processing fee; the omitted act must be completed within the same two-month period (Rule 135(1) EPC). " +
|
||||
"The period is non-extendable. Excluded: the further-processing period itself and the periods listed in Rule 135(2) EPC (notably the appeal period under Art. 108 EPC, the priority period under Art. 87 EPC, and the re-establishment period).",
|
||||
},
|
||||
|
||||
// ─── 5. weiterbehandlung — DPatG § 123a variant ───────────────
|
||||
// No `dpma.grant.*` proceeding_type exists yet, so this rule is
|
||||
// event-rooted (proceeding_type_id NULL) — same pattern as 78
|
||||
// other cross-cutting rules. Editorial follow-up: create a
|
||||
// `dpma.grant.dpma` proceeding_type and reassign.
|
||||
{
|
||||
Label: "weiterbehandlung (DPatG § 123a) → event-rooted (NULL proceeding_type)",
|
||||
ConceptSlug: "weiterbehandlung",
|
||||
ProceedingCode: "", // event-rooted
|
||||
SubmissionCode: "dpma.grant.weiterbeh",
|
||||
Name: "Antrag auf Weiterbehandlung (DPMA)",
|
||||
NameEN: "Request for further processing (DPMA, § 123a PatG)",
|
||||
EventKind: "filing",
|
||||
PrimaryParty: "claimant",
|
||||
DurationValue: 1,
|
||||
DurationUnit: "months",
|
||||
Timing: "after",
|
||||
Priority: "mandatory",
|
||||
IsCourtSet: false,
|
||||
RuleCode: "§ 123a PatG",
|
||||
LegalSource: "DE.PatG.123a.1",
|
||||
DeadlineNotes: "Antrag auf Weiterbehandlung einer DPMA-Patentanmeldung gem. § 123a PatG — 1 Monat ab Zustellung der Mitteilung über die Rechtsfolge der Fristversäumung. " +
|
||||
"Innerhalb dieser Frist müssen (i) der Antrag schriftlich gestellt, (ii) die versäumte Handlung nachgeholt und (iii) die Weiterbehandlungsgebühr nach Patentkostengesetz (PatKostG) gezahlt werden. " +
|
||||
"§ 123a PatG erfasst ausschließlich Anmeldungsfristen, deren Versäumung kraft Gesetzes die Zurückweisung der Anmeldung zur Folge hat. Für sonstige Fristversäumnisse kommt nur die Wiedereinsetzung nach § 123 PatG in Betracht (1 Monat ab Wegfall des Hindernisses, max. 1 Jahr ab Fristablauf). " +
|
||||
"HINWEIS — Taxonomie: bisher kein dpma.grant.* proceeding_type vorhanden; Regel daher event-rooted (proceeding_type_id NULL). Editorial follow-up: dpma.grant.dpma proceeding_type anlegen und diese Regel umhängen.",
|
||||
DeadlineNotesEn: "Request for further processing of a DPMA patent application under § 123a PatG — 1 month from notification of the consequence of the missed deadline. " +
|
||||
"Within this period the applicant must (i) file the written request, (ii) complete the omitted act, and (iii) pay the further-processing fee under the German Patent Costs Act (PatKostG). " +
|
||||
"§ 123a PatG covers only application-stage deadlines whose statutory consequence is rejection. For other missed deadlines, re-establishment under § 123 PatG is the only route (1 month from removal of the obstacle, max 1 year from the missed deadline). " +
|
||||
"TAXONOMY NOTE: no dpma.grant.* proceeding_type exists yet; this rule is event-rooted (proceeding_type_id NULL). Editorial follow-up: create a dpma.grant.dpma proceeding_type and reassign this rule.",
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
dryRun := flag.Bool("dry-run", false, "log the planned drafts but do not write")
|
||||
reason := flag.String("reason", "t-paliad-320: editorial seed of orphan deadline-concept rules (researcher darwin + lex)", "audit reason recorded with each Create()")
|
||||
flag.Parse()
|
||||
|
||||
dbURL := os.Getenv("DATABASE_URL")
|
||||
if dbURL == "" {
|
||||
log.Fatal("DATABASE_URL not set — export the paliad postgres URL before running")
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
conn, err := sqlx.Connect("postgres", dbURL)
|
||||
if err != nil {
|
||||
log.Fatalf("connect db: %v", err)
|
||||
}
|
||||
defer conn.Close()
|
||||
|
||||
rules := services.NewDeadlineRuleService(conn)
|
||||
editor := services.NewRuleEditorService(conn, rules)
|
||||
|
||||
conceptIDs := map[string]uuid.UUID{}
|
||||
proceedingIDs := map[string]int{}
|
||||
specs := drafts()
|
||||
|
||||
for _, s := range specs {
|
||||
if _, ok := conceptIDs[s.ConceptSlug]; ok {
|
||||
continue
|
||||
}
|
||||
var id uuid.UUID
|
||||
if err := conn.GetContext(ctx, &id,
|
||||
`SELECT id FROM paliad.deadline_concepts WHERE slug = $1`, s.ConceptSlug); err != nil {
|
||||
log.Fatalf("lookup concept %q: %v", s.ConceptSlug, err)
|
||||
}
|
||||
conceptIDs[s.ConceptSlug] = id
|
||||
}
|
||||
for _, s := range specs {
|
||||
if s.ProceedingCode == "" {
|
||||
continue
|
||||
}
|
||||
if _, ok := proceedingIDs[s.ProceedingCode]; ok {
|
||||
continue
|
||||
}
|
||||
var id int
|
||||
if err := conn.GetContext(ctx, &id,
|
||||
`SELECT id FROM paliad.proceeding_types WHERE code = $1`, s.ProceedingCode); err != nil {
|
||||
log.Fatalf("lookup proceeding_type %q: %v", s.ProceedingCode, err)
|
||||
}
|
||||
proceedingIDs[s.ProceedingCode] = id
|
||||
}
|
||||
|
||||
fmt.Printf("Seeding %d drafts (dry-run=%v)\n", len(specs), *dryRun)
|
||||
|
||||
for i, s := range specs {
|
||||
conceptID := conceptIDs[s.ConceptSlug]
|
||||
var procID *int
|
||||
if s.ProceedingCode != "" {
|
||||
p := proceedingIDs[s.ProceedingCode]
|
||||
procID = &p
|
||||
}
|
||||
|
||||
// Idempotency: refuse if a rule with the same (concept, proceeding,
|
||||
// rule_code) already exists in any lifecycle state.
|
||||
if existing, err := findExisting(ctx, conn, conceptID, procID, s.RuleCode); err != nil {
|
||||
log.Fatalf("[%d] idempotency check failed for %s: %v", i+1, s.Label, err)
|
||||
} else if existing != uuid.Nil {
|
||||
fmt.Printf(" [%d] SKIP %s — already exists as %s\n", i+1, s.Label, existing)
|
||||
continue
|
||||
}
|
||||
|
||||
input := services.CreateRuleInput{
|
||||
Name: s.Name,
|
||||
NameEN: s.NameEN,
|
||||
ProceedingTypeID: procID,
|
||||
DurationValue: s.DurationValue,
|
||||
DurationUnit: s.DurationUnit,
|
||||
Priority: s.Priority,
|
||||
IsCourtSet: s.IsCourtSet,
|
||||
}
|
||||
input.ConceptID = &conceptID
|
||||
code := s.SubmissionCode
|
||||
input.SubmissionCode = &code
|
||||
ek := s.EventKind
|
||||
input.EventType = &ek
|
||||
t := s.Timing
|
||||
input.Timing = &t
|
||||
rc := s.RuleCode
|
||||
input.RuleCode = &rc
|
||||
ls := s.LegalSource
|
||||
input.LegalSource = &ls
|
||||
dn := s.DeadlineNotes
|
||||
input.DeadlineNotes = &dn
|
||||
dne := s.DeadlineNotesEn
|
||||
input.DeadlineNotesEn = &dne
|
||||
if s.PrimaryParty != "" {
|
||||
pp := s.PrimaryParty
|
||||
input.PrimaryParty = &pp
|
||||
}
|
||||
|
||||
if *dryRun {
|
||||
fmt.Printf(" [%d] DRY %s (concept=%s, proc=%s, code=%s, %d %s, %s)\n",
|
||||
i+1, s.Label, conceptID, codeOrNil(procID), code, s.DurationValue, s.DurationUnit, s.RuleCode)
|
||||
continue
|
||||
}
|
||||
|
||||
row, err := editor.Create(ctx, input, *reason)
|
||||
if err != nil {
|
||||
log.Fatalf(" [%d] CREATE failed for %s: %v", i+1, s.Label, err)
|
||||
}
|
||||
fmt.Printf(" [%d] OK %s → id=%s lifecycle=%s\n",
|
||||
i+1, s.Label, row.ID, row.LifecycleState)
|
||||
}
|
||||
|
||||
fmt.Println("Done.")
|
||||
}
|
||||
|
||||
func findExisting(ctx context.Context, conn *sqlx.DB, conceptID uuid.UUID, procID *int, ruleCode string) (uuid.UUID, error) {
|
||||
var id uuid.UUID
|
||||
q := `
|
||||
SELECT sr.id
|
||||
FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
WHERE pe.concept_id = $1
|
||||
AND sr.rule_code IS NOT DISTINCT FROM $2
|
||||
AND sr.proceeding_type_id IS NOT DISTINCT FROM $3
|
||||
LIMIT 1`
|
||||
err := conn.GetContext(ctx, &id, q, conceptID, ruleCode, procID)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return uuid.Nil, nil
|
||||
}
|
||||
return id, err
|
||||
}
|
||||
|
||||
func codeOrNil(p *int) string {
|
||||
if p == nil {
|
||||
return "<NULL>"
|
||||
}
|
||||
return fmt.Sprintf("%d", *p)
|
||||
}
|
||||
738
docs/assessment-deadline-system-2026-05-27.md
Normal file
738
docs/assessment-deadline-system-2026-05-27.md
Normal file
@@ -0,0 +1,738 @@
|
||||
# Assessment — Deadline + Procedural-Events System
|
||||
|
||||
**Phase 1 of RFC m/paliad#149.** Read-only audit of every consumer of
|
||||
`paliad.sequencing_rules` + `paliad.procedural_events` + the legacy
|
||||
`paliad.trigger_events`, the corpus they project, and the surfaces that
|
||||
read them.
|
||||
|
||||
- Author: athena (consultant role)
|
||||
- Date: 2026-05-27
|
||||
- Live data: youpc Supabase (`paliad` schema), counts captured during the
|
||||
audit window (mig 153 applied).
|
||||
- Scope: assessment only. No design proposals; no schema sketches; no
|
||||
recommendations on column shape. Phase 2 (inventor) decides those.
|
||||
|
||||
---
|
||||
|
||||
## 0. Headline numbers
|
||||
|
||||
| Bucket | Total | Active + published | Notes |
|
||||
|---|--:|--:|---|
|
||||
| `procedural_events` | 236 | 222 | 5 drafts, 9 archived/inactive |
|
||||
| `sequencing_rules` | 236 | 226 | 1:1 row-mirror with events (mig 136 + 140) |
|
||||
| `trigger_events` (legacy) | 110 | — | bigint-keyed catalog; lives parallel to events |
|
||||
| `proceeding_types` | 50 | 23 kind=`proceeding`; 0 active in kind=`phase`/`side_action`/`meta` (mig 153 flipped them off) |
|
||||
|
||||
Rules-corpus shape (active + published, 226 rows):
|
||||
|
||||
| Classification | Rows |
|
||||
|---|--:|
|
||||
| Parent only (chain-linked) | 105 |
|
||||
| Both parent + legacy trigger | 2 |
|
||||
| Legacy `trigger_event_id` only — `proceeding_type_id IS NULL` | **73** |
|
||||
| Neither (root) — `proceeding_type_id` set | 46 |
|
||||
|
||||
Other corpus signals:
|
||||
|
||||
- `condition_expr` populated: 18 rules. Three distinct keys: `flag` (14),
|
||||
`op` + `args` (4 each — always nested AND).
|
||||
- `is_spawn = true`: 4 rules. All four point at the **inactive**
|
||||
`upc.apl.merits` (id=11). The active appeal type is id=160
|
||||
(`upc.apl.unified`). See risk R3.
|
||||
- `is_court_set = true`: 46 rules.
|
||||
- `is_bilateral = true`: 4 rules.
|
||||
- `choices_offered` populated: 28 rules. Three shapes:
|
||||
`{appellant:[…]}` (20), `{skip:[…]}` (6), `{include_ccr:[…]}` (2).
|
||||
- `applies_to_target` populated: 16 rules.
|
||||
- 67 distinct events act as chain-anchors (= parent of ≥1 active rule).
|
||||
That is the *derived* trigger set today.
|
||||
- `paliad.project_event_choices`: schema present, **0 rows** live.
|
||||
- `paliad.scenarios` (mig 145): table created, **0 rows**.
|
||||
`paliad.projects.active_scenario_id`: **0/18 projects** populated.
|
||||
|
||||
A more granular per-proceeding-type breakdown is in §4.
|
||||
|
||||
---
|
||||
|
||||
## 1. Audit — consumers of `sequencing_rules` + `procedural_events`
|
||||
|
||||
Every read site, by surface. File paths are repo-relative.
|
||||
|
||||
### 1.1 Direct services
|
||||
|
||||
| Service | File | What it reads | Surface(s) it backs |
|
||||
|---|---|---|---|
|
||||
| `DeadlineRuleService` | `internal/services/deadline_rule_service.go:14-365` | `paliad.deadline_rules_unified` view (sequencing_rules + procedural_events + legal_sources), + `paliad.trigger_events` for parent-chain labels (`:226-285`) | Admin rules list/editor, Fristenrechner result panel |
|
||||
| `FristenrechnerService` | `internal/services/fristenrechner.go:115-172,1-700+` | `sequencing_rules` + `procedural_events` (proceeding-type catalog; `EXISTS` over rules); scenarios table (`:583-627`) | `/api/tools/fristenrechner` (Mode A + Mode B + Mode C) |
|
||||
| `FristenrechnerService.LookupFollowUps` | `internal/services/fristenrechner_followups.go:87-403` | resolves anchor by `pe.id`/`pe.code`/`sr.id` (`:241-287`); one-hop children via `parent_id` (`:345-403`) | `/api/tools/fristenrechner/follow-ups` |
|
||||
| `DeadlineSearchService` | `internal/services/fristenrechner_search_events.go:143-170,194,233,696` | sequencing_rules ⋈ procedural_events ⋈ proceeding_types + legal_sources; counts child rules via `parent_id` subquery | `/api/tools/fristenrechner/search` |
|
||||
| `EventDeadlineService` | `internal/services/event_deadline_service.go:31-79,186-195,244` | `paliad.trigger_events` + `sequencing_rules WHERE trigger_event_id IS NOT NULL` | `/api/tools/event-deadlines` (legacy bigint surface) |
|
||||
| `EventTriggerService` | `internal/services/event_trigger_service.go:24-230` | `event_types.trigger_event_id` bridge + sequencing_rules | `/api/tools/event-trigger` |
|
||||
| `RuleEditorService` | `internal/services/rule_editor_service.go:104,136,232,371,381,459,625-843` | full CRUD on sequencing_rules + procedural_events; reads `trigger_event_id` as an optional filter on list | `/admin/api/procedural-events/*` (Slice B.5) |
|
||||
| `RuleEditorOrphans` | `internal/services/rule_editor_orphans.go:218-224` | sub-select on sequencing_rules for orphaned deadlines | `/admin/api/orphans` |
|
||||
| `DualWriteService` | `internal/services/dual_write.go` (+ `dual_write_test.go:50-300`) | parity assertion between legacy + unified projection | internal — write-side guard, no HTTP |
|
||||
| `ProjectionService` (SmartTimeline) | `internal/services/projection_service.go:3+` | composes the timeline by reading via `DeadlineRuleService` + `FristenrechnerService`; does NOT touch `sequencing_rules` directly | `GET /api/projects/{id}/timeline`, milestone + counterclaim endpoints in `internal/handlers/projection.go:35-436+` |
|
||||
| `ExportService` | `internal/services/export_service.go:1680` | bulk-exports `paliad.trigger_events` as the `ref__trigger_events` workbook sheet | `/api/admin/export/*` |
|
||||
| `EventChoiceService` | `internal/services/event_choice_service.go:15-180` | reads + writes `paliad.project_event_choices` | per-project flag persistence (no rows live today) |
|
||||
| `EventTypeService` | `internal/services/event_type_service.go:40-414` | user-defined `paliad.event_types` rows with optional `trigger_event_id` bridge | `/api/event-types` + Pipeline C compose |
|
||||
| `ProjectService.validateProceedingTypeCategory` | `internal/services/project_service.go:1176-1267` | reads `paliad.proceeding_types.category` + `kind` + `is_active` | binding guard for `projects.proceeding_type_id` (sister to mig-153 trigger) |
|
||||
|
||||
The handlers behind each route are listed in §1.2.
|
||||
|
||||
### 1.2 HTTP routes
|
||||
|
||||
Every route that ultimately surfaces sequencing/event data. Path
|
||||
literals + handler file:line cited.
|
||||
|
||||
**Knowledge-tool surface (public-ish, behind auth):**
|
||||
|
||||
| Route | Handler | Reads |
|
||||
|---|---|---|
|
||||
| `POST /api/tools/fristenrechner` | `internal/handlers/fristenrechner.go:39-95+` | `FristenrechnerService.CalculateForProceeding` → engine in `pkg/litigationplanner` |
|
||||
| `GET /api/tools/fristenrechner/search` | `internal/handlers/fristenrechner_search.go` (filter params: `event_kind`, `primary_party`, `jurisdiction`) | `DeadlineSearchService.SearchEvents` |
|
||||
| `GET /api/tools/fristenrechner/follow-ups` | `internal/handlers/fristenrechner_followups.go:27-65` | `FristenrechnerService.LookupFollowUps` |
|
||||
| `GET /api/tools/proceeding-types` | `internal/handlers/event_types.go` | proceeding_types filter (event_kind, jurisdiction) |
|
||||
| `GET /api/tools/trigger-events` | `internal/handlers/event_types.go` | trigger_events catalog (active only) |
|
||||
| `POST /api/tools/event-trigger` | `internal/handlers/event_trigger.go:39-106` | unified Pipeline-A + Pipeline-C compose |
|
||||
| `POST /api/tools/event-deadlines` | `internal/handlers/deadline_rules_db.go:67+` | **legacy** bigint trigger_event_id → rule list |
|
||||
|
||||
**SmartTimeline surface (project-bound):**
|
||||
|
||||
| Route | Handler | Reads |
|
||||
|---|---|---|
|
||||
| `GET /api/projects/{id}/timeline` | `internal/handlers/projection.go:35-109` | `ProjectionService.Render` (no direct rule reads — composes via services) |
|
||||
| `POST /api/projects/{id}/timeline/milestone` | `internal/handlers/projection.go:445+` | milestone insert; reads `proceeding_type.kind` via service |
|
||||
| `POST /api/projects/{id}/timeline/counterclaim` | `internal/handlers/projection.go:387-436` | spawns CCR project; reads `parent_id` on response composition |
|
||||
|
||||
**Admin editor surface (`/admin/procedural-events/*`):**
|
||||
|
||||
| Route | Handler | Reads |
|
||||
|---|---|---|
|
||||
| `GET /admin/procedural-events` | `internal/handlers/admin_rules.go:399-402` | page shell |
|
||||
| `GET /admin/procedural-events/{id}/edit` | `:403-470` | editor form (full rule + event JSON) |
|
||||
| `GET /admin/api/procedural-events` | `:101-160` | paginated list w/ canonical `code` + `event_kind` (Slice B.5 wrapper) |
|
||||
| `GET /admin/api/procedural-events/{id}` | `:161-179` | single rule fetch |
|
||||
| `POST /admin/api/procedural-events` | `:180-204` | create draft |
|
||||
| `PATCH /admin/api/procedural-events/{id}` | `:205-233` | edit draft |
|
||||
| `POST /admin/api/procedural-events/{id}/publish` | `:257-279` | publish flow |
|
||||
| `GET /admin/api/procedural-events/{id}/audit` | `:326-361` | audit log |
|
||||
| `GET /admin/api/orphans` | `:471-484` | orphaned deadlines (Slice 10 backfill UI) |
|
||||
| `POST /admin/api/orphans/{id}/resolve` | `:485-520` | link orphan to rule |
|
||||
| `/admin/rules/*` → `/admin/procedural-events/*` | `:761-772` | **301 redirects** (legacy bookmarks; one-slice deprecation window) |
|
||||
| `?trigger_event_id=…` query param | `:119-122` | exposes legacy trigger filter on the admin list |
|
||||
|
||||
**Scenarios surface (mig 145):**
|
||||
|
||||
| Route | Handler |
|
||||
|---|---|
|
||||
| `GET /api/scenarios?project=<id>|abstract=true` | `internal/handlers/scenarios.go:51-90` |
|
||||
| `GET /api/scenarios/{id}` | `:92-113` |
|
||||
| `POST /api/scenarios` | `:115-136` |
|
||||
| `PATCH /api/scenarios/{id}` | `:138-164` |
|
||||
| `DELETE /api/scenarios/{id}` | `:166-200+` |
|
||||
| `POST /api/paliadin/suggest/deadline` | `internal/handlers/paliadin_suggest.go:63+` (deadline drafts via Paliadin; does not read rules directly — calls into `DeadlineService`) |
|
||||
|
||||
Registration: `internal/handlers/handlers.go:497-501, 880`.
|
||||
|
||||
### 1.3 Frontend (TypeScript) consumers
|
||||
|
||||
These call the routes above; **no direct DB access**. References per the
|
||||
i18n key search and `frontend/src/client/*` greps:
|
||||
|
||||
- `frontend/src/admin-rules-list.tsx:24-105+` — admin list page shell;
|
||||
hits `/admin/api/procedural-events*`.
|
||||
- `frontend/src/admin-rules-edit.tsx:29-187+` — admin editor form; reads
|
||||
`procedural_events.edit.field.{code,event_kind,parent}` i18n keys.
|
||||
- `frontend/src/verfahrensablauf.tsx` — proceeding-type ablauf page
|
||||
(mode C); hits `/api/tools/fristenrechner` with proceeding shape.
|
||||
- `frontend/src/client/fristenrechner-wizard.ts:80` — Mode A wizard;
|
||||
`r4: string // procedural_events.code`.
|
||||
- `frontend/src/client/fristenrechner-mode-a.ts` — Mode A search; hits
|
||||
`/api/tools/fristenrechner/search?kind=events`.
|
||||
- `frontend/src/client/fristenrechner-result.ts` — result panel; hits
|
||||
`/api/tools/fristenrechner/follow-ups`.
|
||||
- `frontend/src/client/projects-new.ts` — type-aware project wizard;
|
||||
hits `/api/tools/fristenrechner?proceeding_type_code=…`.
|
||||
- `frontend/src/client/deadlines-detail.ts` — deadline CRUD detail.
|
||||
- i18n keys: `admin.procedural_events.list/edit/col.*` and translations
|
||||
in `frontend/src/client/i18n.ts:3193-3204, 6338-6346+`.
|
||||
|
||||
### 1.4 Offline snapshot
|
||||
|
||||
- `cmd/gen-upc-snapshot/main.go:150-268` — reads `paliad.trigger_events`,
|
||||
the legacy `paliad.deadline_rules` projection (now via the unified
|
||||
view), and `paliad.proceeding_types`. Writes JSON to
|
||||
`pkg/litigationplanner/embedded/upc/{trigger_events.json,
|
||||
rules.json, proceeding_types.json, meta.json}`.
|
||||
- `pkg/litigationplanner/catalog.go` + `engine.go` + `types.go:73-156` —
|
||||
Rule struct carries `TriggerEventID`, `SpawnProceedingTypeID`,
|
||||
`ConditionExpr`, `Priority`, `IsCourtSet`, `PrimaryParty`, `IsSpawn`,
|
||||
`SpawnLabel`, `CombineOp`. youpc.org consumes this snapshot.
|
||||
|
||||
### 1.5 Migrations touching the tables (chronological)
|
||||
|
||||
`internal/db/migrations/`:
|
||||
|
||||
`028_youpc_deadlines_import`, `030_event_types`, `033_trigger_events_de`,
|
||||
`035_event_deadlines_title_de_backfill`, `038_concept_links_and_legal_source`,
|
||||
`046_cross_cutting_triggers`, `047_deadline_search_view`,
|
||||
`051_proceeding_display_order`, `063_frist_verpasst_upc`,
|
||||
`078_unified_rule_columns`, `091_drop_legacy_rule_columns`,
|
||||
`098_submission_codes_prefix_and_rename`, `125_cross_cutting_filter_legal_source`,
|
||||
`132_wave1_tier1_rule_additions`, **`136_procedural_events_additive`**
|
||||
(the schema-authoritative additive split), `139_deadline_rules_unified_view`,
|
||||
**`140_drop_deadline_rules`** (legacy projection dropped),
|
||||
`151_dedupe_null_procedural_events`, `152_dedupe_identical_sequencing_rule_clones`,
|
||||
**`153_proceeding_types_kind`** (kind discriminator + projects FK trigger).
|
||||
|
||||
Mig 145 is scenario-side: creates `paliad.scenarios` (table, **not**
|
||||
a `scenarios` jsonb column on `projects` — the RFC text was imprecise)
|
||||
and `paliad.projects.active_scenario_id` FK.
|
||||
|
||||
---
|
||||
|
||||
## 2. Health-check per consumer
|
||||
|
||||
### 2.1 Works — green
|
||||
|
||||
- **`DualWriteService` parity.** Every CRUD on the editor surface
|
||||
keeps sequencing_rules + procedural_events + legal_sources locked,
|
||||
asserted by `dual_write_test.go:50-202`.
|
||||
- **Admin editor (`/admin/procedural-events/*`).** Full create / edit /
|
||||
publish / audit loop. Drafts state respected.
|
||||
- **Mode A picker via search.** `DeadlineSearchService` filters by
|
||||
`event_kind` / `primary_party` / `jurisdiction`; returns child-rule
|
||||
counts (`fristenrechner_search_events.go:159`).
|
||||
- **Mode B Verfahrensablauf calc.** `pkg/litigationplanner.CalculateRule`
|
||||
+ the `proceeding_type` fan-out works for every type that has any
|
||||
rule (17/23).
|
||||
- **`gen-upc-snapshot`.** UPC snapshot for youpc.org keeps shipping;
|
||||
no DB writes; reads only.
|
||||
- **Counterclaim spawn project creation.**
|
||||
`internal/handlers/projection.go:387-436` + mig 153 trigger guard
|
||||
reject any non-`proceeding` `proceeding_type_id`.
|
||||
- **EventChoiceService** SQL is wired and tested — but see §2.3.
|
||||
|
||||
### 2.2 Works with known caveats — yellow
|
||||
|
||||
- **Spawn rules.** Behaviour is correct in the abstract (rule fires,
|
||||
user can spawn a child case), but every spawn target points at the
|
||||
**inactive** `upc.apl.merits` (id=11). Surfaces that resolve the
|
||||
spawn target via `paliad.proceeding_types` will return an inactive
|
||||
row. See R3. Cited at `sequencing_rules` 4 rows; service code in
|
||||
`fristenrechner_followups.go:388` SELECTs `spt.code` via
|
||||
`LEFT JOIN paliad.proceeding_types spt ON spt.id = sr.spawn_proceeding_type_id`
|
||||
— no `is_active` filter on the join. Frontend renders an "open
|
||||
Berufungsverfahren" CTA that points at a UI flow expecting the
|
||||
active id=160 (`upc.apl.unified`).
|
||||
- **Legacy 73 globals.** 73 rules with `proceeding_type_id IS NULL`
|
||||
and `trigger_event_id NOT NULL`. These all anchor on legacy
|
||||
`null.<8hex>` event codes that don't match any `proceeding_types.code`
|
||||
prefix. They are consumed via `/api/tools/event-deadlines` (the
|
||||
bigint route) AND surface on the unified view. They have no place
|
||||
in the Mode B "proceeding-type ablauf" view because they have no
|
||||
proceeding. See R4.
|
||||
- **Legacy `/api/tools/event-deadlines` route.** Live, used by
|
||||
Pipeline-C `event_types` consumers (`EventTypeService`). The
|
||||
`ExportService:1680` also still emits `ref__trigger_events` to the
|
||||
workbook. Deprecation has been deferred — see R5.
|
||||
|
||||
### 2.3 Broken / leaky — red
|
||||
|
||||
- **B1 — Follow-up cross-party filter is over-broad.**
|
||||
`fristenrechner_followups.go:358-367`:
|
||||
|
||||
```go
|
||||
if party == "claimant" || party == "defendant" {
|
||||
args = append(args, party)
|
||||
where = append(where, fmt.Sprintf(
|
||||
"(sr.primary_party = $%d OR sr.primary_party = 'both' OR sr.primary_party IS NULL)",
|
||||
len(args)))
|
||||
}
|
||||
```
|
||||
|
||||
The filter keeps `both` + `NULL` rules but **drops cross-party
|
||||
follow-ups**. From the corpus there are 39 active rules whose
|
||||
`primary_party` differs from their parent's primary_party (excluding
|
||||
`court`). Example: `upc.inf.cfi.def_to_ccr` is claimant-filed; its
|
||||
child rule `RoP.029.d → reply_def_ccr` is defendant-filed. With
|
||||
`party=claimant` selected on the result view, the defendant child
|
||||
is hidden and the user reads "Keine Folge-Fristen" — a lie. This
|
||||
is the exact bug the RFC §"What's actually broken" item 2 calls
|
||||
out.
|
||||
|
||||
- **B2 — Picker doesn't distinguish triggers from leaves.**
|
||||
`LookupFollowUps` (`fristenrechner_followups.go:241-287`) resolves
|
||||
by `pe.id` / `pe.code` / `sr.id` with no
|
||||
"is-this-event-actually-a-trigger" gate. The data already supports
|
||||
derivation — 67 of 222 active events act as a chain anchor. The
|
||||
picker just isn't wired to the derivation. Compounding: 4 events
|
||||
are *spawn-only* consequences (`upc.{inf,rev,pi,dmgs}.cfi.appeal_spawn`)
|
||||
— picking one returns the spawn rule itself with no follow-ups,
|
||||
which surfaces as "Keine Folge-Fristen".
|
||||
|
||||
- **B3 — Scenario state is forked across three stores by design but
|
||||
zero stores by data.**
|
||||
- `paliad.project_event_choices` (mig 129) — schema present, 0 rows.
|
||||
`EventChoiceService` reads + writes it via
|
||||
`internal/services/event_choice_service.go:74,123,180`.
|
||||
- `paliad.scenarios` (mig 145) — 0 rows, 0/18 projects bound via
|
||||
`active_scenario_id`. `ScenarioService.LoadScenarios` in
|
||||
`internal/services/fristenrechner.go:583-627` reads it.
|
||||
- DOM state on the result view — Verfahrensablauf checkbox state
|
||||
only lives client-side. Confirmed by absence of a write path
|
||||
from `verfahrensablauf.tsx` to either DB-side store.
|
||||
|
||||
The RFC's "three independent stores" claim is *architecturally*
|
||||
true today, but every store is empty. Risk is dormant — until
|
||||
someone enables persistence on either path and the divergence
|
||||
materialises. See R6.
|
||||
|
||||
- **B4 — 6 active `proceeding_types` have zero rules.**
|
||||
`upc.bsv.cfi`, `upc.ccr.cfi`, `upc.costs.cfi`, `upc.dni.cfi`,
|
||||
`upc.epo.review`, `upc.pl.cfi`. They appear in
|
||||
`/api/tools/proceeding-types` (`is_active=true` + `kind='proceeding'`)
|
||||
but produce empty timelines when chosen. The Mode A picker can
|
||||
bind a project to them; the Mode B result view is blank.
|
||||
|
||||
### 2.4 Dead-or-decaying code
|
||||
|
||||
- **`paliad.trigger_events` table.** 110 rows; columns
|
||||
`(id, code, name, name_de, description, is_active, created_at, concept_id)`.
|
||||
Bigint PK. No `parent_id`, no `proceeding_type_id`. Consumed by:
|
||||
`deadline_rule_service.go:226-285` (label fallback), `event_deadline_service.go`
|
||||
(legacy route), `event_type_service.go` (Pipeline C bridge),
|
||||
`export_service.go:1680` (workbook sheet), and 80 active
|
||||
sequencing_rules' `trigger_event_id` (which is in turn primarily a
|
||||
bridge for the 73 globals + 7 hybrid rules with a real proceeding).
|
||||
- **Inactive proceeding_types still referenced by spawn rules.**
|
||||
id 11 (`upc.apl.merits`), 19 (`upc.apl.cost`), 20 (`upc.apl.order`).
|
||||
Mig 138 (`appeal_target_backfill_merits_order`) split them, mig
|
||||
later unified them onto id 160. The 4 spawn rules' FK was not
|
||||
updated.
|
||||
- **3 non-`proceeding` kinds.** 23 rows total
|
||||
(`phase` × 4 + `side_action` × 10 + `meta` × 9), all
|
||||
`is_active=false` after mig 153. Live in the table for audit;
|
||||
unused by any active surface. The Slice 10 orphan-resolution path
|
||||
(`rule_editor_orphans.go`) could theoretically encounter them, but
|
||||
active = false filters them out.
|
||||
|
||||
---
|
||||
|
||||
## 3. Rules-corpus quality audit (live data)
|
||||
|
||||
### 3.1 `parent_id` coverage
|
||||
|
||||
- 107/226 active+published rules have `parent_id` set (**47%**, matches
|
||||
RFC).
|
||||
- 119/226 do not. Decomposition (active+published):
|
||||
|
||||
| Subset | Rows | Meaning |
|
||||
|---|--:|---|
|
||||
| `parent_id NULL` AND `trigger_event_id IS NULL` AND `proceeding_type_id` set | 46 | Genuine proceeding-level roots (each PT has 1–6 such). |
|
||||
| `parent_id NULL` AND `trigger_event_id` set AND `proceeding_type_id NULL` | 73 | The legacy globals — no place in the new chain model yet. |
|
||||
|
||||
Of the 46 proceeding-level roots:
|
||||
|
||||
| `proceeding_type.code` | roots | active rules |
|
||||
|---|--:|--:|
|
||||
| `de.inf.lg` | 5 | 9 |
|
||||
| `de.null.bpatg` | 4 | 10 |
|
||||
| `epa.grant.exa` | 4 | 7 |
|
||||
| `upc.apl.unified` | 6 | 16 |
|
||||
| `epa.opp.boa` | 3 | 8 |
|
||||
| `upc.pi.cfi` | 3 | 7 |
|
||||
| `epa.opp.opd` | 2 | 8 |
|
||||
| `de.inf.bgh`, `de.inf.olg`, `de.null.bgh`, `dpma.appeal.bgh`, `dpma.appeal.bpatg`, `dpma.opp.dpma`, `upc.disc.cfi` | 1 each | various |
|
||||
| `upc.dmgs.cfi`, `upc.inf.cfi`, `upc.rev.cfi` | 4 each | 8/25/17 |
|
||||
|
||||
Most "root" rules are legitimate (the chain start event has no logical
|
||||
predecessor — `Klageerhebung`, `Zustellung`, `Veröffentlichung`,
|
||||
`Anmeldung`, etc.). A small number are leaves whose parent chain just
|
||||
hasn't been seeded (e.g. `de.inf.lg.berufung` / `de.inf.lg.beruf_begr`
|
||||
list "Berufungsfrist" and "Berufungsbegründung" as parent-NULL despite
|
||||
both having a logical predecessor in `de.inf.lg.urteil`).
|
||||
|
||||
### 3.2 `condition_expr` usage
|
||||
|
||||
18 rules use the column. Three keys total:
|
||||
|
||||
| Key | Uses | Sample shape |
|
||||
|---|--:|---|
|
||||
| `flag` | 14 | `{"flag":"with_ccr"}`, `{"flag":"with_amend"}`, `{"flag":"with_cci"}` |
|
||||
| `op` | 4 | `{"op":"and","args":[{"flag":"with_ccr"},{"flag":"with_amend"}]}` |
|
||||
| `args` | 4 | always nested under an `op:and` |
|
||||
|
||||
Distinct expressions (4 total, all UPC inf/rev):
|
||||
`{"flag":"with_ccr"}` (×6), `{"op":"and","args":[{"flag":"with_ccr"},{"flag":"with_amend"}]}` (×4), `{"flag":"with_cci"}` (×4), `{"flag":"with_amend"}` (×4).
|
||||
|
||||
No formal validation at write time — `RuleEditorService` accepts the
|
||||
column as freeform jsonb. The 3 flags are de-facto convention.
|
||||
|
||||
### 3.3 Spawn distribution
|
||||
|
||||
4 rules, all in the UPC CFI cluster, all `priority='optional'` +
|
||||
`primary_party='both'` + spawn target id=11 (`upc.apl.merits`, inactive):
|
||||
|
||||
| Anchor event | Spawn label | Target |
|
||||
|---|---|---|
|
||||
| `upc.inf.cfi.appeal_spawn` | "Berufungsverfahren öffnen" | id=11 (inactive) |
|
||||
| `upc.rev.cfi.appeal_spawn` | "Berufungsverfahren öffnen" | id=11 (inactive) |
|
||||
| `upc.pi.cfi.appeal_spawn` | "Berufungsverfahren öffnen" | id=11 (inactive) |
|
||||
| `upc.dmgs.cfi.appeal_spawn` | "Berufungsverfahren öffnen" | id=11 (inactive) |
|
||||
|
||||
### 3.4 `primary_party` distribution
|
||||
|
||||
Excluding the 73 globals (all NULL), the published+active rules split:
|
||||
|
||||
| `proceeding_type` cluster | `claimant` | `defendant` | `both` | `court` |
|
||||
|---|--:|--:|--:|--:|
|
||||
| `upc.inf.cfi` (25) | 6 | 7 | 8 | 4 |
|
||||
| `upc.rev.cfi` (17) | 6 | 7 | 1 | 3 |
|
||||
| `upc.apl.unified` (16) | 0 | 0 | 12 | 4 |
|
||||
| `de.null.bpatg` (10) | 2 | 2 | 3 | 3 |
|
||||
| `de.inf.lg` (9) | 2 | 3 | 2 | 2 |
|
||||
| `epa.opp.opd` (8) | 0 | 1 | 6 | 1 |
|
||||
| `epa.opp.boa` (8) | 0 | 0 | 6 | 2 |
|
||||
| `de.inf.bgh` (8) | 0 | 0 | 6 | 2 |
|
||||
| `upc.dmgs.cfi` (8) | 2 | 2 | 1 | 3 |
|
||||
|
||||
39 rules have a `primary_party` value that differs from their parent
|
||||
rule's `primary_party` (excluding `court` ↔ anything, which is
|
||||
trivial). All 39 are legitimate "ball-in-other-court" hand-offs
|
||||
(claimant SoC → defendant SoD → claimant Reply → defendant Rejoinder
|
||||
…). The /follow-ups filter (§2.3 B1) hides all of them when the user
|
||||
picks a perspective.
|
||||
|
||||
### 3.5 `is_court_set` coverage
|
||||
|
||||
46 rules carry `is_court_set=true`. Distribution: every proceeding has
|
||||
at least one (the decision / order / oral-hearing rows). Highest:
|
||||
`de.inf.lg` (5), `epa.grant.exa` (4), `upc.apl.unified` (4),
|
||||
`upc.inf.cfi` (3), `upc.rev.cfi` (3), `upc.pi.cfi` (3), `upc.dmgs.cfi`
|
||||
(3). Calculator skips these in date math — they surface as
|
||||
"wird vom Gericht bestimmt" markers.
|
||||
|
||||
### 3.6 Legacy `trigger_event_id` overlap with `parent_id`
|
||||
|
||||
| Combination | Rows |
|
||||
|---|--:|
|
||||
| `parent_id` set AND `trigger_event_id` set | **2** |
|
||||
| `parent_id` set AND `trigger_event_id` NULL | 105 |
|
||||
| `parent_id` NULL AND `trigger_event_id` set | 73 |
|
||||
| `parent_id` NULL AND `trigger_event_id` NULL | 46 |
|
||||
|
||||
**Overlap is 2 rules out of 226 (0.9%).** The two models are
|
||||
effectively **disjoint** in the corpus: the 73 legacy globals own the
|
||||
`trigger_event_id` lane; the 105 chain-linked rules own `parent_id`.
|
||||
The schema permits both columns to be set simultaneously, and 2 rules
|
||||
exercise that — but they are outliers, not a documented pattern.
|
||||
|
||||
The legacy `paliad.trigger_events` table is still read for label
|
||||
display by `deadline_rule_service.go:226-285` (the "abhängig von …"
|
||||
chip rule fallback when `parent_id` isn't set) and for the legacy
|
||||
`/api/tools/event-deadlines` route.
|
||||
|
||||
---
|
||||
|
||||
## 4. Editorial gap map
|
||||
|
||||
Per `proceeding_type` (active, kind=`proceeding`). Columns:
|
||||
|
||||
- **A** = active+published rules
|
||||
- **P** = rules with `parent_id` set
|
||||
- **R** = rules without `parent_id` (roots + leaves with missing parent)
|
||||
- **E** = active+published events whose code matches this PT's
|
||||
prefix
|
||||
|
||||
| PT code | A | P | R | E | Health |
|
||||
|---|--:|--:|--:|--:|---|
|
||||
| `upc.inf.cfi` | 25 | 21 | 4 | 25 | 84% chained — strongest |
|
||||
| `upc.rev.cfi` | 17 | 13 | 4 | 17 | 76% |
|
||||
| `upc.apl.unified` | 16 | 10 | 6 | 16 † | 63% — code-prefix issue, see below |
|
||||
| `de.null.bpatg` | 10 | 6 | 4 | 10 | 60% |
|
||||
| `de.inf.lg` | 9 | 4 | 5 | 9 | 44% — gappy |
|
||||
| `epa.opp.opd` | 8 | 6 | 2 | 8 | 75% |
|
||||
| `epa.opp.boa` | 8 | 5 | 3 | 8 | 63% |
|
||||
| `de.inf.bgh` | 8 | 7 | 1 | 8 | 88% |
|
||||
| `upc.dmgs.cfi` | 8 | 4 | 4 | 8 | 50% |
|
||||
| `upc.pi.cfi` | 7 | 4 | 3 | 7 | 57% |
|
||||
| `de.inf.olg` | 7 | 6 | 1 | 7 | 86% |
|
||||
| `epa.grant.exa` | 7 | 3 | 4 | 7 | 43% |
|
||||
| `de.null.bgh` | 6 | 5 | 1 | 6 | 83% |
|
||||
| `dpma.appeal.bpatg` | 5 | 4 | 1 | 5 | 80% |
|
||||
| `dpma.appeal.bgh` | 4 | 3 | 1 | 4 | 75% |
|
||||
| `dpma.opp.dpma` | 4 | 3 | 1 | 4 | 75% |
|
||||
| `upc.disc.cfi` | 4 | 3 | 1 | 4 | 75% |
|
||||
| `upc.bsv.cfi` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
| `upc.ccr.cfi` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
| `upc.costs.cfi` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
| `upc.dni.cfi` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
| `upc.epo.review` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
| `upc.pl.cfi` | 0 | 0 | 0 | 0 | **unruled** |
|
||||
|
||||
† `upc.apl.unified` (id=160) is the active type, but its 16 events
|
||||
retain the *legacy* code prefixes `upc.apl.{merits,cost,order}.*`
|
||||
from the pre-unification taxonomy. The rules' `proceeding_type_id`
|
||||
was rebound to 160; the event codes were not renamed. Functional but
|
||||
inconsistent — see R3.
|
||||
|
||||
**Events with no rule:** 0. Every active+published event has at least
|
||||
one rule (corpus is 1:1 since mig 136). Editorial gap is therefore
|
||||
parent-chain-shaped, not rule-coverage-shaped.
|
||||
|
||||
**Unmatched-prefix events:** 69 events with `code LIKE 'null.%'`. They
|
||||
have rules (the 73 legacy globals — note the disparity: 73 rules but
|
||||
69 events, because dedupe in mig 151 collapsed some duplicates while
|
||||
the rules still point at the canonical event). They do not belong to
|
||||
any proceeding_type and never will under the current taxonomy.
|
||||
|
||||
---
|
||||
|
||||
## 5. Risk register
|
||||
|
||||
Eleven items. Each: what, where, severity. Severity scale:
|
||||
**critical** (user-visible incorrect output / data loss possible) →
|
||||
**high** (user-visible UX lie, no data corruption) → **medium**
|
||||
(developer-trap; breaks at next refactor) → **low** (cosmetic / dead
|
||||
code, deferred maintenance).
|
||||
|
||||
### R1 — Cross-party follow-up filter drops legitimate hand-offs — **high**
|
||||
|
||||
- Where: `internal/services/fristenrechner_followups.go:358-367`.
|
||||
- Effect: with `party=claimant|defendant`, 39 active rules are hidden
|
||||
because their `primary_party` is the *other* side. Result-view
|
||||
reports "Keine Folge-Fristen" on chains that continue cross-party
|
||||
(e.g. `def_to_ccr` claimant-filed → `reply_def_ccr` defendant-filed
|
||||
in `upc.inf.cfi`).
|
||||
- Impact: UX lies to users about chain completion; can lead to missed
|
||||
deadlines on the opposing side's view.
|
||||
|
||||
### R2 — Picker accepts spawn-only and leaf events — **high**
|
||||
|
||||
- Where: `internal/services/fristenrechner_followups.go:241-287` (anchor
|
||||
resolution does not check chain-anchor status); `internal/services/fristenrechner_search_events.go`
|
||||
(search returns every event).
|
||||
- Effect: Picking `upc.{inf,rev,pi,dmgs}.cfi.appeal_spawn` (spawn-only)
|
||||
shows the spawn rule itself but no follow-ups → "Keine Folge-Fristen".
|
||||
Picking a leaf event (e.g. `upc.inf.cfi.def_to_ccr`) only reaches
|
||||
whatever hop-1 children exist on the leaf's own party, see R1.
|
||||
- 67/222 active events are chain-anchors. Today's picker shows all
|
||||
222 with equal weight.
|
||||
|
||||
### R3 — 4 spawn rules point at an inactive `proceeding_type` — **high**
|
||||
|
||||
- Where: 4 rows in `paliad.sequencing_rules` with `is_spawn=true`
|
||||
and `spawn_proceeding_type_id=11` (`upc.apl.merits`, `is_active=false`).
|
||||
The active appeal type is id=160 (`upc.apl.unified`).
|
||||
- Effect: any consumer that joins on `spt.is_active=true` (none today,
|
||||
but the moment any does) returns NULL for the spawn target. Today
|
||||
the join is permissive (`fristenrechner_followups.go:394`) — it
|
||||
returns `upc.apl.merits` to the frontend, which may surface as a
|
||||
CTA pointing at a stale type slug.
|
||||
- Plus consequence: `upc.apl.unified` events kept legacy code prefixes
|
||||
`upc.apl.{merits,cost,order}.*` even though the type rebinds to 160.
|
||||
Code/PT mismatch is harmless today; trap for any future code-prefix
|
||||
routing.
|
||||
|
||||
### R4 — 73 "global" legacy rules orphan from the chain model — **medium**
|
||||
|
||||
- Where: `paliad.sequencing_rules WHERE proceeding_type_id IS NULL AND trigger_event_id IS NOT NULL` (73 rows). Anchored on `null.<8hex>`
|
||||
procedural_events (69 distinct events, 73 rules — small overlap from
|
||||
pre-dedupe history).
|
||||
- Effect: invisible to Mode B (proceeding-type ablauf) because they
|
||||
don't bind to any PT; visible to the legacy bigint route
|
||||
`/api/tools/event-deadlines` and to /admin/procedural-events.
|
||||
- Migration debt: any "deprecate `trigger_event_id`" plan must decide
|
||||
whether to (a) reparent these onto a PT + parent chain, (b) keep them
|
||||
as floating cross-cutting rules in a separate lane, or (c) drop them.
|
||||
|
||||
### R5 — Legacy `paliad.trigger_events` table is read by 5 surfaces — **medium**
|
||||
|
||||
- Where:
|
||||
- `internal/services/deadline_rule_service.go:226-285` — bulk-load for
|
||||
"abhängig von …" chip label fallback.
|
||||
- `internal/services/event_deadline_service.go:79,244` — legacy
|
||||
`/api/tools/event-deadlines` route.
|
||||
- `internal/services/event_type_service.go:40-414` — Pipeline-C event
|
||||
types bridge (`event_types.trigger_event_id`).
|
||||
- `internal/services/export_service.go:1680` — `ref__trigger_events`
|
||||
workbook sheet.
|
||||
- `cmd/gen-upc-snapshot/main.go:185-202` — UPC offline snapshot for
|
||||
youpc.org.
|
||||
- Effect: 110-row catalog with bigint PK lives alongside the 222 active
|
||||
procedural_events (UUID PK). Two ID spaces, two label sources,
|
||||
partial overlap.
|
||||
|
||||
### R6 — Three scenario stores: 0 rows each, but 3 live read/write paths — **medium**
|
||||
|
||||
- Stores: `paliad.project_event_choices` (0 rows), `paliad.scenarios`
|
||||
(0 rows), DOM state on Verfahrensablauf checkboxes.
|
||||
- Paths:
|
||||
- `EventChoiceService` (`internal/services/event_choice_service.go:15-180`)
|
||||
reads + writes the table.
|
||||
- `ScenarioService.LoadScenarios` + handlers
|
||||
(`internal/services/fristenrechner.go:583-627`, `internal/handlers/scenarios.go:14-200+`)
|
||||
read + write the table.
|
||||
- Verfahrensablauf result view writes nothing back — DOM only.
|
||||
- Effect today: nothing — empty tables. Effect tomorrow: the moment any
|
||||
surface starts persisting, the three paths can diverge. The RFC
|
||||
(§"What's actually broken" item 3) calls out the symptom: toggling
|
||||
"Mit Widerklage" on Verfahrensablauf doesn't drive conditional
|
||||
checkboxes in result-view submission cards.
|
||||
|
||||
### R7 — 6 active `proceeding_types` are entirely unruled — **medium**
|
||||
|
||||
- Where: `upc.bsv.cfi`, `upc.ccr.cfi`, `upc.costs.cfi`, `upc.dni.cfi`,
|
||||
`upc.epo.review`, `upc.pl.cfi`. All `is_active=true`, `kind='proceeding'`,
|
||||
0 active+published rules, 0 events with their code prefix.
|
||||
- Effect: pickable on `/api/tools/proceeding-types`, bindable on
|
||||
`paliad.projects.proceeding_type_id` (mig 153 only rejects non-
|
||||
proceeding kind, not zero-rule). Binding succeeds → SmartTimeline +
|
||||
Mode B render an empty result. UX lies.
|
||||
|
||||
### R8 — `condition_expr` is freeform jsonb — **medium**
|
||||
|
||||
- Where: column declaration in mig 136; consumer in
|
||||
`deadline_rule_service.go` (selected + passed to engine in
|
||||
`pkg/litigationplanner/engine.go`); writer in
|
||||
`internal/services/rule_editor_service.go:625-843` (no validation).
|
||||
- Effect: 4 distinct shapes used today, 3 keys (`flag`, `op`, `args`).
|
||||
No write-time validation. New keys can be silently added; the
|
||||
engine consumes by switching on string literals. Refactor trap.
|
||||
|
||||
### R9 — Inactive `proceeding_types` rows linger (23) — **low**
|
||||
|
||||
- Where: mig 153 flipped 4 phase + 10 side_action + 9 meta rows to
|
||||
`is_active=false`. They still exist for audit.
|
||||
- Effect: snapshots and snapshots-of-snapshots
|
||||
(`proceeding_types_pre_153`, `procedural_events_pre_151`,
|
||||
`sequencing_rules_pre_151/_pre_152`) accumulate without a decay
|
||||
policy. Storage cost is trivial; query-shape cost is real if any
|
||||
query forgets `WHERE kind='proceeding' AND is_active=true`.
|
||||
|
||||
### R10 — `event_kind` is nullable + not enumerated in DB — **low**
|
||||
|
||||
- Where: `paliad.procedural_events.event_kind text NULL`. Code at
|
||||
`frontend/src/admin-rules-edit.tsx:187` lists `filing / hearing /
|
||||
decision / order` in the UI but the DB accepts anything.
|
||||
- Effect: drift between UI vocab and persisted values is possible.
|
||||
Currently 5 buckets: `filing`, `hearing`, `decision`, `order`, NULL
|
||||
(per RFC).
|
||||
|
||||
### R11 — `applies_to_target` + `choices_offered` lack a schema — **low**
|
||||
|
||||
- Where: `paliad.sequencing_rules.applies_to_target text[]`,
|
||||
`choices_offered jsonb`.
|
||||
- Effect: 16 rules use `applies_to_target`, 28 use `choices_offered`.
|
||||
Three observed `choices_offered` shapes: `{appellant:[…]}` (20),
|
||||
`{skip:[…]}` (6), `{include_ccr:[…]}` (2). Wire-level convention,
|
||||
no documentation. New shapes silently land if a future editor
|
||||
decides on one.
|
||||
|
||||
---
|
||||
|
||||
## 6. Recommendation — order of operations for the inventor
|
||||
|
||||
Phase 2 design starts with the highest-stakes, hardest-to-rewind
|
||||
decisions and finishes with editorial/cleanup. Each step is a
|
||||
question for m, not a design choice for the inventor.
|
||||
|
||||
### Tier 1 — model decisions (grill first)
|
||||
|
||||
1. **Trigger semantics.** Keep `parent_id` as the canonical link?
|
||||
What is the role of `trigger_event_id` after this RFC ships? If
|
||||
deprecated, what happens to the 73 legacy globals (R4) — reparent
|
||||
onto PTs, keep as a separate "cross-cutting" lane, or drop?
|
||||
2. **Trigger discoverability.** Derive from data (events that
|
||||
parent ≥1 rule = 67 today), maintain a materialised view, or carry
|
||||
an explicit `is_trigger` flag on `procedural_events`? Affects R2.
|
||||
3. **Scenario state — single home.** Of the three stores in R6, which
|
||||
wins? Migration shape for the others? The RFC mis-spoke about
|
||||
`projects.scenarios jsonb` — the table is `paliad.scenarios` with
|
||||
a `spec` jsonb column (mig 145). Confirm which storage the inventor
|
||||
reasons from.
|
||||
4. **Cross-party display semantics.** Backend stops filtering,
|
||||
frontend groups by side? Or backend tags + frontend renders an
|
||||
"andere Partei" group? Affects R1.
|
||||
|
||||
### Tier 2 — surface decisions
|
||||
|
||||
5. **Spawn → consequence-only events.** Stop surfacing spawn-only
|
||||
events in the picker (R2), or keep them and tag visually?
|
||||
6. **Re-target the 4 spawn rules** (R3) — point at id=160 vs reseed
|
||||
legacy ids; align event code prefixes vs. accept the mismatch.
|
||||
7. **Sequence-from-proceeding-type view** (Entry A). Where does it
|
||||
live? How do its toggles persist to the chosen scenario store?
|
||||
8. **Legacy `/api/tools/event-deadlines` deprecation** (R5). Drop,
|
||||
redirect, or keep behind a flag during transition?
|
||||
|
||||
### Tier 3 — editorial + cleanup
|
||||
|
||||
9. **Editorial backfill plan.** Which of the 119 parent-NULL rules
|
||||
are real roots vs. unseeded leaves (a per-PT walkthrough by m).
|
||||
10. **Empty proceeding_types** (R7). Stub with placeholder rules, or
|
||||
hide from the picker until rules land?
|
||||
11. **`condition_expr` formalisation** (R8). Pick a grammar, document
|
||||
it, add write-time validation. Same question for `choices_offered`
|
||||
+ `applies_to_target` (R11).
|
||||
12. **Legacy `trigger_events` table fate.** Drop, archive, or
|
||||
repurpose? Depends on Q1 + Q2 above.
|
||||
|
||||
The inventor should grill m on Tier 1 before sketching anything.
|
||||
Tier 2 follows from Tier 1's decisions. Tier 3 is mechanical once
|
||||
Tier 1+2 land.
|
||||
|
||||
---
|
||||
|
||||
## Appendix — query receipts
|
||||
|
||||
All counts in this assessment came from the live `paliad` schema on
|
||||
the youpc Supabase instance during the audit window (2026-05-27).
|
||||
Representative queries:
|
||||
|
||||
```sql
|
||||
-- §0 + §3.1 + §3.6
|
||||
SELECT
|
||||
CASE
|
||||
WHEN parent_id IS NOT NULL AND trigger_event_id IS NOT NULL THEN 'both'
|
||||
WHEN parent_id IS NOT NULL AND trigger_event_id IS NULL THEN 'parent only'
|
||||
WHEN parent_id IS NULL AND trigger_event_id IS NOT NULL THEN 'legacy only'
|
||||
ELSE 'neither (root)'
|
||||
END AS classification,
|
||||
proceeding_type_id IS NULL AS pt_null, count(*) AS rules
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE is_active AND lifecycle_state = 'published'
|
||||
GROUP BY classification, pt_null
|
||||
ORDER BY classification, pt_null;
|
||||
-- → both/false=2, legacy only/true=73, neither/false=46, parent only/false=105
|
||||
|
||||
-- §3.4
|
||||
SELECT pt.code, sr.primary_party, count(*)
|
||||
FROM paliad.sequencing_rules sr
|
||||
LEFT JOIN paliad.proceeding_types pt ON pt.id = sr.proceeding_type_id
|
||||
WHERE sr.is_active AND sr.lifecycle_state='published'
|
||||
GROUP BY pt.code, sr.primary_party ORDER BY pt.code, count(*) DESC;
|
||||
|
||||
-- §4 (gap map)
|
||||
SELECT pt.code, count(sr.id) AS active_rules,
|
||||
count(*) FILTER (WHERE sr.parent_id IS NULL) AS roots
|
||||
FROM paliad.proceeding_types pt
|
||||
LEFT JOIN paliad.sequencing_rules sr ON sr.proceeding_type_id = pt.id
|
||||
AND sr.is_active AND sr.lifecycle_state='published'
|
||||
WHERE pt.is_active AND pt.kind='proceeding'
|
||||
GROUP BY pt.code ORDER BY pt.code;
|
||||
|
||||
-- §3.2 (condition_expr keys)
|
||||
WITH expanded AS (
|
||||
SELECT jsonb_object_keys(condition_expr) AS k
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE condition_expr IS NOT NULL AND condition_expr::text <> '{}'
|
||||
) SELECT k, count(*) FROM expanded GROUP BY k ORDER BY count(*) DESC;
|
||||
-- → flag=14, args=4, op=4
|
||||
```
|
||||
|
||||
Full set of queries used during the audit is available in the agent
|
||||
transcript; reproducible against any read-only Supabase role.
|
||||
|
||||
— end of assessment.
|
||||
776
docs/design-deadline-system-revision-2026-05-27.md
Normal file
776
docs/design-deadline-system-revision-2026-05-27.md
Normal file
@@ -0,0 +1,776 @@
|
||||
# Design — Deadline + procedural-events system revision (Phase 2 of RFC m/paliad#149)
|
||||
|
||||
**Task:** t-paliad-329
|
||||
**Gitea:** m/paliad#149 (Phase 2)
|
||||
**Inventor:** atlas (shift-1)
|
||||
**Date:** 2026-05-27
|
||||
**Status:** Draft — coder gate held; awaiting m's go on the slice train
|
||||
**Branch:** `mai/atlas/inventor-deadline-system`
|
||||
|
||||
**Builds on:**
|
||||
- `docs/assessment-deadline-system-2026-05-27.md` (athena Phase 1, 738 lines — premises here are athena's)
|
||||
- `docs/design-fristenrechner-followup-rules-2026-05-27.md` (atlas t-paliad-327, pre-ratified subset: cross-party display + scenario SSoT + spawn-only picker exclusion)
|
||||
- `docs/design-proceeding-types-taxonomy-2026-05-26.md` (mig 153 shipped; `kind` discriminator)
|
||||
- `docs/design-fristenrechner-overhaul-2026-05-26.md` (Entry B foundation S1-S6 shipped)
|
||||
|
||||
m authorised Phase 2 at 2026-05-27 11:33 ("Go on"). m's "big picture" direction at 13:53 ("yeah, b - big! We need an overall schema for all procedural events and how they are connected") makes the connection graph itself the spine of this design.
|
||||
|
||||
---
|
||||
|
||||
## §0 Premises — reconciliation with athena's audit
|
||||
|
||||
Athena established the live data; this design takes that as given. Three cross-checks ran 2026-05-27 against the live `paliad` schema; counts match athena's §0/§3 numbers (chain-linked 107 / PT-roots 46 / legacy globals 73 / overlap 2). The only material refinement is athena's R3 finding ("4 spawn rules point at INACTIVE id=11") — which m's Q5 answer now re-interprets as **correct** rather than broken (see §3.1).
|
||||
|
||||
### §0.1 The athena↔RFC conflicts surfaced
|
||||
|
||||
| Item | RFC said | Athena found | Picked side |
|
||||
|---|---|---|---|
|
||||
| Scenario state shape | "`projects.scenarios` jsonb (mig 145)" exists | `paliad.scenarios` table exists; `projects.scenarios` jsonb does **not** | Athena. Use new `projects.scenario_flags jsonb` column (Q4) — different from both. |
|
||||
| Three stores diverge | "Three independent stores. No single source of truth." | All three stores empty (0 rows in `project_event_choices`, 0 in `scenarios`, DOM-only). Risk dormant. | Athena. Design picks one store going forward; nothing to migrate. |
|
||||
| Spawn FK is "broken" | Implied | Athena R3: 4 spawn rules point at inactive `upc.apl.merits`. | m's Q5 inverts: the unification was the bug, not the FK. Re-split apl into merits/cost/order (§3.1). |
|
||||
|
||||
### §0.2 The pre-ratified subset from t-paliad-327
|
||||
|
||||
m ratified the following on 2026-05-27 (via `AskUserQuestion`, all on-recommendation in that task) — Phase 2 carries them forward unchanged:
|
||||
|
||||
- Cross-party display: backend stops filtering by party, `is_cross_party` derived field, "Gegenseitig" badge, muted/greyed visual, unchecked default, write-back excluded unconditionally. (Folded into §2.4.)
|
||||
- Scenario flag SSoT: `paliad.projects.scenario_flags jsonb` column + GET/PATCH `/api/projects/{id}/scenario-flags`. (Folded into §2.3.)
|
||||
- Spawn-only event picker exclusion: `SearchEvents` SQL adds `AND sr.is_spawn = false`. (Folded into §2.2.)
|
||||
|
||||
These are not re-asked. They are the foundation Phase 2 builds on.
|
||||
|
||||
---
|
||||
|
||||
## §1 The overall connection schema (m's "big picture")
|
||||
|
||||
Per m's direction: document the canonical connection graph across all procedural_events + sequencing_rules + proceeding_types as a unified model.
|
||||
|
||||
### §1.1 Conceptual model in one paragraph
|
||||
|
||||
A **rule** (`paliad.sequencing_rules` row) is the atomic node. It carries one deadline for one event, on one proceeding-type. Every rule has at most one **predecessor edge** via `parent_id` → another rule whose own deadline must elapse before this one starts. The chain root (rule with `parent_id IS NULL`) is anchored to its **proceeding-type root event** (typically a filing — Klageerhebung, Veröffentlichung, Anmeldung). A small number of rules are **spawn rules** (`is_spawn=true`) — they don't compute their own deadline; instead they open a fresh proceeding of a different type, edge labelled by `spawn_proceeding_type_id`. Conditional rules carry a `condition_expr` jsonb predicate over a small flag vocabulary (`with_ccr`, `with_amend`, `with_cci`); the active subset of the graph for a given project is the rules whose predicate is satisfied by `projects.scenario_flags`. **The only canonical predecessor link is `parent_id`. The `trigger_event_id` column is deprecated** (Q1). Trigger discoverability is **derived from data**: any event whose anchor rule has `EXISTS (non-spawn child WHERE child.parent_id = anchor.id)` is a valid trigger; everything else (spawn-only consequences, terminal leaves) is filtered out at the picker (Q3, §2.2).
|
||||
|
||||
### §1.2 The shape — ASCII tree per representative PT
|
||||
|
||||
Showing 3 representative PTs (the rest follow the same structural pattern; counts in §1.4).
|
||||
|
||||
#### upc.inf.cfi (25 rules, depth 5, the densest tree)
|
||||
|
||||
```
|
||||
upc.inf.cfi (Verletzungsverfahren CFI)
|
||||
├─ RoP.013.1 soc Klageerhebung [claimant · M] ← anchor
|
||||
│ ├─ RoP.019.1 prelim Vorl. Einwendungen [defendant · O]
|
||||
│ ├─ RoP.262.2 confidentiality_response Vertraulichkeit [both · O]
|
||||
│ ├─ RoP.023 sod Klageerwiderung [defendant · M]
|
||||
│ │ └─ RoP.029.b reply Replik [claimant · M · ?with_ccr]
|
||||
│ │ └─ RoP.029.c rejoin Duplik [defendant · M · ?with_ccr]
|
||||
│ ├─ RoP.025 ccr Widerklage auf Nichtigkeit [defendant · O · ?with_ccr]
|
||||
│ │ └─ RoP.029.a def_to_ccr Erwiderung auf CCR [claimant · M · ?with_ccr]
|
||||
│ │ └─ RoP.029.d reply_def_ccr Replik auf Erw. CCR [defendant · M · ?with_ccr] ← X-party from claimant
|
||||
│ │ └─ RoP.029.e rejoin_reply_ccr Duplik auf Replik CCR [claimant · M · ?with_ccr]
|
||||
│ │ └─ RoP.030.1 app_to_amend Antrag auf Patentänderung [claimant · M · ?with_amend]
|
||||
│ │ └─ RoP.032.1 def_to_amend Erwiderung auf Änderung [defendant · M · ?with_amend]
|
||||
│ │ └─ RoP.032.3 reply_def_amd Replik auf Erw. Änderung [claimant · M · ?with_amend]
|
||||
│ │ └─ RoP.032.3 rejoin_amd Duplik auf Replik Änderung [defendant · M · ?with_amend]
|
||||
│ ├─ RoP.333.2 cmo_review Antrag CMO-Überprüfung [both · O]
|
||||
│ ├─ RoP.109.1 translation_request Übersetzungsantrag [both · O]
|
||||
│ ├─ RoP.109.5 translations_lodge Übersetzungen einreichen [both · M]
|
||||
│ ├─ RoP.118.4 cons_orders Antrag Folgenanordnungen [both · O]
|
||||
│ ├─ RoP.151 cost_app Kostenantrag [both · O]
|
||||
│ ├─ RoP.353 rectification Berichtigungsantrag [both · O]
|
||||
│ └─ RoP.220.1.a appeal_spawn ⇲ Berufungsverfahren öffnen [both · O · SPAWN→ upc.apl.merits]
|
||||
├─ RoP.104 interim Zwischenanhörung [court · M]
|
||||
├─ (n/a) oral Mündliche Verhandlung [court · M]
|
||||
├─ (n/a) decision Endentscheidung [court · M]
|
||||
│ (Note: interim/oral/decision are court-set; they're chain-anchored but
|
||||
│ have no scheduled rule of their own — phase markers carried via event_kind.)
|
||||
└─ RoP.109.4 interpreter_cost Dolmetscherkosten [court · M]
|
||||
```
|
||||
|
||||
**Legend.** `[party · M|O · ?flag · SPAWN→target]`. `M` = mandatory, `O` = optional. `?flag` = conditional on the scenario flag. ← X-party = cross-party row vs claimant perspective; see §2.4 for display. SPAWN → opens a new proceeding under that PT.
|
||||
|
||||
#### upc.rev.cfi (17 rules, depth 4, mirrors inf.cfi shape)
|
||||
|
||||
Same SoC → SoD → Reply → Rejoinder spine; CCR mirrored as Erwiderung auf Widerklage on revocation. `with_cci` (Widerklage auf Verletzung — the inverse of with_ccr) replaces `with_ccr`. Same `with_amend` branch for R.30. 13 chain-linked, 5 roots, 1 spawn (→ upc.apl.merits, post-Q5 split).
|
||||
|
||||
#### upc.apl (POST-Q5 SPLIT — 3 trees, 16 rules total)
|
||||
|
||||
After §3.1 mig: id=160 `upc.apl.unified` is retired; rules re-bound to the 3 reactivated PTs (id=11 `upc.apl.merits` 7 rules / id=19 `upc.apl.cost` 2 rules / id=20 `upc.apl.order` 7 rules). Trees:
|
||||
|
||||
```
|
||||
upc.apl.merits (7 rules)
|
||||
├─ RoP.224.1.a notice Berufungseinlegung
|
||||
│ └─ RoP.224.2.a grounds Berufungsbegründung
|
||||
│ └─ RoP.235.1 response Berufungserwiderung
|
||||
│ └─ RoP.237 cross_a Anschlussberufung
|
||||
│ └─ RoP.238.1 cross_a_reply Erwiderung Anschlussberufung
|
||||
├─ (n/a) oral Mündliche Verhandlung [court · M]
|
||||
└─ (n/a) decision Entscheidung [court · M]
|
||||
|
||||
upc.apl.cost (2 rules)
|
||||
├─ RoP.221.1 leave_app Antrag auf Berufungszulassung
|
||||
└─ (n/a) decision Kostenfestsetzungsbeschluss
|
||||
|
||||
upc.apl.order (7 rules)
|
||||
├─ (n/a) order angegriffene Entscheidung
|
||||
│ ├─ RoP.220.2 with_leave Berufung mit Zulassung
|
||||
│ └─ RoP.220.3 discretion Ermessensüberprüfung
|
||||
├─ RoP.224.2.b grounds_orders Berufungsbegründung (Orders Track)
|
||||
│ └─ RoP.235.2 response_orders Berufungserwiderung (Orders Track)
|
||||
└─ RoP.237 cross Anschlussberufung
|
||||
└─ RoP.238.2 cross_reply Erwiderung Anschlussberufung
|
||||
```
|
||||
|
||||
The 3 trees are independent. Determinator UX (proceeding_mapping.go) keeps a single user-facing "Berufung" entry that fans out to one of the 3 based on what's being appealed (judgment → merits, cost decision → cost, order → order). Routing layer unchanged from t-paliad-204 S1; only the data shape changes.
|
||||
|
||||
The remaining 14 ruled PTs (de.inf.lg / .olg / .bgh, de.null.bpatg / .bgh, dpma.opp / .appeal.bpatg / .bgh, epa.opp.opd / .opp.boa / .grant.exa, upc.dmgs.cfi, upc.disc.cfi, upc.pi.cfi) follow the same shape — root anchored on a filing/grant event, chain depth 1-3, optionals and conditionals branching off the root or first-hop. Athena's §4 gap map gives the per-PT P/R counts; see also §1.4 below.
|
||||
|
||||
### §1.3 Cross-PT edges — the spawn graph (post-Q5)
|
||||
|
||||
```mermaid
|
||||
graph LR
|
||||
upc_inf_cfi[upc.inf.cfi<br/>Verletzungsverfahren CFI] -.->|R.220.1.a<br/>appeal_spawn| upc_apl_merits[upc.apl.merits<br/>Berufung Hauptsache]
|
||||
upc_rev_cfi[upc.rev.cfi<br/>Nichtigkeitsverfahren CFI] -.->|R.220.1.a<br/>appeal_spawn| upc_apl_merits
|
||||
upc_dmgs_cfi[upc.dmgs.cfi<br/>Schadensbemessung] -.->|R.220.1.a<br/>appeal_spawn| upc_apl_merits
|
||||
upc_pi_cfi[upc.pi.cfi<br/>Einstweilige Maßnahmen] -.->|R.220.1.a<br/>appeal_spawn| upc_apl_order[upc.apl.order<br/>Berufung Orders Track]
|
||||
```
|
||||
|
||||
4 spawn edges, all in the UPC CFI cluster. PI appeals go to the orders track (not main proceedings); the rest go to merits. The cost-decision-appeal track (`upc.apl.cost`) is reached not via spawn but via direct filing (`leave_app` rule); cost decisions arrive within their parent proceeding and the cost-appeal opens as a standalone application.
|
||||
|
||||
DE-side, EPA-side, DPMA-side: no spawn edges today. Each tier-of-court is a separate `proceeding_type` (de.inf.lg / .olg / .bgh) with its own root + chain; chained-by-instance is not modelled as a spawn (the user explicitly creates a new project for the appeal stage). m may revisit this if DE-side workflow benefits from spawn edges; out of scope for this revision.
|
||||
|
||||
### §1.4 Per-PT health summary (post-Q5)
|
||||
|
||||
| PT code | rules | roots | chained | conditional | spawns | gap |
|
||||
|---|--:|--:|--:|--:|--:|---|
|
||||
| upc.inf.cfi | 25 | 4 | 21 | 10 | 1 | 84% chained — strongest |
|
||||
| upc.rev.cfi | 17 | 4 | 13 | 8 | 1 | 76% |
|
||||
| upc.apl.merits | 7 | 3 | 4 | 0 | 0 | post-Q5 split — to be re-rooted |
|
||||
| upc.apl.order | 7 | 3 | 4 | 0 | 0 | post-Q5 split |
|
||||
| upc.apl.cost | 2 | 1 | 1 | 0 | 0 | post-Q5 split |
|
||||
| de.inf.lg | 9 | 5 | 4 | 0 | 0 | 44% — gappy |
|
||||
| de.null.bpatg | 10 | 4 | 6 | 0 | 0 | 60% |
|
||||
| de.inf.olg | 7 | 1 | 6 | 0 | 0 | 86% |
|
||||
| de.inf.bgh | 8 | 1 | 7 | 0 | 0 | 88% |
|
||||
| de.null.bgh | 6 | 1 | 5 | 0 | 0 | 83% |
|
||||
| dpma.opp.dpma | 4 | 1 | 3 | 0 | 0 | 75% |
|
||||
| dpma.appeal.bpatg | 5 | 1 | 4 | 0 | 0 | 80% |
|
||||
| dpma.appeal.bgh | 4 | 1 | 3 | 0 | 0 | 75% |
|
||||
| epa.opp.opd | 8 | 2 | 6 | 0 | 0 | 75% |
|
||||
| epa.opp.boa | 8 | 3 | 5 | 0 | 0 | 63% |
|
||||
| epa.grant.exa | 7 | 4 | 3 | 0 | 0 | 43% |
|
||||
| upc.dmgs.cfi | 8 | 4 | 4 | 0 | 1 | 50% |
|
||||
| upc.pi.cfi | 7 | 3 | 4 | 0 | 1 | 57% |
|
||||
| upc.disc.cfi | 4 | 1 | 3 | 0 | 0 | 75% |
|
||||
| **Empty (Q6)** | | | | | | |
|
||||
| upc.bsv.cfi | 0 | — | — | — | — | unruled — badge "Keine Regeln" |
|
||||
| upc.ccr.cfi | 0 | — | — | — | — | unruled — badge |
|
||||
| upc.costs.cfi | 0 | — | — | — | — | unruled — badge |
|
||||
| upc.dni.cfi | 0 | — | — | — | — | unruled — badge |
|
||||
| upc.epo.review | 0 | — | — | — | — | unruled — badge |
|
||||
| upc.pl.cfi | 0 | — | — | — | — | unruled — badge |
|
||||
|
||||
Plus **73 legacy globals** sitting in the corpus with `proceeding_type_id IS NULL` — these are the editorial backfill target (Q2 / §4.2). Each needs to be reparented onto one of the 23 PTs.
|
||||
|
||||
---
|
||||
|
||||
## §2 Tier 1 — model decisions (m ratified all 4 on-recommendation)
|
||||
|
||||
### §2.1 `parent_id` is the canonical predecessor link
|
||||
|
||||
`paliad.sequencing_rules.parent_id` (uuid FK to another rule) is the **only** predecessor pointer going forward. `paliad.sequencing_rules.trigger_event_id` (bigint FK to legacy `paliad.trigger_events`) gets dropped at the end of the migration train (§5).
|
||||
|
||||
**Implication for the 75 rules that currently use `trigger_event_id`:**
|
||||
|
||||
- The 73 legacy globals (proceeding_type_id IS NULL): editorial walk reparents each onto a real PT chain (Q2, §4.2). Slow but right — no data is lost, just structurally normalised.
|
||||
- The 2 hybrid rules (both parent_id AND trigger_event_id set): keep `parent_id`, NULL out `trigger_event_id`. No data loss — `parent_id` already carries the live edge.
|
||||
|
||||
After backfill, `trigger_event_id` is unused — safe to drop the column (§5, Mig P4).
|
||||
|
||||
### §2.2 Trigger discoverability — derive from data
|
||||
|
||||
A `procedural_event` is a **picker-eligible trigger** when EXISTS a published+active non-spawn rule with `parent_id` pointing at this event's anchor rule. The picker SQL gains:
|
||||
|
||||
```sql
|
||||
WHERE EXISTS (
|
||||
SELECT 1 FROM paliad.sequencing_rules child
|
||||
WHERE child.parent_id = anchor.id
|
||||
AND child.is_active = true
|
||||
AND child.lifecycle_state = 'published'
|
||||
AND child.is_spawn = false -- spawn-only consequences not pickable (t-paliad-327 §3a)
|
||||
)
|
||||
```
|
||||
|
||||
No new column. No materialised view. The EXISTS subquery uses the existing `sequencing_rules.parent_id` index. At today's scale (226 rules) it's cheap; at 10× scale still fine (parent_id is indexed; child lookup is index-only scan).
|
||||
|
||||
Mode A's `SearchEvents` (`internal/services/fristenrechner_search_events.go`) and Mode B R4's chip-strip both apply this filter. Terminal leaves (Duplik etc.) stay pickable — they have a non-spawn anchor rule and result in an empty follow-up list, which is honest UX (t-paliad-327 §3a.4, m ratified).
|
||||
|
||||
### §2.3 Scenario state SSoT — `projects.scenario_flags jsonb`
|
||||
|
||||
Reconfirmed from t-paliad-327 §3.2:
|
||||
|
||||
```sql
|
||||
ALTER TABLE paliad.projects
|
||||
ADD COLUMN scenario_flags jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||
```
|
||||
|
||||
Shape:
|
||||
```json
|
||||
{ "with_ccr": true, "with_amend": false, "with_cci": false }
|
||||
```
|
||||
|
||||
Whitelist-validated against the set of flag names appearing in `sequencing_rules.condition_expr` (today: `with_ccr`, `with_amend`, `with_cci`).
|
||||
|
||||
API: `GET /api/projects/{id}/scenario-flags` returns the map; `PATCH /api/projects/{id}/scenario-flags` accepts partial deltas (null deletes a key).
|
||||
|
||||
**Kontextfrei (no project):** stays on localStorage. No DB writes when `project_id IS NULL`.
|
||||
|
||||
**Relationship with `paliad.scenarios`:** complementary, not duplicate. `scenarios.spec.flags[]` (the Litigation Planner Slice D shape) is a *named snapshot*; activating a scenario copies its flag array into `projects.scenario_flags`. Live edits write to `scenario_flags`. `paliad.project_event_choices` (the legacy empty table) is deprecated (§4.3).
|
||||
|
||||
### §2.4a Selection state + detail-level view-mode filter
|
||||
|
||||
m's reframe (14:40): the real ask isn't "rarity" — it's **detail-level control over the timeline**. Every event/rule is a card; the user picks which optional cards belong to *their* scenario; the Verfahrensablauf has a view-mode toggle that controls how much of the picture surfaces.
|
||||
|
||||
m's quote (14:40): *"It is more that I want a grade of detail in our swimlane display […] I want to show them but also be able to 'focus' by not displaying optional things. And we can select these options somehow, for example like we do with the appeal in the Decision dropdown. And if none is selected, none are displayed. We need an option 'Show unselected options' or 'show only selected' or 'mandatory' […] It would be great to basically filter events from the timeline based on whether they are selected in this scenario."*
|
||||
|
||||
The underlying mental model:
|
||||
|
||||
- **Mandatory rules** are always in the scenario. They render in every view-mode. The user cannot deselect them.
|
||||
- **Recommended rules** are *selected by default* in the scenario. The user can deselect them.
|
||||
- **Optional rules** are *not selected by default*. The user opts in via the same UI mechanism that already exists for `with_ccr` / `with_amend` (a chip / dropdown / "Aufnehmen" CTA per rule).
|
||||
- **Conditional rules** (with `condition_expr`) are gated by scenario flags first, then by selection (a conditional rule whose flag is on still respects its priority's default selection rule).
|
||||
|
||||
The Verfahrensablauf gets a three-way **detail-level toggle** (§3.3a):
|
||||
|
||||
- **Nur Pflicht (Mandatory only)** — only `priority='mandatory'` cards.
|
||||
- **Gewählt (Selected)** — mandatory + every rule the scenario has explicitly selected. Default.
|
||||
- **Alle Optionen (All considered)** — every rule that *could* belong, including unselected optionals (rendered with a dotted border + "Aufnehmen" CTA) and conditional rules whose flag isn't set (rendered greyed with a "wenn-…" hint).
|
||||
|
||||
#### Schema — no new column on `sequencing_rules`
|
||||
|
||||
The original §2.4a strawman proposed `is_edge_case boolean` as a chain-head flag. m's reframe makes that wrong: **every** optional rule is potentially "rare" depending on the lawyer's scenario; the dimension isn't a property of the rule, it's a property of the scenario.
|
||||
|
||||
Instead, the selection state lives entirely in **`projects.scenario_flags jsonb`** (already on the table from P0, §2.3) with an extended shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"with_ccr": true,
|
||||
"with_amend": false,
|
||||
"with_cci": false,
|
||||
"rule:<uuid_of_recommended_X>": false,
|
||||
"rule:<uuid_of_optional_Y>": true
|
||||
}
|
||||
```
|
||||
|
||||
The flat-map shape stays — entries are either named scenario flags (`with_*`) or per-rule selection deviations (`rule:<uuid>`). Storage only carries **deviations from the priority default**:
|
||||
- `priority='recommended'` is selected-by-default; `rule:X = false` records an explicit deselection.
|
||||
- `priority='optional'` is unselected-by-default; `rule:X = true` records an explicit selection.
|
||||
- `priority='mandatory'` is always selected; trying to store `rule:X = false` is rejected (422 from the PATCH endpoint).
|
||||
|
||||
Whitelist (Q9 catalog) gains a wildcard pattern `rule:<uuid>` — any well-formed UUID matches; the handler validates that the UUID resolves to an active+published rule on the project's proceeding_type before persisting.
|
||||
|
||||
Kontextfrei (no project): localStorage stores the same shape under a per-PT key (`scenario:upc.inf.cfi`). Different PT → different stored selection set; this matches how kontextfrei users explore.
|
||||
|
||||
#### Visual — generalising the CCR dropdown to per-rule chips
|
||||
|
||||
The existing `with_ccr` / `with_amend` checkboxes are *coarse* scenario flags. The new per-rule selection is *fine-grained* but uses the same UI vocabulary:
|
||||
|
||||
- **Selected rule**: solid card, normal background. (Identical to today's mandatory render.)
|
||||
- **Selected optional that's deselectable**: solid card with a small `[Entfernen]` chip; click removes from `selected_optionals` (writes `rule:X = false`).
|
||||
- **Unselected optional (default state in "Alle Optionen" mode)**: dotted-border card, muted background, `[Aufnehmen]` CTA. Click writes `rule:X = true`.
|
||||
- **Conditional rule whose flag isn't set**: greyed card with a "Aktivieren via 'Mit Widerklage' im Szenario" hint; clicking the hint scrolls to the scenario-flags strip.
|
||||
- **Cross-party** (§2.4): orthogonal — applies its `Gegenseitig` badge and muted style on top of whichever state above.
|
||||
|
||||
Each card thus carries up to four orthogonal axes of display state — priority, selection, conditional-gate, cross-party. The 4 axes compose; no axis dominates.
|
||||
|
||||
#### Subtree semantics — implicit via parent chain
|
||||
|
||||
When a chain head is deselected (e.g. R.109.1 Übersetzungsantrag = `false`), its descendants in the parent_id tree (R.109.4 Mitteilung etc.) **inherit the deselected state for display** without needing their own entries in `selected_optionals`. The tree renderer walks the chain; if any ancestor is unselected, the descendant doesn't render in "Gewählt" mode. In "Alle Optionen" mode, the whole subtree renders greyed under the deselected head.
|
||||
|
||||
If a descendant has its own explicit `rule:X = true` entry, that overrides the ancestor — the user has explicitly pulled this leaf into their scenario despite not selecting the parent. Edge case; documented but no special UI affordance.
|
||||
|
||||
#### Default population on project creation
|
||||
|
||||
When a project is created with `proceeding_type_id = X`, the server seeds `scenario_flags = {}`. Nothing in the map. The tree renderer computes per-rule selection on-the-fly from priority + scenario_flags entries. No upfront write-storm of "rule:X = true" for every recommended rule — only deviations land in storage.
|
||||
|
||||
#### Why this beats the `is_edge_case` boolean
|
||||
|
||||
- **No new column.** All state lives in the existing `projects.scenario_flags jsonb` from P0.
|
||||
- **Generalised.** Every optional rule is selectable, not just the few flagged as "rare". m's "sequence density is very high" complaint is solved by the user controlling which optionals belong to *their* scenario, rather than the editorial process having to decide globally which rules deserve dotted-border treatment.
|
||||
- **Composable with condition_expr.** A conditional rule is selectable when its flag is on; the selection state is independent of the flag state.
|
||||
- **Matches m's stated UX prior art.** The CCR dropdown pattern *is* the model; we're just generalising it from 3 named flags to N per-rule selections.
|
||||
|
||||
### §2.4 Cross-party display
|
||||
|
||||
From t-paliad-327 §2 (m ratified on-recommendation all 8 sub-Qs):
|
||||
|
||||
- Backend: drop the perspective WHERE clause in `queryFollowUpRows`; return all rows; add server-computed `is_cross_party` boolean.
|
||||
- UI: render cross-party rows with a `Gegenseitig` badge, muted/greyed style, unchecked by default, date visible.
|
||||
- Write-back: cross-party rows are **unconditionally excluded** from the project-deadline bulk insert, even if the user manually checks the box.
|
||||
|
||||
Composite `condition_expr` (and-of-flags) — checkbox is read-only in the result view; Verfahrensablauf is the canonical toggle surface for individual flags.
|
||||
|
||||
Sync: `document.dispatchEvent(new CustomEvent('scenario-flag-changed', { detail: { flag, value } }))`. Single-tab v1; cross-tab in Akte mode deferred.
|
||||
|
||||
---
|
||||
|
||||
## §3 Tier 2 — surface decisions
|
||||
|
||||
### §3.1 Appeal re-split: revert upc.apl.unified → merits/cost/order (m's Q5 divergent pick)
|
||||
|
||||
**m's call (2026-05-27):** *"Reverse the unification as suggested in 3. They are different proceedings, I only wanted the approach to be unified in the 'determinator' — but they are actually different proceedings!"*
|
||||
|
||||
The current state (mig 096 unified the appeal track):
|
||||
- id=160 `upc.apl.unified` is `is_active=true`, holds 16 rules.
|
||||
- id=11 `upc.apl.merits` is `is_active=false`.
|
||||
- id=19 `upc.apl.cost` is `is_active=false`.
|
||||
- id=20 `upc.apl.order` is `is_active=false`.
|
||||
- 4 spawn rules point at id=11 (inactive) — looks like the R3 bug but is actually correctly aimed at merits since cost+order arrive differently (athena R3 partially mis-classified the situation).
|
||||
- Event codes already carry the split prefix: `upc.apl.{merits,cost,order}.*`. 16 events split cleanly into 7 merits + 2 cost + 7 order.
|
||||
|
||||
The migration:
|
||||
|
||||
```sql
|
||||
-- Mig P1: re-activate the three discrete appeal PTs and retire the unified row.
|
||||
UPDATE paliad.proceeding_types SET is_active = true WHERE id IN (11, 19, 20);
|
||||
UPDATE paliad.proceeding_types SET is_active = false WHERE id = 160;
|
||||
|
||||
-- Mig P1: re-target each rule whose proceeding_type_id is currently 160
|
||||
-- to the right reactivated PT based on its event_code prefix.
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET proceeding_type_id = 11
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.id = sr.procedural_event_id
|
||||
AND sr.proceeding_type_id = 160
|
||||
AND pe.code LIKE 'upc.apl.merits.%';
|
||||
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET proceeding_type_id = 19
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.id = sr.procedural_event_id
|
||||
AND sr.proceeding_type_id = 160
|
||||
AND pe.code LIKE 'upc.apl.cost.%';
|
||||
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET proceeding_type_id = 20
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.id = sr.procedural_event_id
|
||||
AND sr.proceeding_type_id = 160
|
||||
AND pe.code LIKE 'upc.apl.order.%';
|
||||
|
||||
-- 4 spawn FKs: stay at id=11 (merits) for inf/rev/dmgs; update upc.pi.cfi's
|
||||
-- spawn to point at id=20 (order) — appeals against PI orders go to the
|
||||
-- orders track, not merits.
|
||||
UPDATE paliad.sequencing_rules
|
||||
SET spawn_proceeding_type_id = 20
|
||||
WHERE is_spawn AND procedural_event_id = (
|
||||
SELECT id FROM paliad.procedural_events WHERE code = 'upc.pi.cfi.appeal_spawn'
|
||||
);
|
||||
-- The other 3 spawn rules (inf/rev/dmgs) keep spawn_proceeding_type_id = 11
|
||||
-- (correct after re-activation).
|
||||
```
|
||||
|
||||
**Determinator UX preserved.** `internal/services/proceeding_mapping.go` (t-paliad-204 S1) keeps its single "Berufung" front door. The mapping fans out to id=11/19/20 based on what's being appealed (judgment / cost decision / order). No user-facing routing change. The change is purely structural.
|
||||
|
||||
**Active scenarios / projects pointing at id=160:** none (`paliad.scenarios` and `paliad.projects.active_scenario_id` both empty per athena §0; only 6 projects have any `proceeding_type_id` set and none of them is 160). Zero data migration on the project side.
|
||||
|
||||
### §3.2 Empty PTs — show with "Keine Regeln gepflegt" badge
|
||||
|
||||
Per m's Q6 — option 2 with a follow-on editorial note ("We need to publish rules then... but yeah, show with the badge for now"):
|
||||
|
||||
Picker query for `/api/tools/proceeding-types` gains a flag-not-filter:
|
||||
|
||||
```sql
|
||||
SELECT pt.*,
|
||||
EXISTS (
|
||||
SELECT 1 FROM paliad.sequencing_rules sr
|
||||
WHERE sr.proceeding_type_id = pt.id
|
||||
AND sr.is_active AND sr.lifecycle_state = 'published'
|
||||
) AS has_rules
|
||||
FROM paliad.proceeding_types pt
|
||||
WHERE pt.is_active AND pt.kind = 'proceeding';
|
||||
```
|
||||
|
||||
Frontend renders the chip with a muted/disabled treatment + badge "Keine Regeln gepflegt" when `has_rules = false`. Project creation can still bind to an empty PT (admin override), but Mode A/B/Verfahrensablauf surface a clear "this proceeding has no seeded rules yet" message.
|
||||
|
||||
Editorial follow-up: m publishes rules for the 6 empty PTs (`upc.bsv.cfi`, `upc.ccr.cfi`, `upc.costs.cfi`, `upc.dni.cfi`, `upc.epo.review`, `upc.pl.cfi`) over time; each new published rule auto-removes the badge for its PT. Not blocking this design.
|
||||
|
||||
### §3.3 Entry A — extend /tools/verfahrensablauf
|
||||
|
||||
Per m's Q7. The existing `/tools/verfahrensablauf` page (used by `frontend/src/client/verfahrensablauf.ts` + shared `views/verfahrensablauf-core.ts`) already serves the pick-a-PT shape. Extend it to:
|
||||
|
||||
- Render the parent_id chain as a **collapsible tree** (top-down chronological). Same data shape as §1.2's ASCII trees.
|
||||
- Expose **optionals + conditionals as toggleable checkboxes** in the tree itself. Ticking writes via `PATCH /api/projects/{id}/scenario-flags` (Akte mode) or localStorage (kontextfrei).
|
||||
- Reflect cross-party rows with the same muted style as §2.4 (Gegenseitig badge).
|
||||
- Spawn rows render as **leaf with edge annotation** (⇲ Berufungsverfahren öffnen) and a "create child case" CTA in Akte mode.
|
||||
- Optionally: a "Zur Frist-Ansicht" deeplink on each tree node → opens Mode B Fristenrechner with that event pre-locked as the trigger.
|
||||
|
||||
Backend: extend `/api/tools/fristenrechner` (the proceeding-type fan-out endpoint) to return a tree-shaped payload (`parent_id` resolved into nested children). New handler param or new endpoint `/api/tools/verfahrensablauf/tree?proceeding_type_code=X&project=Y`.
|
||||
|
||||
The legacy `/tools/fristenrechner?legacy=1` Procedure-mode page deprecates naturally — same scope, replaced by this Entry A view.
|
||||
|
||||
### §3.3a Verfahrensablauf view-mode toggle
|
||||
|
||||
A three-way segmented control above the tree at the Verfahrensablauf surface:
|
||||
|
||||
```
|
||||
┌─ Anzeige ──────────────────────────────────────┐
|
||||
│ ( ) Nur Pflicht (•) Gewählt ( ) Alle Optionen │
|
||||
└────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Behaviour:
|
||||
- **Nur Pflicht**: only `priority='mandatory'` cards render. Tightest view.
|
||||
- **Gewählt** (default): mandatory + every rule that resolves to "selected" given current scenario state (mandatory always; recommended unless explicitly deselected via `rule:X = false`; optional only if explicitly selected via `rule:X = true`; conditional only if its flag predicate holds AND the priority-default-or-deviation puts it in the selected set). Honest summary of what *this* lawyer has chosen for *this* project.
|
||||
- **Alle Optionen**: everything that could belong, with unselected optionals rendered with the dotted-border + `[Aufnehmen]` CTA, and conditional rules whose flag isn't set rendered greyed with the activation hint.
|
||||
|
||||
**Persistence**: per-user, per-browser via `localStorage` under key `verfahrensablauf:view_mode`. Not project-scoped — the same user looking at two different projects probably wants the same verbosity. Not in `scenario_flags` either — view-mode is a UI preference, not a scenario fact. No new schema; no API; no migration.
|
||||
|
||||
Cross-surface sync: the **Mode B result view** does NOT carry its own view-mode toggle. It always renders in "Gewählt" semantics (mandatory + selected). Rationale: Mode B locks a single trigger event and lists its follow-ups; the lawyer isn't browsing the full ablauf, they're focused on one moment. The view-mode toggle is a Verfahrensablauf-only affordance.
|
||||
|
||||
The view-mode toggle composes with the scenario-flags strip (§2.3). Toggling "Mit Widerklage auf Nichtigkeit" off in "Gewählt" mode removes the CCR conditional branch from view; flipping to "Alle Optionen" re-renders the CCR branch greyed with the activation hint. The user can see what they're *not* currently considering without losing the simplified default view.
|
||||
|
||||
### §3.4 Legacy `/api/tools/event-deadlines` deprecation
|
||||
|
||||
Per m's Q8. Sequence:
|
||||
|
||||
1. **Mig P3 — 73-globals reparenting completes** (§4.2, editorial work). Once `paliad.sequencing_rules WHERE proceeding_type_id IS NULL` is empty, the legacy route has no live data shape it uniquely serves.
|
||||
2. **Code drop:** remove `/api/tools/event-deadlines` route + `EventDeadlineService` + the `deadline_rule_service.go:226-285` label-fallback path + the `ExportService:1680` workbook sheet.
|
||||
3. **Table drop:** `DROP TABLE paliad.trigger_events` (mig P4, §4.3).
|
||||
4. **Snapshot generator:** `cmd/gen-upc-snapshot/main.go` stops reading `paliad.trigger_events`; UPC snapshot for youpc.org only carries the unified rule shape.
|
||||
|
||||
The cleanup is gated on §4.2 completion. If editorial backfill is slow, the route can live behind a `/api/legacy/` prefix until done — but the design assumption is that we close the loop within the slice train.
|
||||
|
||||
---
|
||||
|
||||
## §4 Tier 3 — editorial + cleanup framework
|
||||
|
||||
### §4.1 `condition_expr` grammar formalisation
|
||||
|
||||
Per m's Q9. The grammar:
|
||||
|
||||
```ts
|
||||
type CondExpr =
|
||||
| { flag: KnownFlag } // leaf
|
||||
| { op: 'and' | 'or'; args: CondExpr[] } // composite (recursive)
|
||||
|
||||
type KnownFlag = 'with_ccr' | 'with_amend' | 'with_cci' // closed set; extensible via admin
|
||||
```
|
||||
|
||||
Implementation:
|
||||
|
||||
- A JSON-schema validator in `RuleEditorService.create`/`update` rejects writes that don't match. Today's 18 rules all conform; no data migration.
|
||||
- Known-flag whitelist sourced from a small Go constant + an admin-editable `paliad.scenario_flag_catalog(name, description, added_at)` table — keeps the vocabulary discoverable. (Lightweight ALTER, not a major migration.)
|
||||
- Engine consumer (`pkg/litigationplanner/expr.go`, currently a switch over string literals) gains exhaustive-case enforcement against the same catalog. Linter catches drift between catalog and engine.
|
||||
|
||||
`choices_offered` and `applies_to_target` (athena R11) — same grammar treatment in a separate ticket (not blocking this revision). Document their 3 known shapes (`appellant`, `skip`, `include_ccr`) in code comments meanwhile.
|
||||
|
||||
### §4.2 Editorial backfill workflow — `/admin/procedural-events` parent-NULL filter
|
||||
|
||||
Per m's Q10:
|
||||
|
||||
- Add filter chip "parent: nicht gesetzt" to the admin list at `/admin/procedural-events`. The filter URL `?parent_filter=null` (or similar).
|
||||
- Track completion per PT via the existing gap-map query (athena §3.1) — show as a progress bar in the admin shell ("upc.inf.cfi: 4/4 roots OK" / "de.inf.lg: 2/5 roots remain").
|
||||
- For the 73 globals: a separate filter `?orphan=true` showing only `proceeding_type_id IS NULL` rules. m clicks each, assigns a PT + parent rule via the editor.
|
||||
- Each save flips lifecycle_state to draft (unchanged from existing editor flow); m publishes a batch when satisfied with a PT.
|
||||
|
||||
No new code surface — the existing admin list + editor handle everything once the filter is added.
|
||||
|
||||
This is editorial work, not coder work. The design captures the framework; m drives the content at his own cadence. No mig is gated on completion (the parent-NULL filter is a feature add; rules stay valid in their current shape during the walk).
|
||||
|
||||
#### §4.2.1 Worked editorial example — R.109 translation chain
|
||||
|
||||
m flagged this case (14:35) as a concrete instance of malformed parent-chain shape. The current data for `upc.inf.cfi`:
|
||||
|
||||
| rule | event | current parent | current primary_party | correct shape |
|
||||
|---|---|---|---|---|
|
||||
| `RoP.109.1` | `upc.inf.cfi.translation_request` (Antrag auf Simultanübersetzung) | upc.inf.cfi root (Mündliche Verhandlung) | both | parent stays at MV; flagged optional (default-unselected) |
|
||||
| `RoP.109.4` | `upc.inf.cfi.interpreter_cost` (Mitteilung Dolmetscherkosten) | upc.inf.cfi root (Mündliche Verhandlung) — **WRONG** | court — **WRONG** | parent = R.109.1; primary_party = both (parties give the Mitteilung, not the court); condition_expr = `{"flag": "with_interpreter_denied"}` |
|
||||
| `RoP.109.5` | `upc.inf.cfi.translations_lodge` (Übersetzungen einreichen) | upc.inf.cfi root | both | parent = R.109.1 (lodging follows the request); priority stays mandatory but conditional via `{"flag": "with_translation_granted"}` |
|
||||
|
||||
Two new scenario flags introduced (`with_interpreter_denied`, `with_translation_granted`) get added to the `scenario_flag_catalog` (§4.1) when the editor saves these rules.
|
||||
|
||||
Editorial walk for m:
|
||||
1. Open `/admin/procedural-events?orphan=false&parent_filter=null&proceeding_type=upc.inf.cfi`.
|
||||
2. Find R.109.1, R.109.4, R.109.5 — they sit at depth 1 under the root.
|
||||
3. Edit R.109.4: set `parent_id = <R.109.1's id>`; set `primary_party = both`; set `condition_expr = {"flag": "with_interpreter_denied"}`. Save (draft).
|
||||
4. Edit R.109.5: set `parent_id = <R.109.1's id>`; set `condition_expr = {"flag": "with_translation_granted"}`. Save (draft).
|
||||
5. Publish both.
|
||||
6. The catalog accepts the two new flag names; the validator updates.
|
||||
|
||||
Result in the Verfahrensablauf tree (post-fix):
|
||||
|
||||
```
|
||||
upc.inf.cfi root
|
||||
├─ Mündliche Verhandlung (court · M)
|
||||
├─ Antrag auf Simultanübersetzung (RoP.109.1) [both · O]
|
||||
│ ├─ Mitteilung Dolmetscherkosten (RoP.109.4) [both · M · ?with_interpreter_denied]
|
||||
│ └─ Übersetzungen einreichen (RoP.109.5) [both · M · ?with_translation_granted]
|
||||
```
|
||||
|
||||
In **Gewählt** mode without scenario flags: only the root + Mündliche Verhandlung surface. R.109.1 is an unselected optional → hidden. R.109.4 + R.109.5 are conditional + below an unselected ancestor → hidden.
|
||||
|
||||
In **Gewählt** mode after the user clicks `[Aufnehmen]` on R.109.1: R.109.1 appears. R.109.4 still hidden (its flag `with_interpreter_denied` isn't set; the user would need to know the court denied the Antrag, then tick the flag in the Szenario-Flags strip). R.109.5 similarly hidden until `with_translation_granted` is on.
|
||||
|
||||
In **Alle Optionen** mode: every rule renders, conditionals greyed with their flag hint, R.109.1 dotted with `[Aufnehmen]`.
|
||||
|
||||
This is the model in miniature: the editorial fix is data-only (no schema change, just `parent_id` + `condition_expr` + `primary_party` UPDATEs via the editor); the display fix is policy that the existing scenario_flags + view-mode mechanism already supports.
|
||||
|
||||
### §4.3 `paliad.trigger_events` table fate — drop
|
||||
|
||||
Per m's Q11. Sequence (chained to §3.4):
|
||||
|
||||
1. After 73-globals reparented + route dropped + label-fallback ported to `procedural_events.name`:
|
||||
2. `DROP TABLE paliad.trigger_events` (mig P5, last in the train).
|
||||
3. Migrate `cmd/gen-upc-snapshot/main.go` to no longer SELECT from this table.
|
||||
4. Remove the `ref__trigger_events` sheet from `ExportService` workbook output.
|
||||
|
||||
The bigint PK / parallel taxonomy disappears entirely. `procedural_events` (uuid PK) is the only event catalog.
|
||||
|
||||
---
|
||||
|
||||
## §5 Schema delta + migration plan (slice train)
|
||||
|
||||
Six slices, sequential where data-coupled, parallelisable where not. Each slice ships as one or two PRs.
|
||||
|
||||
| Slice | Mig | What ships | Reversible? |
|
||||
|---|---|---|---|
|
||||
| **P0 — Scenario SSoT** | mig 154 | `ALTER TABLE projects ADD COLUMN scenario_flags jsonb`; GET/PATCH endpoints w/ extended whitelist (named flags + `rule:<uuid>` per-rule entries, validated against project's PT rule set); Verfahrensablauf + result-view binding; `scenario_flag_catalog` table (§4.1) | Yes — DROP COLUMN |
|
||||
| **P1 — Appeal re-split** | mig 155 | UPDATE proceeding_types (re-activate 11/19/20, deactivate 160); UPDATE sequencing_rules (rebind 16 rules to merits/cost/order by event_code prefix); UPDATE pi.cfi spawn FK → 20 | Reversible by inverse UPDATEs; documented in down mig |
|
||||
| **S1+S1a from t-paliad-327** | — | Cross-party display backend + frontend; spawn-only picker filter (`sr.is_spawn = false` in SearchEvents) | Yes — code-only |
|
||||
| **P2 — Empty-PT badge** | — | `has_rules` flag on /api/tools/proceeding-types; frontend muted-chip rendering | Yes — code-only |
|
||||
| **P3 — Entry A (Verfahrensablauf tree)** | — | Tree endpoint + tree UI in /tools/verfahrensablauf; three-way view-mode toggle (localStorage); per-rule `[Aufnehmen]`/`[Entfernen]` chips wire to scenario_flags `rule:<uuid>` entries; subtree-hide-on-unselected-ancestor render logic | Yes — code-only |
|
||||
| **P4 — Editorial walk (73 globals)** | — | parent-NULL filter on /admin/procedural-events; editorial work by m (no coder task per se) | Trivially reversible |
|
||||
| **P5 — trigger_event_id deprecation** | mig 156 | DROP `/api/tools/event-deadlines`; DROP `EventDeadlineService`; port label-fallback in deadline_rule_service.go; remove ref__trigger_events sheet; `ALTER TABLE sequencing_rules DROP COLUMN trigger_event_id`; `DROP TABLE trigger_events`; condition_expr write-time validator | Last; downgrade requires re-adding column + re-populating — irreversible in practice |
|
||||
|
||||
Constraint: **P5 is gated on P4 completion** (no rules can have NULL proceeding_type_id when DROP runs). All other slices ship independently.
|
||||
|
||||
Ordering rationale:
|
||||
- P0 unblocks the Fristenrechner-side bugs immediately (no waiting on appeal-split editorial).
|
||||
- P1 is data-only, low risk, can land in parallel with P0.
|
||||
- S1+S1a are code-only follow-ons to P0 (same scenario-flag plumbing).
|
||||
- P2 ships once P1 lands (re-activated PTs need badge support too).
|
||||
- P3 builds on P2 + the tree endpoint; depends on P0 for flag persistence.
|
||||
- P4 is m's editorial work — duration depends on m's cadence, not coder velocity.
|
||||
- P5 is the cleanup at the end. Only safe when P4 is done.
|
||||
|
||||
---
|
||||
|
||||
## §6 Entry A UI spec (sequence-from-proceeding-type)
|
||||
|
||||
Live URL: `/tools/verfahrensablauf?project=<id>&proceeding_type=upc.inf.cfi`.
|
||||
|
||||
### §6.1 Layout
|
||||
|
||||
```
|
||||
┌─ Akte / kontextfrei ─────────┐ ┌─ Verfahren ──┐ ┌─ Anzeige ──────────────────────────┐
|
||||
│ HL-2024-001 ▼ │ ohne Akte │ │ upc.inf.cfi ▼│ │ Nur Pflicht ⦿ Gewählt ○ Alle Optionen │
|
||||
└──────────────────────────────┘ └──────────────┘ └────────────────────────────────────┘
|
||||
|
||||
┌─ Szenario-Flags ──────────────────────────────────┐
|
||||
│ ☑ Mit Widerklage auf Nichtigkeit (with_ccr) │
|
||||
│ ☐ Mit Antrag auf Patentänderung R.30 (with_amend) │
|
||||
│ ☐ Mit Widerklage auf Verletzung (with_cci) │
|
||||
└────────────────────────────────────────────────────┘
|
||||
|
||||
┌─ Ablauf ── (view-mode: Gewählt) ───────────────────────────────────┐
|
||||
│ 📥 Klageerhebung [claimant · mandatory] │
|
||||
│ ├─ Klageerwiderung [defendant · mandatory] │
|
||||
│ │ └─ Replik [claimant · M · ?with_ccr]│
|
||||
│ │ └─ Duplik [defendant · M · ?with_ccr]│
|
||||
│ ├─ Widerklage auf Nichtigkeit [defendant · O · ?with_ccr][Entfernen]│ ← selected optional
|
||||
│ │ └─ Erwiderung auf CCR [claimant · M · ?with_ccr]│
|
||||
│ │ └─ Replik auf Erw. CCR [defendant · M · ?with_ccr][Gegenseitig]│
|
||||
│ │ └─ Duplik auf Replik [claimant · M · ?with_ccr]│
|
||||
│ └─ ⇲ Berufungsverfahren öffnen [SPAWN → upc.apl.merits] │
|
||||
│ 🏛️ Zwischenanhörung [court · mandatory] │
|
||||
│ 🏛️ Mündliche Verhandlung [court · mandatory] │
|
||||
│ ⚖️ Endentscheidung [court · mandatory] │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
|
||||
↓ (user flips view-mode to "Alle Optionen")
|
||||
|
||||
┌─ Ablauf ── (view-mode: Alle Optionen) ─────────────────────────────┐
|
||||
│ 📥 Klageerhebung [claimant · mandatory] │
|
||||
│ ├─ ┄ Vorl. Einwendungen [defendant · O] [Aufnehmen]┄ │ ← unselected, dotted
|
||||
│ ├─ Klageerwiderung [defendant · mandatory] │
|
||||
│ ├─ Widerklage auf Nichtigkeit [defendant · O · ?with_ccr][Entfernen]│
|
||||
│ ├─ ┄ Antrag auf Patentänderung [O · ?with_amend] greyed │ ← flag not set
|
||||
│ │ └─ wenn 'Mit Patentänderung' im Szenario aktiv │
|
||||
│ ├─ ┄ Antrag auf Simultanübersetzung [O] [Aufnehmen]┄ │ ← post-§4.2.1
|
||||
│ │ ├─ ┄ Mitteilung Dolmetscherkosten [M · ?with_interpreter_denied]│
|
||||
│ │ └─ ┄ Übersetzungen einreichen [M · ?with_translation_granted]│
|
||||
│ ├─ ┄ Antrag CMO-Überprüfung [both · O] [Aufnehmen]┄ │
|
||||
│ ├─ ┄ Antrag Folgenanordnungen R.118(4) [both · O] [Aufnehmen]┄ │
|
||||
│ └─ ⇲ Berufungsverfahren öffnen [SPAWN → upc.apl.merits] │
|
||||
│ 🏛️ ... │
|
||||
└────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
### §6.2 Behaviour
|
||||
|
||||
- **Project picker (Step 0)** unchanged from Fristenrechner.
|
||||
- **Proceeding-type picker** chips → switching re-fetches the tree.
|
||||
- **View-mode toggle (§3.3a)** — three-way segmented control (Nur Pflicht / Gewählt / Alle Optionen). State in `localStorage["verfahrensablauf:view_mode"]`. Default = "Gewählt". Re-renders the tree on toggle; no network call.
|
||||
- **Szenario-Flags strip** reads/writes `projects.scenario_flags` (Akte) or localStorage (kontextfrei). Same `scenario-flag-changed` CustomEvent as Mode B's result view — both surfaces stay in sync. Flag entries (`with_ccr` etc.) live alongside per-rule entries (`rule:<uuid>`) in the same jsonb.
|
||||
- **Per-rule selection chips** — every non-mandatory rule's card carries `[Aufnehmen]` (unselected → tick selects) or `[Entfernen]` (selected → tick deselects). The handler PATCHes `projects.scenario_flags` with `{ "rule:<uuid>": true|false }` and fires the same `scenario-flag-changed` event.
|
||||
- **Subtree hide-on-deselect** — when a chain head (any rule with children via `parent_id`) is unselected in "Gewählt" mode, its descendants don't render. The tree walker checks each rule's full ancestor chain; any unselected ancestor hides the descendant. In "Alle Optionen" mode, descendants render greyed under the unselected ancestor.
|
||||
- **Cross-party rows** render with `Gegenseitig` badge, muted style (same as Mode B result view §2.4). Composes with selection state and view-mode independently.
|
||||
- **Spawn rows** render as leaves with the ⇲ symbol + "Neues Verfahren öffnen" CTA (Akte mode only; kontextfrei shows the badge without the CTA). Spawn rows ignore selection state — they always render in "Gewählt" + "Alle Optionen" modes since they represent a possible next-procedure rather than an in-scenario deadline.
|
||||
- **Empty PT** (the 6 unruled): tree area renders an inline "Für dieses Verfahren sind noch keine Regeln gepflegt" message + a link to /admin if the user is admin.
|
||||
- **Deeplink to Mode B:** each tree node has a "Frist berechnen" link that opens `/tools/fristenrechner?event=<code>&trigger_date=…&project=…`.
|
||||
|
||||
### §6.3 Backend
|
||||
|
||||
New handler: `GET /api/tools/verfahrensablauf/tree?proceeding_type=upc.inf.cfi&project=<id>` returns:
|
||||
|
||||
```jsonc
|
||||
{
|
||||
"proceeding_type": { "code": "upc.inf.cfi", "name_de": "...", "name_en": "..." },
|
||||
"scenario_flags": { "with_ccr": true, "with_amend": false },
|
||||
"tree": [
|
||||
{
|
||||
"rule_id": "...", "event_code": "upc.inf.cfi.soc",
|
||||
"name_de": "Klageerhebung", "primary_party": "claimant",
|
||||
"priority": "mandatory", "has_condition": false, "is_spawn": false,
|
||||
"is_cross_party": false,
|
||||
"children": [
|
||||
{ "rule_id": "...", "event_code": "upc.inf.cfi.sod", ... , "children": [...] },
|
||||
...
|
||||
]
|
||||
},
|
||||
... // chain-anchored roots
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
The tree is the result of walking `parent_id` recursively from the PT's root rules (those with `parent_id IS NULL` for this PT). Computed via one recursive CTE; cached per-PT (the tree shape changes only on rule edits).
|
||||
|
||||
`is_cross_party` is computed against `projects.our_side` (Akte mode) or the request's `?party=` query param (kontextfrei).
|
||||
|
||||
---
|
||||
|
||||
## §7 Entry B UI spec — reaffirms shipped Fristenrechner Mode A+B
|
||||
|
||||
Mode A (`/tools/fristenrechner?mode=search`) and Mode B (`?mode=wizard`) — both shipped via t-paliad-322 S1-S6. Surgical follow-ons from t-paliad-327 design (§0.2):
|
||||
|
||||
- Mode A search: add `AND sr.is_spawn = false` to `SearchEvents` WHERE block + add the derived-trigger filter `EXISTS (non-spawn child)` from §2.2. Compiled together as one PR (S1+S1a).
|
||||
- Mode B R4 chip-strip: identical filter on the wizard's event-pool query.
|
||||
- Result view: stop filtering follow-ups by party server-side (§2.4); render cross-party with badge.
|
||||
- Scenario flag binding: result-view CONDITIONAL group reads/writes `projects.scenario_flags` via the new API (P0). Same CustomEvent sync as Entry A.
|
||||
|
||||
No layout changes. The mode tabs (⚡ Direkt suchen / 🧭 Geführt) stay as today. The 3rd entry path is Entry A on the verfahrensablauf page — not a Mode C.
|
||||
|
||||
---
|
||||
|
||||
## §8 Worked examples
|
||||
|
||||
### §8.1 Entry A — claimant on HL-2024-001 (upc.inf.cfi, with_ccr=true)
|
||||
|
||||
User opens `/tools/verfahrensablauf?project=HL-2024-001&proceeding_type=upc.inf.cfi`.
|
||||
|
||||
- Project context loads. `scenario_flags = {with_ccr: true}`.
|
||||
- Tree GET returns the §1.2 shape, with conditional rules' `has_condition` flagged.
|
||||
- UI renders: top-level SoC anchor → branches. The CCR branch is fully expanded because `with_ccr=true`. The R.30 amend branch renders but conditionals are greyed (with_amend=false).
|
||||
- User clicks "Mit Antrag auf Patentänderung R.30" in the Szenario-Flags strip.
|
||||
- Frontend fires `PATCH /api/projects/HL-2024-001/scenario-flags { with_amend: true }`. Server stores. CustomEvent dispatches.
|
||||
- Tree re-renders: R.30 amend branch ungreys; conditional rules become live.
|
||||
- User scrolls to "Erwiderung auf CCR" → clicks "Frist berechnen" → deeplinks to Mode B with `event=upc.inf.cfi.def_to_ccr&trigger_date=<today>&project=HL-2024-001`.
|
||||
- Mode B result view loads. Cross-party RoP.029.d (defendant Replik) shows with `Gegenseitig` badge.
|
||||
|
||||
### §8.2 Entry B — Mode A search after picker filter
|
||||
|
||||
User types "Berufung" in Mode A.
|
||||
|
||||
- Backend SQL (post-§2.2 + post-spawn filter):
|
||||
```sql
|
||||
WHERE pe.name % 'Berufung' OR pe.code % 'Berufung'
|
||||
AND sr.is_active AND sr.is_spawn = false
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM paliad.sequencing_rules child
|
||||
WHERE child.parent_id = sr.id AND child.is_active AND NOT child.is_spawn
|
||||
)
|
||||
```
|
||||
- Returns: real triggers in the appeal track (`upc.apl.merits.notice`, `upc.apl.merits.grounds`, `upc.apl.order.with_leave`, etc. — post-Q5 split). Does NOT return: `upc.{inf,rev,pi,dmgs}.cfi.appeal_spawn` (spawn-only) or terminal leaves (no children).
|
||||
|
||||
User picks `upc.apl.merits.notice` → result view loads its follow-ups. Tree renders cleanly because the Q5 split gave merits its own chain root.
|
||||
|
||||
### §8.3 Editorial flow — m reparents a legacy global
|
||||
|
||||
m opens `/admin/procedural-events?orphan=true`. Sees the 73-row list.
|
||||
|
||||
- m clicks row "Antrag auf Verlängerung der Klagefrist" (one of the legacy globals with `proceeding_type_id NULL`).
|
||||
- Editor opens. m assigns `proceeding_type_id = upc.inf.cfi` and `parent_id = <RoP.013.1 soc rule>`.
|
||||
- Save. Rule lifecycle flips to draft. m clicks Publish.
|
||||
- The rule now sits under upc.inf.cfi's tree as a hop-1 child of SoC. Mode A picker EXISTS check passes for SoC (was already passing); the tree gains one more chip.
|
||||
- 72 globals to go. m walks at own cadence; no coder time blocked.
|
||||
|
||||
---
|
||||
|
||||
## §9 Out of scope
|
||||
|
||||
- **Calculator (`pkg/litigationplanner.CalculateRule`).** Working as designed.
|
||||
- **Holiday / working-day logic.** Out of scope.
|
||||
- **`choices_offered` + `applies_to_target` formalisation** (athena R11). Same shape as condition_expr would warrant — separate ticket once condition_expr formalisation ships.
|
||||
- **Adding new proceeding_types.** The 23 are stable; editorial work fills the 6 unruled ones.
|
||||
- **DE-side spawn edges** (LG → OLG → BGH as spawns instead of separate projects). Possible v2; not driven by current pain.
|
||||
- **AI-extracted deadlines from documents.** Deferred per memory `b6a11b55…`.
|
||||
- **Cross-tab scenario-flag sync in Akte mode.** Single-tab v1; SSE/WebSocket if it matters later.
|
||||
- **`event_kind` ENUM-ing** (athena R10). Cosmetic; vocab is stable.
|
||||
|
||||
---
|
||||
|
||||
## §10 m's decisions (2026-05-27)
|
||||
|
||||
All 12 questions answered via `AskUserQuestion` on 2026-05-27 ~13:55 (3 batches of 4). 11 picks on-recommendation; Q5 diverged with verbatim reasoning. Plus 8 pre-ratified picks from t-paliad-327 carried forward (§0.2).
|
||||
|
||||
### Tier 1 — model decisions
|
||||
|
||||
- **Q1 (Trigger link canonical): `parent_id` wins, deprecate `trigger_event_id`.** [= recommendation] **Locks §2.1.** Drop the column after backfill completes.
|
||||
- **Q2 (73 legacy globals fate): Reparent onto PT chains via editorial walk.** [= recommendation] **Locks §4.2.** m drives the walk at admin /admin/procedural-events; the orphan filter is the only new UI surface.
|
||||
- **Q3 (Trigger discoverability): Derive from data.** [= recommendation] **Locks §2.2.** EXISTS subquery on parent_id; no new column, no view.
|
||||
- **Q4 (Scenario SSoT shape): `projects.scenario_flags jsonb`.** [= recommendation; confirms t-paliad-327 design under wider scrutiny] **Locks §2.3.**
|
||||
|
||||
### Tier 2 — surface decisions
|
||||
|
||||
- **Q5 (Appeal taxonomy): Reverse the unification — split upc.apl.unified back into merits/cost/order.** [≠ recommendation; m picked option 3, "reverse the unification"] m's verbatim:
|
||||
> yes, reverse the unification as suggested in 3. They are different proceedings, I only wanted the approach to be unified in the "determinator" - but they are actually different proceedings!
|
||||
**Updates §1.4 + §3.1.** Mig P1 re-activates id=11/19/20, retires id=160, rebinds 16 rules by event_code prefix, retargets the pi.cfi spawn FK to id=20. Determinator routing layer (proceeding_mapping.go) keeps the single "Berufung" front door but fans out to the 3 PTs.
|
||||
- **Q6 (Empty PTs): Show with "Keine Regeln gepflegt" badge for now.** [= recommendation; option 2] m's note: "We need to publish rules then... but yeah, show with the badge for now." **Locks §3.2.** Editorial follow-up is m's; not blocking the design.
|
||||
- **Q7 (Entry A location): Fold into /tools/verfahrensablauf.** [= recommendation] **Locks §3.3 + §6.**
|
||||
- **Q8 (Legacy /event-deadlines route): Drop after Tier 1 + 73-globals reparenting.** [= recommendation] **Locks §3.4. Gated on §4.2 completion.**
|
||||
|
||||
### Tier 3 — editorial + cleanup framework
|
||||
|
||||
- **Q9 (condition_expr grammar): Lock to `{flag: "X"} | {op: "and"|"or", args: [...]}`.** [= recommendation] **Locks §4.1.** Write-time JSON-schema validator + known-flag catalog table.
|
||||
- **Q10 (Editorial backfill workflow): Admin /admin/procedural-events with parent-NULL filter.** [= recommendation] **Locks §4.2.** No new UI surface beyond the filter chip.
|
||||
- **Q11 (`trigger_events` table fate): Drop after route is gone.** [= recommendation] **Locks §4.3.** Sequenced as Mig P5, last in the slice train.
|
||||
- **Q12 (Visual format): ASCII trees per PT + Mermaid for spawn edges.** [= recommendation] **Locks §1.2 + §1.3.**
|
||||
|
||||
### 10.0a Post-ratification additions (m, 2026-05-27 14:34–14:40)
|
||||
|
||||
After the §10 main grilling, m added three directions on top of the ratified design. None re-opened a Tier 1 decision; all extended the Verfahrensablauf surface.
|
||||
|
||||
- **Selection state + detail-level filter (m 14:40, supersedes earlier "rarity" framing).** Every optional rule becomes a per-scenario selectable card; selection state lives in the existing `projects.scenario_flags jsonb` with extended shape (`{flag: bool, "rule:<uuid>": bool}`). Recommended = default-selected; optional = default-unselected; mandatory = locked. Deviations only land in storage. No new column on `sequencing_rules`. **Locks §2.4a.** Replaces the pre-clarification strawman that proposed `is_edge_case boolean` — m's reframe makes that wrong (rarity is a scenario property, not a rule property).
|
||||
- **View-mode toggle on Verfahrensablauf.** Three-way segmented control: Nur Pflicht / Gewählt / Alle Optionen. Per-user persistence via `localStorage["verfahrensablauf:view_mode"]`. Default "Gewählt". **Locks §3.3a.** Mode B result view does NOT carry the toggle — it's a Verfahrensablauf-only affordance.
|
||||
- **R.109 chain editorial worked example.** m flagged R.109.1 / R.109.4 / R.109.5 as a concrete editorial-backfill case (wrong parent_id, wrong primary_party on R.109.4, missing condition_expr on R.109.4/.5). Folded as **§4.2.1** worked example demonstrating the parent-NULL filter workflow without code change. Two new scenario-flag names introduced (`with_interpreter_denied`, `with_translation_granted`); both land in the `scenario_flag_catalog` (§4.1) at edit time.
|
||||
|
||||
These additions don't change the slice train sequence (§5). They tighten P0 (the `scenario_flags` PATCH endpoint now validates `rule:<uuid>` keys against the project's active rule set) and P3 (Entry A tree now renders the view-mode toggle + per-rule selection chips), but no new mig is added.
|
||||
|
||||
### 10.1 What changed from the strawman as a result
|
||||
|
||||
Beyond §10.0a additions, the Q5 divergence is the only material change:
|
||||
|
||||
- **Mig P1 (appeal re-split)** is now part of the slice train. It was NOT in the strawman; the strawman assumed athena's R3 was a simple FK retarget. m's pick recasts the unification itself as the bug.
|
||||
- §1.4 per-PT table shows 3 separate appeal PT rows (merits/cost/order) instead of one unified row. The 16 rules under id=160 redistribute to id=11/19/20.
|
||||
- §1.3 spawn graph fan-out has merits (3 edges from inf/rev/dmgs) + order (1 edge from pi) as distinct targets instead of all 4 pointing at a single unified row.
|
||||
|
||||
All other §1-§8 sections hold as originally drafted.
|
||||
|
||||
---
|
||||
|
||||
## §11 Synthesis links
|
||||
|
||||
- mBrian: file as `[synthesis]` linked `triggered_by` t-paliad-329; `related_to` athena's assessment (`document-assessment-deadline-system`) + my proceeding_types taxonomy synthesis + Fristenrechner overhaul synthesis + t-paliad-327 follow-up rules synthesis.
|
||||
- Cross-refs: `docs/assessment-deadline-system-2026-05-27.md` (athena), `docs/design-fristenrechner-followup-rules-2026-05-27.md` (atlas, pre-ratified subset), `docs/design-fristenrechner-overhaul-2026-05-26.md` (cronus, S1-S6 shipped), `docs/design-proceeding-types-taxonomy-2026-05-26.md` (atlas, mig 153 shipped).
|
||||
- Related migrations: 084 (condition_expr backfill), 136 (procedural_events additive), 140 (drop legacy deadline_rules), 145 (`scenarios` table), 153 (proceeding_types.kind).
|
||||
- Coder phase (deferred per inventor SKILL): runs after m ratifies. Slice ordering per §5. NOT cronus (parked) / NOT atlas (inventor). A pattern-fluent Sonnet coder picks up P0 first; P1 + S1/S1a can parallelise; P3 follows; P4 + P5 are gated on each other.
|
||||
553
docs/design-fristenrechner-overhaul-2026-05-26.md
Normal file
553
docs/design-fristenrechner-overhaul-2026-05-26.md
Normal file
@@ -0,0 +1,553 @@
|
||||
# Design — Fristenrechner complete UX overhaul (dual-mode + project write-back)
|
||||
|
||||
**Task:** t-paliad-322
|
||||
**Gitea:** m/paliad#146
|
||||
**Inventor:** cronus (shift-1)
|
||||
**Date:** 2026-05-26
|
||||
**Status:** Draft for m's ratification — coder gate held
|
||||
|
||||
## 0. Premises verified live (before designing)
|
||||
|
||||
Verified against the live youpc Postgres (port 11833, paliad schema) and the live source tree on `mai/cronus/inventor-fristenrechner` @ HEAD.
|
||||
|
||||
### 0.1 Rule-and-event corpus today
|
||||
|
||||
| Table | Active+published rows | Notes |
|
||||
|---|---|---|
|
||||
| `paliad.procedural_events` | 222 (236 total) | The events that anchor a deadline. 4 `event_kind` buckets: `filing`, `hearing`, `decision`, `order`, plus `NULL` for legacy/dpma stragglers. |
|
||||
| `paliad.sequencing_rules` | 231 | The deadlines themselves, anchored on `procedural_event_id` and (sometimes) `trigger_event_id`. 80 carry a `trigger_event_id`, 4 are `is_spawn=true`, 45 are `is_court_set=true`, 18 carry a `condition_expr`. |
|
||||
| `paliad.deadline_concepts` | 57 | Hub layer above events (Klageerhebung, Wiedereinsetzung, …). |
|
||||
| `paliad.proceeding_types` | 46 fristenrechner | 4 jurisdictions: UPC (35), DE (5), EPA (3), DPMA (3). |
|
||||
| `paliad.event_categories` | 125 (103 leaves) | The current cascade tree — 5 user-bucket roots (`cms-eingang`, `muendl-verhandlung`, `beschluss-entscheidung`, `frist-verpasst`, `ich-moechte-einreichen`) + `sonstiges` leaf. UI hides the forward-workflow root (`HIDDEN_CASCADE_ROOTS` in `client/fristenrechner.ts:2605`). |
|
||||
| `paliad.deadlines` | 10 (8 with `sequencing_rule_id`) | Demand-side still tiny. The 2 without `sequencing_rule_id` are manual entries. |
|
||||
|
||||
Live `primary_party` vocabulary on `sequencing_rules`: `claimant`, `defendant`, `both`, `court`, `NULL`. Live `priority` vocabulary: `mandatory`, `recommended`, `optional` (no `informational` rows yet — Phase 2 reserved the slot but seeding is deferred).
|
||||
|
||||
### 0.2 The legacy `deadline_rules` reader is a view
|
||||
|
||||
`paliad.deadline_rules_unified` (mig 139, Slice B.3) is a **view** over `sequencing_rules ⋈ procedural_events ⋈ legal_sources`. All Go calculator paths read through it (see `deadline_rule_service.go:70`). The physical `paliad.deadline_rules` table was dropped in mig 140; the view is the canonical legacy-shape reader. Important for this design: there is no "trigger event" table parallel to events — the rule rows themselves are the things the wizard must land on. `trigger_events` (110 rows) is the youpc-parity legacy table used by `/api/tools/event-deadlines` only.
|
||||
|
||||
### 0.3 The frontend today (`/tools/fristenrechner`)
|
||||
|
||||
Two server-rendered surfaces share the same page (`frontend/src/fristenrechner.tsx`, 657 lines) — the legacy "Procedure mode" (R1 step-list, proceeding picker, trigger date, flag checkboxes) and the **Pathway-B row stack** (`buildRowStack` at `client/fristenrechner.ts:2848`, 4009 lines total). Row stack composes three row kinds via a single `.fristen-row` primitive:
|
||||
|
||||
| Row | Source | Filter or qualifier today |
|
||||
|---|---|---|
|
||||
| R1 Perspective (Beide / Klägerseite / Beklagtenseite) | `currentPerspective`, prefilled from `project.our_side` | hybrid — narrows party-tagged cascade chips AND is used as a column-bucket hint in the result view |
|
||||
| R2 Inbox channel (CMS / beA / Postal / Alle) | `currentInboxChannel` | filter — narrows cascade by forum (CMS → upc, beA → de, …) |
|
||||
| R3..Rn Cascade chain | `event_categories` tree | each step narrows children by `inboxFilterAllowsForums` + `perspectiveAllowsParty` + `cascadeChildAllowsProject` |
|
||||
|
||||
The cascade auto-walks single-child branches under a project context and stops at the first branching point. The user picks a leaf; the leaf's slug feeds `/api/tools/fristenrechner/search?event_category_slug=…` which returns concept cards. Each card expands inline to a calc panel (trigger-date input + flags + computed deadline + "in Akte" CTA).
|
||||
|
||||
### 0.4 What is broken in this UI (m's verdict, 2026-05-26 21:21)
|
||||
|
||||
m's brief in m/paliad#146 enumerates four visible bugs:
|
||||
|
||||
1. **"Beide" as default perspective** is incoherent for the headline use case ("file a deadline because something happened" — you ARE one side).
|
||||
2. **R2 (inbox) does not constrain R3 (cascade)** the way a user expects — picking CMS still leaves "Mündliche Verhandlung" / "Frist verpasst" on the next step. (Cause: those roots have `forums=NULL` in the seed → neutral → visible from every inbox.)
|
||||
3. **Mixed axes** — the form layers filters (forum, inbox channel) on top of qualifiers (event-kind, perspective, proceeding_type) without making the difference visible. The user can't tell which picks narrow and which define.
|
||||
4. **Trigger vs follow-up confusion** — the wizard's purpose is to identify the *trigger event*, then surface the *follow-up deadlines*. Today that split is not reflected in the form. After landing on a leaf, the user gets a flat list of concept cards and has to figure out which one is "the thing that happened" vs "the thing I have to file next".
|
||||
|
||||
m's verdict: "complete overhaul. Should be easy to use."
|
||||
|
||||
### 0.5 Anchor files for the eventual coder
|
||||
|
||||
- `frontend/src/client/fristenrechner.ts` (4009 LoC) — page brain. `buildRowStack` @ L2848, `renderRowStack` @ L3112, `runB1Search` (concept-card render) downstream, `expandCardCalc` @ L1337 (inline calc panel), `openSaveModal` @ L290 + `submitSave` @ L374 (project write-back).
|
||||
- `frontend/src/fristenrechner.tsx` (657 LoC) — server-rendered shell. Contains both the Procedure-mode form **and** the Pathway-B row-stack scaffold. The new design replaces the row-stack scaffold; the procedure-mode form survives.
|
||||
- `internal/handlers/fristenrechner.go` + `_search.go` + `_event_categories.go` — three handler files. `POST /api/tools/fristenrechner` (procedure-mode calc), `GET /search` (concept cards), `GET /event-categories` (cascade tree).
|
||||
- `internal/services/fristenrechner.go` (661 LoC) — calculator adapter to `pkg/litigationplanner`. The calculator is **not** touched by this design.
|
||||
- `internal/handlers/deadlines.go:167` + `services/deadline_service.go:411` (`CreateBulk`) — the project write-back endpoint (`POST /api/projects/{id}/deadlines/bulk`). This survives; the design extends its caller.
|
||||
|
||||
### 0.6 Adjacent design docs to read alongside
|
||||
|
||||
- `docs/design-determinator-row-cascade-2026-05-13.md` — the row-cascade pillars (Project-driven narrowing / Visual hierarchy overhaul / Persistent row stack). This overhaul **keeps** Pillars 2 and 3 and reworks Pillar 1's contract.
|
||||
- `docs/design-fristen-phase2-2026-05-15.md` — the unified `sequencing_rules` model the calculator already runs on.
|
||||
- `docs/audit-fristen-logic-2026-05-13.md` — the trigger-event / Pipeline-A-vs-C distinction.
|
||||
|
||||
---
|
||||
|
||||
## 1. Vision
|
||||
|
||||
**One page, two complementary entry paths, one result surface, one write-back.**
|
||||
|
||||
```text
|
||||
┌───────────────────────── /tools/fristenrechner ─────────────────────────┐
|
||||
│ │
|
||||
│ ╭──────── Akte / kontextfrei ────────╮ (Step 0 — unchanged today) │
|
||||
│ │ HL-2024-001 ▼ | ohne Akte │ │
|
||||
│ ╰─────────────────────────────────────╯ │
|
||||
│ │
|
||||
│ ╭────── Entry mode tabs ──────╮ │
|
||||
│ │ [⚡ Direkt suchen] │ ◀── A: power user, search + chips │
|
||||
│ │ [🧭 Geführt] │ ◀── B: 3-5 question wizard │
|
||||
│ ╰─────────────────────────────╯ │
|
||||
│ │
|
||||
│ ┌── Mode A: Suche ──────────────┐ ┌── Mode B: Wizard ────────────────┐│
|
||||
│ │ search-box ▢▢▢▢▢▢▢▢▢▢▢▢▢▢▢ │ │ R1 Was ist passiert? ✓ filing ││
|
||||
│ │ filter chips: │ │ R2 Forum? ✓ UPC ││
|
||||
│ │ Forum · Proceeding · Event- │ │ R3 Verfahren? ✓ INF ││
|
||||
│ │ Kind · Partei │ │ R4 Welcher Schritt? [active] ││
|
||||
│ │ ┌ Ergebnis-Liste ────────────┐│ │ R5 Welche Seite? ✓ Kläger ││
|
||||
│ │ │ procedural_event hits ││ │ ││
|
||||
│ │ │ [Trigger einrasten →] ││ │ (Direkt-suchen ←) ││
|
||||
│ │ └────────────────────────────┘│ └───────────────────────────────────┘│
|
||||
│ └────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ════ shared from here ═══════════════════════════════════════════════ │
|
||||
│ │
|
||||
│ ┌── Trigger event (locked) ──────────────────────────────────────────┐ │
|
||||
│ │ 📥 Klageschrift wurde eingereicht │ │
|
||||
│ │ upc.inf.cfi · Verletzungsverfahren · Klägerseite │ │
|
||||
│ │ Trigger-Datum: [📅 2026-05-20] (heute) │ │
|
||||
│ │ ändern ↩ │ │
|
||||
│ └─────────────────────────────────────────────────────────────────────┘ │
|
||||
│ │
|
||||
│ ┌── Folge-Fristen ────────────────────────────────────────────────────┐ │
|
||||
│ │ ◉ MANDATORY (auto-checked) │ │
|
||||
│ │ ☑ Klageerwiderung (3 Monate) — 20.08.2026 — RoP 23 ✏ Datum │ │
|
||||
│ │ ☑ ... │ │
|
||||
│ │ ◇ OPTIONAL │ │
|
||||
│ │ □ Wiedereinsetzungsantrag (R.320) — bei Versäumnis │ │
|
||||
│ │ ◊ CONDITIONAL │ │
|
||||
│ │ □ Erwiderung auf Nichtigkeitswiderklage nur wenn CCR │ │
|
||||
│ │ ⇲ SPAWNED │ │
|
||||
│ │ ☑ Berufung gegen Endurteil (kein Datum) │ │
|
||||
│ │ ╭────────────────────────────╮ │ │
|
||||
│ │ │ 4 ausgewählt → in Akte ▶ │ │ │
|
||||
│ │ ╰────────────────────────────╯ │ │
|
||||
│ └─────────────────────────────────────────────────────────────────────┘ │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The two modes never compete: they're two front doors into the **same** locked-trigger-event → follow-up-list → write-back flow.
|
||||
|
||||
---
|
||||
|
||||
## 2. Axis taxonomy — ratified (filters vs qualifiers)
|
||||
|
||||
The headline source of today's UX confusion is the unmarked mixing of *filters* (narrowing the question space without committing to an answer) and *qualifiers* (parts of the eventual deadline definition).
|
||||
|
||||
| Axis | Role | Source | Constrains | Visual in new UI |
|
||||
|---|---|---|---|---|
|
||||
| `forum` | **filter** | derived from `proceeding_types.jurisdiction` (UPC/DE/EPA/DPMA), or from `project.proceeding_type_id`, or user pick | which `proceeding_types` are reachable; which `event_categories` are visible | Mode A: filter chip strip. Mode B: explicit wizard row (R2). Pre-filled + collapsed when there's a project. |
|
||||
| `proceeding_type` | **qualifier** | `project.proceeding_type_id` (binds via mig 096 codes) OR user pick during wizard | the set of `sequencing_rules` rows that can apply | Mode A: filter chip strip. Mode B: explicit wizard row (R3). Pre-filled + collapsed when there's a project. |
|
||||
| `event_kind` | **filter** | `procedural_events.event_kind` (filing / hearing / decision / order) | which `procedural_events` are reachable as triggers | Mode A: filter chip strip. Mode B: explicit wizard row (R1 — the headline question). |
|
||||
| `inbox channel` | **filter** (today) → **out of scope row** (new) | user pick | nothing the user can see (the rule corpus has no "inbox" column; it was only used to recolour the cascade) | Removed from the primary wizard. Pushed into Mode A's secondary chips (off by default). See §3.3. |
|
||||
| `perspective (our_side)` | **qualifier in file-mode**, **filter in explore-mode** | `project.our_side` OR user pick OR implicit-via-event-kind | `sequencing_rules.primary_party`; result-view column bucketing | Wizard tail (R5) **only when** the trigger event's follow-ups actually differ by side. Pre-filled when project has `our_side`. |
|
||||
| `instance_level` (first / appeal / cassation) | qualifier | `project.instance_level` (mig 084) — sparse | rare — used to disambiguate APP+DE | Surfaced only when the wizard hits APP+DE-style ambiguity. |
|
||||
|
||||
**Rule:** a **filter** narrows the visible options without locking in a deadline answer; it can be cleared and re-applied. A **qualifier** is part of the resulting deadline calculation and is locked the moment it's picked. Filters must propagate forward (Mode A's forum-chip narrows the proceeding-chip's options). Qualifiers are picked once and the answer view reads them.
|
||||
|
||||
The "Beide" perspective default (today's bug) is wrong because perspective is a *qualifier* in the headline use case ("file a deadline because something happened — you are one side"), not a *filter*. New default in Mode B: derive from the project's `our_side`, otherwise force a R5 pick (no "Beide"). See Q8 for the explore-mode exception.
|
||||
|
||||
---
|
||||
|
||||
## 3. Mode taxonomy
|
||||
|
||||
### 3.1 Mode A — "⚡ Direkt suchen" (power user)
|
||||
|
||||
Two visually distinct strips (per m §11.Q3):
|
||||
|
||||
```text
|
||||
┌── Filter (eingrenzen) ─────────────────────────────────────────────────┐
|
||||
│ Forum: [UPC] [DE] [EPA] [DPMA] [Alle] │
|
||||
│ Verfahren: [upc.inf.cfi] [...] [Alle] │
|
||||
│ Was passierte: [📥 Eingereicht] [🏛️ Termin] [⚖️ Entscheidung] [📜 Verfügung] [Alle] │
|
||||
│ Partei: [Klägerseite] [Beklagtenseite] [Beide] │
|
||||
├── Suchen ──────────────────────────────────────────────────────────────┤
|
||||
│ 🔎 [_______________________________________________________________] │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
┌── Ergebnisse (klicken = als Trigger einrasten) ────────────────────────┐
|
||||
│ 📥 Klageerhebung · upc.inf.cfi · UPC · 3 Folge-Fristen → │
|
||||
│ ... │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
Single text input, four filter chip strips above it (Forum · Proceeding · Event-Kind · Partei), and a ranked result list of `procedural_events` underneath. The "Filter" strip is visibly grouped (e.g. light background + "Filter (eingrenzen)" header) so users see at a glance that those picks narrow but don't commit; clicking a result row IS the commit (the qualifier action).
|
||||
|
||||
- Search hits `/api/tools/fristenrechner/search` (extended to return events, not just concepts — see §6.1).
|
||||
- Filter chips compose with the text query (`?forum=upc&pt=upc.inf.cfi&kind=filing&party=defendant&q=Klageerwiderung`).
|
||||
- Result rows are individual `procedural_events` (not aggregated concept-cards). Each row shows: name (DE/EN), proceeding_type code, jurisdiction badge, event_kind icon, the rule-count it triggers ("3 Folge-Fristen").
|
||||
- Click a row → "lock as trigger event" → page transitions to the §4 result view.
|
||||
- Power affordance: a row with multiple linked rules can be locked in **per-rule** ("nur diese Frist") via a kebab menu on the row. (Sane default: lock the whole event; the kebab is for the lawyer who only wants one specific reactive deadline.)
|
||||
|
||||
### 3.2 Mode B — "🧭 Geführt" (the wizard)
|
||||
|
||||
A 3-5 question row stack that lands on one `procedural_events` row.
|
||||
|
||||
**Question order (strawman; m to ratify in Q5):**
|
||||
|
||||
1. **R1 — Was ist passiert?** Chips: 📥 Eingereicht (`filing`) · 🏛️ Termin (`hearing`) · ⚖️ Entscheidung (`decision`) · 📜 Verfügung (`order`) · 🕒 Frist versäumt (special bucket, routes to Wiedereinsetzung). One chip = one `event_kind` (or the special). Always asked. ~6 chips, fits one row.
|
||||
2. **R2 — Vor welchem Gericht / bei welchem Amt?** Chips: UPC · LG/OLG/BGH · EPA · DPMA. Pre-filled from `project.proceeding_type → jurisdiction` (or `project.court` substring). **Skipped if R1 narrows to a single forum** (e.g. "Termin" + project has UPC → R2 is implied).
|
||||
3. **R3 — In welchem Verfahren?** Chips: every active `proceeding_type` whose jurisdiction matches R2 AND whose event roster contains at least one event with R1's kind. Pre-filled from `project.proceeding_type_id`. **Auto-skipped** when the narrowed scope has only one candidate.
|
||||
4. **R4 — Welches Schriftstück / Welcher Termin?** This is the wizard's landing question. Chips = `procedural_events` filtered by (R2 forum, R3 proceeding_type, R1 event_kind). Typical scope: 1-12 events. If the user types into this row, the chip layout flips to a search list (same widget as Mode A's result list, narrowed to the wizard's filters).
|
||||
5. **R5 — Vertreten Sie Kläger- oder Beklagtenseite?** Asked **only when** the selected event's `sequencing_rules` have follow-ups that differ by `primary_party` (a quick "are there both claimant- and defendant-tagged rules among the follow-ups?" check on the catalog). Pre-filled from `project.our_side`. **Skipped otherwise.**
|
||||
|
||||
**Row badges** (per m §11.Q3): each wizard row carries a small "Filter" or "Qualifier" tag next to its row-number badge. R1 (event_kind), R2 (forum) → "Filter". R3 (proceeding_type), R4 (procedural_event), R5 (perspective) → "Qualifier". A user can tell at a glance which picks lock in vs which narrow.
|
||||
|
||||
Branching policy (locked):
|
||||
|
||||
- Pre-fill + collapse a row when the answer is implied by the project (Determinator §4 pattern, unchanged).
|
||||
- Auto-skip a row when the narrowed scope has exactly one option (the user has effectively no choice). Show the skipped row as a compact `.fristen-row.is-prefilled` line with "(aus Akte)" or "(implizit aus R1)" annotation. *Don't hide the row* — m's "see your selections" pillar from the row-cascade design demands every decision stays visible.
|
||||
- A user-edited upstream answer **preserves compatible downstream picks** (m §11.Q10): if a re-picked R2 (forum) keeps the existing R1 (event_kind) legal, R1 stays; if it makes R3 (proceeding_type) illegal, R3 resets to active. Rows whose pick was carried across an upstream change render with a one-render "erhalten" annotation so the user notices.
|
||||
- "Welches Schriftstück?" (R4) is the landing question. Once R4 is answered, the wizard exits and the §4 result view takes over.
|
||||
|
||||
### 3.3 The dropped `inbox channel` row
|
||||
|
||||
R2-inbox in today's row stack is removed from the primary surface for both modes. Rationale:
|
||||
|
||||
- The rule corpus has no `inbox` column. The cascade's `forums=['cms']` etc. tags were a presentation-layer reflection of which forum naturally arrives on which channel — but the rule itself doesn't change based on whether a UPC document arrived via CMS or by post (it can't; only CMS is legal). So the only honest role for "inbox" is to nudge the forum filter on Mode A.
|
||||
- Mode A keeps inbox as a *secondary* chip strip ("Erweitert" toggle, off by default). Picking CMS auto-sets the forum chip to UPC; picking beA auto-sets it to DE. The user can override.
|
||||
- Mode B never asks. The wizard derives forum from project context or from R2.
|
||||
|
||||
This collapses one bug class entirely (R2-not-constraining-R3) by retiring R2 from the headline path.
|
||||
|
||||
---
|
||||
|
||||
## 4. Shared result view — "follow-up deadlines"
|
||||
|
||||
Once a trigger event is locked (via Mode A click or Mode B R4 pick), the same result view renders.
|
||||
|
||||
### 4.1 Trigger card (sticky header)
|
||||
|
||||
```text
|
||||
┌─ Trigger-Ereignis ─────────────────────────────────────────────────────┐
|
||||
│ 📥 Klageerhebung │
|
||||
│ upc.inf.cfi · Verletzungsverfahren · UPC │
|
||||
│ ⓘ "Einreichung der Klageschrift gemäß R.13 RoP" │
|
||||
│ Trigger-Datum: 📅 2026-05-20 [ändern ↩] │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
`Trigger-Datum` defaults to today. The user can change it inline (date picker). Changing it re-renders the follow-ups with new computed dates.
|
||||
|
||||
The "ändern" link drops back to whichever mode the user came from with R1-R4 still answered. (Per Q4: the wizard preserves compatible upstream picks rather than rebooting.)
|
||||
|
||||
### 4.2 Follow-up groups
|
||||
|
||||
Group `sequencing_rules` rows that have the trigger event as **anchor** (i.e. `sr.procedural_event_id = trigger.id`) into 4 visible groups:
|
||||
|
||||
1. **MANDATORY** (`priority='mandatory'`) — pre-checked. The bread-and-butter follow-ups.
|
||||
2. **RECOMMENDED** (`priority='recommended'`) — pre-checked. Best-practice fillings (R.19 EPÜ Einspruch, replication briefs).
|
||||
3. **OPTIONAL** (`priority='optional'`) — unchecked. Discretionary actions (R.320 Wiedereinsetzung).
|
||||
4. **CONDITIONAL** (`condition_expr IS NOT NULL`) — unchecked, with the condition rendered ("nur wenn CCR im Verfahren"). Lawyer ticks if applicable.
|
||||
|
||||
Plus a fifth implicit bucket:
|
||||
|
||||
5. **SPAWNED / CROSS-PROCEEDING** (`is_spawn=true`, `spawn_proceeding_type_id IS NOT NULL`) — surfaced as a separate sub-section with a clear "leitet ein neues Verfahren ein" annotation. Pre-checked when mandatory.
|
||||
|
||||
Recommendation (Q6): **4 visible groups, with SPAWNED inlined into whichever priority bucket it belongs to but tagged with a "⇲ neues Verfahren" badge.** Five groups is too many for a one-page result; folding SPAWNED into its priority keeps the math right (mandatory spawned = mandatory) while still flagging the cross-proceeding implication.
|
||||
|
||||
### 4.3 Per-rule row
|
||||
|
||||
```text
|
||||
☑ Klageerwiderung ✏ Datum
|
||||
3 Monate nach Klageerhebung 20.08.2026
|
||||
RoP 23 · Beklagtenseite
|
||||
ⓘ Schriftlich, mit Vollmacht. Erstmaliges Bestreiten der Patentverletzung.
|
||||
```
|
||||
|
||||
Columns: checkbox · title (DE/EN) · duration phrase · computed due date · rule citation · party stance · expandable notes.
|
||||
|
||||
Inline date editor (✏ Datum) lets the lawyer override the computed date for this rule (same affordance as today's `wireDateEditClicks`). The override flows into the write-back payload.
|
||||
|
||||
`is_court_set=true` rules render with the "wird vom Gericht bestimmt" placeholder instead of a date and are unchecked-by-default (matches the current `openSaveModal` behaviour).
|
||||
|
||||
### 4.4 Result-view footer (write-back CTA)
|
||||
|
||||
```text
|
||||
┌─ Auswahl ──────────────────────────────────────────────────────────────┐
|
||||
│ 4 Fristen ausgewählt → In Akte HL-2024-001 eintragen ▶ │
|
||||
│ (oder: 2 mit eigenem Datum, 2 mit Standardberechnung) │
|
||||
└─────────────────────────────────────────────────────────────────────────┘
|
||||
```
|
||||
|
||||
The CTA opens a **confirm-and-edit-dates modal** (per m §11.Q6) where the lawyer can revise each selected deadline's due date one last time, then commits via `POST /api/projects/{id}/deadlines/bulk` (today's endpoint).
|
||||
|
||||
**Kontextfrei mode (no Akte)** — per m §11.Q7, the entire write-back footer **does not render** when `project == null`. The result view stays informational. In its place, an inline nudge appears above the deadline groups:
|
||||
|
||||
```text
|
||||
ⓘ Tipp: Wähle oben eine Akte, um diese Fristen einzutragen.
|
||||
```
|
||||
|
||||
The "oben" link focuses the Akte picker. Once a project is picked, the nudge collapses and the footer materialises; no page reload, no result-view rebuild (the trigger event and date persist across the project pick).
|
||||
|
||||
Modal payload per deadline (extends today's `CreateDeadlineInput`):
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Klageerwiderung",
|
||||
"rule_code": "RoP 23",
|
||||
"due_date": "2026-08-20",
|
||||
"original_due_date": "2026-08-20",
|
||||
"source": "fristenrechner",
|
||||
"rule_id": "<sequencing_rules.id>", /* maps to deadlines.sequencing_rule_id */
|
||||
"notes": "..."
|
||||
}
|
||||
```
|
||||
|
||||
**audit_reason wording (per Q12):** every row inserted via this flow carries an audit-log breadcrumb on the project (matches the deadline `Verlauf` pattern). Default reason string:
|
||||
|
||||
> `Aus Fristenrechner — Trigger: {trigger_event_name} ({trigger_date_iso})`
|
||||
|
||||
e.g. `Aus Fristenrechner — Trigger: Klageerhebung (2026-05-20)`. Falls into `paliad.project_events` with `kind='deadline_created'` via the existing `DeadlineService.CreateBulk` audit hook; no schema change needed.
|
||||
|
||||
---
|
||||
|
||||
## 5. URL / state representation
|
||||
|
||||
The new flow keeps Pathway-B's URL-as-state contract, simplified:
|
||||
|
||||
| Param | Owner | Meaning |
|
||||
|---|---|---|
|
||||
| `project` | Step 0 | Active project UUID. Drives the prefills. |
|
||||
| `mode` | mode tab | `wizard` (default) or `search`. |
|
||||
| `q` | Mode A | Free text query. |
|
||||
| `forum` | Mode A | Comma-separated forum codes (`upc,de`). Mode B writes this only when the wizard derives it. |
|
||||
| `pt` | Mode A | Selected proceeding_type code. |
|
||||
| `kind` | Mode A | event_kind chip pick. |
|
||||
| `party` | both | Perspective. Mode A's chip; Mode B's R5. |
|
||||
| `wizard` | Mode B | Dotted state cursor encoding which row is active and the picks made: `wizard=kind:filing,forum:upc,pt:upc.inf.cfi,active:event`. |
|
||||
| `event` | both | The locked trigger `procedural_events.code`. Once set, the result view renders. |
|
||||
| `trigger_date` | result | ISO date. Default = today; URL only carries it when overridden. |
|
||||
| `selected` | result | Comma-separated `sequencing_rules.id` checkbox state. Only carried when it differs from the priority default. |
|
||||
|
||||
Deep links work end-to-end: `?project=…&event=upc.inf.cfi.soc&trigger_date=2026-05-20&selected=…` jumps a colleague straight to the result view with the same picks. (Per Q11 — query string, not pathname.)
|
||||
|
||||
`popstate` rebuilds the page from the params alone (same pattern as today). The wizard state cursor lets browser back/forward step the wizard rows instead of dropping back to the page root.
|
||||
|
||||
---
|
||||
|
||||
## 6. Backend contract changes
|
||||
|
||||
### 6.1 Extend `/api/tools/fristenrechner/search`
|
||||
|
||||
Today returns concept-cards. Add an alternate response shape (or a `?kind=events` flag) that returns `procedural_events` rows directly:
|
||||
|
||||
```json
|
||||
{
|
||||
"query": "Klageerhebung",
|
||||
"filters": { "forum": "upc", "pt": null, "kind": "filing", "party": null },
|
||||
"events": [
|
||||
{
|
||||
"id": "<uuid>",
|
||||
"code": "upc.inf.cfi.soc",
|
||||
"name_de": "Klageerhebung",
|
||||
"name_en": "Statement of Claim",
|
||||
"event_kind": "filing",
|
||||
"proceeding_type": { "code": "upc.inf.cfi", "jurisdiction": "UPC", "name": "..." },
|
||||
"follow_up_count": 3,
|
||||
"concept_id": "<uuid>",
|
||||
"score": 0.92
|
||||
}
|
||||
],
|
||||
"total": 12
|
||||
}
|
||||
```
|
||||
|
||||
The concept-card shape stays available for the legacy Pathway-B-filter route (kept as a deep-link compat surface, not user-facing).
|
||||
|
||||
### 6.2 New `/api/tools/fristenrechner/follow-ups`
|
||||
|
||||
Given a trigger event id + trigger date + optional party qualifier, return the follow-up `sequencing_rules` rows, grouped + with computed dates. Wire shape:
|
||||
|
||||
```json
|
||||
{
|
||||
"trigger": { "id": "...", "code": "upc.inf.cfi.soc", "name_de": "Klageerhebung", "event_kind": "filing", "proceeding_type": { "code": "upc.inf.cfi", "name_de": "Verletzungsverfahren", "jurisdiction": "UPC" } },
|
||||
"trigger_date": "2026-05-20",
|
||||
"party": "claimant",
|
||||
"follow_ups": [
|
||||
{
|
||||
"rule_id": "<uuid>",
|
||||
"title_de": "Klageerwiderung",
|
||||
"title_en": "Defence",
|
||||
"priority": "mandatory",
|
||||
"primary_party": "defendant",
|
||||
"duration_phrase": "3 Monate",
|
||||
"due_date": "2026-08-20",
|
||||
"is_court_set": false,
|
||||
"is_spawn": false,
|
||||
"condition_expr": null,
|
||||
"rule_code": "RoP 23",
|
||||
"notes_de": "...",
|
||||
"spawn_label": null,
|
||||
"spawn_proceeding_type": null,
|
||||
"appeal_target": null
|
||||
}
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
Implementation: `FristenrechnerService.LookupFollowUps(ctx, eventID, triggerDate, party)` — wraps `catalog.LookupEvents(axes={EventID:…, Depth:Next})` (already implemented for the Litigation Planner per `services/fristenrechner.go:251`) and runs the result through `pkg/litigationplanner.Calculate` to fill the dates. The calculator is unchanged.
|
||||
|
||||
### 6.3 No schema changes
|
||||
|
||||
This design is pure UX + handler shape. The unified `sequencing_rules` model already has every column needed (priority, condition_expr, spawn_*, is_court_set, primary_party, applies_to_target). No migration accompanies this design.
|
||||
|
||||
---
|
||||
|
||||
## 7. Migration plan — from current row stack to the overhaul
|
||||
|
||||
Drop nothing on day one; co-exist for one release. The cutover is by URL flag.
|
||||
|
||||
| Phase | What changes | What survives | Branch |
|
||||
|---|---|---|---|
|
||||
| **S1 — Backend** | Add `GET /search?kind=events`. Add `GET /follow-ups`. Both feature-flagged behind a request header (off by default). | Existing endpoints. | one PR |
|
||||
| **S2 — Result view** | New `frontend/src/client/fristenrechner-result.ts` module — given a trigger event + date, render the §4 result view. Mount under a `?overhaul=1` query flag on /tools/fristenrechner. The legacy `renderProcedureResults` stays. | All today's UI. | one PR |
|
||||
| **S3 — Mode A** | New search-with-filter-chips UI. Mount alongside the row stack under `?overhaul=1`. | Row stack still primary. | one PR |
|
||||
| **S4 — Mode B (wizard)** | New `frontend/src/client/fristenrechner-wizard.ts` — the 3-5 row stack. Replaces today's `buildRowStack` only when `?overhaul=1`. Project prefill logic from `buildRowStack` ports 1:1. | The legacy row stack stays in place under no flag. | one PR |
|
||||
| **S5 — Flip the flag** | `?overhaul=1` becomes the default. Legacy row stack and `event_categories`-based cascade rendered with a hard-coded `?legacy=1` for two weeks. | Procedure mode (the upper half of `fristenrechner.tsx`) is unchanged throughout. | one PR |
|
||||
| **S6 — Cleanup** | Drop the `buildRowStack` function tree and the `event_categories`-served cascade endpoint (the table can stay — it's still semantically a useful taxonomy for future tools, just not the Fristenrechner's UI). Drop the `HIDDEN_CASCADE_ROOTS` constant and the cascade-segment bridge. | None of today's row-stack code. | one PR |
|
||||
|
||||
Single project per slice; each PR rebases off main; no shared branches.
|
||||
|
||||
The `event_categories` table itself **stays** — `audit-fristen-logic-2026-05-13.md` §2.4 already calls it "a config layer" useful for taxonomy work. The Fristenrechner just no longer reads it. Future tools (the "Ich möchte einreichen" forward-workflow surface m hid in `HIDDEN_CASCADE_ROOTS`) can resurrect it without DB migration.
|
||||
|
||||
---
|
||||
|
||||
## 8. Worked example — "PA at LG Düsseldorf bekommt einen Hinweisbeschluss via CMS in einer aktiven Akte"
|
||||
|
||||
Project: `HL-2024-001`, proceeding_type=`de.inf.lg` (Verletzungsverfahren LG), `our_side='defendant'`, `court='LG Düsseldorf'`.
|
||||
|
||||
### 8.1 Wizard path (Mode B, default)
|
||||
|
||||
User opens /tools/fristenrechner with that project in Step 0. Mode tab defaults to "🧭 Geführt".
|
||||
|
||||
Wizard rows render top-to-bottom, pre-filled where the project implies:
|
||||
|
||||
```text
|
||||
[1] Was ist passiert? [ active — chips for filing/hearing/decision/order/missed ]
|
||||
[2] Vor welchem Gericht? ✓ LG (aus Akte: HL-2024-001) ← prefilled+collapsed
|
||||
[3] In welchem Verfahren? ✓ Verletzungsverfahren (de.inf.lg) ← prefilled+collapsed
|
||||
```
|
||||
|
||||
User clicks ⚖️ Entscheidung in R1.
|
||||
|
||||
Row stack updates:
|
||||
```text
|
||||
[1] Was ist passiert? ✓ Entscheidung ← answered
|
||||
[2] Vor welchem Gericht? ✓ LG (aus Akte) ← prefilled
|
||||
[3] In welchem Verfahren? ✓ Verletzungsverfahren (de.inf.lg) ← prefilled
|
||||
[4] Welche Entscheidung konkret? [ active — chips: Urteil, Beschluss, Hinweisbeschluss, ... ]
|
||||
```
|
||||
|
||||
R4 chip set is the `procedural_events` whose `proceeding_type_id` = de.inf.lg AND `event_kind` = 'decision'. (Hinweisbeschluss is in this set — `de.inf.lg.hinweisbeschluss` or similar.)
|
||||
|
||||
User clicks Hinweisbeschluss. The wizard checks: do the follow-up rules differ by `primary_party`? In this case yes (the Hinweis triggers a reply window for the defendant only). So R5 fires:
|
||||
|
||||
```text
|
||||
[5] Welche Seite vertreten Sie? ✓ Beklagtenseite (aus Akte) ← prefilled
|
||||
```
|
||||
|
||||
R5 is pre-filled from `project.our_side='defendant'`. The user could click ändern to override, but doesn't.
|
||||
|
||||
Wizard transitions to the §4 result view. Trigger card: "📜 Hinweisbeschluss · de.inf.lg · LG · Beklagtenseite". Trigger date defaults to today.
|
||||
|
||||
### 8.2 Result view
|
||||
|
||||
Three follow-ups in scope (illustrative):
|
||||
|
||||
```text
|
||||
MANDATORY
|
||||
☑ Stellungnahme zum Hinweisbeschluss (Frist 4 Wochen) — 24.06.2026 — ZPO §139
|
||||
RECOMMENDED
|
||||
☑ Anpassung der Klageerwiderung — 24.06.2026 — best practice
|
||||
OPTIONAL
|
||||
□ Antrag auf Fristverlängerung (begründet) — auf Antrag
|
||||
```
|
||||
|
||||
User unchecks "Anpassung", changes the Stellungnahme date inline to 2026-06-20 (one weekday earlier), clicks "In Akte HL-2024-001 eintragen ▶".
|
||||
|
||||
Modal opens with the 1 selected deadline + the user's date override. User confirms.
|
||||
|
||||
### 8.3 Write-back
|
||||
|
||||
Server-side: `POST /api/projects/HL-2024-001/deadlines/bulk` with one `CreateDeadlineInput`:
|
||||
|
||||
```json
|
||||
{
|
||||
"title": "Stellungnahme zum Hinweisbeschluss",
|
||||
"rule_code": "ZPO §139",
|
||||
"due_date": "2026-06-20",
|
||||
"original_due_date": "2026-06-24",
|
||||
"source": "fristenrechner",
|
||||
"rule_id": "<sr-uuid>",
|
||||
"notes": null
|
||||
}
|
||||
```
|
||||
|
||||
`DeadlineService.CreateBulk` inserts the row into `paliad.deadlines` (with `sequencing_rule_id` populated from `rule_id`), creates the audit event with the wording "Aus Fristenrechner — Trigger: Hinweisbeschluss (2026-05-26)", and the user is redirected to `/deadlines?project_id=…` with a green success toast.
|
||||
|
||||
### 8.4 Mode A path for the same user
|
||||
|
||||
User flips the mode tab to "⚡ Direkt suchen". Filter chips auto-load to Forum=DE + Proceeding=de.inf.lg (from project context). User types "Hinweis" — the result list shows `de.inf.lg.hinweisbeschluss` (and maybe `upc.inf.cfi.hinweis` filtered out because Forum=DE narrows it). User clicks. Same result view appears.
|
||||
|
||||
Total clicks Mode A: 2 (type + click). Mode B: 2 (R1 chip + R4 chip; R2/R3/R5 prefilled). The wizard wins for trainees who don't know vocabulary; search wins for power users who know "Hinweisbeschluss" and can type 4 chars.
|
||||
|
||||
---
|
||||
|
||||
## 9. What's NOT in scope
|
||||
|
||||
- **Replacing the `sequencing_rules` model.** Phase 3 schema is already what the calculator runs on.
|
||||
- **Paliadin (LLM) integration into the wizard.** A "Frist-Extraktion aus Dokument" path is filed elsewhere (memory `b6a11b55…`) and stays out of this design. The wizard could later call out to Paliadin for "the user typed something we don't know" — Phase 2 of *this* overhaul, not Phase 1.
|
||||
- **Calendar / Outlook sync** of created deadlines. Separate t-paliad ticket per project-status.md long-term goals.
|
||||
- **Editing `sequencing_rules`** from the result view. Read-only here. The admin surface at `/admin/procedural-events` handles editing.
|
||||
- **The Procedure-mode surface** (upper half of `fristenrechner.tsx`). The proceeding-picker + trigger-date + flag-checkbox UI stays exactly as it is today. That surface answers a different question ("show me the full procedural ablauf for upc.inf.cfi") and is the right tool for that question; the overhaul targets only the Pathway-B / row-stack half of the page.
|
||||
|
||||
---
|
||||
|
||||
## 10. Open questions for m (12 questions, batched for `AskUserQuestion`)
|
||||
|
||||
All 12 questions tracked in m/paliad#146 § "Open design questions". Each gets a recommended option (listed first in the AskUserQuestion call). Bundled into 3 batches of 4.
|
||||
|
||||
| # | Topic | Recommended pick |
|
||||
|---|---|---|
|
||||
| Q1 | Single page or stepper? | Single page with mode-tabs + collapsible rows. |
|
||||
| Q2 | Mode switcher placement | Tab pair under Step-0 ("Akte / kontextfrei"). |
|
||||
| Q3 | Filter-vs-qualifier UX | Qualifiers carry a small "(Pflichtangabe)" tag; filters render in a slimmer pill. |
|
||||
| Q4 | Cascade tree (keep/replace) | Replace with the 5-question wizard. Drop `event_categories` from the Fristenrechner UI (table stays). |
|
||||
| Q5 | Result grouping | 4 visible groups (Mandatory / Recommended / Optional / Conditional), SPAWNED folded with badge. |
|
||||
| Q6 | Project write-back UX | Confirm-and-edit-dates modal (revise each date once before commit). |
|
||||
| Q7 | No-project mode | CTA disabled with hint ("Wähle eine Akte oben"). Match today's pattern. |
|
||||
| Q8 | Perspective semantics by mode | Mode B (file): qualifier — required pick. Mode A (search): filter — optional. |
|
||||
| Q9 | Trigger-date input timing | In the result-view trigger card; default today; inline editable. |
|
||||
| Q10 | Backward navigation | Preserve compatible downstream picks; reset only those invalidated. |
|
||||
| Q11 | Deep-link encoding | Query string (`?event=…&trigger_date=…`). |
|
||||
| Q12 | Audit reason wording | `Aus Fristenrechner — Trigger: {name} ({date})`. |
|
||||
|
||||
(Recommendations land as the "first option" in each AskUserQuestion call per the inventor SKILL contract.)
|
||||
|
||||
---
|
||||
|
||||
## 11. m's decisions (2026-05-26)
|
||||
|
||||
All 12 questions answered via `AskUserQuestion` on 2026-05-26 21:30. Recording each pick + the reasoning where it diverges from the inventor's recommendation. Sections of the design that are now load-bearing on these answers carry a "(m §11.Q{n})" cross-reference.
|
||||
|
||||
- **Q1 (Page layout): Single page, mode-tabs.** [= recommendation] Both modes share /tools/fristenrechner; the mode-tabs swap the question surface in place. Result view is shared. **Locks §3, §4, §5.**
|
||||
- **Q2 (Mode switcher): Tab pair under Step-0.** [= recommendation] "⚡ Direkt suchen" / "🧭 Geführt" tabs render directly below the Akte picker. Project context survives the tab flip; compatible filter picks (forum, proceeding) carry across.
|
||||
- **Q3 (Filter-vs-qualifier UX): Section split — Filter above, Qualifier below.** [≠ recommendation; m picked option 2.] Mode A's filter chips render in a "Filter (eingrenzen)" strip on top; below it, the result list is the qualifier surface (clicking a row locks). Mode B wizard rows carry a small "Filter" / "Qualifier" badge in the row badge area (e.g. R1/R2 = Filter, R3/R5 = Qualifier). The "(Pflichtangabe)" tag from the original recommendation is replaced by this section-level visual hierarchy. **Updates §3.1 (Mode A layout) and §3.2 (wizard row badges).**
|
||||
- **Q4 (Cascade tree): Replace with wizard, keep table.** [= recommendation] The Fristenrechner UI stops reading `paliad.event_categories`. The table stays for future tools (the hidden "Ich möchte einreichen" forward-workflow). **Locks §3.2 and the cleanup in §7 S6.**
|
||||
- **Q5 (Result grouping): 4 groups + SPAWNED badge.** [= recommendation] Mandatory / Recommended / Optional / Conditional are the four sub-sections; spawned rules fold into their priority bucket with a `⇲ neues Verfahren` badge. **Locks §4.2.**
|
||||
- **Q6 (Write-back UX): Confirm-and-edit-dates modal.** [= recommendation] Inline checkbox selection in the result view → "In Akte eintragen ▶" → modal with editable due-date fields per row + Akte picker. **Locks §4.4.**
|
||||
- **Q7 (No-project mode): Hide the CTA entirely.** [≠ recommendation; m picked option 3.] In kontextfrei mode the result view renders without the write-back footer at all — no disabled-with-hint button. Rationale (inferred from m's pick): the result view is informational by design in explore mode, and a permanently-disabled CTA is visual noise. **Updates §4.4** — the CTA is conditional on `project != null`, not on `disabled`. The hint message moves into the Step-0 picker: when a user is in kontextfrei mode and reaches a result view, a one-line nudge appears above the result groups ("Tipp: Wähle oben eine Akte, um diese Fristen einzutragen") with a link to focus the Akte picker. This preserves the affordance discovery without polluting the footer.
|
||||
- **Q8 (Perspective semantics): Mode B qualifier, Mode A filter.** [= recommendation] Wizard Mode B's R5 is required and Klagerseite/Beklagtenseite only (no "Beide"); Mode A's perspective chip is a filter with a "Beide" option, off by default. **Locks §2 axis table and §3.2 R5 description.**
|
||||
- **Q9 (Trigger-date input): In the result-view trigger card.** [= recommendation] The sticky header card on the result view shows the date; default today; inline editable. Changing it re-renders follow-up dates live. **Locks §4.1.**
|
||||
- **Q10 (Backward navigation): Preserve compatible picks.** [= recommendation] Re-opening any wizard row keeps downstream picks that are still legal under the new upstream value; resets only the picks the new value invalidates. A small chip-strip annotation ("erhalten") appears for one render-cycle on rows whose pick was carried so the user notices. **Updates §3.2 branching policy.**
|
||||
- **Q11 (Deep-link encoding): Query string.** [= recommendation] `?project=…&mode=…&event=…&trigger_date=…&selected=…&forum=…&pt=…&kind=…&party=…` — every state piece is a query param. `popstate` rebuilds the page from params. **Locks §5.**
|
||||
- **Q12 (Audit reason wording): `Aus Fristenrechner — Trigger: {name} ({date})`.** [= recommendation] German-locale, includes the trigger event name and its ISO date. Stored as `paliad.project_events.metadata->>'audit_reason'` via the existing `DeadlineService.CreateBulk` audit hook. **Locks §4.4.**
|
||||
|
||||
### 11.1 What changed from the strawman as a result
|
||||
|
||||
Two follow-on edits flow from m's picks:
|
||||
|
||||
1. **§3.1 Mode A layout** — top strip is "Filter (eingrenzen)" with the four filter chip groups (Forum · Proceeding · Event-Kind · Partei); the result list directly below carries the implicit "click here to lock" qualifier action. No "(Pflichtangabe)" tag.
|
||||
2. **§4.4 Write-back footer** — the footer is rendered conditionally on `project != null`. The kontextfrei-mode informational nudge moves into the result view body above the deadline groups.
|
||||
|
||||
These edits don't change the §7 migration plan or the §6 backend contracts.
|
||||
|
||||
---
|
||||
|
||||
## 12. Synthesis links
|
||||
|
||||
- mBrian topic: `topic-fristenrechner` (existing) — file this design as a `[synthesis]` node linked `triggered_by` t-paliad-322 and `related_to` the row-cascade + Phase 2 designs.
|
||||
- Related memories: row-cascade design `0fbd2c1a-…`, Phase 2 design `a454dc86-…`, audit logic `f6c0c3a2-…`.
|
||||
580
docs/design-proceeding-types-taxonomy-2026-05-26.md
Normal file
580
docs/design-proceeding-types-taxonomy-2026-05-26.md
Normal file
@@ -0,0 +1,580 @@
|
||||
# Design — `paliad.proceeding_types` taxonomy cleanup: primary proceedings vs phases vs side-actions vs meta
|
||||
|
||||
**Task:** t-paliad-324
|
||||
**Gitea:** m/paliad#147
|
||||
**Inventor:** atlas (shift-1)
|
||||
**Date:** 2026-05-26
|
||||
**Status:** Draft — coder gate held until m ratifies the 10 design questions in §9
|
||||
**Branch:** `mai/atlas/inventor-proceeding`
|
||||
|
||||
---
|
||||
|
||||
## 0. Premises verified live (before designing)
|
||||
|
||||
Verified against live youpc Postgres (port 11833, `paliad` schema) on 2026-05-26 22:05. Findings supersede the audit grouping in m/paliad#147 wherever they diverge — the issue body was correct on shape but conservative on counts.
|
||||
|
||||
### 0.1 The 46-row table, fully classified by usage
|
||||
|
||||
`paliad.proceeding_types` has 49 rows total; 46 active, 3 inactive (`upc.apl.merits/cost/order` — superseded by `upc.apl.unified`, id 160) plus 1 archive bucket (`_archived_litigation`, id 32). Cross-references against the four downstream consumers:
|
||||
|
||||
| Consumer | Column | Active rows that point at the 46 active types |
|
||||
|---|---|---|
|
||||
| `paliad.sequencing_rules.proceeding_type_id` | rule's anchor proceeding | **18 distinct rows used** — the primaries with corpus. 28 rows have 0 rules. |
|
||||
| `paliad.sequencing_rules.spawn_proceeding_type_id` | cross-proceeding spawn target | **1 distinct row used** — `upc.apl.merits` (id=11, **inactive!**). 0 active types are spawn targets. |
|
||||
| `paliad.projects.proceeding_type_id` | project's primary type | **6 distinct rows used** (across 18 projects). All 6 are in the 18 primaries. |
|
||||
| `paliad.event_category_concepts.proceeding_type_code` | concept's owning proceeding | **18 distinct codes used.** 3 of those codes (`upc.apl.merits`, `upc.apl.order`, `upc.apl.cost`) point at **inactive** rows — pre-existing data drift from the `upc.apl.unified` merger (flagged §8, out of scope here). |
|
||||
|
||||
The audit answer in one sentence: **of the 46 active rows, only 18 have any downstream consumer pointing at them today** (the 18 primaries with corpus). The remaining 28 rows are decorative — they exist in the table but nothing references them.
|
||||
|
||||
This makes reparenting **trivially safe**: no FK invariant breaks, no SQL update touches existing data, no migration risk.
|
||||
|
||||
### 0.2 The 18 primaries with corpus (rules + concepts)
|
||||
|
||||
Ordered by `paliad.sequencing_rules` count (descending), with `event_category_concepts` count alongside:
|
||||
|
||||
| id | code | jurisdiction | rules | concepts | projects |
|
||||
|---:|---|---|---:|---:|---:|
|
||||
| 8 | `upc.inf.cfi` | UPC | 25 | 14 | 1 |
|
||||
| 9 | `upc.rev.cfi` | UPC | 17 | 10 | 0 |
|
||||
| 160 | `upc.apl.unified` | UPC | 16 | 0 *(see drift note)* | 0 |
|
||||
| 12 | `de.inf.lg` | DE | 11 | 4 | 1 |
|
||||
| 13 | `de.null.bpatg` | DE | 10 | 4 | 1 |
|
||||
| 14 | `epa.opp.opd` | EPA | 8 | 7 | 1 |
|
||||
| 15 | `epa.opp.boa` | EPA | 8 | 12 | 0 |
|
||||
| 16 | `epa.grant.exa` | EPA | 8 | 0 | 0 |
|
||||
| 17 | `upc.dmgs.cfi` | UPC | 8 | 1 | 0 |
|
||||
| 26 | `de.inf.bgh` | DE | 8 | 17 | 0 |
|
||||
| 25 | `de.inf.olg` | DE | 7 | 8 | 0 |
|
||||
| 10 | `upc.pi.cfi` | UPC | 7 | 3 | 0 |
|
||||
| 27 | `de.null.bgh` | DE | 6 | 10 | 0 |
|
||||
| 29 | `dpma.appeal.bpatg` | DPMA | 5 | 6 | 0 |
|
||||
| 30 | `dpma.appeal.bgh` | DPMA | 4 | 8 | 0 |
|
||||
| 28 | `dpma.opp.dpma` | DPMA | 4 | 3 | 1 |
|
||||
| 18 | `upc.disc.cfi` | UPC | 4 | 1 | 0 |
|
||||
| 35 | `upc.ccr.cfi` | UPC | 1 | 0 | 1 |
|
||||
|
||||
These 18 are unambiguously **primary proceedings** in the m/paliad#147 sense — self-contained matters, own filing, own deadline cascade, own ablauf. They survive every model.
|
||||
|
||||
### 0.3 The 4 unloaded primaries (Group A continued)
|
||||
|
||||
Four more active rows are conceptually primaries but carry **zero rules and zero concepts today** — seeded for catalog completeness, waiting for corpus:
|
||||
|
||||
| id | code | jurisdiction | what it is |
|
||||
|---:|---|---|---|
|
||||
| 171 | `upc.dni.cfi` | UPC | Negative Feststellungsklage — standalone declaratory action |
|
||||
| 172 | `upc.epo.review` | UPC | Überprüfung von EPA-Entscheidungen — standalone review action |
|
||||
| 179 | `upc.bsv.cfi` | UPC | Beweissicherung / saisie — standalone evidence-preservation order |
|
||||
| 188 | `upc.pl.cfi` | UPC | Schutzschrift — pre-litigation defensive filing |
|
||||
|
||||
These are **primary** by character (each has its own RoP-defined filing pathway and its own deadline tree once rules get seeded) but **unloaded** today. Decision: keep them as `kind='proceeding'` so Mode B R3 surfaces them for future rule attachment and `pkg/litigationplanner` accepts them as valid catalog codes.
|
||||
|
||||
§9 Q3.b discusses `upc.pl.cfi` (it's the only borderline — Schutzschrift is technically a pre-action filing, not a proceeding at the time of filing). m's call.
|
||||
|
||||
### 0.4 The 28 non-primary rows
|
||||
|
||||
The 28 active rows that have **zero rules + zero concepts + zero projects pointing at them** group cleanly into three categories:
|
||||
|
||||
#### Group B — Phases of a primary CFI proceeding (5 rows)
|
||||
|
||||
These describe stages *within* an existing CFI proceeding, not standalone matters. A `upc.inf.cfi` action passes through interim → oral → decision phases; the phase isn't a separately-elected proceeding type.
|
||||
|
||||
| id | code | name |
|
||||
|---:|---|---|
|
||||
| 173 | `upc.cfi.interim` | CFI - Zwischenverfahren |
|
||||
| 174 | `upc.cfi.oral` | CFI - Mündliche Verhandlung |
|
||||
| 175 | `upc.cfi.decision` | CFI - Endentscheidung |
|
||||
| 176 | `upc.costs.cfi` | Separate Kostenentscheidung *(post-decision sub-phase)* |
|
||||
| 185 | `upc.default.cfi` | Versäumnisentscheidung *(alt. decision outcome)* |
|
||||
|
||||
The "phase" concept already has a natural home in the data model: `paliad.procedural_events.event_kind` (filing/hearing/decision/order). What `upc.cfi.interim` actually represents is "all events with kind=filing under upc.inf.cfi/upc.rev.cfi/upc.pi.cfi/etc."; `upc.cfi.oral` is "all events with kind=hearing"; `upc.cfi.decision` is "all events with kind=decision". The proceeding-type row buys nothing the event_kind already carries.
|
||||
|
||||
#### Group C — Side-actions inside a proceeding (10 rows)
|
||||
|
||||
Applications and court orders that arise *inside* a primary proceeding. They could each become a `condition_expr`-gated rule on the parent proceeding when corpus arrives; they don't need their own proceeding row.
|
||||
|
||||
| id | code | name |
|
||||
|---:|---|---|
|
||||
| 178 | `upc.evidence.cfi` | Beweisanordnungen (allgemein) |
|
||||
| 182 | `upc.experiments.cfi` | Gerichtlich angeordnete Versuche |
|
||||
| 177 | `upc.security.cfi` | Sicherheitsleistung |
|
||||
| 184 | `upc.intervention.rop` | Streitbeitritt |
|
||||
| 165 | `upc.parties.change` | Parteiwechsel / Patentübergang |
|
||||
| 170 | `upc.optout.cfi` | Antrag auf Opt-out |
|
||||
| 180 | `upc.inspection.cfi` | Besichtigungsantrag |
|
||||
| 181 | `upc.freezing.cfi` | Anordnung zur Vermögenssperre |
|
||||
| 187 | `upc.withdrawal.rop` | Klagerücknahme |
|
||||
| 183 | `upc.rehearing.coa` | Wiederaufnahmeantrag |
|
||||
|
||||
A subtle distinction: `upc.bsv.cfi` (Beweissicherung) IS a standalone primary (its own RoP filing) whereas `upc.evidence.cfi` (Beweisanordnungen allgemein) is a side-action class (orders the court makes inside any proceeding). The two are not duplicates; the categorisation is structural, not nominal.
|
||||
|
||||
#### Group D — Cross-cutting administrative / meta (8 rows)
|
||||
|
||||
These describe rules-of-procedure mechanics, not matters a lawyer takes on. None of them is a "Verfahren" in any user-facing sense.
|
||||
|
||||
| id | code | name |
|
||||
|---:|---|---|
|
||||
| 162 | `upc.case.mgmt` | Verfahrensverwaltung |
|
||||
| 161 | `upc.general.rop` | Allgemeine Bestimmungen |
|
||||
| 163 | `upc.service.rop` | Zustellung von Schriftsätzen |
|
||||
| 168 | `upc.language.rop` | Verfahrenssprache |
|
||||
| 164 | `upc.representation.rop` | Vertretung / Anwaltsprivileg |
|
||||
| 166 | `upc.fees.court` | Gerichtsgebühren |
|
||||
| 167 | `upc.legalaid.cfi` | Prozesskostenhilfe |
|
||||
| 186 | `upc.special.cfi` | Besondere Verfahrenslagen |
|
||||
| 169 | `upc.reestablishment.rop` | Wiedereinsetzung in den vorigen Stand *(cross-cutting; applies to every proceeding)* |
|
||||
|
||||
`upc.reestablishment.rop` lands in Group D because **every** proceeding has a Wiedereinsetzung path — it isn't a kind-of-proceeding, it's a cross-cutting remedy. Today's rules already model it correctly (it's a `condition_expr`-gated rule on each primary, not a separately-elected proceeding type).
|
||||
|
||||
### 0.5 Counts reconciled
|
||||
|
||||
| Group | Count | Total of 46 |
|
||||
|---|---:|---:|
|
||||
| A.1 Primary with corpus (18 rows) | 18 | |
|
||||
| A.2 Primary, unloaded (4 rows) | 4 | |
|
||||
| B Phases (5 rows) | 5 | |
|
||||
| C Side-actions (10 rows) | 10 | |
|
||||
| D Meta / cross-cutting (9 rows) | 9 | |
|
||||
| **Total** | | **46 ✓** |
|
||||
|
||||
m/paliad#147's audit listed 8 Group-D rows; live data shows 9 once `upc.reestablishment.rop` is moved into the meta bucket (it appeared as ambiguous "cross-cutting admin / meta" — confirming this design's read).
|
||||
|
||||
---
|
||||
|
||||
## 1. Categorization — ratified
|
||||
|
||||
The taxonomy proposal: a row in `paliad.proceeding_types` has exactly one of four **structural kinds**.
|
||||
|
||||
| `kind` | What it is | Visible in Mode B R3 wizard? | In `pkg/litigationplanner` catalog? | Eligible for `projects.proceeding_type_id`? |
|
||||
|---|---|---|---|---|
|
||||
| `proceeding` | A self-contained matter with its own filing pathway and its own deadline tree | **Yes** | **Yes** (filtered by `kind='proceeding' AND is_active=true`) | **Yes** |
|
||||
| `phase` | A stage *within* a primary proceeding | No | No | No |
|
||||
| `side_action` | An application/order that arises inside a primary proceeding | No | No | No |
|
||||
| `meta` | RoP mechanics, cross-cutting rules, court administration | No | No | No |
|
||||
|
||||
This is **Model 1 from m/paliad#147** (kind discriminator on `proceeding_types`). §2 explains why it beats Models 2-4 for the actual data.
|
||||
|
||||
The 46 active rows map to the 4 kinds as follows:
|
||||
|
||||
- **`proceeding` (22 rows):** all 18 primaries-with-corpus + the 4 unloaded primaries from §0.3. Specifically the union of §0.2 + §0.3.
|
||||
- **`phase` (5 rows):** the §0.4 Group B list.
|
||||
- **`side_action` (10 rows):** the §0.4 Group C list.
|
||||
- **`meta` (9 rows):** the §0.4 Group D list (incl. `upc.reestablishment.rop`).
|
||||
|
||||
### 1.1 Edge calls
|
||||
|
||||
- **`upc.ccr.cfi` (id 35)** — stays `kind='proceeding'` with the existing routing-to-`upc.inf.cfi` from t-paliad-204 §0.3 S1 (the determinator surfaces it, the mapping returns inf.cfi's id with `with_ccr=true`). Rationale: the routing layer is already built and m ratified it 2026-05-18. This design does not re-open that decision. §9 Q7 lets m revisit.
|
||||
- **`upc.pl.cfi` (Schutzschrift, id 188)** — borderline. Schutzschrift is filed *before* a proceeding exists; it's a defensive pre-litigation filing. Recommendation: keep as `kind='proceeding'` (it has its own RoP path + its own deadlines once seeded). The alternative — calling it `side_action` of a not-yet-existing inf.cfi — is semantically backwards. §9 Q3.b lets m revisit.
|
||||
- **`upc.bsv.cfi` (saisie, id 179)** vs **`upc.evidence.cfi` (id 178)** — bsv stays `kind='proceeding'` (own RoP filing under R.192-198), evidence stays `kind='side_action'` (the orders a court makes inside any proceeding under R.190). The codes are not duplicates.
|
||||
|
||||
### 1.2 What the categorisation buys
|
||||
|
||||
- **Mode B R3 (Fristenrechner overhaul, t-paliad-322)** queries `proceeding_types WHERE is_active AND kind='proceeding'` and gets a clean 22-row pick list — no phase/side-action/meta noise.
|
||||
- **`projects.proceeding_type_id` integrity** is enforceable: an FK + CHECK (or a triggered constraint, see §3.3) blocks setting a project's type to anything except `kind='proceeding'`.
|
||||
- **`pkg/litigationplanner` snapshot generator** filters identically; youpc.org's catalog stays UPC-primary-only with no leakage of phase/admin rows.
|
||||
- **Determinator + dropdowns** get a forward-compatible filter; future feature work (e.g. "show me all side-actions available in this proceeding") becomes a different query against the same table.
|
||||
- **Forward-compatibility for new rows** — when corpus for a side-action arrives (e.g. `upc.evidence.cfi` gains 4 sequencing_rules with `condition_expr='evidence_order_issued'`), the rules anchor on the *parent* primary, not on the side-action row. The kind classification stays correct; the side-action row remains a taxonomic label.
|
||||
|
||||
---
|
||||
|
||||
## 2. Model choice — Model 1 (kind discriminator)
|
||||
|
||||
### 2.1 The four candidate models, scored
|
||||
|
||||
| Model | Schema churn | Models phase parentage? | Mode B R3 filter | Migration risk | Verdict |
|
||||
|---|---|---|---|---|---|
|
||||
| **1. `kind` discriminator on `proceeding_types`** | One column + CHECK constraint | No, but doesn't need to | `WHERE kind='proceeding'` | Trivial — UPDATE only | **Recommended** |
|
||||
| 2. Self-referencing `parent_id` | One column + FK + CHECK | Yes, but parentage is wrong shape (phases are phase-of-EVERY-CFI, not of one) | `WHERE parent_id IS NULL` | Trivial | Over-modelled |
|
||||
| 3. Separate tables | Three new tables + view/JOINs | Yes, fully | Just query `proceeding_types` | Migration churn + every consumer query learns a new shape | Overkill for 28 unused rows |
|
||||
| 4. Move phases into `procedural_events` | One mass row-move + DELETE | n/a (phases vanish from `proceeding_types`) | Trivial | Highest — would touch event_kind taxonomy and Fristenrechner result-view structure | Wrong shape (phases ≠ events) |
|
||||
|
||||
### 2.2 Why Model 1 wins
|
||||
|
||||
The fundamental observation: **the 28 non-primary rows have zero downstream pressure**. No rule, no project, no concept, no spawn FK references them. They exist in the table as taxonomic placeholders — names someone wrote down so future corpus could attach. We don't need to physically restructure the table; we just need to label what's what so consumers can filter correctly.
|
||||
|
||||
Model 1 gives us exactly that with one column. The other models pay schema/migration cost to model a parent-child relationship that **no consumer queries**. Mode B R3 doesn't ask "what are the phases of upc.inf.cfi?" — it asks "what are the proceedings I can pick?". The Fristenrechner result view doesn't ask the proceeding-types table about phases — phases live inside `procedural_events.event_kind` and the priority-bucket sub-sections in the §4.2 of the Fristenrechner overhaul doc.
|
||||
|
||||
Model 2's `parent_id` is wrong in shape: `upc.cfi.interim` doesn't have ONE parent (`upc.inf.cfi`), it has SEVEN parents (every CFI proceeding). Modelling that as a self-reference would force either (a) duplicating the phase rows per primary, or (b) using NULL parent_id for "applies to all". Both options are uglier than just dropping parent_id and trusting `kind='phase'`.
|
||||
|
||||
Model 3's separate tables would create rich relations that no consumer reads. Premature relational normalisation.
|
||||
|
||||
Model 4 would force phases into `procedural_events`, but phases aren't events. A phase is a *bucket of events*. The bucket is already implicit in the `event_kind` column (filing → interim, hearing → oral, decision → decision). If anything, Model 4 is *backwards* — phases should disappear into `event_kind`, not become event rows. The way to "delete" the phase rows from proceeding_types is just to deactivate them (or mark them `kind='phase'`); we don't need to re-locate them into another table to claim that conceptual move.
|
||||
|
||||
### 2.3 What we don't do — physical deletion
|
||||
|
||||
The 28 non-primary rows are NOT dropped from the table. They:
|
||||
|
||||
- Get tagged with the right `kind` value.
|
||||
- Optionally get `is_active=false` flipped (m's call, §9 Q9).
|
||||
- Stay in the table so consumers that historically referenced them by id (admin tools, audit logs, future schema-rescue scripts) keep working.
|
||||
|
||||
`DROP` is a one-way door we don't need to walk through. The CHECK constraint + kind tagging gives us the same logical cleanliness with none of the irreversibility risk.
|
||||
|
||||
---
|
||||
|
||||
## 3. Schema sketch + migration plan
|
||||
|
||||
### 3.1 DDL — the new column
|
||||
|
||||
```sql
|
||||
-- Migration NNN_proceeding_types_kind.up.sql
|
||||
-- (NNN = whatever MAX(version) + 1 is at write time; see project-status.md
|
||||
-- for the live numbering. As of 2026-05-26 the head is mig 152 per the
|
||||
-- recent dedupe of identical sequencing_rule clones.)
|
||||
|
||||
ALTER TABLE paliad.proceeding_types
|
||||
ADD COLUMN kind text NOT NULL DEFAULT 'proceeding'
|
||||
CHECK (kind IN ('proceeding', 'phase', 'side_action', 'meta'));
|
||||
|
||||
COMMENT ON COLUMN paliad.proceeding_types.kind IS
|
||||
'Structural classification — see docs/design-proceeding-types-taxonomy-2026-05-26.md §1. '
|
||||
'proceeding = self-contained matter (own filing + deadline tree); '
|
||||
'phase = stage inside a primary CFI proceeding; '
|
||||
'side_action = application/order inside a proceeding; '
|
||||
'meta = RoP mechanics, court admin, cross-cutting remedies.';
|
||||
|
||||
CREATE INDEX proceeding_types_kind_active_idx
|
||||
ON paliad.proceeding_types(kind, is_active)
|
||||
WHERE is_active = true;
|
||||
```
|
||||
|
||||
The DEFAULT keeps existing inserts (admin tooling, snapshot tests) safe: any new row defaults to `proceeding`. The CHECK enforces the vocabulary at write time.
|
||||
|
||||
### 3.2 Data move — UPDATE statements, no INSERT/DELETE
|
||||
|
||||
```sql
|
||||
-- Phases (per m's Q2 carve-out: upc.costs.cfi (176) is NOT a phase, it stays primary)
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'phase'
|
||||
WHERE id IN (173, 174, 175, 185); -- §0.4 Group B minus 176
|
||||
|
||||
-- Side-actions
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'side_action'
|
||||
WHERE id IN (178, 182, 177, 184, 165, 170, 180, 181, 187, 183); -- §0.4 Group C
|
||||
|
||||
-- Meta / cross-cutting
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'meta'
|
||||
WHERE id IN (162, 161, 163, 168, 164, 166, 167, 186, 169); -- §0.4 Group D
|
||||
|
||||
-- Primaries (incl. m's Q2 carve-out for upc.costs.cfi) stay on the DEFAULT
|
||||
-- 'proceeding' value — no UPDATE needed.
|
||||
|
||||
-- Per m's Q9: deactivate the non-primary rows so the admin list surfaces only
|
||||
-- primaries. The kind column carries the semantic info; is_active controls UI
|
||||
-- visibility. Reversible — flip is_active back on if a row gains corpus.
|
||||
UPDATE paliad.proceeding_types
|
||||
SET is_active = false
|
||||
WHERE kind IN ('phase', 'side_action', 'meta');
|
||||
```
|
||||
|
||||
Per m's Q9, the `is_active=false` flip is mandatory in this mig. After it: 23 active rows (all `kind='proceeding'`), 23 inactive rows (the phase/side_action/meta set), in addition to the pre-existing inactive appeal-triplet + archived bucket. The `kind` column tells consumers what each row IS; `is_active` tells consumers whether to show it.
|
||||
|
||||
### 3.3 Optional integrity constraints
|
||||
|
||||
If m wants stronger guarantees that `projects.proceeding_type_id` can only point at primaries, add a deferrable FK validator. Cleanest pattern in Postgres:
|
||||
|
||||
```sql
|
||||
-- Option A: trigger-based check (works for any kind set, deferred-friendly).
|
||||
CREATE OR REPLACE FUNCTION paliad.assert_project_type_is_proceeding()
|
||||
RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
IF NEW.proceeding_type_id IS NOT NULL THEN
|
||||
PERFORM 1 FROM paliad.proceeding_types
|
||||
WHERE id = NEW.proceeding_type_id AND kind = 'proceeding';
|
||||
IF NOT FOUND THEN
|
||||
RAISE EXCEPTION 'projects.proceeding_type_id must reference a kind=proceeding row, got id=%', NEW.proceeding_type_id
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
END IF;
|
||||
RETURN NEW;
|
||||
END $$;
|
||||
|
||||
CREATE TRIGGER projects_proceeding_type_kind_check
|
||||
BEFORE INSERT OR UPDATE OF proceeding_type_id ON paliad.projects
|
||||
FOR EACH ROW EXECUTE FUNCTION paliad.assert_project_type_is_proceeding();
|
||||
```
|
||||
|
||||
Per m's Q8: **trigger on `projects` only**, no symmetric enforcement on `sequencing_rules`. Projects are written via the public app (the surface most exposed to operator error); rules are edited via the admin `/admin/procedural-events` surface which already validates against active+published lifecycle. The single trigger is enough.
|
||||
|
||||
### 3.4 Migration sequencing — single self-contained mig
|
||||
|
||||
One migration file:
|
||||
|
||||
```
|
||||
internal/db/migrations/153_proceeding_types_kind.up.sql
|
||||
internal/db/migrations/153_proceeding_types_kind.down.sql
|
||||
```
|
||||
|
||||
Up does ALTER + UPDATE + (optional) trigger creation. Down does DROP COLUMN (cascading the trigger if present). No data loss on either direction — the kind column is purely additive.
|
||||
|
||||
Mig number depends on what knuth lands first; the coder reads `MAX(version)` at write time per the project's mig conventions.
|
||||
|
||||
---
|
||||
|
||||
## 4. FK reparenting tables
|
||||
|
||||
There is no reparenting to do. Below for completeness:
|
||||
|
||||
| Source table.column | Pointing at non-primary rows? | Action |
|
||||
|---|---|---|
|
||||
| `sequencing_rules.proceeding_type_id` | **0 active rules** (verified §0.1) | None |
|
||||
| `sequencing_rules.spawn_proceeding_type_id` | **0 active rules** point at non-primaries; 4 active rules point at id=11 (inactive `upc.apl.merits`) | Pre-existing drift, out of scope (§8) |
|
||||
| `projects.proceeding_type_id` | **0 projects** (all 6 distinct values are primaries) | None |
|
||||
| `event_category_concepts.proceeding_type_code` | **0 concepts** point at non-primary codes; 30 concepts point at `upc.apl.merits/order/cost` codes (which are inactive but conceptually primaries) | Pre-existing drift, out of scope (§8) |
|
||||
|
||||
The "FK reparent" section of the acceptance criteria in m/paliad#147 is a no-op for this design: the 28 rows being re-classified have **no incoming references** to reparent. The migration is pure relabelling.
|
||||
|
||||
---
|
||||
|
||||
## 5. Worked example — `upc.cfi.interim` after the mig
|
||||
|
||||
### 5.1 Today (broken)
|
||||
|
||||
Someone created the row `upc.cfi.interim` (id 173, name "CFI - Zwischenverfahren") in `paliad.proceeding_types` with `category='fristenrechner'`. The intent was probably "we'll attach interim-phase rules here later". Result:
|
||||
|
||||
- The row appears in the Mode B R3 wizard chip strip (if R3 queries `WHERE is_active=true AND jurisdiction='UPC'`) — confusing to the user, because "Zwischenverfahren" is not a proceeding they pick; it's a stage their proceeding passes through.
|
||||
- The row could be set as `projects.proceeding_type_id` (no FK constraint forbids it today) — corrupting the SmartTimeline's lane logic, which assumes the project's type is a primary.
|
||||
- The row appears in admin /admin/proceeding-types lists, polluting the primary-proceedings overview.
|
||||
|
||||
### 5.2 After mig 153
|
||||
|
||||
The migration runs:
|
||||
|
||||
```sql
|
||||
UPDATE paliad.proceeding_types SET kind = 'phase' WHERE id = 173;
|
||||
-- Optionally: UPDATE paliad.proceeding_types SET is_active = false WHERE id = 173;
|
||||
```
|
||||
|
||||
Now:
|
||||
|
||||
- Mode B R3 query becomes `WHERE is_active=true AND jurisdiction = $1 AND kind='proceeding'`. `upc.cfi.interim` is filtered out — it is not a "Verfahren" the user can pick.
|
||||
- A future admin who tries to set a project's `proceeding_type_id = 173` either fails the optional trigger from §3.3 (with a clear error) or gets a code-level rejection from `ProjectService.SetProceedingType` (which the coder will harden to filter by `kind='proceeding'`).
|
||||
- The `pkg/litigationplanner` snapshot generator filter becomes `WHERE is_active=true AND category='fristenrechner' AND kind='proceeding' AND jurisdiction IN ('UPC')`. The row never makes it into the youpc.org catalog.
|
||||
|
||||
The row itself stays in the database. Its id is stable. Future work that wants to *use* the phase row as a taxonomic label (e.g. "show me which event_kinds map to which UPC phases") gets a clean shape: query `WHERE kind='phase' AND code LIKE 'upc.cfi.%'`.
|
||||
|
||||
### 5.3 Where interim-phase deadlines actually live
|
||||
|
||||
The user-facing concept "interim phase" is already modelled correctly, just elsewhere:
|
||||
|
||||
- A `procedural_events` row like `upc.inf.cfi.soc` (Statement of Claim) has `event_kind='filing'`. The Fristenrechner overhaul (t-paliad-322 §4.2) groups follow-ups by priority + presents them under the trigger card. There is no UI element that needs a "Zwischenverfahren" proceeding-type label to operate.
|
||||
- A future "show me the full ablauf of UPC inf, broken down by phase" feature can derive phases from `procedural_events.event_kind` ordering + the rule sequence_order. The `proceeding_types` table doesn't need to carry the phase labels.
|
||||
|
||||
---
|
||||
|
||||
## 6. Consumer impact
|
||||
|
||||
### 6.1 `projects.proceeding_type_id`
|
||||
|
||||
| Concern | Before | After mig 153 |
|
||||
|---|---|---|
|
||||
| Valid values | Any active proceeding_types row | Any `kind='proceeding'` active row (22 rows) |
|
||||
| Enforcement | None at DB level | Optional trigger (§3.3 / §9 Q8) |
|
||||
| Code-level filter in ProjectService | No filter on kind | Filter to `kind='proceeding'` when listing pickable types |
|
||||
| Existing data | 6 distinct values (all in 22) | No change — all 6 are kind='proceeding' |
|
||||
| SmartTimeline lane logic | Assumes primary-proceeding shape | Assumption now FK-enforceable |
|
||||
|
||||
**No data migration on existing projects.** The 6 currently-used proceeding types are all in the primary set.
|
||||
|
||||
### 6.2 `sequencing_rules.proceeding_type_id` + `spawn_proceeding_type_id`
|
||||
|
||||
| Concern | Before | After mig 153 |
|
||||
|---|---|---|
|
||||
| `proceeding_type_id` valid values | Any active row | Any active row (no enforcement change; admin curation suffices) |
|
||||
| `spawn_proceeding_type_id` valid values | Any active row | Same — spawns conceptually must point at a primary, but enforcement stays in admin tooling |
|
||||
| Existing data | 157 rules anchored on 18 primaries | No change — all 157 already on `kind='proceeding'` rows |
|
||||
| `id=11 spawn pressure` (`upc.apl.merits`, inactive) | 4 active spawn rules point here | Pre-existing drift, out of scope (§8) |
|
||||
|
||||
No `sequencing_rules` table changes accompany this mig. The post-mig invariant **"every active rule's `proceeding_type_id` is a `kind='proceeding'` row"** holds without any UPDATE.
|
||||
|
||||
### 6.3 Fristenrechner Mode B R3 (t-paliad-322, knuth's S3+)
|
||||
|
||||
§3.2 R3 of the Fristenrechner overhaul says:
|
||||
|
||||
> Chips: every active `proceeding_type` whose jurisdiction matches R2 AND whose event roster contains at least one event with R1's kind.
|
||||
|
||||
After mig 153, the R3 query gains one more AND-clause:
|
||||
|
||||
```sql
|
||||
SELECT pt.id, pt.code, pt.name, pt.name_en, pt.sort_order
|
||||
FROM paliad.proceeding_types pt
|
||||
WHERE pt.is_active = true
|
||||
AND pt.kind = 'proceeding' -- NEW
|
||||
AND pt.jurisdiction = $1 -- from R2
|
||||
AND EXISTS (
|
||||
SELECT 1 FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
WHERE sr.proceeding_type_id = pt.id
|
||||
AND pe.event_kind = $2 -- from R1
|
||||
AND sr.is_active = true
|
||||
)
|
||||
ORDER BY pt.sort_order, pt.code;
|
||||
```
|
||||
|
||||
The `kind='proceeding'` filter is the only line that changes. Knuth's S3 implementation reads from this query; the chip pool shrinks from "all 35 active UPC types" to "the 14 primary UPC types that have rules" (still narrowed further by R1's event_kind via the EXISTS subquery).
|
||||
|
||||
No coder churn beyond adding the AND-clause. The mig 153 lands either alongside knuth's S3 work or independently (§7 sequencing decision).
|
||||
|
||||
### 6.4 Litigation Planner suite (t-paliad-292)
|
||||
|
||||
The package's catalog snapshot generator (`pkg/litigationplanner/scripts/snapshot/main.go`) currently filters:
|
||||
|
||||
```go
|
||||
// scripts/snapshot/main.go
|
||||
const proceedingTypesQuery = `
|
||||
SELECT id, code, name, name_en, jurisdiction, default_color, sort_order, display_order,
|
||||
trigger_event_label_de, trigger_event_label_en
|
||||
FROM paliad.proceeding_types
|
||||
WHERE is_active = true
|
||||
AND category = 'fristenrechner'
|
||||
AND jurisdiction = $1
|
||||
`
|
||||
```
|
||||
|
||||
After mig 153, this query gains the same `AND kind = 'proceeding'` line. The UPC snapshot shrinks from "potentially 35 rows" to a clean primary-only set. Today's snapshot probably already includes the phase/side-action/meta rows (since `is_active=true` is true for all of them) — depending on whether a snapshot has been regenerated since the 161-188 rows landed, the embedded JSON may be carrying decorative rows that the youpc.org catalog never resolves to rules. Mig 153 + a snapshot regen cleans this up.
|
||||
|
||||
The package's `Catalog.Proceeding(ctx, code, hint)` interface stays unchanged. A youpc-side call asking for `code='upc.cfi.interim'` previously returned the row + zero rules (technically valid but useless); after mig 153 the snapshot doesn't include it and the call returns `ErrUnknownProceedingType`. That's the correct shape — youpc users never had a reason to ask for a phase row.
|
||||
|
||||
The scenarios design (`paliad.scenarios.spec.proceedings[].code`) gains an integrity check at write time: the validator already asserts every code resolves to an active proceeding; now it additionally asserts `kind='proceeding'`. A user trying to compose a scenario with `code='upc.cfi.interim'` gets a clear error. (The validator is paliad-side, not library-side — see Litigation Planner doc §5 "Validatable at write time".)
|
||||
|
||||
### 6.5 Admin /admin/procedural-events list (recently shipped, t-paliad-321)
|
||||
|
||||
The proceeding-type column in the admin list (m/paliad#144 follow-up, just landed) renders one of the 46 active codes per row. Post-mig 153, the admin filter dropdown can:
|
||||
|
||||
- Default to showing only `kind='proceeding'` rows (clean primary view).
|
||||
- Offer a "show all kinds" toggle for admins triaging the non-primary rows.
|
||||
|
||||
This is presentation-only — the underlying admin queries don't need to change immediately. The kind column is a forward-compat hook.
|
||||
|
||||
### 6.6 Knowledge-platform pages (Gerichtsverzeichnis, Patentglossar)
|
||||
|
||||
Untouched. None of those pages query `proceeding_types` directly.
|
||||
|
||||
### 6.7 Fristen export / paliad data export (t-paliad-279)
|
||||
|
||||
Untouched. The exporter dumps `proceeding_types` as a whole (no kind-filter); after mig 153 it dumps the same rows with the new kind column. Forward-compat by default.
|
||||
|
||||
---
|
||||
|
||||
## 7. Migration sequencing decision vs m/paliad#146
|
||||
|
||||
m/paliad#146 (Fristenrechner overhaul, t-paliad-322 / 323) is on the S1-S6 train under knuth. m's directive at task brief time: **knuth pauses at the S1+S2 seam waiting for this taxonomy decision**.
|
||||
|
||||
Three options were on the table:
|
||||
|
||||
(a) **Pause #146 until taxonomy clean** — knuth blocked, this design lands first, then knuth resumes S3+.
|
||||
(b) **Land #146 against current shape, migrate later** — knuth ships S3-S6 against the current 46-row table, taxonomy mig follows.
|
||||
(c) **Land taxonomy in parallel, knuth re-targets if needed** — both run, knuth's S3 picks up the new filter when mig 153 is ready.
|
||||
|
||||
**Recommendation: (c) parallel-land** with the following caveats:
|
||||
|
||||
- The taxonomy mig is **additive** (ADD COLUMN with safe DEFAULT, no DROP, no data move beyond UPDATEs that touch unreferenced rows). Knuth's S3 implementation can be written with or without the `kind='proceeding'` filter — adding the filter is a one-line patch the moment mig 153 lands.
|
||||
- The R3 chip-pool query in knuth's S3 PR should be **future-proofed by also adding the `kind='proceeding'` filter behind a feature flag or an env-time SQL constant**, defaulting to "no filter" pre-mig and "filter" post-mig. (Or simpler: knuth writes the filter unconditionally; the migration lands first; ordering is mechanical.)
|
||||
- The mig 153 PR should land **before** knuth's S3 PR ships to main, so the filter is never false-positive (chipping phase rows users can't actually pick). Both PRs can be drafted in parallel; the squeeze happens at merge time.
|
||||
- Sequence on main: mig 153 → knuth S3 (with filter) → knuth S4-S6.
|
||||
|
||||
Option (c) keeps knuth productive (S3 work can start immediately after this design ratifies; doesn't have to wait for the mig to merge) and avoids the option (a) idle cost.
|
||||
|
||||
Option (b) was rejected because it leaves the Mode B R3 wizard chipping 35 UPC rows on initial release — exactly the bug m flagged in m/paliad#147 ("half of the 46 active proceeding_types are not primary proceedings"). The user would see phase rows in R3 day one of the Fristenrechner overhaul shipping; we'd be shipping the bug.
|
||||
|
||||
Option (a) was rejected as the safest but slowest path. The taxonomy mig is trivial enough (one ALTER + four UPDATE statements + optional trigger) that parallel-running has no real risk.
|
||||
|
||||
§9 Q10 gives m the chance to pick differently.
|
||||
|
||||
---
|
||||
|
||||
## 8. Out of scope (flagged for separate work)
|
||||
|
||||
- **`upc.apl.*` data drift.** 30 rows in `paliad.event_category_concepts` reference the inactive `upc.apl.merits` / `upc.apl.order` / `upc.apl.cost` codes (the pre-`upc.apl.unified` triplet). 4 active sequencing_rules reference `spawn_proceeding_type_id=11` (the inactive `upc.apl.merits` row). This is a pre-existing inconsistency from the appeal unification mig — needs its own follow-up ticket. Not blocking this design; can be cleaned up in a separate migration that retargets concepts + spawn FKs to `upc.apl.unified` (id=160).
|
||||
- **Renaming or relabelling primary proceedings.** Out per m/paliad#147 acceptance — editorial work, not structural.
|
||||
- **Adding new proceeding types beyond the existing corpus.** Out per m/paliad#147 acceptance.
|
||||
- **The Fristenrechner UI overhaul itself (m/paliad#146).** Separate track; this design only tells knuth's S3 what set to chip.
|
||||
- **The scenarios design (m/paliad#124).** Already ratified in `docs/design-litigation-planner-2026-05-26.md` §5; this design only refines the spec validator's "every code resolves to a primary" check.
|
||||
- **DROPing the non-primary rows physically.** Reversible deactivation via `kind=...` + optional `is_active=false` is enough; physical deletion adds irreversibility risk for no functional gain.
|
||||
- **Migration of `event_category_concepts.proceeding_type_code` to a real FK.** It's text today, joined softly; converting to FK is a separate hardening task.
|
||||
|
||||
---
|
||||
|
||||
## 9. Open questions for m (10 decision questions)
|
||||
|
||||
Sent via `AskUserQuestion` in 3 batches per inventor SKILL contract (4+3+3). m's picks land in §10 below after the round-trip.
|
||||
|
||||
| # | Topic | Recommended pick |
|
||||
|---|---|---|
|
||||
| Q1 | Model choice | Model 1 (kind discriminator) |
|
||||
| Q2 | Phases — linear sub-phases of every CFI, or separately-elected? | Implicit: phases live in `procedural_events.event_kind`, not as proceeding_types |
|
||||
| Q3.a | Side-actions — triggered by parent event, or initiated out-of-band? | Mixed; today's data has no rules, future rules anchor on the parent primary with `condition_expr` |
|
||||
| Q3.b | `upc.pl.cfi` (Schutzschrift) — primary or side-action? | Primary (own RoP filing pathway) |
|
||||
| Q4 | Collapse `de.inf.lg`/`olg`/`bgh` into one `de.inf` with instance_level qualifier? | No — keep discrete |
|
||||
| Q5 | Collapse `de.null.bpatg`/`bgh` into one `de.null` with instance_level qualifier? | No — keep discrete |
|
||||
| Q6 | Should DE follow the `upc.apl.unified` pattern? | No (= keep discrete, locks Q4+Q5) |
|
||||
| Q7 | `upc.ccr.cfi` — proceeding row with routing (status quo), or `with_ccr` flag on `upc.inf.cfi`? | Keep as proceeding (status quo per t-paliad-204 S1) |
|
||||
| Q8 | Enforce `projects.proceeding_type_id` → `kind='proceeding'` at the DB level? | Yes, via trigger (§3.3) |
|
||||
| Q9 | Set `is_active=false` on the 28 non-primary rows after mig 153? | Yes (cleanest admin UX) |
|
||||
| Q10 | Sequencing vs m/paliad#146 — pause / parallel / re-target? | (c) parallel-land — mig first, then knuth S3 with filter |
|
||||
|
||||
Q11 in the issue body ("how many rules need new condition_expr disambiguation?") is **empirically answered, no decision needed**: 0 rules need new condition_expr — every active rule is already correctly anchored to a primary. Surfaced in §4 + §6.2.
|
||||
|
||||
---
|
||||
|
||||
## 10. m's decisions (2026-05-27)
|
||||
|
||||
All 11 questions answered via `AskUserQuestion` on 2026-05-27 09:52 (3 batches of 4+4+3). 10 of 11 picks = recommendation; Q9 diverged at the chip-picker but m's follow-up instruction ("I follow your recommendation") flips Q9 to the recommendation as well. Q2 carries a precise carve-out captured verbatim below.
|
||||
|
||||
- **Q1 (Model): Model 1 — kind discriminator.** [= recommendation] One column + CHECK constraint + UPDATE statements. **Locks §1, §2, §3.1, §3.2.**
|
||||
- **Q2 (Phases): Generally option 1 (implicit via `procedural_events.event_kind`), with carve-outs.** [≈ option 1 with carve-out] m's verbatim call:
|
||||
> Generally 1, but I agree with costs which are not only a phase but also "standalone" side proceedings. But default decision application is not.
|
||||
Concretely:
|
||||
- `upc.cfi.interim` (173) → `kind='phase'`
|
||||
- `upc.cfi.oral` (174) → `kind='phase'`
|
||||
- `upc.cfi.decision` (175) → `kind='phase'`
|
||||
- `upc.default.cfi` (185) → `kind='phase'` (m: "default decision application is not [a standalone side proceeding]")
|
||||
- **`upc.costs.cfi` (176) → `kind='proceeding'`** (m: "costs are not only a phase but also standalone side proceedings"). The Separate Kostenentscheidung can be filed as its own application under R.151 RoP independently of the parent decision; m's read is that the standalone-application character outweighs the phase-of-CFI character.
|
||||
Net: 4 phase rows (not 5 as in the strawman), 23 primary-proceeding rows (not 22). **Updates §0.4 Group B count, §0.5 totals row, §1 categorisation, §3.2 UPDATE statement IDs (drop 176 from the phase UPDATE).**
|
||||
- **Q3.a (Side-actions): kind='side_action', rules anchor on parent primary.** [= recommendation] All 10 §0.4 Group C rows get `kind='side_action'`. When corpus arrives, rules attach to the parent primary with a `condition_expr` flag. **Locks §1.1, §3.2 side-action UPDATE.**
|
||||
- **Q3.b (Schutzschrift): kind='proceeding'.** [= recommendation] `upc.pl.cfi` (188) stays in the primary set on the strength of its own RoP filing pathway. **Locks §0.3 unloaded-primary list.**
|
||||
- **Q4 (DE inf collapse): Keep discrete.** [= recommendation] `de.inf.lg/olg/bgh` stay as 3 separate primaries. No collapse, no instance_level qualifier introduction. **Locks §0.2 + §1 DE-side categorisation.**
|
||||
- **Q5 (DE null collapse): Keep discrete.** [= recommendation] `de.null.bpatg/bgh` stay separate. Symmetric with Q4. **Locks §0.2 + §1 DE-side categorisation.**
|
||||
- **Q6 (DE follow upc.apl pattern): No — keep DE discrete.** [= recommendation] Locks Q4+Q5. The `upc.apl.unified` consolidation was about same-court appeal variants; DE appeals are different-court-instance appeals — different problem. **No code-rename work falls out of this design.**
|
||||
- **Q7 (CCR shape): Keep status quo.** [= recommendation] `upc.ccr.cfi` stays as `kind='proceeding'` with the existing routing-to-`upc.inf.cfi` from t-paliad-204 §0.3 S1. **Locks §1.1.**
|
||||
- **Q8 (DB trigger): Trigger on `projects` only.** [= recommendation] BEFORE INSERT/UPDATE trigger on `paliad.projects` enforces `proceeding_type_id → kind='proceeding'`. No trigger on `sequencing_rules` (admin tooling already gates). **Locks §3.3 — keep the `projects` trigger DDL, drop the optional `sequencing_rules` variant.**
|
||||
- **Q9 (Deactivate non-primaries): Yes — deactivate.** [m's chip-pick was "keep active"; flipped to recommendation per m's "I follow your recommendation" instruction] All `kind IN ('phase', 'side_action', 'meta')` rows get `is_active=false` in mig 153. The admin `/admin/proceeding-types` list shows only the 23 active primaries. Rows stay in the table with their `kind` tag so future tooling that wants to surface them can flip `is_active` back on. **Updates §3.2 — uncomment the optional `UPDATE … SET is_active=false` block.**
|
||||
- **Q10 (Sequencing vs #146): Parallel-land.** [= recommendation] Mig 153 + knuth's S3 PR drafted in parallel; mig merges first; knuth's S3 includes the `kind='proceeding'` filter in R3's chip query from day one. No idle cost; no bug shipped. **Locks §7.**
|
||||
|
||||
### 10.1 What changed from the strawman as a result
|
||||
|
||||
Two material edits flow from m's picks:
|
||||
|
||||
1. **§0.4 Group B (Phases) drops `upc.costs.cfi` (id 176)** — moved into the primary set. Phase count: 5 → 4. Primary count: 22 → 23. §0.2 picks up id 176 as an unloaded primary (zero rules today; future corpus will attach).
|
||||
2. **§3.2 migration includes the `is_active=false` UPDATE** (was optional in the strawman, now mandatory):
|
||||
|
||||
```sql
|
||||
UPDATE paliad.proceeding_types
|
||||
SET is_active = false
|
||||
WHERE kind IN ('phase', 'side_action', 'meta');
|
||||
```
|
||||
|
||||
This is what the post-mig 153 cleanup looks like: 23 active rows (all `kind='proceeding'`), 23 inactive rows (4 phase + 10 side_action + 9 meta + the pre-existing 3 inactive appeal-triplet + 1 archived bucket = 27 inactive total, but 23 of those are the freshly-deactivated taxonomy rows).
|
||||
|
||||
These edits don't change the §7 sequencing decision or the §6 consumer-impact analysis. They tighten the mig file and shift one row's classification.
|
||||
|
||||
### 10.2 Final categorisation (post-decisions)
|
||||
|
||||
| `kind` | Count | Codes |
|
||||
|---|---:|---|
|
||||
| `proceeding` | **23** | upc.inf.cfi, upc.rev.cfi, upc.pi.cfi, upc.dmgs.cfi, upc.disc.cfi, upc.ccr.cfi, upc.apl.unified, upc.dni.cfi, upc.epo.review, upc.bsv.cfi, upc.pl.cfi, **upc.costs.cfi** (m's Q2 carve-out), de.inf.lg, de.inf.olg, de.inf.bgh, de.null.bpatg, de.null.bgh, epa.opp.opd, epa.opp.boa, epa.grant.exa, dpma.opp.dpma, dpma.appeal.bpatg, dpma.appeal.bgh |
|
||||
| `phase` | **4** | upc.cfi.interim, upc.cfi.oral, upc.cfi.decision, upc.default.cfi |
|
||||
| `side_action` | **10** | upc.evidence.cfi, upc.experiments.cfi, upc.security.cfi, upc.intervention.rop, upc.parties.change, upc.optout.cfi, upc.inspection.cfi, upc.freezing.cfi, upc.withdrawal.rop, upc.rehearing.coa |
|
||||
| `meta` | **9** | upc.case.mgmt, upc.general.rop, upc.service.rop, upc.language.rop, upc.representation.rop, upc.fees.court, upc.legalaid.cfi, upc.special.cfi, upc.reestablishment.rop |
|
||||
| **Total** | **46** | ✓ |
|
||||
|
||||
Post-mig 153: 23 active (all `kind='proceeding'`), 23 deactivated (the phase/side_action/meta set).
|
||||
|
||||
---
|
||||
|
||||
## 11. Synthesis links
|
||||
|
||||
- mBrian topic: `topic-fristenrechner` — file this design as a `[synthesis]` node, link `related_to` the proceeding-code-taxonomy doc (2026-05-18) and the Fristenrechner overhaul (2026-05-26), `triggered_by` t-paliad-324.
|
||||
- Related design docs: `docs/design-proceeding-code-taxonomy-2026-05-18.md` (the code-shape doc), `docs/design-fristenrechner-overhaul-2026-05-26.md` (knuth's parent design), `docs/design-litigation-planner-2026-05-26.md` §5 (scenarios spec validator).
|
||||
- Related migrations: 095 (fristen gap-fill, spawn FK invariant), 096 (proceeding code rename), 152 (sequencing_rule dedupe + admin column).
|
||||
@@ -102,9 +102,9 @@ export function renderAdminRulesList(): string {
|
||||
<thead>
|
||||
<tr>
|
||||
<th data-i18n="admin.procedural_events.col.code">Submission Code</th>
|
||||
<th data-i18n="admin.procedural_events.col.proceeding">Verfahren</th>
|
||||
<th data-i18n="admin.rules.col.legal_citation">Rechtsgrundlage</th>
|
||||
<th data-i18n="admin.rules.col.name">Name</th>
|
||||
<th data-i18n="admin.rules.col.proceeding">Verfahrenstyp</th>
|
||||
<th data-i18n="admin.rules.col.priority">Priorität</th>
|
||||
<th data-i18n="admin.rules.col.lifecycle">Lifecycle</th>
|
||||
<th data-i18n="admin.rules.col.modified">Zuletzt geändert</th>
|
||||
|
||||
@@ -11,6 +11,13 @@ import { initSidebar } from "./sidebar";
|
||||
interface Rule {
|
||||
id: string;
|
||||
proceeding_type_id?: number | null;
|
||||
// proceeding_type_code is the joined paliad.proceeding_types.code
|
||||
// for proceeding_type_id, populated server-side by the
|
||||
// /admin/api/procedural-events LIST handler (t-paliad-321). Lets the
|
||||
// table show the 3-segment proceeding code (e.g. "upc.inf.cfi") at
|
||||
// a glance without depending on the FILTER-dropdown's limited
|
||||
// proceeding list. NULL on event-rooted rules.
|
||||
proceeding_type_code?: string | null;
|
||||
// submission_code is the proceeding-prefixed identifier of this rule
|
||||
// within its proceeding (e.g. `upc.inf.cfi.soc`), distinct from
|
||||
// rule_code (the legal citation, e.g. `RoP.013.1`).
|
||||
@@ -138,6 +145,19 @@ function proceedingLabel(id: number | null | undefined): string {
|
||||
return `${pt.code} · ${name}`;
|
||||
}
|
||||
|
||||
// proceedingCodeCell renders the LIST table's Proceeding column. Uses
|
||||
// the server-side joined proceeding_type_code when available
|
||||
// (t-paliad-321), falling back to the dropdown-lookup proceedingLabel
|
||||
// for older API responses or for rules whose proceeding_type_id
|
||||
// resolves but proceeding_type_code didn't (defence-in-depth). NULL
|
||||
// proceeding_type_id renders as the em-dash placeholder used
|
||||
// elsewhere in the admin table.
|
||||
function proceedingCodeCell(r: Rule): string {
|
||||
if (r.proceeding_type_code) return r.proceeding_type_code;
|
||||
if (r.proceeding_type_id == null) return "—";
|
||||
return proceedingLabel(r.proceeding_type_id);
|
||||
}
|
||||
|
||||
function buildFilterURL(): string {
|
||||
const qs = new URLSearchParams();
|
||||
if (activeProceeding) qs.set("proceeding_type_id", activeProceeding);
|
||||
@@ -233,9 +253,9 @@ function renderRulesTable() {
|
||||
tbody.innerHTML = rules.map((r) => `
|
||||
<tr data-row-id="${esc(r.id)}" class="admin-rules-row">
|
||||
<td class="admin-rules-col-code"><code>${esc(r.submission_code || "")}</code></td>
|
||||
<td class="admin-rules-col-proceeding"><code>${esc(proceedingCodeCell(r))}</code></td>
|
||||
<td class="admin-rules-col-legal"><code>${esc(r.rule_code || "")}</code></td>
|
||||
<td>${esc(name(r))}</td>
|
||||
<td>${esc(proceedingLabel(r.proceeding_type_id ?? null))}</td>
|
||||
<td><span class="admin-rules-priority admin-rules-priority-${esc(r.priority)}">${esc(priorityLabel(r.priority))}</span></td>
|
||||
<td><span class="${lifecycleClass(r.lifecycle_state)}">${esc(lifecycleLabel(r.lifecycle_state))}</span></td>
|
||||
<td class="admin-rules-col-modified">${esc(fmtDateTime(r.updated_at))}</td>
|
||||
|
||||
507
frontend/src/client/fristenrechner-mode-a.ts
Normal file
507
frontend/src/client/fristenrechner-mode-a.ts
Normal file
@@ -0,0 +1,507 @@
|
||||
// Fristenrechner overhaul Mode A — "Direkt suchen" (design §3.1).
|
||||
//
|
||||
// Power-user surface: a filter strip (Forum / Verfahren / Was passierte /
|
||||
// Partei) over a free-text search box over a result list of
|
||||
// procedural_events. Clicking a row locks the event as the trigger and
|
||||
// transitions to the shared result view (S2). Inbox channel chip lives
|
||||
// as a secondary "Erweitert" toggle per design §3.3 — picking CMS / beA
|
||||
// / Postal auto-sets the Forum chip.
|
||||
//
|
||||
// Section-split visual hierarchy per m §11.Q3: filter strip on top
|
||||
// ("Filter (eingrenzen)") with the four chip groups, search box and
|
||||
// result list below — clicking a result row IS the qualifier action.
|
||||
|
||||
import { escAttr, escHtml } from "./views/verfahrensablauf-core";
|
||||
import { getLang, t, tDyn } from "./i18n";
|
||||
import { mountResultView } from "./fristenrechner-result";
|
||||
|
||||
// Wire shape from GET /api/tools/fristenrechner/search?kind=events.
|
||||
// Mirrors services.EventSearchResponse server-side.
|
||||
interface EventSearchHit {
|
||||
id: string;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
event_kind?: string;
|
||||
description?: string;
|
||||
primary_party?: string;
|
||||
proceeding_type: {
|
||||
id: number;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
jurisdiction?: string;
|
||||
};
|
||||
anchor_rule_id: string;
|
||||
follow_up_count: number;
|
||||
concept_id?: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
interface EventSearchResponse {
|
||||
query: string;
|
||||
events: EventSearchHit[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface ProceedingChip {
|
||||
code: string;
|
||||
name: string;
|
||||
nameEN: string;
|
||||
group: string;
|
||||
}
|
||||
|
||||
// Module-local state — single Mode A surface at a time.
|
||||
interface ModeAState {
|
||||
jurisdiction: string; // "" = Alle
|
||||
proc: string; // proceeding_types.code, "" = Alle
|
||||
eventKind: string; // "" = Alle
|
||||
party: string; // "" = Alle (Mode A's filter semantics, §11.Q8)
|
||||
q: string; // free-text query
|
||||
inbox: string; // CMS / bea / postal / "" — secondary, design §3.3
|
||||
inboxOpen: boolean;
|
||||
}
|
||||
|
||||
const state: ModeAState = {
|
||||
jurisdiction: "",
|
||||
proc: "",
|
||||
eventKind: "",
|
||||
party: "",
|
||||
q: "",
|
||||
inbox: "",
|
||||
inboxOpen: false,
|
||||
};
|
||||
|
||||
// Debounce token for search input — avoid hammering the server on
|
||||
// every keystroke.
|
||||
let searchSeq = 0;
|
||||
let searchTimer: ReturnType<typeof setTimeout> | null = null;
|
||||
|
||||
// Chip data — static. Forum and event-kind are closed-set per design;
|
||||
// party is closed-set with "Beide" option (Mode A is filter mode,
|
||||
// §11.Q8). Inbox secondary chip set per §3.3.
|
||||
const FORUMS = ["UPC", "DE", "EPA", "DPMA"] as const;
|
||||
const EVENT_KINDS = ["filing", "hearing", "decision", "order"] as const;
|
||||
const PARTIES = ["claimant", "defendant", "both"] as const;
|
||||
|
||||
// Forum auto-derivation from inbox chip per §3.3: CMS → UPC, beA → DE,
|
||||
// Postal → no narrowing (postal arrives at every jurisdiction).
|
||||
const INBOX_TO_FORUM: Record<string, string> = {
|
||||
cms: "UPC",
|
||||
bea: "DE",
|
||||
postal: "",
|
||||
};
|
||||
|
||||
// MODE_A_HOST_ID is the DOM id of the container Mode A renders into.
|
||||
// The mode shell (fristenrechner-result.mountModeShell) creates this
|
||||
// element under the overhaul root and hands it to Mode A; Mode A
|
||||
// otherwise has no opinion about its placement on the page.
|
||||
const MODE_A_HOST_ID = "fristen-overhaul-mode-host";
|
||||
|
||||
export function isModeASurfaceMounted(): boolean {
|
||||
return !!document.getElementById("fristen-mode-a-root");
|
||||
}
|
||||
|
||||
// mountModeA renders the Mode A surface into the overhaul root. Reads
|
||||
// initial state from URL params so deep links restore the previous
|
||||
// filter / search state.
|
||||
export async function mountModeA(): Promise<void> {
|
||||
const root = document.getElementById(MODE_A_HOST_ID);
|
||||
if (!root) return;
|
||||
|
||||
// Hydrate state from URL.
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
state.jurisdiction = (params.get("forum") || "").toUpperCase();
|
||||
state.proc = params.get("pt") || "";
|
||||
state.eventKind = params.get("kind") || "";
|
||||
state.party = params.get("party") || "";
|
||||
state.q = params.get("q") || "";
|
||||
|
||||
renderShell();
|
||||
await loadProceedingChips();
|
||||
void runSearch();
|
||||
}
|
||||
|
||||
// renderShell builds the Mode A markup. Idempotent re-call from the
|
||||
// boot path; row-level rewrites use renderResults / renderFilterStrip
|
||||
// for finer-grained updates.
|
||||
function renderShell(): void {
|
||||
const root = document.getElementById("fristen-overhaul-root");
|
||||
if (!root) return;
|
||||
root.innerHTML = `
|
||||
<div id="fristen-mode-a-root" class="fristen-mode-a-root">
|
||||
<section class="fristen-mode-a-filters" aria-label="${escAttr(t("deadlines.overhaul.modea.filters.label"))}">
|
||||
<header class="fristen-mode-a-filters-header">
|
||||
<span class="fristen-mode-a-filters-title">${escHtml(t("deadlines.overhaul.modea.filters.heading"))}</span>
|
||||
</header>
|
||||
<div class="fristen-mode-a-chip-row" data-axis="forum">
|
||||
<span class="fristen-mode-a-axis-label">${escHtml(t("deadlines.overhaul.modea.axis.forum"))}</span>
|
||||
<div class="fristen-mode-a-chips" id="fristen-mode-a-chips-forum"></div>
|
||||
</div>
|
||||
<div class="fristen-mode-a-chip-row" data-axis="proc">
|
||||
<span class="fristen-mode-a-axis-label">${escHtml(t("deadlines.overhaul.modea.axis.proc"))}</span>
|
||||
<div class="fristen-mode-a-chips" id="fristen-mode-a-chips-proc"></div>
|
||||
</div>
|
||||
<div class="fristen-mode-a-chip-row" data-axis="kind">
|
||||
<span class="fristen-mode-a-axis-label">${escHtml(t("deadlines.overhaul.modea.axis.kind"))}</span>
|
||||
<div class="fristen-mode-a-chips" id="fristen-mode-a-chips-kind"></div>
|
||||
</div>
|
||||
<div class="fristen-mode-a-chip-row" data-axis="party">
|
||||
<span class="fristen-mode-a-axis-label">${escHtml(t("deadlines.overhaul.modea.axis.party"))}</span>
|
||||
<div class="fristen-mode-a-chips" id="fristen-mode-a-chips-party"></div>
|
||||
</div>
|
||||
<details class="fristen-mode-a-inbox" ${state.inboxOpen ? "open" : ""}>
|
||||
<summary class="fristen-mode-a-inbox-summary">${escHtml(t("deadlines.overhaul.modea.inbox.summary"))}</summary>
|
||||
<div class="fristen-mode-a-chip-row" data-axis="inbox">
|
||||
<span class="fristen-mode-a-axis-label">${escHtml(t("deadlines.overhaul.modea.axis.inbox"))}</span>
|
||||
<div class="fristen-mode-a-chips" id="fristen-mode-a-chips-inbox"></div>
|
||||
</div>
|
||||
</details>
|
||||
</section>
|
||||
|
||||
<section class="fristen-mode-a-search" aria-label="${escAttr(t("deadlines.overhaul.modea.search.label"))}">
|
||||
<div class="fristen-mode-a-search-input-wrap">
|
||||
<svg class="fristen-mode-a-search-icon" width="18" height="18" viewBox="0 0 24 24" fill="none"
|
||||
stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<circle cx="11" cy="11" r="7"></circle>
|
||||
<line x1="21" y1="21" x2="16.65" y2="16.65"></line>
|
||||
</svg>
|
||||
<input type="search" id="fristen-mode-a-search-input"
|
||||
class="fristen-mode-a-search-input"
|
||||
autocomplete="off" spellcheck="false"
|
||||
data-i18n-placeholder="deadlines.overhaul.modea.search.placeholder"
|
||||
placeholder="Klageerhebung, Hinweisbeschluss, oral hearing…"
|
||||
value="${escAttr(state.q)}" />
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="fristen-mode-a-results" aria-label="${escAttr(t("deadlines.overhaul.modea.results.label"))}">
|
||||
<header class="fristen-mode-a-results-header">
|
||||
<span class="fristen-mode-a-results-title">${escHtml(t("deadlines.overhaul.modea.results.heading"))}</span>
|
||||
<span class="fristen-mode-a-results-count" id="fristen-mode-a-results-count"></span>
|
||||
</header>
|
||||
<ul class="fristen-mode-a-result-list" id="fristen-mode-a-result-list" role="listbox" aria-live="polite"></ul>
|
||||
</section>
|
||||
</div>
|
||||
`;
|
||||
|
||||
renderForumChips();
|
||||
renderKindChips();
|
||||
renderPartyChips();
|
||||
renderInboxChips();
|
||||
// Proceeding chips render later, after fetch.
|
||||
|
||||
// Wire search input.
|
||||
const input = document.getElementById("fristen-mode-a-search-input") as HTMLInputElement | null;
|
||||
if (input) {
|
||||
input.addEventListener("input", () => {
|
||||
state.q = input.value;
|
||||
scheduleSearch(180);
|
||||
});
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if ((e as KeyboardEvent).key === "Enter") {
|
||||
e.preventDefault();
|
||||
scheduleSearch(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Filter-strip chip renderers ----------------------------------------
|
||||
|
||||
function renderForumChips(): void {
|
||||
const host = document.getElementById("fristen-mode-a-chips-forum");
|
||||
if (!host) return;
|
||||
const chips = [
|
||||
chipHtml("forum", "", t("deadlines.overhaul.modea.chip.all"), state.jurisdiction === ""),
|
||||
...FORUMS.map((j) => chipHtml("forum", j, j, state.jurisdiction === j)),
|
||||
];
|
||||
host.innerHTML = chips.join("");
|
||||
host.querySelectorAll<HTMLButtonElement>(".fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const v = btn.dataset.value || "";
|
||||
state.jurisdiction = v;
|
||||
// Forum change invalidates the proc pick if it falls outside.
|
||||
state.proc = "";
|
||||
syncUrl();
|
||||
renderForumChips();
|
||||
void loadProceedingChips();
|
||||
scheduleSearch(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderKindChips(): void {
|
||||
const host = document.getElementById("fristen-mode-a-chips-kind");
|
||||
if (!host) return;
|
||||
const chips = [
|
||||
chipHtml("kind", "", t("deadlines.overhaul.modea.chip.all"), state.eventKind === ""),
|
||||
...EVENT_KINDS.map((k) => chipHtml("kind", k, t(`deadlines.overhaul.kind.${k}` as never), state.eventKind === k, eventKindIconForChip(k))),
|
||||
];
|
||||
host.innerHTML = chips.join("");
|
||||
host.querySelectorAll<HTMLButtonElement>(".fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
state.eventKind = btn.dataset.value || "";
|
||||
syncUrl();
|
||||
renderKindChips();
|
||||
scheduleSearch(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderPartyChips(): void {
|
||||
const host = document.getElementById("fristen-mode-a-chips-party");
|
||||
if (!host) return;
|
||||
const chips = [
|
||||
chipHtml("party", "", t("deadlines.overhaul.modea.chip.all"), state.party === ""),
|
||||
...PARTIES.map((p) => chipHtml("party", p, t(`deadlines.party.${p}` as never), state.party === p)),
|
||||
];
|
||||
host.innerHTML = chips.join("");
|
||||
host.querySelectorAll<HTMLButtonElement>(".fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
state.party = btn.dataset.value || "";
|
||||
syncUrl();
|
||||
renderPartyChips();
|
||||
scheduleSearch(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function renderInboxChips(): void {
|
||||
const host = document.getElementById("fristen-mode-a-chips-inbox");
|
||||
if (!host) return;
|
||||
const opts = [
|
||||
{ v: "", label: t("deadlines.overhaul.modea.chip.all") },
|
||||
{ v: "cms", label: "CMS" },
|
||||
{ v: "bea", label: "beA" },
|
||||
{ v: "postal", label: t("deadlines.overhaul.modea.inbox.postal") },
|
||||
];
|
||||
host.innerHTML = opts.map((o) => chipHtml("inbox", o.v, o.label, state.inbox === o.v)).join("");
|
||||
host.querySelectorAll<HTMLButtonElement>(".fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const v = btn.dataset.value || "";
|
||||
state.inbox = v;
|
||||
// Auto-nudge forum from inbox per design §3.3.
|
||||
const nudge = INBOX_TO_FORUM[v];
|
||||
if (nudge !== undefined && nudge !== "") {
|
||||
state.jurisdiction = nudge;
|
||||
state.proc = "";
|
||||
renderForumChips();
|
||||
void loadProceedingChips();
|
||||
}
|
||||
renderInboxChips();
|
||||
scheduleSearch(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Proceeding chips — dynamic fetch.
|
||||
|
||||
let lastProcFetchKey = "";
|
||||
|
||||
async function loadProceedingChips(): Promise<void> {
|
||||
const host = document.getElementById("fristen-mode-a-chips-proc");
|
||||
if (!host) return;
|
||||
const key = `j=${state.jurisdiction}`;
|
||||
if (lastProcFetchKey === key) return; // cached for current jurisdiction
|
||||
lastProcFetchKey = key;
|
||||
host.innerHTML = `<span class="fristen-mode-a-chip-loading">${escHtml(t("deadlines.overhaul.modea.loading"))}</span>`;
|
||||
|
||||
const url = new URL("/api/tools/proceeding-types", window.location.origin);
|
||||
url.searchParams.set("kind", "proceeding");
|
||||
if (state.jurisdiction) url.searchParams.set("jurisdiction", state.jurisdiction);
|
||||
|
||||
let chips: ProceedingChip[] = [];
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (resp.ok) {
|
||||
const data = (await resp.json()) as ProceedingChip[] | null;
|
||||
chips = data || [];
|
||||
}
|
||||
} catch {
|
||||
// Soft-fail: chip strip just hides; search still runs without
|
||||
// proceeding narrowing.
|
||||
}
|
||||
|
||||
renderProceedingChips(chips);
|
||||
}
|
||||
|
||||
function renderProceedingChips(chips: ProceedingChip[]): void {
|
||||
const host = document.getElementById("fristen-mode-a-chips-proc");
|
||||
if (!host) return;
|
||||
const lang = getLang();
|
||||
if (chips.length === 0) {
|
||||
host.innerHTML = `<span class="fristen-mode-a-chip-empty">${escHtml(t("deadlines.overhaul.modea.no_proceedings"))}</span>`;
|
||||
return;
|
||||
}
|
||||
const rendered = [
|
||||
chipHtml("proc", "", t("deadlines.overhaul.modea.chip.all"), state.proc === ""),
|
||||
...chips.map((c) => {
|
||||
const label = lang === "en" ? c.nameEN || c.name : c.name;
|
||||
return chipHtml("proc", c.code, label, state.proc === c.code, undefined, c.code);
|
||||
}),
|
||||
];
|
||||
host.innerHTML = rendered.join("");
|
||||
host.querySelectorAll<HTMLButtonElement>(".fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
state.proc = btn.dataset.value || "";
|
||||
syncUrl();
|
||||
renderProceedingChips(chips);
|
||||
scheduleSearch(0);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Search ------------------------------------------------------------
|
||||
|
||||
function scheduleSearch(delayMs: number): void {
|
||||
if (searchTimer !== null) clearTimeout(searchTimer);
|
||||
searchTimer = setTimeout(() => {
|
||||
searchTimer = null;
|
||||
void runSearch();
|
||||
}, delayMs);
|
||||
}
|
||||
|
||||
async function runSearch(): Promise<void> {
|
||||
searchSeq++;
|
||||
const mySeq = searchSeq;
|
||||
|
||||
const list = document.getElementById("fristen-mode-a-result-list");
|
||||
const count = document.getElementById("fristen-mode-a-results-count");
|
||||
if (!list || !count) return;
|
||||
|
||||
list.innerHTML = `<li class="fristen-mode-a-result-loading">${escHtml(t("deadlines.overhaul.modea.loading"))}</li>`;
|
||||
count.textContent = "";
|
||||
|
||||
const url = new URL("/api/tools/fristenrechner/search", window.location.origin);
|
||||
url.searchParams.set("kind", "events");
|
||||
if (state.q) url.searchParams.set("q", state.q);
|
||||
if (state.jurisdiction) url.searchParams.set("jurisdiction", state.jurisdiction);
|
||||
if (state.proc) url.searchParams.set("proc", state.proc);
|
||||
if (state.eventKind) url.searchParams.set("event_kind", state.eventKind);
|
||||
if (state.party) url.searchParams.set("party", state.party);
|
||||
|
||||
let data: EventSearchResponse;
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) {
|
||||
if (mySeq === searchSeq) {
|
||||
list.innerHTML = `<li class="fristen-mode-a-result-error">${escHtml(t("deadlines.overhaul.modea.search_error"))}</li>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
data = (await resp.json()) as EventSearchResponse;
|
||||
} catch {
|
||||
if (mySeq === searchSeq) {
|
||||
list.innerHTML = `<li class="fristen-mode-a-result-error">${escHtml(t("deadlines.overhaul.modea.search_error"))}</li>`;
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (mySeq !== searchSeq) return; // stale response
|
||||
|
||||
renderResults(data);
|
||||
}
|
||||
|
||||
function renderResults(data: EventSearchResponse): void {
|
||||
const list = document.getElementById("fristen-mode-a-result-list");
|
||||
const count = document.getElementById("fristen-mode-a-results-count");
|
||||
if (!list || !count) return;
|
||||
count.textContent = tDyn("deadlines.overhaul.modea.results.count").replace("{n}", String(data.total));
|
||||
|
||||
if (data.events.length === 0) {
|
||||
list.innerHTML = `<li class="fristen-mode-a-result-empty">${escHtml(t("deadlines.overhaul.modea.no_results"))}</li>`;
|
||||
return;
|
||||
}
|
||||
|
||||
const lang = getLang();
|
||||
list.innerHTML = data.events.map((e) => {
|
||||
const name = lang === "en" ? e.name_en || e.name_de : e.name_de;
|
||||
const pt = e.proceeding_type;
|
||||
const ptName = lang === "en" ? pt.name_en || pt.name_de : pt.name_de;
|
||||
const icon = eventKindIconForChip(e.event_kind);
|
||||
const followUps = tDyn("deadlines.overhaul.modea.row.followups").replace("{n}", String(e.follow_up_count));
|
||||
const juris = pt.jurisdiction || "";
|
||||
return `
|
||||
<li class="fristen-mode-a-result" data-event-code="${escAttr(e.code)}" tabindex="0" role="option">
|
||||
<span class="fristen-mode-a-result-icon" aria-hidden="true">${icon}</span>
|
||||
<div class="fristen-mode-a-result-body">
|
||||
<div class="fristen-mode-a-result-title">${escHtml(name)}</div>
|
||||
<div class="fristen-mode-a-result-meta">
|
||||
<span class="fristen-mode-a-result-pt">${escHtml(pt.code)}</span>
|
||||
<span class="fristen-mode-a-result-pt-name">${escHtml(ptName)}</span>
|
||||
${juris ? `<span class="fristen-mode-a-result-juris">${escHtml(juris)}</span>` : ""}
|
||||
<span class="fristen-mode-a-result-followups">${escHtml(followUps)}</span>
|
||||
</div>
|
||||
</div>
|
||||
<span class="fristen-mode-a-result-cta" aria-hidden="true">→</span>
|
||||
</li>
|
||||
`;
|
||||
}).join("");
|
||||
|
||||
list.querySelectorAll<HTMLLIElement>(".fristen-mode-a-result").forEach((li) => {
|
||||
li.addEventListener("click", () => commitEvent(li.dataset.eventCode || ""));
|
||||
li.addEventListener("keydown", (e) => {
|
||||
const k = (e as KeyboardEvent).key;
|
||||
if (k === "Enter" || k === " ") {
|
||||
e.preventDefault();
|
||||
commitEvent(li.dataset.eventCode || "");
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Commit — user picked a result; lock the event as trigger and
|
||||
// transition to the §4 result view (S2).
|
||||
function commitEvent(code: string): void {
|
||||
if (!code) return;
|
||||
// Reflect in URL before re-mounting so the result view's deep link
|
||||
// is consistent.
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("overhaul", "1");
|
||||
url.searchParams.set("event", code);
|
||||
// Preserve project / forum / kind filters so a back-navigation
|
||||
// brings Mode A back with the same filters.
|
||||
history.pushState(null, "", url.pathname + url.search + url.hash);
|
||||
void mountResultView({
|
||||
eventRef: code,
|
||||
party: state.party || undefined,
|
||||
});
|
||||
}
|
||||
|
||||
// Helpers -----------------------------------------------------------
|
||||
|
||||
function chipHtml(axis: string, value: string, label: string, active: boolean, icon?: string, title?: string): string {
|
||||
const cls = `fristen-mode-a-chip${active ? " is-active" : ""}`;
|
||||
const t = title ? ` title="${escAttr(title)}"` : "";
|
||||
const i = icon ? `<span class="fristen-mode-a-chip-icon" aria-hidden="true">${icon}</span>` : "";
|
||||
return `<button type="button" class="${cls}" data-axis="${escAttr(axis)}" data-value="${escAttr(value)}"${t}>${i}<span class="fristen-mode-a-chip-label">${escHtml(label)}</span></button>`;
|
||||
}
|
||||
|
||||
function eventKindIconForChip(kind?: string): string {
|
||||
switch (kind) {
|
||||
case "filing": return "📥";
|
||||
case "hearing": return "🏛️";
|
||||
case "decision": return "⚖️";
|
||||
case "order": return "📜";
|
||||
default: return "🔍";
|
||||
}
|
||||
}
|
||||
|
||||
// syncUrl writes the active filter set into the URL so the deep link
|
||||
// restores Mode A in the same state.
|
||||
function syncUrl(): void {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("overhaul", "1");
|
||||
setOrClear(url, "forum", state.jurisdiction);
|
||||
setOrClear(url, "pt", state.proc);
|
||||
setOrClear(url, "kind", state.eventKind);
|
||||
setOrClear(url, "party", state.party);
|
||||
setOrClear(url, "q", state.q);
|
||||
history.replaceState(null, "", url.pathname + url.search + url.hash);
|
||||
}
|
||||
|
||||
function setOrClear(url: URL, key: string, val: string): void {
|
||||
if (val) url.searchParams.set(key, val);
|
||||
else url.searchParams.delete(key);
|
||||
}
|
||||
72
frontend/src/client/fristenrechner-result.test.ts
Normal file
72
frontend/src/client/fristenrechner-result.test.ts
Normal file
@@ -0,0 +1,72 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import {
|
||||
defaultChecked,
|
||||
groupFollowUps,
|
||||
type FollowUpRule,
|
||||
} from "./fristenrechner-result";
|
||||
|
||||
// Pure helpers exercised here; the DOM-driven render path is covered
|
||||
// by the live page test path (S2 is mount-on-deep-link, S3+S4 add the
|
||||
// entry-mode UIs in later slices).
|
||||
|
||||
function mk(partial: Partial<FollowUpRule>): FollowUpRule {
|
||||
return {
|
||||
rule_id: "r" + Math.random().toString(36).slice(2, 8),
|
||||
event_code: "evt",
|
||||
title_de: "Frist",
|
||||
title_en: "Deadline",
|
||||
priority: "mandatory",
|
||||
is_court_set: false,
|
||||
is_spawn: false,
|
||||
is_bilateral: false,
|
||||
has_condition: false,
|
||||
...partial,
|
||||
};
|
||||
}
|
||||
|
||||
describe("groupFollowUps — design §4.2 priority+condition buckets", () => {
|
||||
test("groups by priority; conditional takes precedence over priority", () => {
|
||||
const rows = [
|
||||
mk({ priority: "mandatory" }),
|
||||
mk({ priority: "recommended" }),
|
||||
mk({ priority: "optional" }),
|
||||
mk({ priority: "mandatory", has_condition: true }), // → conditional
|
||||
mk({ priority: "optional", has_condition: true }), // → conditional
|
||||
];
|
||||
const g = groupFollowUps(rows);
|
||||
expect(g.mandatory.length).toBe(1);
|
||||
expect(g.recommended.length).toBe(1);
|
||||
expect(g.optional.length).toBe(1);
|
||||
expect(g.conditional.length).toBe(2);
|
||||
});
|
||||
|
||||
test("unknown priority falls through to optional", () => {
|
||||
const g = groupFollowUps([mk({ priority: "informational" })]);
|
||||
expect(g.optional.length).toBe(1);
|
||||
expect(g.mandatory.length).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("defaultChecked — pre-checks mandatory + recommended, not conditional/court-set", () => {
|
||||
test("mandatory rules pre-checked", () => {
|
||||
expect(defaultChecked(mk({ priority: "mandatory" }))).toBe(true);
|
||||
});
|
||||
test("recommended rules pre-checked", () => {
|
||||
expect(defaultChecked(mk({ priority: "recommended" }))).toBe(true);
|
||||
});
|
||||
test("optional rules unchecked", () => {
|
||||
expect(defaultChecked(mk({ priority: "optional" }))).toBe(false);
|
||||
});
|
||||
test("conditional rules unchecked", () => {
|
||||
expect(defaultChecked(mk({ priority: "mandatory", has_condition: true }))).toBe(false);
|
||||
});
|
||||
test("court-set rules unchecked even when mandatory", () => {
|
||||
expect(defaultChecked(mk({ priority: "mandatory", is_court_set: true }))).toBe(false);
|
||||
});
|
||||
test("spawned rules pre-checked when mandatory", () => {
|
||||
expect(defaultChecked(mk({ priority: "mandatory", is_spawn: true }))).toBe(true);
|
||||
});
|
||||
test("spawned optional rules unchecked", () => {
|
||||
expect(defaultChecked(mk({ priority: "optional", is_spawn: true }))).toBe(false);
|
||||
});
|
||||
});
|
||||
672
frontend/src/client/fristenrechner-result.ts
Normal file
672
frontend/src/client/fristenrechner-result.ts
Normal file
@@ -0,0 +1,672 @@
|
||||
// Fristenrechner overhaul — shared result view (design §4).
|
||||
//
|
||||
// Given a locked trigger event + a trigger date, this module renders
|
||||
// the result surface: a sticky trigger card on top, then four priority
|
||||
// groups (mandatory / recommended / optional / conditional) of follow-up
|
||||
// rules with computed dates, then a write-back footer that calls the
|
||||
// existing POST /api/projects/{id}/deadlines/bulk.
|
||||
//
|
||||
// The two future entry paths (Mode A "Direkt suchen" in S3, Mode B
|
||||
// wizard in S4) both land here once they've identified a trigger
|
||||
// procedural_event. S2 mounts the surface under `?overhaul=1` and is
|
||||
// deep-linkable on its own via `?overhaul=1&event=<code>&trigger_date=…`.
|
||||
|
||||
import { escAttr, escHtml } from "./views/verfahrensablauf-core";
|
||||
import { getLang, t, tDyn } from "./i18n";
|
||||
|
||||
// Wire shape from GET /api/tools/fristenrechner/follow-ups. Mirrors
|
||||
// services.FollowUpsResponse server-side.
|
||||
export interface FollowUpRule {
|
||||
rule_id: string;
|
||||
event_code: string;
|
||||
title_de: string;
|
||||
title_en: string;
|
||||
priority: string;
|
||||
primary_party?: string;
|
||||
duration_value?: number;
|
||||
duration_unit?: string;
|
||||
timing?: string;
|
||||
due_date?: string;
|
||||
original_due_date?: string;
|
||||
was_adjusted?: boolean;
|
||||
is_court_set: boolean;
|
||||
is_spawn: boolean;
|
||||
is_bilateral: boolean;
|
||||
has_condition: boolean;
|
||||
rule_code?: string;
|
||||
legal_source?: string;
|
||||
legal_source_display?: string;
|
||||
legal_source_url?: string;
|
||||
notes_de?: string;
|
||||
notes_en?: string;
|
||||
spawn_label?: string;
|
||||
spawn_proceeding_code?: string;
|
||||
concept_id?: string;
|
||||
}
|
||||
|
||||
export interface FollowUpsResponse {
|
||||
trigger: {
|
||||
id: string;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
event_kind?: string;
|
||||
proceeding_type: {
|
||||
id: number;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
jurisdiction?: string;
|
||||
};
|
||||
anchor_rule_id: string;
|
||||
};
|
||||
trigger_date: string;
|
||||
party?: string;
|
||||
follow_ups: FollowUpRule[];
|
||||
}
|
||||
|
||||
// Per-rule UI state — checkbox, optional date override.
|
||||
interface RuleSelection {
|
||||
checked: boolean;
|
||||
override?: string;
|
||||
}
|
||||
|
||||
// Module-local state. Single result view at a time; the surface
|
||||
// re-renders in place when the user changes the trigger date or
|
||||
// re-locks a different event.
|
||||
let currentResponse: FollowUpsResponse | null = null;
|
||||
const selections = new Map<string, RuleSelection>();
|
||||
let currentProjectId: string | null = null;
|
||||
|
||||
// Public API ----------------------------------------------------------
|
||||
|
||||
// isOverhaulMode reports whether the page is in overhaul mode.
|
||||
// After Slice S5 (t-paliad-323), overhaul is the default; the legacy
|
||||
// wizard / row-stack / cascade is only reachable via `?legacy=1` for
|
||||
// a two-week deprecation window. The `?overhaul=1` deep links from
|
||||
// S2-S4 still work — they're now redundant with the default but kept
|
||||
// alive so bookmarks don't 302 / lose state.
|
||||
export function isOverhaulMode(): boolean {
|
||||
return new URLSearchParams(window.location.search).get("legacy") !== "1";
|
||||
}
|
||||
|
||||
// resolveProjectId reads the active Akte from the URL query string.
|
||||
// Returns null when in kontextfrei mode (no project picked).
|
||||
function resolveProjectId(): string | null {
|
||||
const p = new URLSearchParams(window.location.search).get("project");
|
||||
return p && p.length > 0 ? p : null;
|
||||
}
|
||||
|
||||
// MODE_TAB_KEYS — the two entry-mode tabs landed by S3 + S4. S2's deep
|
||||
// link path bypasses these (jumps straight to the result view via
|
||||
// ?event=); the tabs appear when no event is locked yet.
|
||||
export type ModeTab = "search" | "wizard";
|
||||
|
||||
// mountModeShell renders the mode-tab pair under the page header and
|
||||
// hosts whichever mode panel is currently active. Called from the boot
|
||||
// path when no `?event=` is present. S3 wires Mode A; S4 will add
|
||||
// Mode B and the actual tab switching.
|
||||
export async function mountModeShell(activeTab: ModeTab): Promise<void> {
|
||||
const root = document.getElementById("fristen-overhaul-root");
|
||||
if (!root) return;
|
||||
root.hidden = false;
|
||||
// Defer to the per-mode module to render into the root. The tab
|
||||
// strip itself is a small header above the mode panel — for S3 we
|
||||
// render the shell + Mode A in one shot.
|
||||
// S4 will replace this with a real tab switcher.
|
||||
const tabs = `
|
||||
<nav class="fristen-mode-tabs" role="tablist" aria-label="${escAttr(t("deadlines.overhaul.modes.label"))}">
|
||||
<button type="button" class="fristen-mode-tab${activeTab === "search" ? " is-active" : ""}" role="tab"
|
||||
aria-selected="${activeTab === "search"}" data-tab="search">
|
||||
<span class="fristen-mode-tab-icon" aria-hidden="true">⚡</span>
|
||||
<span class="fristen-mode-tab-label">${escHtml(t("deadlines.overhaul.modes.search"))}</span>
|
||||
</button>
|
||||
<button type="button" class="fristen-mode-tab${activeTab === "wizard" ? " is-active" : ""}" role="tab"
|
||||
aria-selected="${activeTab === "wizard"}" data-tab="wizard">
|
||||
<span class="fristen-mode-tab-icon" aria-hidden="true">🧭</span>
|
||||
<span class="fristen-mode-tab-label">${escHtml(t("deadlines.overhaul.modes.wizard"))}</span>
|
||||
</button>
|
||||
</nav>
|
||||
<div id="fristen-overhaul-mode-host"></div>
|
||||
`;
|
||||
root.innerHTML = tabs;
|
||||
|
||||
// Wire tab switching. S3 only has Mode A wired; Mode B is a
|
||||
// placeholder until S4.
|
||||
root.querySelectorAll<HTMLButtonElement>(".fristen-mode-tab").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const tab = (btn.dataset.tab || "search") as ModeTab;
|
||||
void mountModeShell(tab);
|
||||
});
|
||||
});
|
||||
|
||||
// Mount the active mode panel into the host. S3 only routes "search";
|
||||
// "wizard" renders a placeholder until S4 lands.
|
||||
const host = document.getElementById("fristen-overhaul-mode-host");
|
||||
if (!host) return;
|
||||
if (activeTab === "search") {
|
||||
// Lazy import to keep the bundle layered and avoid a circular ref
|
||||
// between fristenrechner-result.ts ↔ fristenrechner-mode-a.ts.
|
||||
const mod = await import("./fristenrechner-mode-a");
|
||||
await mod.mountModeA();
|
||||
} else {
|
||||
const mod = await import("./fristenrechner-wizard");
|
||||
await mod.mountWizard();
|
||||
}
|
||||
}
|
||||
|
||||
// MountOptions configures the surface entry. Both entry-mode paths
|
||||
// (Mode A in S3, Mode B in S4) call mount() with the event reference
|
||||
// that the user committed.
|
||||
export interface MountOptions {
|
||||
// eventRef is the procedural_event code OR its uuid OR the anchor
|
||||
// sequencing_rule id. Resolved server-side; the wire returns the
|
||||
// canonical code so the URL bookmark is stable.
|
||||
eventRef: string;
|
||||
// triggerDate is YYYY-MM-DD. Defaults to today when omitted.
|
||||
triggerDate?: string;
|
||||
// party is "claimant" | "defendant"; mode A may pass "both" or
|
||||
// "court". When omitted, follow-ups are returned without party
|
||||
// narrowing.
|
||||
party?: string;
|
||||
// courtId selects the holiday calendar for the per-rule date
|
||||
// adjustment. Optional.
|
||||
courtId?: string;
|
||||
}
|
||||
|
||||
// mountResultView fetches /follow-ups and renders the result surface
|
||||
// into the host container. Re-callable: replaces previous state.
|
||||
export async function mountResultView(opts: MountOptions): Promise<void> {
|
||||
const root = document.getElementById("fristen-overhaul-root");
|
||||
if (!root) return;
|
||||
root.hidden = false;
|
||||
|
||||
const triggerDate = opts.triggerDate || todayIso();
|
||||
currentProjectId = resolveProjectId();
|
||||
|
||||
// Show a quick "loading…" placeholder so the user sees something
|
||||
// immediately, even on a cold fetch.
|
||||
root.innerHTML = `<div class="fristen-overhaul-loading">${escHtml(t("deadlines.overhaul.loading"))}</div>`;
|
||||
|
||||
const url = new URL("/api/tools/fristenrechner/follow-ups", window.location.origin);
|
||||
url.searchParams.set("event", opts.eventRef);
|
||||
url.searchParams.set("trigger_date", triggerDate);
|
||||
if (opts.party) url.searchParams.set("party", opts.party);
|
||||
if (opts.courtId) url.searchParams.set("court_id", opts.courtId);
|
||||
|
||||
let data: FollowUpsResponse;
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) {
|
||||
const body = await resp.json().catch(() => ({}) as { error?: string });
|
||||
root.innerHTML = `<div class="fristen-overhaul-error">${escHtml(body.error || t("deadlines.overhaul.load_error"))}</div>`;
|
||||
return;
|
||||
}
|
||||
data = (await resp.json()) as FollowUpsResponse;
|
||||
} catch (err) {
|
||||
root.innerHTML = `<div class="fristen-overhaul-error">${escHtml(t("deadlines.overhaul.load_error"))}</div>`;
|
||||
return;
|
||||
}
|
||||
|
||||
currentResponse = data;
|
||||
selections.clear();
|
||||
for (const r of data.follow_ups) {
|
||||
selections.set(r.rule_id, { checked: defaultChecked(r) });
|
||||
}
|
||||
|
||||
renderSurface();
|
||||
// Reflect the canonical event code + trigger date in the URL so the
|
||||
// deep-link survives a reload.
|
||||
syncUrlState(data.trigger.code, data.trigger_date);
|
||||
}
|
||||
|
||||
// Render --------------------------------------------------------------
|
||||
|
||||
function renderSurface(): void {
|
||||
const root = document.getElementById("fristen-overhaul-root");
|
||||
if (!root || !currentResponse) return;
|
||||
|
||||
const lang = getLang();
|
||||
const trig = currentResponse.trigger;
|
||||
const triggerName = lang === "en" ? trig.name_en || trig.name_de : trig.name_de;
|
||||
const ptName = lang === "en" ? trig.proceeding_type.name_en || trig.proceeding_type.name_de : trig.proceeding_type.name_de;
|
||||
const juris = trig.proceeding_type.jurisdiction || "";
|
||||
const kindIcon = eventKindIcon(trig.event_kind);
|
||||
|
||||
const triggerCard = `
|
||||
<section class="fristen-overhaul-trigger" aria-label="${escAttr(t("deadlines.overhaul.trigger.label"))}">
|
||||
<header class="fristen-overhaul-trigger-header">
|
||||
<span class="fristen-overhaul-kind-icon" aria-hidden="true">${kindIcon}</span>
|
||||
<h2 class="fristen-overhaul-trigger-title">${escHtml(triggerName)}</h2>
|
||||
</header>
|
||||
<div class="fristen-overhaul-trigger-meta">
|
||||
<span class="fristen-overhaul-trigger-code">${escHtml(trig.code)}</span>
|
||||
<span class="fristen-overhaul-trigger-pt">${escHtml(ptName)}</span>
|
||||
${juris ? `<span class="fristen-overhaul-trigger-juris">${escHtml(juris)}</span>` : ""}
|
||||
</div>
|
||||
<div class="fristen-overhaul-trigger-date">
|
||||
<label for="fristen-overhaul-trigger-date" class="fristen-overhaul-trigger-date-label">
|
||||
${escHtml(t("deadlines.overhaul.trigger.date"))}
|
||||
</label>
|
||||
<input type="date" id="fristen-overhaul-trigger-date" class="fristen-overhaul-trigger-date-input"
|
||||
value="${escAttr(currentResponse.trigger_date)}" />
|
||||
</div>
|
||||
</section>
|
||||
`;
|
||||
|
||||
const groups = groupFollowUps(currentResponse.follow_ups);
|
||||
const groupHtml = renderGroups(groups, lang);
|
||||
|
||||
const nudge = currentProjectId
|
||||
? ""
|
||||
: `<div class="fristen-overhaul-nudge">${escHtml(t("deadlines.overhaul.nudge.no_project"))}</div>`;
|
||||
|
||||
const footer = currentProjectId
|
||||
? renderFooter()
|
||||
: "";
|
||||
|
||||
root.innerHTML = `
|
||||
${triggerCard}
|
||||
${nudge}
|
||||
<section class="fristen-overhaul-groups" aria-label="${escAttr(t("deadlines.overhaul.followups.label"))}">
|
||||
${groupHtml}
|
||||
</section>
|
||||
${footer}
|
||||
<div class="fristen-overhaul-msg" id="fristen-overhaul-msg" role="status" aria-live="polite"></div>
|
||||
`;
|
||||
|
||||
wireSurfaceEvents();
|
||||
}
|
||||
|
||||
export interface GroupedFollowUps {
|
||||
mandatory: FollowUpRule[];
|
||||
recommended: FollowUpRule[];
|
||||
optional: FollowUpRule[];
|
||||
conditional: FollowUpRule[];
|
||||
}
|
||||
|
||||
// groupFollowUps splits the wire list into the four visible groups per
|
||||
// design §4.2. Conditional (sr.condition_expr IS NOT NULL) takes
|
||||
// precedence over the priority bucket so a "nur wenn CCR" mandatory
|
||||
// rule renders under Conditional with the gating language visible.
|
||||
export function groupFollowUps(rows: FollowUpRule[]): GroupedFollowUps {
|
||||
const out: GroupedFollowUps = { mandatory: [], recommended: [], optional: [], conditional: [] };
|
||||
for (const r of rows) {
|
||||
if (r.has_condition) {
|
||||
out.conditional.push(r);
|
||||
continue;
|
||||
}
|
||||
switch (r.priority) {
|
||||
case "mandatory":
|
||||
out.mandatory.push(r);
|
||||
break;
|
||||
case "recommended":
|
||||
out.recommended.push(r);
|
||||
break;
|
||||
case "optional":
|
||||
out.optional.push(r);
|
||||
break;
|
||||
default:
|
||||
// unknown / informational — fold into optional so the row is at
|
||||
// least visible. Future Phase 2 'informational' tier gets a
|
||||
// dedicated bucket once seeded.
|
||||
out.optional.push(r);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function renderGroups(groups: GroupedFollowUps, lang: "de" | "en"): string {
|
||||
const blocks: string[] = [];
|
||||
if (groups.mandatory.length > 0) {
|
||||
blocks.push(renderGroup("mandatory", t("deadlines.overhaul.group.mandatory"), groups.mandatory, lang));
|
||||
}
|
||||
if (groups.recommended.length > 0) {
|
||||
blocks.push(renderGroup("recommended", t("deadlines.overhaul.group.recommended"), groups.recommended, lang));
|
||||
}
|
||||
if (groups.optional.length > 0) {
|
||||
blocks.push(renderGroup("optional", t("deadlines.overhaul.group.optional"), groups.optional, lang));
|
||||
}
|
||||
if (groups.conditional.length > 0) {
|
||||
blocks.push(renderGroup("conditional", t("deadlines.overhaul.group.conditional"), groups.conditional, lang));
|
||||
}
|
||||
if (blocks.length === 0) {
|
||||
return `<div class="fristen-overhaul-empty">${escHtml(t("deadlines.overhaul.empty"))}</div>`;
|
||||
}
|
||||
return blocks.join("");
|
||||
}
|
||||
|
||||
function renderGroup(slug: string, label: string, rows: FollowUpRule[], lang: "de" | "en"): string {
|
||||
const items = rows.map((r) => renderRule(r, lang)).join("");
|
||||
return `
|
||||
<div class="fristen-overhaul-group fristen-overhaul-group--${escAttr(slug)}">
|
||||
<h3 class="fristen-overhaul-group-title">${escHtml(label)}</h3>
|
||||
<ul class="fristen-overhaul-rule-list">
|
||||
${items}
|
||||
</ul>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderRule(r: FollowUpRule, lang: "de" | "en"): string {
|
||||
const title = lang === "en" ? r.title_en || r.title_de : r.title_de;
|
||||
const notes = lang === "en" ? r.notes_en || r.notes_de : r.notes_de;
|
||||
const sel = selections.get(r.rule_id);
|
||||
const checked = sel ? sel.checked : defaultChecked(r);
|
||||
const dateOverride = sel?.override;
|
||||
const computedDate = r.due_date || "";
|
||||
const effectiveDate = dateOverride || computedDate;
|
||||
const disabled = r.is_court_set || (r.is_spawn && !r.due_date);
|
||||
|
||||
// Duration phrase: "3 Monate" / "14 Tage" — language-aware.
|
||||
const durationPhrase = formatDurationPhrase(r, lang);
|
||||
const dateCell = r.is_court_set
|
||||
? `<span class="fristen-overhaul-rule-court-set">${escHtml(t("deadlines.court.set"))}</span>`
|
||||
: effectiveDate
|
||||
? `<span class="fristen-overhaul-rule-date" data-rule-id="${escAttr(r.rule_id)}">${escHtml(formatDateForLang(effectiveDate, lang))}</span>`
|
||||
: `<span class="fristen-overhaul-rule-date fristen-overhaul-rule-date--unknown">—</span>`;
|
||||
|
||||
const partyBadge = r.primary_party
|
||||
? `<span class="fristen-overhaul-rule-party fristen-overhaul-rule-party--${escAttr(r.primary_party)}">${escHtml(t(`deadlines.party.${r.primary_party}` as never))}</span>`
|
||||
: "";
|
||||
|
||||
const sourceBadge = r.legal_source_display
|
||||
? r.legal_source_url
|
||||
? `<a class="fristen-overhaul-rule-source" href="${escAttr(r.legal_source_url)}" target="_blank" rel="noreferrer">${escHtml(r.legal_source_display)}</a>`
|
||||
: `<span class="fristen-overhaul-rule-source">${escHtml(r.legal_source_display)}</span>`
|
||||
: r.rule_code
|
||||
? `<span class="fristen-overhaul-rule-source">${escHtml(r.rule_code)}</span>`
|
||||
: "";
|
||||
|
||||
const spawnBadge = r.is_spawn
|
||||
? `<span class="fristen-overhaul-rule-spawn" title="${escAttr(t("deadlines.overhaul.spawn.tooltip"))}">${escHtml(t("deadlines.overhaul.spawn.badge"))}${r.spawn_proceeding_code ? ` · ${escHtml(r.spawn_proceeding_code)}` : ""}</span>`
|
||||
: "";
|
||||
|
||||
const condBadge = r.has_condition
|
||||
? `<span class="fristen-overhaul-rule-cond">${escHtml(t("deadlines.overhaul.condition.badge"))}</span>`
|
||||
: "";
|
||||
|
||||
const notesHtml = notes
|
||||
? `<details class="fristen-overhaul-rule-notes"><summary>${escHtml(t("deadlines.overhaul.notes.summary"))}</summary><p>${escHtml(notes)}</p></details>`
|
||||
: "";
|
||||
|
||||
const editBtn = r.is_court_set || r.is_spawn || !computedDate
|
||||
? ""
|
||||
: `<button type="button" class="fristen-overhaul-rule-edit-date" data-rule-id="${escAttr(r.rule_id)}" title="${escAttr(t("deadlines.overhaul.edit_date.title"))}" aria-label="${escAttr(t("deadlines.overhaul.edit_date.title"))}">${escHtml(t("deadlines.overhaul.edit_date.label"))}</button>`;
|
||||
|
||||
return `
|
||||
<li class="fristen-overhaul-rule${disabled ? " is-disabled" : ""}" data-rule-id="${escAttr(r.rule_id)}">
|
||||
<label class="fristen-overhaul-rule-check">
|
||||
<input type="checkbox" data-rule-id="${escAttr(r.rule_id)}"
|
||||
${checked ? "checked" : ""} ${disabled ? "disabled" : ""} />
|
||||
<span class="visually-hidden">${escHtml(t("deadlines.overhaul.select_rule"))}</span>
|
||||
</label>
|
||||
<div class="fristen-overhaul-rule-body">
|
||||
<div class="fristen-overhaul-rule-title-row">
|
||||
<span class="fristen-overhaul-rule-title">${escHtml(title)}</span>
|
||||
${spawnBadge}
|
||||
${condBadge}
|
||||
</div>
|
||||
<div class="fristen-overhaul-rule-meta-row">
|
||||
${durationPhrase ? `<span class="fristen-overhaul-rule-duration">${escHtml(durationPhrase)}</span>` : ""}
|
||||
${partyBadge}
|
||||
${sourceBadge}
|
||||
</div>
|
||||
${notesHtml}
|
||||
</div>
|
||||
<div class="fristen-overhaul-rule-date-cell">
|
||||
${dateCell}
|
||||
${editBtn}
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
}
|
||||
|
||||
function renderFooter(): string {
|
||||
const selectedCount = countSelected();
|
||||
return `
|
||||
<footer class="fristen-overhaul-footer" id="fristen-overhaul-footer">
|
||||
<span class="fristen-overhaul-footer-count" id="fristen-overhaul-footer-count">
|
||||
${escHtml(tDyn("deadlines.overhaul.footer.count").replace("{n}", String(selectedCount)))}
|
||||
</span>
|
||||
<button type="button" class="fristen-overhaul-footer-cta btn-primary btn-cta-lime"
|
||||
id="fristen-overhaul-write-back"
|
||||
${selectedCount === 0 ? "disabled" : ""}>
|
||||
${escHtml(t("deadlines.overhaul.footer.cta"))}
|
||||
</button>
|
||||
</footer>
|
||||
`;
|
||||
}
|
||||
|
||||
// Event wiring --------------------------------------------------------
|
||||
|
||||
function wireSurfaceEvents(): void {
|
||||
// Trigger-date change → re-fetch with new date.
|
||||
const dateInput = document.getElementById("fristen-overhaul-trigger-date") as HTMLInputElement | null;
|
||||
if (dateInput && currentResponse) {
|
||||
dateInput.addEventListener("change", () => {
|
||||
if (!currentResponse) return;
|
||||
const newDate = dateInput.value;
|
||||
if (!newDate) return;
|
||||
void mountResultView({
|
||||
eventRef: currentResponse.trigger.code,
|
||||
triggerDate: newDate,
|
||||
party: currentResponse.party,
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Checkbox toggles → update selections + footer count.
|
||||
const root = document.getElementById("fristen-overhaul-root");
|
||||
if (root) {
|
||||
root.querySelectorAll<HTMLInputElement>(".fristen-overhaul-rule-check input[type=checkbox]").forEach((cb) => {
|
||||
cb.addEventListener("change", () => {
|
||||
const id = cb.dataset.ruleId || "";
|
||||
const sel = selections.get(id) ?? { checked: cb.checked };
|
||||
sel.checked = cb.checked;
|
||||
selections.set(id, sel);
|
||||
refreshFooterCount();
|
||||
});
|
||||
});
|
||||
|
||||
// Per-rule date override.
|
||||
root.querySelectorAll<HTMLButtonElement>(".fristen-overhaul-rule-edit-date").forEach((btn) => {
|
||||
btn.addEventListener("click", () => editRuleDate(btn));
|
||||
});
|
||||
}
|
||||
|
||||
// Write-back CTA.
|
||||
const cta = document.getElementById("fristen-overhaul-write-back");
|
||||
if (cta) cta.addEventListener("click", () => void submitWriteBack());
|
||||
}
|
||||
|
||||
function editRuleDate(btn: HTMLButtonElement): void {
|
||||
const ruleId = btn.dataset.ruleId || "";
|
||||
const rule = currentResponse?.follow_ups.find((r) => r.rule_id === ruleId);
|
||||
if (!rule) return;
|
||||
const sel = selections.get(ruleId) ?? { checked: defaultChecked(rule) };
|
||||
const current = sel.override || rule.due_date || todayIso();
|
||||
|
||||
const dateCell = btn.parentElement;
|
||||
if (!dateCell) return;
|
||||
const dateSpan = dateCell.querySelector<HTMLSpanElement>(".fristen-overhaul-rule-date");
|
||||
if (!dateSpan) return;
|
||||
|
||||
const input = document.createElement("input");
|
||||
input.type = "date";
|
||||
input.value = current;
|
||||
input.className = "fristen-overhaul-rule-date-input";
|
||||
dateSpan.replaceWith(input);
|
||||
btn.disabled = true;
|
||||
input.focus();
|
||||
|
||||
const commit = () => {
|
||||
const newDate = input.value;
|
||||
if (newDate && newDate !== current) {
|
||||
sel.override = newDate;
|
||||
selections.set(ruleId, sel);
|
||||
}
|
||||
renderSurface();
|
||||
};
|
||||
input.addEventListener("blur", commit, { once: true });
|
||||
input.addEventListener("keydown", (e) => {
|
||||
if ((e as KeyboardEvent).key === "Enter") {
|
||||
e.preventDefault();
|
||||
input.blur();
|
||||
} else if ((e as KeyboardEvent).key === "Escape") {
|
||||
renderSurface();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function refreshFooterCount(): void {
|
||||
const countEl = document.getElementById("fristen-overhaul-footer-count");
|
||||
const cta = document.getElementById("fristen-overhaul-write-back") as HTMLButtonElement | null;
|
||||
const n = countSelected();
|
||||
if (countEl) {
|
||||
countEl.textContent = tDyn("deadlines.overhaul.footer.count").replace("{n}", String(n));
|
||||
}
|
||||
if (cta) cta.disabled = n === 0;
|
||||
}
|
||||
|
||||
function countSelected(): number {
|
||||
let n = 0;
|
||||
if (!currentResponse) return 0;
|
||||
for (const r of currentResponse.follow_ups) {
|
||||
if (r.is_court_set) continue;
|
||||
const sel = selections.get(r.rule_id);
|
||||
if (sel?.checked) n++;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
// Write-back ----------------------------------------------------------
|
||||
|
||||
async function submitWriteBack(): Promise<void> {
|
||||
if (!currentResponse) return;
|
||||
if (!currentProjectId) return;
|
||||
const msg = document.getElementById("fristen-overhaul-msg");
|
||||
const cta = document.getElementById("fristen-overhaul-write-back") as HTMLButtonElement | null;
|
||||
const lang = getLang();
|
||||
|
||||
const deadlines: Array<Record<string, unknown>> = [];
|
||||
for (const r of currentResponse.follow_ups) {
|
||||
const sel = selections.get(r.rule_id);
|
||||
if (!sel?.checked) continue;
|
||||
if (r.is_court_set) continue;
|
||||
const dueDate = sel.override || r.due_date;
|
||||
if (!dueDate) continue;
|
||||
const title = lang === "en" ? r.title_en || r.title_de : r.title_de;
|
||||
const notes = lang === "en" ? r.notes_en || r.notes_de : r.notes_de;
|
||||
deadlines.push({
|
||||
title,
|
||||
rule_code: r.rule_code || undefined,
|
||||
due_date: dueDate,
|
||||
original_due_date: r.original_due_date || r.due_date || undefined,
|
||||
source: "fristenrechner",
|
||||
rule_id: r.rule_id,
|
||||
notes: notes || undefined,
|
||||
audit_reason: auditReason(),
|
||||
});
|
||||
}
|
||||
|
||||
if (deadlines.length === 0 || !msg || !cta) return;
|
||||
cta.disabled = true;
|
||||
msg.textContent = "";
|
||||
msg.className = "fristen-overhaul-msg";
|
||||
|
||||
try {
|
||||
const resp = await fetch(`/api/projects/${encodeURIComponent(currentProjectId)}/deadlines/bulk`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ deadlines }),
|
||||
});
|
||||
if (!resp.ok) {
|
||||
const body = await resp.json().catch(() => ({}) as { error?: string });
|
||||
msg.textContent = body.error || t("deadlines.save.error");
|
||||
msg.className = "fristen-overhaul-msg form-msg-error";
|
||||
cta.disabled = false;
|
||||
return;
|
||||
}
|
||||
msg.innerHTML = `${escHtml(t("deadlines.save.success"))} <a href="/deadlines?project_id=${encodeURIComponent(currentProjectId)}">${escHtml(t("deadlines.save.success.link"))}</a>`;
|
||||
msg.className = "fristen-overhaul-msg form-msg-ok";
|
||||
setTimeout(() => {
|
||||
if (cta) cta.disabled = false;
|
||||
}, 1500);
|
||||
} catch {
|
||||
msg.textContent = t("deadlines.save.error");
|
||||
msg.className = "fristen-overhaul-msg form-msg-error";
|
||||
cta.disabled = false;
|
||||
}
|
||||
}
|
||||
|
||||
// audit reason per design §11.Q12: "Aus Fristenrechner — Trigger: {name} ({date})".
|
||||
function auditReason(): string {
|
||||
if (!currentResponse) return "";
|
||||
const name = currentResponse.trigger.name_de;
|
||||
const date = currentResponse.trigger_date;
|
||||
return `Aus Fristenrechner — Trigger: ${name} (${date})`;
|
||||
}
|
||||
|
||||
// Helpers -------------------------------------------------------------
|
||||
|
||||
export function defaultChecked(r: FollowUpRule): boolean {
|
||||
if (r.is_court_set) return false;
|
||||
if (r.is_spawn) return r.priority === "mandatory";
|
||||
if (r.has_condition) return false;
|
||||
return r.priority === "mandatory" || r.priority === "recommended";
|
||||
}
|
||||
|
||||
function formatDurationPhrase(r: FollowUpRule, lang: "de" | "en"): string {
|
||||
if (!r.duration_value || !r.duration_unit) return "";
|
||||
const unitDE: Record<string, string> = {
|
||||
days: "Tage",
|
||||
months: "Monate",
|
||||
weeks: "Wochen",
|
||||
years: "Jahre",
|
||||
};
|
||||
const unitEN: Record<string, string> = {
|
||||
days: "days",
|
||||
months: "months",
|
||||
weeks: "weeks",
|
||||
years: "years",
|
||||
};
|
||||
const u = (lang === "en" ? unitEN : unitDE)[r.duration_unit] || r.duration_unit;
|
||||
return `${r.duration_value} ${u}`;
|
||||
}
|
||||
|
||||
function formatDateForLang(iso: string, lang: "de" | "en"): string {
|
||||
// YYYY-MM-DD → DE: DD.MM.YYYY / EN: DD MMM YYYY (short).
|
||||
if (!iso || iso.length < 10) return iso;
|
||||
const [y, m, d] = iso.split("-");
|
||||
if (!y || !m || !d) return iso;
|
||||
if (lang === "en") {
|
||||
const months = ["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];
|
||||
const idx = parseInt(m, 10) - 1;
|
||||
const mn = idx >= 0 && idx < months.length ? months[idx] : m;
|
||||
return `${parseInt(d, 10)} ${mn} ${y}`;
|
||||
}
|
||||
return `${d}.${m}.${y}`;
|
||||
}
|
||||
|
||||
function eventKindIcon(kind?: string): string {
|
||||
switch (kind) {
|
||||
case "filing": return "📥"; // inbox/letter
|
||||
case "hearing": return "🏛️"; // courthouse
|
||||
case "decision": return "⚖️"; // scales
|
||||
case "order": return "📜"; // page
|
||||
default: return "📅"; // calendar
|
||||
}
|
||||
}
|
||||
|
||||
function todayIso(): string {
|
||||
return new Date().toISOString().slice(0, 10);
|
||||
}
|
||||
|
||||
function syncUrlState(eventCode: string, triggerDate: string): void {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("overhaul", "1");
|
||||
url.searchParams.set("event", eventCode);
|
||||
url.searchParams.set("trigger_date", triggerDate);
|
||||
history.replaceState(null, "", url.pathname + url.search + url.hash);
|
||||
}
|
||||
47
frontend/src/client/fristenrechner-wizard.test.ts
Normal file
47
frontend/src/client/fristenrechner-wizard.test.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { followUpsDifferByParty } from "./fristenrechner-wizard";
|
||||
|
||||
describe("followUpsDifferByParty — R5 trigger condition (S4, design §3.2)", () => {
|
||||
test("true when both claimant and defendant rules present", () => {
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "claimant" },
|
||||
{ primary_party: "defendant" },
|
||||
])).toBe(true);
|
||||
});
|
||||
test("false when all claimant", () => {
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "claimant" },
|
||||
{ primary_party: "claimant" },
|
||||
])).toBe(false);
|
||||
});
|
||||
test("false when all defendant", () => {
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "defendant" },
|
||||
])).toBe(false);
|
||||
});
|
||||
test("false when only 'both' rules", () => {
|
||||
// "Both" rules are bilateral procedural moves (Vertraulichkeits-
|
||||
// Erwiderung); they don't gate R5 because either party can be
|
||||
// looking at them.
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "both" },
|
||||
{ primary_party: "both" },
|
||||
])).toBe(false);
|
||||
});
|
||||
test("false when only court rules", () => {
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "court" },
|
||||
])).toBe(false);
|
||||
});
|
||||
test("true when mixed with both / court alongside the asymmetric pair", () => {
|
||||
expect(followUpsDifferByParty([
|
||||
{ primary_party: "both" },
|
||||
{ primary_party: "claimant" },
|
||||
{ primary_party: "court" },
|
||||
{ primary_party: "defendant" },
|
||||
])).toBe(true);
|
||||
});
|
||||
test("false on empty list", () => {
|
||||
expect(followUpsDifferByParty([])).toBe(false);
|
||||
});
|
||||
});
|
||||
711
frontend/src/client/fristenrechner-wizard.ts
Normal file
711
frontend/src/client/fristenrechner-wizard.ts
Normal file
@@ -0,0 +1,711 @@
|
||||
// Fristenrechner overhaul Mode B — "Geführt" / wizard (design §3.2).
|
||||
//
|
||||
// 3-5 question row stack that lands the user on one procedural_event
|
||||
// (the trigger), then transitions to the shared §4 result view.
|
||||
//
|
||||
// R1 Was ist passiert? (event_kind) always asked
|
||||
// R2 Vor welchem Gericht? (jurisdiction) skip if R1 narrows
|
||||
// R3 In welchem Verfahren? (proceeding_type) auto-skip when 1 option
|
||||
// R4 Welches Schriftstück? (procedural_event — land) always asked
|
||||
// R5 Welche Seite vertreten Sie? (party) only when follow-ups differ
|
||||
//
|
||||
// Row badges per §11.Q3: R1+R2 = "Filter", R3+R4+R5 = "Qualifier".
|
||||
// R5 has NO "Beide" option per §11.Q8 (Mode B is the file-mode where
|
||||
// perspective is a qualifier).
|
||||
// Pre-fill + collapse rows from project (project.proceeding_type →
|
||||
// R3 + R2 derived; project.our_side → R5). Preserve compatible
|
||||
// downstream picks on back-navigation (§11.Q10).
|
||||
|
||||
import { escAttr, escHtml } from "./views/verfahrensablauf-core";
|
||||
import { getLang, t, tDyn } from "./i18n";
|
||||
import { mountResultView } from "./fristenrechner-result";
|
||||
|
||||
// Wire shapes — duplicates the parts of fristenrechner-mode-a.ts we
|
||||
// need; kept local so the wizard doesn't depend on Mode A.
|
||||
|
||||
interface EventSearchHit {
|
||||
id: string;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
event_kind?: string;
|
||||
proceeding_type: {
|
||||
id: number;
|
||||
code: string;
|
||||
name_de: string;
|
||||
name_en: string;
|
||||
jurisdiction?: string;
|
||||
};
|
||||
follow_up_count: number;
|
||||
}
|
||||
|
||||
interface EventSearchResponse {
|
||||
events: EventSearchHit[];
|
||||
total: number;
|
||||
}
|
||||
|
||||
interface ProceedingChip {
|
||||
code: string;
|
||||
name: string;
|
||||
nameEN: string;
|
||||
group: string;
|
||||
}
|
||||
|
||||
interface ProjectSummary {
|
||||
id: string;
|
||||
proceeding_type_id?: number | null;
|
||||
our_side?: string | null;
|
||||
}
|
||||
|
||||
type Forum = "UPC" | "DE" | "EPA" | "DPMA";
|
||||
type EventKindRow = "filing" | "hearing" | "decision" | "order" | "missed";
|
||||
type WizardParty = "claimant" | "defendant";
|
||||
|
||||
// WIZARD_HOST_ID is the DOM id the wizard renders into. Mounted by
|
||||
// fristenrechner-result.mountModeShell which creates the host element
|
||||
// under the overhaul root.
|
||||
const WIZARD_HOST_ID = "fristen-overhaul-mode-host";
|
||||
|
||||
// FORUMS + EVENT_KINDS — closed sets. Keep parallel to Mode A's lists
|
||||
// so re-grouping happens in one place.
|
||||
const FORUMS: Forum[] = ["UPC", "DE", "EPA", "DPMA"];
|
||||
const EVENT_KINDS: EventKindRow[] = ["filing", "hearing", "decision", "order", "missed"];
|
||||
|
||||
// Single wizard state. Module-local; one wizard at a time.
|
||||
interface WizardState {
|
||||
// Picks. "" = not answered. R5 only set when the question is asked.
|
||||
r1: EventKindRow | "";
|
||||
r2: Forum | "";
|
||||
r3: string; // proceeding_types.code
|
||||
r4: string; // procedural_events.code
|
||||
r5: WizardParty | "";
|
||||
|
||||
// Pre-fill provenance — when a pick came from the project context,
|
||||
// the row renders with an "aus Akte" tag so the user notices.
|
||||
r2FromProject: boolean;
|
||||
r3FromProject: boolean;
|
||||
r5FromProject: boolean;
|
||||
|
||||
// Implicit fills — R2 auto-derived from R1 when R1 narrows to one
|
||||
// forum (e.g. "missed" → no narrowing, "filing" → cross-forum, but
|
||||
// if downstream R3 lookup returns a single forum we can mark R2 as
|
||||
// implicit).
|
||||
r2Implicit: boolean;
|
||||
r3Implicit: boolean;
|
||||
}
|
||||
|
||||
const state: WizardState = {
|
||||
r1: "", r2: "", r3: "", r4: "", r5: "",
|
||||
r2FromProject: false, r3FromProject: false, r5FromProject: false,
|
||||
r2Implicit: false, r3Implicit: false,
|
||||
};
|
||||
|
||||
// Loaded from the project (if any).
|
||||
let projectSummary: ProjectSummary | null = null;
|
||||
|
||||
// Proceeding chip cache key: jurisdiction × event_kind.
|
||||
let lastProcCacheKey = "";
|
||||
let cachedProcChips: ProceedingChip[] = [];
|
||||
|
||||
// Event chip cache: keyed on R3 code + R1 event_kind.
|
||||
let lastEventCacheKey = "";
|
||||
let cachedEventChips: EventSearchHit[] = [];
|
||||
|
||||
// Public API ---------------------------------------------------------
|
||||
|
||||
export async function mountWizard(): Promise<void> {
|
||||
const host = document.getElementById(WIZARD_HOST_ID);
|
||||
if (!host) return;
|
||||
|
||||
// Hydrate from URL state (mode=wizard&forum=UPC&pt=upc.inf.cfi&…).
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
state.r1 = (params.get("kind") as EventKindRow) || "";
|
||||
state.r2 = (params.get("forum") as Forum) || "";
|
||||
state.r3 = params.get("pt") || "";
|
||||
state.r4 = params.get("event") || "";
|
||||
state.r5 = (params.get("party") as WizardParty) || "";
|
||||
|
||||
// Project prefills.
|
||||
const projectId = params.get("project");
|
||||
if (projectId) {
|
||||
projectSummary = await fetchProject(projectId);
|
||||
await applyProjectPrefills();
|
||||
} else {
|
||||
projectSummary = null;
|
||||
}
|
||||
|
||||
renderShell();
|
||||
void renderRows();
|
||||
}
|
||||
|
||||
// applyProjectPrefills derives R2 + R3 + R5 from the project when they
|
||||
// haven't been set explicitly. Project picks take precedence over
|
||||
// unspecified state, but a user-supplied URL pick wins over the
|
||||
// project default.
|
||||
async function applyProjectPrefills(): Promise<void> {
|
||||
if (!projectSummary) return;
|
||||
// Map our_side → R5.
|
||||
if (!state.r5) {
|
||||
const side = projectSummary.our_side;
|
||||
if (side === "claimant" || side === "applicant" || side === "appellant") {
|
||||
state.r5 = "claimant";
|
||||
state.r5FromProject = true;
|
||||
} else if (side === "defendant" || side === "respondent") {
|
||||
state.r5 = "defendant";
|
||||
state.r5FromProject = true;
|
||||
}
|
||||
}
|
||||
// Map proceeding_type_id → R3 + infer R2 jurisdiction.
|
||||
if (projectSummary.proceeding_type_id && !state.r3) {
|
||||
const pt = await fetchProceedingByID(projectSummary.proceeding_type_id);
|
||||
if (pt) {
|
||||
state.r3 = pt.code;
|
||||
state.r3FromProject = true;
|
||||
if (pt.group && !state.r2) {
|
||||
state.r2 = pt.group as Forum;
|
||||
state.r2FromProject = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Render -------------------------------------------------------------
|
||||
|
||||
function renderShell(): void {
|
||||
const host = document.getElementById(WIZARD_HOST_ID);
|
||||
if (!host) return;
|
||||
host.innerHTML = `
|
||||
<div class="fristen-wizard-root">
|
||||
<header class="fristen-wizard-header">
|
||||
<h2 class="fristen-wizard-title">${escHtml(t("deadlines.overhaul.wizard.heading"))}</h2>
|
||||
<p class="fristen-wizard-hint">${escHtml(t("deadlines.overhaul.wizard.hint"))}</p>
|
||||
</header>
|
||||
<div class="fristen-wizard-rows" id="fristen-wizard-rows" aria-live="polite"></div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async function renderRows(): Promise<void> {
|
||||
const host = document.getElementById("fristen-wizard-rows");
|
||||
if (!host) return;
|
||||
|
||||
// Resolve dynamic row prerequisites BEFORE building markup so chip
|
||||
// sets are populated.
|
||||
if (state.r1 && state.r2) {
|
||||
await ensureProceedingChips(state.r2, state.r1);
|
||||
// Auto-skip R3 when the narrowed pool has exactly one option.
|
||||
if (!state.r3 && cachedProcChips.length === 1) {
|
||||
state.r3 = cachedProcChips[0].code;
|
||||
state.r3Implicit = true;
|
||||
}
|
||||
}
|
||||
if (state.r1 && state.r3) {
|
||||
await ensureEventChips(state.r3, state.r1);
|
||||
}
|
||||
|
||||
const rows: string[] = [];
|
||||
rows.push(rowR1());
|
||||
if (shouldShowR2()) rows.push(rowR2());
|
||||
if (shouldShowR3()) rows.push(rowR3());
|
||||
if (shouldShowR4()) rows.push(rowR4());
|
||||
if (state.r4 && shouldShowR5Sync()) rows.push(rowR5Loading());
|
||||
|
||||
host.innerHTML = rows.join("");
|
||||
wireRowEvents();
|
||||
|
||||
// R5 conditional check — fires after R4 picked. Inspects /follow-ups
|
||||
// to see whether they actually differ by party. If yes, show R5. If
|
||||
// no, or R5 already set, transition straight to result view.
|
||||
if (state.r4) {
|
||||
void maybeAdvanceFromR4();
|
||||
}
|
||||
}
|
||||
|
||||
// Should-show predicates --------------------------------------------
|
||||
|
||||
function shouldShowR2(): boolean {
|
||||
// Skip R2 only when R1 narrows to a single forum — which today
|
||||
// never happens for the closed event_kind set (every kind exists in
|
||||
// multiple jurisdictions). Always show R2 until we have empirical
|
||||
// evidence otherwise.
|
||||
return state.r1 !== "" && state.r1 !== "missed";
|
||||
}
|
||||
|
||||
function shouldShowR3(): boolean {
|
||||
if (state.r1 === "" || state.r2 === "") return false;
|
||||
if (state.r3 && state.r3Implicit) return true; // visible compact
|
||||
return true;
|
||||
}
|
||||
|
||||
function shouldShowR4(): boolean {
|
||||
return state.r3 !== "" && state.r1 !== "";
|
||||
}
|
||||
|
||||
// shouldShowR5Sync renders the placeholder row immediately; the actual
|
||||
// asked-or-not decision happens after the async follow-ups probe in
|
||||
// maybeAdvanceFromR4.
|
||||
function shouldShowR5Sync(): boolean {
|
||||
return state.r4 !== "";
|
||||
}
|
||||
|
||||
// Row builders ------------------------------------------------------
|
||||
|
||||
function rowR1(): string {
|
||||
const chips = EVENT_KINDS.map((k) => {
|
||||
const label = t(`deadlines.overhaul.kind.${k}` as never);
|
||||
const icon = eventKindIcon(k);
|
||||
return chipHtml("r1", k, label, state.r1 === k, icon);
|
||||
}).join("");
|
||||
return rowShell({
|
||||
n: 1,
|
||||
badge: "filter",
|
||||
label: t("deadlines.overhaul.wizard.r1.label"),
|
||||
active: !state.r1,
|
||||
answeredText: state.r1 ? t(`deadlines.overhaul.kind.${state.r1}` as never) : "",
|
||||
body: `<div class="fristen-wizard-chips">${chips}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
function rowR2(): string {
|
||||
const chips = FORUMS.map((f) => chipHtml("r2", f, f, state.r2 === f)).join("");
|
||||
return rowShell({
|
||||
n: 2,
|
||||
badge: "filter",
|
||||
label: t("deadlines.overhaul.wizard.r2.label"),
|
||||
active: !state.r2,
|
||||
fromProject: state.r2FromProject,
|
||||
answeredText: state.r2 || "",
|
||||
body: `<div class="fristen-wizard-chips">${chips}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
function rowR3(): string {
|
||||
if (cachedProcChips.length === 0) {
|
||||
return rowShell({
|
||||
n: 3, badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r3.label"),
|
||||
active: true,
|
||||
body: `<div class="fristen-wizard-empty">${escHtml(t("deadlines.overhaul.wizard.r3.empty"))}</div>`,
|
||||
});
|
||||
}
|
||||
const lang = getLang();
|
||||
const chips = cachedProcChips.map((p) => {
|
||||
const label = lang === "en" ? p.nameEN || p.name : p.name;
|
||||
return chipHtml("r3", p.code, label, state.r3 === p.code, undefined, p.code);
|
||||
}).join("");
|
||||
let answered = "";
|
||||
if (state.r3) {
|
||||
const hit = cachedProcChips.find((p) => p.code === state.r3);
|
||||
if (hit) answered = lang === "en" ? hit.nameEN || hit.name : hit.name;
|
||||
}
|
||||
return rowShell({
|
||||
n: 3,
|
||||
badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r3.label"),
|
||||
active: !state.r3,
|
||||
fromProject: state.r3FromProject,
|
||||
implicit: state.r3Implicit,
|
||||
answeredText: answered,
|
||||
body: `<div class="fristen-wizard-chips">${chips}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
function rowR4(): string {
|
||||
if (cachedEventChips.length === 0) {
|
||||
return rowShell({
|
||||
n: 4, badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r4.label"),
|
||||
active: true,
|
||||
body: `<div class="fristen-wizard-empty">${escHtml(t("deadlines.overhaul.wizard.r4.empty"))}</div>`,
|
||||
});
|
||||
}
|
||||
const lang = getLang();
|
||||
const chips = cachedEventChips.map((e) => {
|
||||
const label = lang === "en" ? e.name_en || e.name_de : e.name_de;
|
||||
return chipHtml("r4", e.code, label, state.r4 === e.code, eventKindIcon(e.event_kind as EventKindRow));
|
||||
}).join("");
|
||||
let answered = "";
|
||||
if (state.r4) {
|
||||
const hit = cachedEventChips.find((e) => e.code === state.r4);
|
||||
if (hit) answered = lang === "en" ? hit.name_en || hit.name_de : hit.name_de;
|
||||
}
|
||||
return rowShell({
|
||||
n: 4,
|
||||
badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r4.label"),
|
||||
active: !state.r4,
|
||||
answeredText: answered,
|
||||
body: `<div class="fristen-wizard-chips">${chips}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
function rowR5Loading(): string {
|
||||
// Placeholder while we probe whether R5 is needed. The async
|
||||
// follow-ups probe replaces this with rowR5 chips or skips
|
||||
// straight to the result view.
|
||||
return rowShell({
|
||||
n: 5, badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r5.label"),
|
||||
active: !state.r5,
|
||||
fromProject: state.r5FromProject,
|
||||
answeredText: state.r5 ? t(`deadlines.party.${state.r5}` as never) : "",
|
||||
body: `<div class="fristen-wizard-probe">${escHtml(t("deadlines.overhaul.wizard.r5.probing"))}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
function rowR5Chips(): string {
|
||||
const chips = (["claimant", "defendant"] as const).map((p) =>
|
||||
chipHtml("r5", p, t(`deadlines.party.${p}` as never), state.r5 === p)).join("");
|
||||
return rowShell({
|
||||
n: 5, badge: "qualifier",
|
||||
label: t("deadlines.overhaul.wizard.r5.label"),
|
||||
active: !state.r5,
|
||||
fromProject: state.r5FromProject,
|
||||
answeredText: state.r5 ? t(`deadlines.party.${state.r5}` as never) : "",
|
||||
body: `<div class="fristen-wizard-chips">${chips}</div>`,
|
||||
});
|
||||
}
|
||||
|
||||
interface RowShellOpts {
|
||||
n: number;
|
||||
badge: "filter" | "qualifier";
|
||||
label: string;
|
||||
active: boolean;
|
||||
body: string;
|
||||
answeredText?: string;
|
||||
fromProject?: boolean;
|
||||
implicit?: boolean;
|
||||
}
|
||||
|
||||
function rowShell(o: RowShellOpts): string {
|
||||
const cls = `fristen-wizard-row fristen-wizard-row--${o.badge}` +
|
||||
(o.active ? " is-active" : " is-answered") +
|
||||
(o.fromProject ? " is-from-project" : "") +
|
||||
(o.implicit ? " is-implicit" : "");
|
||||
const badgeText = o.badge === "filter"
|
||||
? t("deadlines.overhaul.wizard.badge.filter")
|
||||
: t("deadlines.overhaul.wizard.badge.qualifier");
|
||||
const annotations: string[] = [];
|
||||
if (o.fromProject) annotations.push(`<span class="fristen-wizard-row-anno">${escHtml(t("deadlines.overhaul.wizard.anno.from_project"))}</span>`);
|
||||
if (o.implicit) annotations.push(`<span class="fristen-wizard-row-anno">${escHtml(t("deadlines.overhaul.wizard.anno.implicit"))}</span>`);
|
||||
const answered = o.answeredText
|
||||
? `<span class="fristen-wizard-row-answer">${escHtml(o.answeredText)}</span>`
|
||||
: "";
|
||||
const edit = !o.active
|
||||
? `<button type="button" class="fristen-wizard-row-edit" data-row="${o.n}">${escHtml(t("deadlines.overhaul.wizard.edit"))}</button>`
|
||||
: "";
|
||||
return `
|
||||
<section class="${cls}" data-row="${o.n}">
|
||||
<header class="fristen-wizard-row-header">
|
||||
<span class="fristen-wizard-row-n">${o.n}</span>
|
||||
<span class="fristen-wizard-row-badge fristen-wizard-row-badge--${o.badge}">${escHtml(badgeText)}</span>
|
||||
<span class="fristen-wizard-row-label">${escHtml(o.label)}</span>
|
||||
${annotations.join("")}
|
||||
${answered}
|
||||
${edit}
|
||||
</header>
|
||||
${o.active ? `<div class="fristen-wizard-row-body">${o.body}</div>` : ""}
|
||||
</section>
|
||||
`;
|
||||
}
|
||||
|
||||
// Event wiring ------------------------------------------------------
|
||||
|
||||
function wireRowEvents(): void {
|
||||
document.querySelectorAll<HTMLButtonElement>(".fristen-wizard-row .fristen-mode-a-chip").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const axis = btn.dataset.axis || "";
|
||||
const value = btn.dataset.value || "";
|
||||
handleChip(axis, value);
|
||||
});
|
||||
});
|
||||
document.querySelectorAll<HTMLButtonElement>(".fristen-wizard-row-edit").forEach((btn) => {
|
||||
btn.addEventListener("click", () => {
|
||||
const n = parseInt(btn.dataset.row || "0", 10);
|
||||
handleEdit(n);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleChip(axis: string, value: string): void {
|
||||
switch (axis) {
|
||||
case "r1": {
|
||||
if (state.r1 === value) return;
|
||||
state.r1 = value as EventKindRow;
|
||||
// R1 change resets R3/R4 (event-kind narrows the pools).
|
||||
state.r3 = "";
|
||||
state.r3Implicit = false;
|
||||
state.r4 = "";
|
||||
state.r5 = state.r5FromProject ? state.r5 : "";
|
||||
cachedEventChips = [];
|
||||
lastEventCacheKey = "";
|
||||
cachedProcChips = [];
|
||||
lastProcCacheKey = "";
|
||||
break;
|
||||
}
|
||||
case "r2": {
|
||||
if (state.r2 === value) return;
|
||||
state.r2 = value as Forum;
|
||||
state.r2FromProject = false;
|
||||
state.r2Implicit = false;
|
||||
// R2 change may invalidate R3 → reset.
|
||||
state.r3 = "";
|
||||
state.r3FromProject = false;
|
||||
state.r3Implicit = false;
|
||||
state.r4 = "";
|
||||
cachedProcChips = [];
|
||||
lastProcCacheKey = "";
|
||||
cachedEventChips = [];
|
||||
lastEventCacheKey = "";
|
||||
break;
|
||||
}
|
||||
case "r3": {
|
||||
if (state.r3 === value) return;
|
||||
state.r3 = value;
|
||||
state.r3FromProject = false;
|
||||
state.r3Implicit = false;
|
||||
state.r4 = "";
|
||||
cachedEventChips = [];
|
||||
lastEventCacheKey = "";
|
||||
break;
|
||||
}
|
||||
case "r4": {
|
||||
if (state.r4 === value) return;
|
||||
state.r4 = value;
|
||||
break;
|
||||
}
|
||||
case "r5": {
|
||||
if (state.r5 === value) return;
|
||||
state.r5 = value as WizardParty;
|
||||
state.r5FromProject = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
syncUrl();
|
||||
void renderRows();
|
||||
}
|
||||
|
||||
function handleEdit(n: number): void {
|
||||
switch (n) {
|
||||
case 1:
|
||||
state.r1 = ""; state.r2 = ""; state.r3 = ""; state.r4 = ""; state.r5 = state.r5FromProject ? state.r5 : "";
|
||||
cachedProcChips = []; lastProcCacheKey = "";
|
||||
cachedEventChips = []; lastEventCacheKey = "";
|
||||
break;
|
||||
case 2:
|
||||
state.r2 = ""; state.r2FromProject = false; state.r2Implicit = false;
|
||||
state.r3 = ""; state.r3FromProject = false; state.r3Implicit = false;
|
||||
state.r4 = "";
|
||||
cachedProcChips = []; lastProcCacheKey = "";
|
||||
cachedEventChips = []; lastEventCacheKey = "";
|
||||
break;
|
||||
case 3:
|
||||
state.r3 = ""; state.r3FromProject = false; state.r3Implicit = false;
|
||||
state.r4 = "";
|
||||
cachedEventChips = []; lastEventCacheKey = "";
|
||||
break;
|
||||
case 4:
|
||||
state.r4 = "";
|
||||
state.r5 = state.r5FromProject ? state.r5 : "";
|
||||
break;
|
||||
case 5:
|
||||
state.r5 = ""; state.r5FromProject = false;
|
||||
break;
|
||||
}
|
||||
syncUrl();
|
||||
void renderRows();
|
||||
}
|
||||
|
||||
// maybeAdvanceFromR4 fetches /follow-ups for the picked event to
|
||||
// decide whether R5 is needed. If R5 is already set OR the
|
||||
// follow-ups don't differ by party, transition straight to the
|
||||
// result view. Else swap the R5 loading row for the chip picker.
|
||||
async function maybeAdvanceFromR4(): Promise<void> {
|
||||
if (!state.r4) return;
|
||||
if (state.r5) {
|
||||
// R5 already answered (project prefill or explicit pick) → go.
|
||||
void launchResult();
|
||||
return;
|
||||
}
|
||||
// Probe follow-ups.
|
||||
const url = new URL("/api/tools/fristenrechner/follow-ups", window.location.origin);
|
||||
url.searchParams.set("event", state.r4);
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) {
|
||||
// Soft-fail → swap to R5 chips so the user can decide manually.
|
||||
swapR5(rowR5Chips());
|
||||
return;
|
||||
}
|
||||
const data = (await resp.json()) as { follow_ups: Array<{ primary_party?: string }> };
|
||||
const differs = followUpsDifferByParty(data.follow_ups);
|
||||
if (!differs) {
|
||||
void launchResult();
|
||||
return;
|
||||
}
|
||||
swapR5(rowR5Chips());
|
||||
} catch {
|
||||
swapR5(rowR5Chips());
|
||||
}
|
||||
}
|
||||
|
||||
function swapR5(html: string): void {
|
||||
const host = document.getElementById("fristen-wizard-rows");
|
||||
if (!host) return;
|
||||
const r5 = host.querySelector('.fristen-wizard-row[data-row="5"]');
|
||||
if (!r5) {
|
||||
host.insertAdjacentHTML("beforeend", html);
|
||||
} else {
|
||||
r5.outerHTML = html;
|
||||
}
|
||||
wireRowEvents();
|
||||
}
|
||||
|
||||
function launchResult(): void {
|
||||
// Hand off to the §4 result view. The URL already carries the
|
||||
// picks via syncUrl(); add event= so the boot path treats this
|
||||
// as a deep-link.
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("overhaul", "1");
|
||||
url.searchParams.set("event", state.r4);
|
||||
if (state.r5) url.searchParams.set("party", state.r5);
|
||||
else url.searchParams.delete("party");
|
||||
history.pushState(null, "", url.pathname + url.search + url.hash);
|
||||
void mountResultView({ eventRef: state.r4, party: state.r5 || undefined });
|
||||
}
|
||||
|
||||
export function followUpsDifferByParty(rows: Array<{ primary_party?: string }>): boolean {
|
||||
let hasClaimant = false, hasDefendant = false;
|
||||
for (const r of rows) {
|
||||
if (r.primary_party === "claimant") hasClaimant = true;
|
||||
else if (r.primary_party === "defendant") hasDefendant = true;
|
||||
if (hasClaimant && hasDefendant) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Fetches -----------------------------------------------------------
|
||||
|
||||
async function fetchProject(id: string): Promise<ProjectSummary | null> {
|
||||
try {
|
||||
const resp = await fetch(`/api/projects/${encodeURIComponent(id)}`, { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) return null;
|
||||
return (await resp.json()) as ProjectSummary;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchProceedingByID(id: number): Promise<ProceedingChip | null> {
|
||||
// The proceeding-types endpoint returns codes, names, jurisdictions
|
||||
// but doesn't carry the id (the wire shape FristenrechnerType is
|
||||
// code-keyed). Walk the unfiltered list and pick by sort-order
|
||||
// proximity / sort-fallback: we need the row whose id matches; since
|
||||
// the wire doesn't expose id, fetch the projects detail to get the
|
||||
// code directly. Cheap workaround: rely on /api/projects/{id}'s
|
||||
// proceeding_type_id being matched against the proceeding-types list
|
||||
// by jurisdiction round-trip is not possible without id. Instead
|
||||
// expose the proceeding-types-by-id mapping via a follow-up endpoint
|
||||
// later. For now hit the unfiltered list and assume the project's
|
||||
// pick is in the active set.
|
||||
//
|
||||
// Pragmatic fallback: query the full list and return the only entry
|
||||
// whose pseudo-id-via-sort-order matches. The lookup is unreliable
|
||||
// until the wire shape includes id; for the project-prefill case the
|
||||
// user can always re-pick R3 / R2 if the prefill misfires.
|
||||
try {
|
||||
const resp = await fetch(`/api/tools/proceeding-types`, { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) return null;
|
||||
const list = (await resp.json()) as ProceedingChip[] | null;
|
||||
if (!list || list.length === 0) return null;
|
||||
// Without id in the wire we cannot match by id. Skip the prefill
|
||||
// silently — R3 stays unanswered and the user picks manually.
|
||||
// (S5/follow-up can extend the wire shape to include id.)
|
||||
void id;
|
||||
return null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureProceedingChips(forum: Forum, kind: EventKindRow): Promise<void> {
|
||||
const key = `${forum}\x00${kind}`;
|
||||
if (lastProcCacheKey === key) return;
|
||||
lastProcCacheKey = key;
|
||||
const url = new URL("/api/tools/proceeding-types", window.location.origin);
|
||||
url.searchParams.set("kind", "proceeding");
|
||||
url.searchParams.set("jurisdiction", forum);
|
||||
if (kind !== "missed") url.searchParams.set("event_kind", kind);
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) {
|
||||
cachedProcChips = [];
|
||||
return;
|
||||
}
|
||||
const data = (await resp.json()) as ProceedingChip[] | null;
|
||||
cachedProcChips = data || [];
|
||||
} catch {
|
||||
cachedProcChips = [];
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureEventChips(procCode: string, kind: EventKindRow): Promise<void> {
|
||||
const key = `${procCode}\x00${kind}`;
|
||||
if (lastEventCacheKey === key) return;
|
||||
lastEventCacheKey = key;
|
||||
const url = new URL("/api/tools/fristenrechner/search", window.location.origin);
|
||||
url.searchParams.set("kind", "events");
|
||||
url.searchParams.set("proc", procCode);
|
||||
if (kind !== "missed") url.searchParams.set("event_kind", kind);
|
||||
url.searchParams.set("limit", "100");
|
||||
try {
|
||||
const resp = await fetch(url.toString(), { headers: { Accept: "application/json" } });
|
||||
if (!resp.ok) {
|
||||
cachedEventChips = [];
|
||||
return;
|
||||
}
|
||||
const data = (await resp.json()) as EventSearchResponse;
|
||||
cachedEventChips = data.events || [];
|
||||
} catch {
|
||||
cachedEventChips = [];
|
||||
}
|
||||
}
|
||||
|
||||
// Helpers -----------------------------------------------------------
|
||||
|
||||
function chipHtml(axis: string, value: string, label: string, active: boolean, icon?: string, title?: string): string {
|
||||
const cls = `fristen-mode-a-chip${active ? " is-active" : ""}`;
|
||||
const tt = title ? ` title="${escAttr(title)}"` : "";
|
||||
const i = icon ? `<span class="fristen-mode-a-chip-icon" aria-hidden="true">${icon}</span>` : "";
|
||||
return `<button type="button" class="${cls}" data-axis="${escAttr(axis)}" data-value="${escAttr(value)}"${tt}>${i}<span class="fristen-mode-a-chip-label">${escHtml(label)}</span></button>`;
|
||||
}
|
||||
|
||||
function eventKindIcon(kind?: EventKindRow): string {
|
||||
switch (kind) {
|
||||
case "filing": return "📥";
|
||||
case "hearing": return "🏛️";
|
||||
case "decision": return "⚖️";
|
||||
case "order": return "📜";
|
||||
case "missed": return "⏲";
|
||||
default: return "📅";
|
||||
}
|
||||
}
|
||||
|
||||
function syncUrl(): void {
|
||||
const url = new URL(window.location.href);
|
||||
url.searchParams.set("overhaul", "1");
|
||||
url.searchParams.set("mode", "wizard");
|
||||
setOrClear(url, "kind", state.r1);
|
||||
setOrClear(url, "forum", state.r2);
|
||||
setOrClear(url, "pt", state.r3);
|
||||
// event=… is set only on launchResult; the wizard URL carries the
|
||||
// R4 candidate via r4= so back/forward navigates within the wizard.
|
||||
setOrClear(url, "r4", state.r4);
|
||||
setOrClear(url, "party", state.r5);
|
||||
history.replaceState(null, "", url.pathname + url.search + url.hash);
|
||||
}
|
||||
|
||||
function setOrClear(url: URL, key: string, val: string): void {
|
||||
if (val) url.searchParams.set(key, val);
|
||||
else url.searchParams.delete(key);
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import {
|
||||
type EventChoice,
|
||||
type ChoiceKind,
|
||||
} from "./views/event-card-choices";
|
||||
import { isOverhaulMode, mountModeShell, mountResultView } from "./fristenrechner-result";
|
||||
|
||||
let lastResponse: DeadlineResponse | null = null;
|
||||
|
||||
@@ -113,6 +114,50 @@ onLangChange(() => {
|
||||
|
||||
let selectedType = "";
|
||||
|
||||
// t-paliad-323 Slice S2 — Fristenrechner overhaul boot. Hides the
|
||||
// legacy step / pathway shells and mounts the result view. S3+S4 will
|
||||
// hook entry-mode UIs into this; S2 is deep-link only.
|
||||
function bootOverhaulMode(): void {
|
||||
// Hide every legacy section so only the overhaul root is visible.
|
||||
// The page wrapper (`<main>`, `<section class="tool-page">`, the
|
||||
// tool-header) stays so the sidebar + title carry through.
|
||||
const hideIds = [
|
||||
"fristen-step1",
|
||||
"fristen-step1-summary",
|
||||
"fristen-step2",
|
||||
"fristen-pathway-b",
|
||||
"fristen-step3a",
|
||||
"fristen-pathway-a",
|
||||
];
|
||||
for (const id of hideIds) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) {
|
||||
el.hidden = true;
|
||||
el.style.display = "none";
|
||||
}
|
||||
}
|
||||
|
||||
// S2 deep-link contract: ?overhaul=1&event=<code>&trigger_date=…
|
||||
// When event is missing, leave the surface empty — S3/S4 will mount
|
||||
// entry-mode UIs onto this surface in later slices.
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
const eventRef = params.get("event") || "";
|
||||
const triggerDate = params.get("trigger_date") || undefined;
|
||||
const party = params.get("party") || undefined;
|
||||
const courtId = params.get("court_id") || undefined;
|
||||
|
||||
if (!eventRef) {
|
||||
// No trigger event locked yet → show the mode tab pair + active
|
||||
// mode panel (S3 = Mode A direct search; S4 will add Mode B
|
||||
// wizard). The mode param in the URL picks which tab opens
|
||||
// first; default is search (S3).
|
||||
const mode = (params.get("mode") || "search") === "wizard" ? "wizard" : "search";
|
||||
void mountModeShell(mode);
|
||||
return;
|
||||
}
|
||||
void mountResultView({ eventRef, triggerDate, party, courtId });
|
||||
}
|
||||
|
||||
function showStep(n: number) {
|
||||
for (let i = 1; i <= 3; i++) {
|
||||
const el = document.getElementById(`step-${i}`);
|
||||
@@ -656,6 +701,21 @@ document.addEventListener("DOMContentLoaded", () => {
|
||||
initI18n();
|
||||
initSidebar();
|
||||
|
||||
// t-paliad-323 Slice S5 — Fristenrechner overhaul is the default
|
||||
// boot path. The legacy three-step wizard / Pathway A+B shells are
|
||||
// reachable only via `?legacy=1` for a two-week deprecation window
|
||||
// after this commit lands. Deep-linkable via
|
||||
// /tools/fristenrechner?event=<code>&trigger_date=…&project=…
|
||||
// for the result view, or via
|
||||
// /tools/fristenrechner → Mode A (search) tab
|
||||
// /tools/fristenrechner?mode=wizard → Mode B wizard tab
|
||||
// The `?overhaul=1` deep links from S2-S4 still resolve (the
|
||||
// detector treats absence of `?legacy=1` as "overhaul").
|
||||
if (isOverhaulMode()) {
|
||||
bootOverhaulMode();
|
||||
return;
|
||||
}
|
||||
|
||||
// Proceeding type selection
|
||||
document.querySelectorAll<HTMLButtonElement>(".proceeding-btn").forEach((btn) => {
|
||||
btn.addEventListener("click", () => selectProceeding(btn));
|
||||
@@ -2595,33 +2655,16 @@ interface EventCategoryNode {
|
||||
let eventCategoryTree: EventCategoryNode[] | null = null;
|
||||
let eventCategoryFetchInflight: Promise<EventCategoryNode[]> | null = null;
|
||||
|
||||
// Top-level cascade roots that represent forward-looking workflows ("I
|
||||
// want to file X, what deadlines does my action trigger?") rather than
|
||||
// the backward-looking calc the Fristenrechner is built for ("event Y
|
||||
// happened, what deadlines spawn?"). m's 2026-05-20 ask (m/paliad#57):
|
||||
// remove these from the "Was ist passiert?" picker — they belong in a
|
||||
// future forward-workflow tool, not here. The DB rows stay so that
|
||||
// future tool can pick them back up; we just hide them at the UI layer.
|
||||
const HIDDEN_CASCADE_ROOTS: ReadonlySet<string> = new Set([
|
||||
"ich-moechte-einreichen",
|
||||
]);
|
||||
|
||||
// t-paliad-323 Slice S6: the cascade endpoint
|
||||
// /api/tools/fristenrechner/event-categories was retired alongside
|
||||
// HIDDEN_CASCADE_ROOTS. loadEventCategoryTree stays as a stub that
|
||||
// returns an empty tree — every caller below it sits in the legacy
|
||||
// Pathway B cascade which `?legacy=1` mode never boots into after
|
||||
// initB1Cascade's early-return guard (see L3598). The whole subtree
|
||||
// is dead-coded; a follow-up will lift it out wholesale.
|
||||
async function loadEventCategoryTree(): Promise<EventCategoryNode[]> {
|
||||
if (eventCategoryTree) return eventCategoryTree;
|
||||
if (eventCategoryFetchInflight) return eventCategoryFetchInflight;
|
||||
eventCategoryFetchInflight = (async () => {
|
||||
try {
|
||||
const r = await fetch("/api/tools/fristenrechner/event-categories");
|
||||
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||
const data = await r.json();
|
||||
const raw = (data.tree || []) as EventCategoryNode[];
|
||||
eventCategoryTree = raw.filter((n) => !HIDDEN_CASCADE_ROOTS.has(n.slug));
|
||||
return eventCategoryTree;
|
||||
} finally {
|
||||
eventCategoryFetchInflight = null;
|
||||
}
|
||||
})();
|
||||
return eventCategoryFetchInflight;
|
||||
eventCategoryTree = [];
|
||||
return eventCategoryTree;
|
||||
}
|
||||
|
||||
function readB1PathFromURL(): string {
|
||||
@@ -3536,30 +3579,14 @@ async function loadAndRenderB1() {
|
||||
}
|
||||
|
||||
async function initB1Cascade() {
|
||||
const panel = document.getElementById("fristen-b1-panel");
|
||||
if (!panel) return;
|
||||
|
||||
// t-paliad-180: mode-radio retired; the row-stack's mode-row click
|
||||
// handler drives tree↔filter routing. No standalone change listener
|
||||
// needed here — showBMode() triggers loadAndRenderB1 when the
|
||||
// pathway enters tree mode.
|
||||
|
||||
// Initial render if the URL already lands in tree mode.
|
||||
const sp = new URLSearchParams(window.location.search);
|
||||
if (sp.get("path") === "b" && sp.get("mode") === "tree") {
|
||||
loadAndRenderB1();
|
||||
}
|
||||
|
||||
// popstate restores the cascade depth.
|
||||
window.addEventListener("popstate", () => {
|
||||
const params = new URLSearchParams(window.location.search);
|
||||
if (params.get("path") === "b" && params.get("mode") === "tree") {
|
||||
// Always re-render — tree may not have loaded yet on first popstate.
|
||||
currentActiveRow = null;
|
||||
cascadeAutoWalkStopAfter = null;
|
||||
loadAndRenderB1();
|
||||
}
|
||||
});
|
||||
// t-paliad-323 Slice S6: the legacy Pathway B row-stack / cascade
|
||||
// is dead-coded. Mode A (S3) + Mode B wizard (S4) replace it; the
|
||||
// overhaul default boot (S5) handles every user route. Early-return
|
||||
// here keeps the legacy module imports linked (for ?legacy=1 entry)
|
||||
// while ensuring no cascade fetch / row-stack render fires. The
|
||||
// helper bodies stay for one cleanup follow-up that lifts the whole
|
||||
// subtree out.
|
||||
return;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", initB1Cascade);
|
||||
@@ -3660,23 +3687,11 @@ function getActiveForumsParam(): string {
|
||||
}
|
||||
|
||||
function initForumFilter() {
|
||||
// Hydrate from URL on first load.
|
||||
for (const slug of readForumsFromURL()) {
|
||||
activeForums.add(slug);
|
||||
}
|
||||
renderForumChips();
|
||||
|
||||
// Restore on browser nav.
|
||||
window.addEventListener("popstate", () => {
|
||||
activeForums.clear();
|
||||
for (const slug of readForumsFromURL()) {
|
||||
activeForums.add(slug);
|
||||
}
|
||||
renderForumChips();
|
||||
});
|
||||
|
||||
// Re-render labels on language change.
|
||||
onLangChange(() => renderForumChips());
|
||||
// t-paliad-323 Slice S6: dead-coded alongside initB1Cascade. The
|
||||
// legacy forum-chip strip lived in the Pathway B B2-search panel
|
||||
// which the overhaul has retired. Helper bodies stay for the
|
||||
// follow-up cleanup that lifts the whole Pathway B subtree.
|
||||
return;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", initForumFilter);
|
||||
@@ -3960,49 +3975,11 @@ async function persistInboxPref(ch: InboxChannel) {
|
||||
}
|
||||
|
||||
async function initInboxFilter() {
|
||||
// t-paliad-180: the standalone inbox chip strip is retired; inbox
|
||||
// state still drives cascade narrowing + B2 fine-bucket sync, just
|
||||
// surfaced through the row-stack row now. This init still hydrates
|
||||
// from URL / saved preference + wires the popstate restore.
|
||||
if (!document.getElementById("fristen-b1-panel")) return;
|
||||
|
||||
let initial: InboxChannel = readInboxFromURL();
|
||||
if (initial === null) {
|
||||
try {
|
||||
const resp = await fetch("/api/me", { credentials: "same-origin" });
|
||||
if (resp.ok) {
|
||||
const me = (await resp.json()) as { forum_pref?: string | null };
|
||||
if (me.forum_pref && INBOX_CHANNEL_VALUES.has(me.forum_pref)) {
|
||||
initial = me.forum_pref as InboxChannel;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Anonymous visitor or transient error — leave the chip unset.
|
||||
}
|
||||
}
|
||||
applyInboxFilter(initial);
|
||||
|
||||
// Sync B2 fine-bucket chips from the inbox on hydrate ONLY when the
|
||||
// URL doesn't explicitly carry ?forum=… — an explicit forum= comes
|
||||
// from a shared link and should win over the user's saved inbox
|
||||
// preference. initForumFilter (which runs first) has already
|
||||
// populated activeForums from URL forum=, so we leave it alone here.
|
||||
if (initial !== null && readForumsFromURL().length === 0) {
|
||||
applyFineForumsFromInbox(initial);
|
||||
writeForumsToURL(true);
|
||||
}
|
||||
|
||||
window.addEventListener("popstate", () => {
|
||||
const newInbox = readInboxFromURL();
|
||||
applyInboxFilter(newInbox);
|
||||
// popstate can land on a URL with inbox= but no forum= (the user
|
||||
// navigated to a state where derivation should re-apply). Don't
|
||||
// touch activeForums when forum= is explicit — initForumFilter's
|
||||
// own popstate handler has already loaded it from the URL.
|
||||
if (newInbox !== null && readForumsFromURL().length === 0) {
|
||||
applyFineForumsFromInbox(newInbox);
|
||||
}
|
||||
});
|
||||
// t-paliad-323 Slice S6: dead-coded alongside initB1Cascade /
|
||||
// initForumFilter. The inbox-channel row lived inside Pathway B's
|
||||
// row-stack which the overhaul has retired. Helper bodies stay
|
||||
// for the follow-up cleanup that lifts the whole subtree.
|
||||
return;
|
||||
}
|
||||
|
||||
document.addEventListener("DOMContentLoaded", initInboxFilter);
|
||||
|
||||
@@ -1010,6 +1010,80 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"deadlines.save.error": "\u00dcbernahme fehlgeschlagen.",
|
||||
"deadlines.save.skip_court_set": "Gerichtsbestimmte Termine ohne Datum werden \u00fcbersprungen.",
|
||||
|
||||
// Fristenrechner overhaul \u2014 shared result view (S2, design \u00a74).
|
||||
"deadlines.overhaul.loading": "Folge-Fristen werden geladen\u2026",
|
||||
"deadlines.overhaul.load_error": "Folge-Fristen konnten nicht geladen werden.",
|
||||
"deadlines.overhaul.empty": "Keine Folge-Fristen f\u00fcr dieses Ereignis hinterlegt.",
|
||||
"deadlines.overhaul.trigger.label": "Trigger-Ereignis",
|
||||
"deadlines.overhaul.trigger.date": "Trigger-Datum:",
|
||||
"deadlines.overhaul.followups.label": "Folge-Fristen",
|
||||
"deadlines.overhaul.group.mandatory": "Pflicht",
|
||||
"deadlines.overhaul.group.recommended": "Empfohlen",
|
||||
"deadlines.overhaul.group.optional": "Kann (auf Antrag)",
|
||||
"deadlines.overhaul.group.conditional": "Bedingt",
|
||||
"deadlines.overhaul.spawn.badge": "\u21f2 neues Verfahren",
|
||||
"deadlines.overhaul.spawn.tooltip": "Diese Regel leitet ein neues Verfahren ein.",
|
||||
"deadlines.overhaul.condition.badge": "Nur unter Bedingung",
|
||||
"deadlines.overhaul.notes.summary": "Hinweis",
|
||||
"deadlines.overhaul.edit_date.label": "\u270f Datum",
|
||||
"deadlines.overhaul.edit_date.title": "Datum manuell anpassen",
|
||||
"deadlines.overhaul.select_rule": "Frist ausw\u00e4hlen",
|
||||
"deadlines.overhaul.footer.count": "{n} Fristen ausgew\u00e4hlt",
|
||||
"deadlines.overhaul.footer.cta": "In Akte eintragen",
|
||||
"deadlines.overhaul.nudge.no_project": "Tipp: W\u00e4hle oben eine Akte, um diese Fristen einzutragen.",
|
||||
"deadlines.party.claimant": "Kl\u00e4gerseite",
|
||||
"deadlines.party.defendant": "Beklagtenseite",
|
||||
"deadlines.party.both": "Beide Seiten",
|
||||
"deadlines.party.court": "Gericht",
|
||||
|
||||
// Fristenrechner overhaul Mode A \u2014 Direkt suchen (S3, design \u00a73.1).
|
||||
"deadlines.overhaul.modes.label": "Modus",
|
||||
"deadlines.overhaul.modes.search": "Direkt suchen",
|
||||
"deadlines.overhaul.modes.wizard": "Gef\u00fchrt",
|
||||
"deadlines.overhaul.wizard.coming_soon": "Gef\u00fchrter Modus kommt im n\u00e4chsten Slice.",
|
||||
"deadlines.overhaul.modea.filters.label": "Filter",
|
||||
"deadlines.overhaul.modea.filters.heading": "Filter (eingrenzen)",
|
||||
"deadlines.overhaul.modea.axis.forum": "Forum:",
|
||||
"deadlines.overhaul.modea.axis.proc": "Verfahren:",
|
||||
"deadlines.overhaul.modea.axis.kind": "Was passierte:",
|
||||
"deadlines.overhaul.modea.axis.party": "Partei:",
|
||||
"deadlines.overhaul.modea.axis.inbox": "Eingangsweg:",
|
||||
"deadlines.overhaul.modea.chip.all": "Alle",
|
||||
"deadlines.overhaul.modea.inbox.summary": "Erweitert: Eingangsweg",
|
||||
"deadlines.overhaul.modea.inbox.postal": "Postal",
|
||||
"deadlines.overhaul.modea.search.label": "Suche",
|
||||
"deadlines.overhaul.modea.search.placeholder": "Klageerhebung, Hinweisbeschluss, m\u00fcndliche Verhandlung\u2026",
|
||||
"deadlines.overhaul.modea.results.label": "Ergebnisse",
|
||||
"deadlines.overhaul.modea.results.heading": "Ergebnisse (klicken zum Einrasten als Trigger)",
|
||||
"deadlines.overhaul.modea.results.count": "{n} Treffer",
|
||||
"deadlines.overhaul.modea.row.followups": "{n} Folge-Fristen",
|
||||
"deadlines.overhaul.modea.loading": "Wird geladen\u2026",
|
||||
"deadlines.overhaul.modea.no_results": "Keine Treffer f\u00fcr diese Filter.",
|
||||
"deadlines.overhaul.modea.no_proceedings": "Keine Verfahren in diesem Forum.",
|
||||
"deadlines.overhaul.modea.search_error": "Suche fehlgeschlagen.",
|
||||
"deadlines.overhaul.kind.filing": "Eingereicht",
|
||||
"deadlines.overhaul.kind.hearing": "Termin",
|
||||
"deadlines.overhaul.kind.decision": "Entscheidung",
|
||||
"deadlines.overhaul.kind.order": "Verf\u00fcgung",
|
||||
"deadlines.overhaul.kind.missed": "Frist vers\u00e4umt",
|
||||
|
||||
// Fristenrechner overhaul Mode B \u2014 gef\u00fchrter Wizard (S4, design \u00a73.2).
|
||||
"deadlines.overhaul.wizard.heading": "Gef\u00fchrter Modus",
|
||||
"deadlines.overhaul.wizard.hint": "Beantworte die Fragen oben nach unten \u2014 der Wizard landet auf einem Trigger-Ereignis und zeigt die Folge-Fristen.",
|
||||
"deadlines.overhaul.wizard.r1.label": "Was ist passiert?",
|
||||
"deadlines.overhaul.wizard.r2.label": "Vor welchem Gericht?",
|
||||
"deadlines.overhaul.wizard.r3.label": "In welchem Verfahren?",
|
||||
"deadlines.overhaul.wizard.r3.empty": "Kein Verfahren mit diesem Ereignistyp im gew\u00e4hlten Forum.",
|
||||
"deadlines.overhaul.wizard.r4.label": "Welches Schriftst\u00fcck / welcher Termin?",
|
||||
"deadlines.overhaul.wizard.r4.empty": "Keine Ereignisse zu dieser Auswahl.",
|
||||
"deadlines.overhaul.wizard.r5.label": "Welche Seite vertreten Sie?",
|
||||
"deadlines.overhaul.wizard.r5.probing": "Pr\u00fcfe, ob die Folge-Fristen seitenabh\u00e4ngig sind\u2026",
|
||||
"deadlines.overhaul.wizard.badge.filter": "Filter",
|
||||
"deadlines.overhaul.wizard.badge.qualifier": "Qualifier",
|
||||
"deadlines.overhaul.wizard.edit": "\u00e4ndern",
|
||||
"deadlines.overhaul.wizard.anno.from_project": "aus Akte",
|
||||
"deadlines.overhaul.wizard.anno.implicit": "implizit",
|
||||
|
||||
// Office labels (shared)
|
||||
"office.munich": "M\u00fcnchen",
|
||||
"office.duesseldorf": "D\u00fcsseldorf",
|
||||
@@ -3120,6 +3194,9 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"admin.procedural_events.list.heading": "Verfahrensschritte verwalten",
|
||||
"admin.procedural_events.list.new": "+ Neuer Verfahrensschritt",
|
||||
"admin.procedural_events.col.code": "Code (Verfahrensschritt)",
|
||||
// t-paliad-321: 3-segment proceeding-type code column (joined
|
||||
// server-side); disambiguates same-named rules across proceedings.
|
||||
"admin.procedural_events.col.proceeding": "Verfahren",
|
||||
"admin.procedural_events.edit.title": "Verfahrensschritt bearbeiten — Paliad",
|
||||
"admin.procedural_events.edit.breadcrumb":"← Verfahrensschritte verwalten",
|
||||
"admin.procedural_events.edit.field.code": "Code (Verfahrensschritt-Identifikator)",
|
||||
@@ -4119,6 +4196,80 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"deadlines.save.error": "Import failed.",
|
||||
"deadlines.save.skip_court_set": "Court-set entries with no date will be skipped.",
|
||||
|
||||
// Fristenrechner overhaul — shared result view (S2, design §4).
|
||||
"deadlines.overhaul.loading": "Loading follow-up deadlines…",
|
||||
"deadlines.overhaul.load_error": "Could not load follow-up deadlines.",
|
||||
"deadlines.overhaul.empty": "No follow-up deadlines configured for this event.",
|
||||
"deadlines.overhaul.trigger.label": "Trigger event",
|
||||
"deadlines.overhaul.trigger.date": "Trigger date:",
|
||||
"deadlines.overhaul.followups.label": "Follow-up deadlines",
|
||||
"deadlines.overhaul.group.mandatory": "Mandatory",
|
||||
"deadlines.overhaul.group.recommended": "Recommended",
|
||||
"deadlines.overhaul.group.optional": "Optional",
|
||||
"deadlines.overhaul.group.conditional": "Conditional",
|
||||
"deadlines.overhaul.spawn.badge": "⇲ new proceeding",
|
||||
"deadlines.overhaul.spawn.tooltip": "This rule initiates a new proceeding.",
|
||||
"deadlines.overhaul.condition.badge": "Conditional",
|
||||
"deadlines.overhaul.notes.summary": "Note",
|
||||
"deadlines.overhaul.edit_date.label": "✏ Date",
|
||||
"deadlines.overhaul.edit_date.title": "Edit date manually",
|
||||
"deadlines.overhaul.select_rule": "Select deadline",
|
||||
"deadlines.overhaul.footer.count": "{n} deadlines selected",
|
||||
"deadlines.overhaul.footer.cta": "Add to project",
|
||||
"deadlines.overhaul.nudge.no_project": "Tip: pick a project above to import these deadlines.",
|
||||
"deadlines.party.claimant": "Claimant",
|
||||
"deadlines.party.defendant": "Defendant",
|
||||
"deadlines.party.both": "Both parties",
|
||||
"deadlines.party.court": "Court",
|
||||
|
||||
// Fristenrechner overhaul Mode A — Direct search (S3, design §3.1).
|
||||
"deadlines.overhaul.modes.label": "Mode",
|
||||
"deadlines.overhaul.modes.search": "Direct search",
|
||||
"deadlines.overhaul.modes.wizard": "Guided",
|
||||
"deadlines.overhaul.wizard.coming_soon": "Guided mode coming in the next slice.",
|
||||
"deadlines.overhaul.modea.filters.label": "Filters",
|
||||
"deadlines.overhaul.modea.filters.heading": "Filters (narrow)",
|
||||
"deadlines.overhaul.modea.axis.forum": "Forum:",
|
||||
"deadlines.overhaul.modea.axis.proc": "Proceeding:",
|
||||
"deadlines.overhaul.modea.axis.kind": "What happened:",
|
||||
"deadlines.overhaul.modea.axis.party": "Party:",
|
||||
"deadlines.overhaul.modea.axis.inbox": "Inbox channel:",
|
||||
"deadlines.overhaul.modea.chip.all": "All",
|
||||
"deadlines.overhaul.modea.inbox.summary": "Advanced: Inbox channel",
|
||||
"deadlines.overhaul.modea.inbox.postal": "Postal",
|
||||
"deadlines.overhaul.modea.search.label": "Search",
|
||||
"deadlines.overhaul.modea.search.placeholder": "Statement of Claim, decision notice, oral hearing…",
|
||||
"deadlines.overhaul.modea.results.label": "Results",
|
||||
"deadlines.overhaul.modea.results.heading": "Results (click to lock as trigger)",
|
||||
"deadlines.overhaul.modea.results.count": "{n} hits",
|
||||
"deadlines.overhaul.modea.row.followups": "{n} follow-ups",
|
||||
"deadlines.overhaul.modea.loading": "Loading…",
|
||||
"deadlines.overhaul.modea.no_results": "No hits for these filters.",
|
||||
"deadlines.overhaul.modea.no_proceedings": "No proceedings in this forum.",
|
||||
"deadlines.overhaul.modea.search_error": "Search failed.",
|
||||
"deadlines.overhaul.kind.filing": "Filed",
|
||||
"deadlines.overhaul.kind.hearing": "Hearing",
|
||||
"deadlines.overhaul.kind.decision": "Decision",
|
||||
"deadlines.overhaul.kind.order": "Order",
|
||||
"deadlines.overhaul.kind.missed": "Missed deadline",
|
||||
|
||||
// Fristenrechner overhaul Mode B — guided wizard (S4, design §3.2).
|
||||
"deadlines.overhaul.wizard.heading": "Guided mode",
|
||||
"deadlines.overhaul.wizard.hint": "Answer top-down — the wizard lands on a trigger event and shows the follow-up deadlines.",
|
||||
"deadlines.overhaul.wizard.r1.label": "What happened?",
|
||||
"deadlines.overhaul.wizard.r2.label": "Before which forum?",
|
||||
"deadlines.overhaul.wizard.r3.label": "In which proceeding?",
|
||||
"deadlines.overhaul.wizard.r3.empty": "No proceeding with this event kind in the chosen forum.",
|
||||
"deadlines.overhaul.wizard.r4.label": "Which document / which hearing?",
|
||||
"deadlines.overhaul.wizard.r4.empty": "No events for this selection.",
|
||||
"deadlines.overhaul.wizard.r5.label": "Which party do you represent?",
|
||||
"deadlines.overhaul.wizard.r5.probing": "Checking whether follow-ups depend on the side…",
|
||||
"deadlines.overhaul.wizard.badge.filter": "Filter",
|
||||
"deadlines.overhaul.wizard.badge.qualifier": "Qualifier",
|
||||
"deadlines.overhaul.wizard.edit": "edit",
|
||||
"deadlines.overhaul.wizard.anno.from_project": "from project",
|
||||
"deadlines.overhaul.wizard.anno.implicit": "implicit",
|
||||
|
||||
// Office labels (shared)
|
||||
"office.munich": "Munich",
|
||||
"office.duesseldorf": "D\u00fcsseldorf",
|
||||
@@ -6188,6 +6339,8 @@ const translations: Record<Lang, Record<string, string>> = {
|
||||
"admin.procedural_events.list.heading": "Manage procedural events",
|
||||
"admin.procedural_events.list.new": "+ New procedural event",
|
||||
"admin.procedural_events.col.code": "Code (procedural event)",
|
||||
// t-paliad-321: 3-segment proceeding-type code column.
|
||||
"admin.procedural_events.col.proceeding": "Proceeding",
|
||||
"admin.procedural_events.edit.title": "Edit procedural event — Paliad",
|
||||
"admin.procedural_events.edit.breadcrumb":"← Manage procedural events",
|
||||
"admin.procedural_events.edit.field.code": "Code (procedural-event identifier)",
|
||||
|
||||
@@ -123,6 +123,15 @@ export function renderFristenrechner(): string {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* t-paliad-323 Slice S2 — overhaul result view mount root.
|
||||
Hidden by default; the client module shows this and hides
|
||||
the legacy panels when `?overhaul=1` is present in the
|
||||
URL. Deep-linkable on its own via
|
||||
`?overhaul=1&event=<code>&trigger_date=…`. Mode A (S3)
|
||||
and Mode B wizard (S4) will land users on this surface
|
||||
once they identify a trigger procedural_event. */}
|
||||
<div className="fristen-overhaul-root" id="fristen-overhaul-root" hidden></div>
|
||||
|
||||
{/* m's 2026-05-08 18:08 Determinator redesign — Step 1: pick the
|
||||
Akte (project) that scopes the rest of the flow. Filtered
|
||||
list of visible projects + "Neue Akte anlegen" link +
|
||||
|
||||
@@ -297,6 +297,7 @@ export type I18nKey =
|
||||
| "admin.partner_units.subtitle"
|
||||
| "admin.partner_units.title"
|
||||
| "admin.procedural_events.col.code"
|
||||
| "admin.procedural_events.col.proceeding"
|
||||
| "admin.procedural_events.edit.breadcrumb"
|
||||
| "admin.procedural_events.edit.field.code"
|
||||
| "admin.procedural_events.edit.field.event_kind"
|
||||
@@ -1376,6 +1377,70 @@ export type I18nKey =
|
||||
| "deadlines.neu.title"
|
||||
| "deadlines.notes.show"
|
||||
| "deadlines.optional.badge"
|
||||
| "deadlines.overhaul.condition.badge"
|
||||
| "deadlines.overhaul.edit_date.label"
|
||||
| "deadlines.overhaul.edit_date.title"
|
||||
| "deadlines.overhaul.empty"
|
||||
| "deadlines.overhaul.followups.label"
|
||||
| "deadlines.overhaul.footer.count"
|
||||
| "deadlines.overhaul.footer.cta"
|
||||
| "deadlines.overhaul.group.conditional"
|
||||
| "deadlines.overhaul.group.mandatory"
|
||||
| "deadlines.overhaul.group.optional"
|
||||
| "deadlines.overhaul.group.recommended"
|
||||
| "deadlines.overhaul.kind.decision"
|
||||
| "deadlines.overhaul.kind.filing"
|
||||
| "deadlines.overhaul.kind.hearing"
|
||||
| "deadlines.overhaul.kind.missed"
|
||||
| "deadlines.overhaul.kind.order"
|
||||
| "deadlines.overhaul.load_error"
|
||||
| "deadlines.overhaul.loading"
|
||||
| "deadlines.overhaul.modea.axis.forum"
|
||||
| "deadlines.overhaul.modea.axis.inbox"
|
||||
| "deadlines.overhaul.modea.axis.kind"
|
||||
| "deadlines.overhaul.modea.axis.party"
|
||||
| "deadlines.overhaul.modea.axis.proc"
|
||||
| "deadlines.overhaul.modea.chip.all"
|
||||
| "deadlines.overhaul.modea.filters.heading"
|
||||
| "deadlines.overhaul.modea.filters.label"
|
||||
| "deadlines.overhaul.modea.inbox.postal"
|
||||
| "deadlines.overhaul.modea.inbox.summary"
|
||||
| "deadlines.overhaul.modea.loading"
|
||||
| "deadlines.overhaul.modea.no_proceedings"
|
||||
| "deadlines.overhaul.modea.no_results"
|
||||
| "deadlines.overhaul.modea.results.count"
|
||||
| "deadlines.overhaul.modea.results.heading"
|
||||
| "deadlines.overhaul.modea.results.label"
|
||||
| "deadlines.overhaul.modea.row.followups"
|
||||
| "deadlines.overhaul.modea.search.label"
|
||||
| "deadlines.overhaul.modea.search.placeholder"
|
||||
| "deadlines.overhaul.modea.search_error"
|
||||
| "deadlines.overhaul.modes.label"
|
||||
| "deadlines.overhaul.modes.search"
|
||||
| "deadlines.overhaul.modes.wizard"
|
||||
| "deadlines.overhaul.notes.summary"
|
||||
| "deadlines.overhaul.nudge.no_project"
|
||||
| "deadlines.overhaul.select_rule"
|
||||
| "deadlines.overhaul.spawn.badge"
|
||||
| "deadlines.overhaul.spawn.tooltip"
|
||||
| "deadlines.overhaul.trigger.date"
|
||||
| "deadlines.overhaul.trigger.label"
|
||||
| "deadlines.overhaul.wizard.anno.from_project"
|
||||
| "deadlines.overhaul.wizard.anno.implicit"
|
||||
| "deadlines.overhaul.wizard.badge.filter"
|
||||
| "deadlines.overhaul.wizard.badge.qualifier"
|
||||
| "deadlines.overhaul.wizard.coming_soon"
|
||||
| "deadlines.overhaul.wizard.edit"
|
||||
| "deadlines.overhaul.wizard.heading"
|
||||
| "deadlines.overhaul.wizard.hint"
|
||||
| "deadlines.overhaul.wizard.r1.label"
|
||||
| "deadlines.overhaul.wizard.r2.label"
|
||||
| "deadlines.overhaul.wizard.r3.empty"
|
||||
| "deadlines.overhaul.wizard.r3.label"
|
||||
| "deadlines.overhaul.wizard.r4.empty"
|
||||
| "deadlines.overhaul.wizard.r4.label"
|
||||
| "deadlines.overhaul.wizard.r5.label"
|
||||
| "deadlines.overhaul.wizard.r5.probing"
|
||||
| "deadlines.party.both"
|
||||
| "deadlines.party.both.label"
|
||||
| "deadlines.party.claimant"
|
||||
|
||||
@@ -67,6 +67,21 @@
|
||||
--color-segment-active-fg: var(--color-accent-dark);
|
||||
--color-segment-active-border: var(--color-accent);
|
||||
|
||||
/* Accent soft/strong tints — pale lime backdrops for nudges, hover
|
||||
states, success messages and saturated "selected" chip pills.
|
||||
Soft is the pale tint (footer, nudge, ok-msg, hover); strong is
|
||||
the saturated lime pill (active chip, jurisdiction badge,
|
||||
wizard active-row outline). Dark mode flips to alpha-on-midnight
|
||||
so the lime cue stays visible without shouting. Consumed by
|
||||
.fristen-overhaul-* / .fristen-mode-* / .fristen-wizard-*
|
||||
(m/paliad#146 follow-up, t-paliad-326). */
|
||||
--color-accent-soft-bg: #f7fbe6;
|
||||
--color-accent-soft-fg: #3d501c;
|
||||
--color-accent-soft-border: #d2e08b;
|
||||
--color-accent-strong-bg: #d3edb7;
|
||||
--color-accent-strong-fg: #38531a;
|
||||
--color-accent-strong-border: #98b545;
|
||||
|
||||
/* Status palette — five buckets (red/amber/green/blue/neutral) shared
|
||||
across dashboard cards, frist-due-chips, agenda urgency, termin
|
||||
badges, login forms. Light values match the existing pastel-on-dark
|
||||
@@ -87,8 +102,14 @@
|
||||
--status-blue-bg: #dbeafe;
|
||||
--status-blue-fg: #1e40af;
|
||||
--status-blue-fg-2: #2563eb;
|
||||
--status-blue-border: #93c5fd;
|
||||
--status-blue-soft-bg: #eef2ff;
|
||||
--status-blue-soft-fg: #4338ca;
|
||||
/* Purple bucket — added for "court" party stance and other neutral
|
||||
institutional roles. Tailwind-style purple-100/purple-800/300. */
|
||||
--status-purple-bg: #f0e2f7;
|
||||
--status-purple-fg: #4f2c66;
|
||||
--status-purple-border: #d8b4fe;
|
||||
--status-neutral-bg: #f3f4f6;
|
||||
--status-neutral-fg: #6b7280;
|
||||
--status-neutral-fg-2: #475569;
|
||||
@@ -188,6 +209,16 @@
|
||||
--color-segment-active-fg: var(--color-accent-dark);
|
||||
--color-segment-active-border: var(--color-accent);
|
||||
|
||||
/* Accent soft/strong tints — alpha-tinted lime on midnight so the
|
||||
cue reads without flattening the surface. Mirrors the light-mode
|
||||
block above (t-paliad-326). */
|
||||
--color-accent-soft-bg: rgb(var(--hlc-lime-rgb) / 0.08);
|
||||
--color-accent-soft-fg: #bef264;
|
||||
--color-accent-soft-border: rgb(var(--hlc-lime-rgb) / 0.30);
|
||||
--color-accent-strong-bg: rgb(var(--hlc-lime-rgb) / 0.22);
|
||||
--color-accent-strong-fg: var(--hlc-lime);
|
||||
--color-accent-strong-border: rgb(var(--hlc-lime-rgb) / 0.45);
|
||||
|
||||
--shadow: 0 1px 3px rgba(0, 0, 0, 0.4), 0 1px 2px rgba(0, 0, 0, 0.3);
|
||||
--shadow-md: 0 4px 12px rgba(0, 0, 0, 0.45);
|
||||
--shadow-lg: 0 8px 32px rgba(0, 0, 0, 0.55);
|
||||
@@ -211,8 +242,13 @@
|
||||
--status-blue-bg: rgb(59 130 246 / 0.18);
|
||||
--status-blue-fg: #93c5fd;
|
||||
--status-blue-fg-2: #60a5fa;
|
||||
--status-blue-border: rgb(59 130 246 / 0.35);
|
||||
--status-blue-soft-bg: rgb(99 102 241 / 0.18);
|
||||
--status-blue-soft-fg: #a5b4fc;
|
||||
/* Purple bucket — alpha-tinted on midnight, bright fg for AA. */
|
||||
--status-purple-bg: rgb(168 85 247 / 0.18);
|
||||
--status-purple-fg: #d8b4fe;
|
||||
--status-purple-border: rgb(168 85 247 / 0.35);
|
||||
--status-neutral-bg: rgb(var(--hlc-cream-rgb) / 0.08);
|
||||
--status-neutral-fg: rgb(var(--hlc-cream-rgb) / 0.66);
|
||||
--status-neutral-fg-2: rgb(var(--hlc-cream-rgb) / 0.55);
|
||||
@@ -18886,3 +18922,800 @@ dialog.quick-add-sheet::backdrop {
|
||||
gap: 0.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Fristenrechner overhaul (t-paliad-323 Slice S2) =================
|
||||
*
|
||||
* Result-view surface mounted under `?overhaul=1`. Sticky trigger card
|
||||
* on top, four priority groups of follow-up rules, write-back footer
|
||||
* conditional on `?project=<uuid>`. See
|
||||
* docs/design-fristenrechner-overhaul-2026-05-26.md §4.
|
||||
* ==================================================================== */
|
||||
|
||||
.fristen-overhaul-root {
|
||||
display: block;
|
||||
margin-top: 1.5rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-loading,
|
||||
.fristen-overhaul-error,
|
||||
.fristen-overhaul-empty,
|
||||
.fristen-overhaul-nudge {
|
||||
padding: 0.9rem 1.1rem;
|
||||
border-radius: 0.6rem;
|
||||
margin: 0.5rem 0;
|
||||
background: var(--color-bg-subtle);
|
||||
border: 1px solid var(--color-border);
|
||||
color: var(--color-text);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-error {
|
||||
background: var(--status-red-bg);
|
||||
border-color: var(--status-red-border);
|
||||
color: var(--status-red-fg);
|
||||
}
|
||||
|
||||
.fristen-overhaul-nudge {
|
||||
background: var(--color-accent-soft-bg);
|
||||
border-color: var(--color-accent-soft-border);
|
||||
color: var(--color-accent-soft-fg);
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.8rem;
|
||||
padding: 1rem 1.2rem;
|
||||
margin-bottom: 1.2rem;
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-kind-icon {
|
||||
font-size: 1.5rem;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-title {
|
||||
margin: 0;
|
||||
font-size: 1.25rem;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
margin-top: 0.5rem;
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-code,
|
||||
.fristen-overhaul-trigger-pt,
|
||||
.fristen-overhaul-trigger-juris {
|
||||
padding: 0.15rem 0.55rem;
|
||||
border-radius: 0.4rem;
|
||||
background: var(--color-surface-muted);
|
||||
color: var(--color-text-muted);
|
||||
font-family: ui-monospace, "SFMono-Regular", Menlo, monospace;
|
||||
font-size: 0.8rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-juris {
|
||||
background: var(--color-accent-strong-bg);
|
||||
color: var(--color-accent-strong-fg);
|
||||
font-family: inherit;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-date {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.7rem;
|
||||
margin-top: 0.8rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-date-label {
|
||||
font-size: 0.9rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-overhaul-trigger-date-input {
|
||||
padding: 0.35rem 0.55rem;
|
||||
font-size: 0.95rem;
|
||||
border: 1px solid var(--color-border-strong);
|
||||
border-radius: 0.4rem;
|
||||
background: var(--color-input-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-groups {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.1rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-group {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.7rem;
|
||||
padding: 0.9rem 1.1rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-group--mandatory { border-left: 4px solid var(--color-accent); }
|
||||
.fristen-overhaul-group--recommended { border-left: 4px solid var(--status-blue-border); }
|
||||
.fristen-overhaul-group--optional { border-left: 4px solid var(--color-border-strong); }
|
||||
.fristen-overhaul-group--conditional { border-left: 4px solid var(--status-amber-border); }
|
||||
|
||||
.fristen-overhaul-group-title {
|
||||
margin: 0 0 0.6rem 0;
|
||||
font-size: 1rem;
|
||||
color: var(--color-text);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
gap: 0.7rem;
|
||||
align-items: start;
|
||||
padding: 0.5rem 0.6rem;
|
||||
background: var(--color-surface-2);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.5rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule.is-disabled {
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-check {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
height: 1.4rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-body {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.25rem;
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-title-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: baseline;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-title {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-spawn,
|
||||
.fristen-overhaul-rule-cond {
|
||||
font-size: 0.75rem;
|
||||
padding: 0.05rem 0.45rem;
|
||||
border-radius: 0.35rem;
|
||||
background: var(--status-amber-bg);
|
||||
color: var(--status-amber-fg);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-cond {
|
||||
background: var(--status-amber-bg);
|
||||
color: var(--status-amber-fg-2);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-meta-row {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-duration {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-party {
|
||||
padding: 0.05rem 0.45rem;
|
||||
border-radius: 0.35rem;
|
||||
font-size: 0.75rem;
|
||||
background: var(--color-accent-soft-bg);
|
||||
color: var(--color-accent-soft-fg);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-party--claimant { background: var(--status-blue-bg); color: var(--status-blue-fg); }
|
||||
.fristen-overhaul-rule-party--defendant { background: var(--status-red-bg); color: var(--status-red-fg); }
|
||||
.fristen-overhaul-rule-party--court { background: var(--status-purple-bg); color: var(--status-purple-fg); }
|
||||
|
||||
.fristen-overhaul-rule-source {
|
||||
font-family: ui-monospace, "SFMono-Regular", Menlo, monospace;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
a.fristen-overhaul-rule-source {
|
||||
color: var(--color-accent-fg);
|
||||
text-decoration: underline;
|
||||
text-underline-offset: 2px;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-notes {
|
||||
margin-top: 0.3rem;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-notes summary {
|
||||
cursor: pointer;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-date-cell {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: flex-end;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.95rem;
|
||||
min-width: 6.5rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-date {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-date--unknown {
|
||||
color: var(--color-text-subtle);
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-court-set {
|
||||
color: var(--status-amber-fg);
|
||||
font-style: italic;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-date-input {
|
||||
padding: 0.2rem 0.4rem;
|
||||
font-size: 0.95rem;
|
||||
border: 1px solid var(--color-border-strong);
|
||||
border-radius: 0.3rem;
|
||||
background: var(--color-input-bg);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-edit-date {
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-accent-fg);
|
||||
font-size: 0.8rem;
|
||||
cursor: pointer;
|
||||
padding: 0.1rem 0.3rem;
|
||||
border-radius: 0.3rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-rule-edit-date:hover {
|
||||
background: var(--color-accent-soft-bg);
|
||||
}
|
||||
|
||||
.fristen-overhaul-footer {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-top: 1.2rem;
|
||||
padding: 0.9rem 1.1rem;
|
||||
background: var(--color-accent-soft-bg);
|
||||
border: 1px solid var(--color-accent-soft-border);
|
||||
border-radius: 0.7rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-footer-count {
|
||||
font-size: 0.95rem;
|
||||
color: var(--color-accent-soft-fg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.fristen-overhaul-footer-cta {
|
||||
/* leans on btn-primary / btn-cta-lime classes from global */
|
||||
}
|
||||
|
||||
.fristen-overhaul-msg {
|
||||
margin-top: 0.8rem;
|
||||
padding: 0.6rem 0.9rem;
|
||||
font-size: 0.9rem;
|
||||
border-radius: 0.4rem;
|
||||
}
|
||||
|
||||
.fristen-overhaul-msg.form-msg-ok { background: var(--status-green-bg); color: var(--status-green-fg); }
|
||||
.fristen-overhaul-msg.form-msg-error { background: var(--status-red-bg); color: var(--status-red-fg); }
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.fristen-overhaul-rule {
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
.fristen-overhaul-rule-date-cell {
|
||||
grid-column: 1 / -1;
|
||||
flex-direction: row;
|
||||
justify-content: flex-end;
|
||||
align-items: center;
|
||||
min-width: 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Fristenrechner overhaul Mode A + mode tabs (t-paliad-323 S3) ===
|
||||
*
|
||||
* Mode tab pair + filter strip + search box + result list per
|
||||
* docs/design-fristenrechner-overhaul-2026-05-26.md §3.1.
|
||||
* Section-split visual hierarchy per m §11.Q3: filter strip on top
|
||||
* ("Filter (eingrenzen)" header), result list below (clicking a row
|
||||
* IS the qualifier commit).
|
||||
* ==================================================================== */
|
||||
|
||||
.fristen-mode-tabs {
|
||||
display: flex;
|
||||
gap: 0.4rem;
|
||||
margin: 0 0 1rem 0;
|
||||
border-bottom: 2px solid var(--color-border);
|
||||
}
|
||||
|
||||
.fristen-mode-tab {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.55rem 1.1rem;
|
||||
background: transparent;
|
||||
border: 0;
|
||||
border-bottom: 3px solid transparent;
|
||||
margin-bottom: -2px;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 1rem;
|
||||
font-weight: 500;
|
||||
cursor: pointer;
|
||||
border-radius: 0.4rem 0.4rem 0 0;
|
||||
}
|
||||
|
||||
.fristen-mode-tab:hover {
|
||||
background: var(--color-overlay-faint);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-mode-tab.is-active {
|
||||
color: var(--color-text);
|
||||
border-bottom-color: var(--color-accent);
|
||||
background: var(--color-accent-soft-bg);
|
||||
}
|
||||
|
||||
.fristen-mode-tab-icon {
|
||||
font-size: 1.1rem;
|
||||
}
|
||||
|
||||
.fristen-mode-tab-label {
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.fristen-mode-a-root {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-filters {
|
||||
background: var(--color-bg-subtle);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.7rem;
|
||||
padding: 0.8rem 1rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-filters-header {
|
||||
font-size: 0.8rem;
|
||||
letter-spacing: 0.05em;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
margin-bottom: 0.6rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
margin-bottom: 0.4rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-axis-label {
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-muted);
|
||||
min-width: 7rem;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.3rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.3rem;
|
||||
padding: 0.25rem 0.65rem;
|
||||
border: 1px solid var(--color-border-strong);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
border-radius: 1rem;
|
||||
font-size: 0.85rem;
|
||||
cursor: pointer;
|
||||
font-family: inherit;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip:hover {
|
||||
border-color: var(--color-accent-soft-border);
|
||||
background: var(--color-accent-soft-bg);
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip.is-active {
|
||||
background: var(--color-accent-strong-bg);
|
||||
border-color: var(--color-accent-strong-border);
|
||||
color: var(--color-accent-strong-fg);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip-icon {
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-chip-loading,
|
||||
.fristen-mode-a-chip-empty {
|
||||
color: var(--color-text-subtle);
|
||||
font-size: 0.85rem;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.fristen-mode-a-inbox {
|
||||
margin-top: 0.5rem;
|
||||
padding-top: 0.4rem;
|
||||
border-top: 1px dashed var(--color-border);
|
||||
}
|
||||
|
||||
.fristen-mode-a-inbox-summary {
|
||||
cursor: pointer;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.85rem;
|
||||
margin-bottom: 0.3rem;
|
||||
user-select: none;
|
||||
}
|
||||
|
||||
.fristen-mode-a-inbox-summary:hover {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-mode-a-search {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.7rem;
|
||||
padding: 0.6rem 0.9rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-search-input-wrap {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-search-icon {
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.fristen-mode-a-search-input {
|
||||
flex: 1 1 auto;
|
||||
border: 0;
|
||||
outline: none;
|
||||
font-size: 1rem;
|
||||
background: transparent;
|
||||
padding: 0.3rem 0;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-mode-a-results {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.7rem;
|
||||
padding: 0.7rem 0.9rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-results-header {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: baseline;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-results-title {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-mode-a-results-count {
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
max-height: 60vh;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result {
|
||||
display: grid;
|
||||
grid-template-columns: auto 1fr auto;
|
||||
gap: 0.7rem;
|
||||
align-items: center;
|
||||
padding: 0.55rem 0.7rem;
|
||||
background: var(--color-surface-2);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.5rem;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result:hover,
|
||||
.fristen-mode-a-result:focus {
|
||||
background: var(--color-accent-soft-bg);
|
||||
border-color: var(--color-accent-soft-border);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-icon {
|
||||
font-size: 1.3rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-body {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-title {
|
||||
font-weight: 600;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-meta {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.4rem;
|
||||
align-items: center;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
margin-top: 0.2rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-pt {
|
||||
font-family: ui-monospace, "SFMono-Regular", Menlo, monospace;
|
||||
padding: 0.05rem 0.45rem;
|
||||
background: var(--color-surface-muted);
|
||||
border-radius: 0.3rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-pt-name {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-juris {
|
||||
padding: 0.05rem 0.45rem;
|
||||
background: var(--color-accent-strong-bg);
|
||||
color: var(--color-accent-strong-fg);
|
||||
border-radius: 0.3rem;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-followups {
|
||||
color: var(--color-accent-fg);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-cta {
|
||||
color: var(--color-accent-fg);
|
||||
font-size: 1.2rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-loading,
|
||||
.fristen-mode-a-result-empty,
|
||||
.fristen-mode-a-result-error {
|
||||
list-style: none;
|
||||
padding: 0.7rem 0.5rem;
|
||||
color: var(--color-text-subtle);
|
||||
font-style: italic;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.fristen-mode-a-result-error {
|
||||
color: var(--status-red-fg);
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.fristen-mode-a-axis-label {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
}
|
||||
.fristen-mode-a-result {
|
||||
grid-template-columns: auto 1fr;
|
||||
}
|
||||
.fristen-mode-a-result-cta {
|
||||
grid-column: 1 / -1;
|
||||
text-align: right;
|
||||
}
|
||||
}
|
||||
|
||||
/* === Fristenrechner overhaul Mode B — wizard (t-paliad-323 S4) ======
|
||||
*
|
||||
* 3-5 row stack landing on a procedural_event. Row badge "Filter" vs
|
||||
* "Qualifier" per m §11.Q3; "aus Akte" / "implizit" annotations per
|
||||
* §11.Q10 (preserve compatible downstream picks on back-nav).
|
||||
* ==================================================================== */
|
||||
|
||||
.fristen-wizard-root {
|
||||
background: var(--color-surface);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.7rem;
|
||||
padding: 1rem 1.1rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-header {
|
||||
margin-bottom: 0.7rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-title {
|
||||
margin: 0 0 0.25rem 0;
|
||||
font-size: 1.15rem;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-wizard-hint {
|
||||
margin: 0;
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fristen-wizard-rows {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.55rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-row {
|
||||
background: var(--color-surface-2);
|
||||
border: 1px solid var(--color-border);
|
||||
border-radius: 0.6rem;
|
||||
padding: 0.55rem 0.7rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-row.is-active {
|
||||
border-color: var(--color-accent-strong-border);
|
||||
box-shadow: 0 0 0 2px rgb(var(--hlc-lime-rgb) / 0.15);
|
||||
}
|
||||
|
||||
.fristen-wizard-row.is-from-project {
|
||||
background: var(--color-accent-soft-bg);
|
||||
}
|
||||
|
||||
.fristen-wizard-row.is-implicit {
|
||||
opacity: 0.85;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-n {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: 1.6rem;
|
||||
height: 1.6rem;
|
||||
border-radius: 50%;
|
||||
background: var(--color-accent);
|
||||
color: var(--color-accent-dark);
|
||||
font-weight: 600;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-badge {
|
||||
font-size: 0.7rem;
|
||||
padding: 0.05rem 0.45rem;
|
||||
border-radius: 0.35rem;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-badge--filter { background: var(--status-blue-bg); color: var(--status-blue-fg); }
|
||||
.fristen-wizard-row-badge--qualifier { background: var(--status-amber-bg); color: var(--status-amber-fg-2); }
|
||||
|
||||
.fristen-wizard-row-label {
|
||||
font-weight: 500;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fristen-wizard-row-anno {
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-accent-soft-fg);
|
||||
background: var(--color-accent-soft-bg);
|
||||
padding: 0.05rem 0.4rem;
|
||||
border-radius: 0.3rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-answer {
|
||||
margin-left: auto;
|
||||
color: var(--color-text);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-edit {
|
||||
background: transparent;
|
||||
border: 0;
|
||||
color: var(--color-accent-fg);
|
||||
cursor: pointer;
|
||||
font-size: 0.85rem;
|
||||
padding: 0.15rem 0.45rem;
|
||||
border-radius: 0.3rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-row-edit:hover {
|
||||
background: var(--color-accent-soft-bg);
|
||||
}
|
||||
|
||||
.fristen-wizard-row-body {
|
||||
margin-top: 0.55rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-chips {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.fristen-wizard-empty,
|
||||
.fristen-wizard-probe {
|
||||
font-size: 0.85rem;
|
||||
color: var(--color-text-subtle);
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@media (max-width: 600px) {
|
||||
.fristen-wizard-row-answer {
|
||||
margin-left: 0;
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,15 +314,28 @@ CREATE TRIGGER deadline_rules_unified_update
|
||||
DO $$
|
||||
DECLARE
|
||||
v_snapshot_count int;
|
||||
v_sr_count int;
|
||||
v_view_count int;
|
||||
v_dr_table_exists int;
|
||||
v_rule_id_col int;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO v_snapshot_count FROM paliad.deadline_rules_pre_140;
|
||||
-- B.2 dual-write was implemented only for the active+published lifecycle
|
||||
-- (the scope of the read paths and B.4's pre-flip drift check). Archived
|
||||
-- + draft rows in deadline_rules were never replicated to sequencing_rules
|
||||
-- (they had no production read path). Snapshot includes them all (CREATE
|
||||
-- TABLE AS is unfiltered), so we compare on the same filter B.2 actually
|
||||
-- maintained. Drafts/archived rows are preserved in paliad.deadline_rules_pre_140
|
||||
-- for forensic + future-backfill use.
|
||||
SELECT COUNT(*) INTO v_snapshot_count
|
||||
FROM paliad.deadline_rules_pre_140
|
||||
WHERE is_active = true AND lifecycle_state = 'published';
|
||||
SELECT COUNT(*) INTO v_sr_count
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE is_active = true AND lifecycle_state = 'published';
|
||||
SELECT COUNT(*) INTO v_view_count FROM paliad.deadline_rules_unified;
|
||||
IF v_snapshot_count <> v_view_count THEN
|
||||
RAISE EXCEPTION '[mig 140] FAILED POST: snapshot has % rows, view has % rows — drift between final state and snapshot',
|
||||
v_snapshot_count, v_view_count;
|
||||
IF v_snapshot_count <> v_sr_count THEN
|
||||
RAISE EXCEPTION '[mig 140] FAILED POST: snapshot active+published has % rows, sequencing_rules active+published has % rows — dual-write drift',
|
||||
v_snapshot_count, v_sr_count;
|
||||
END IF;
|
||||
|
||||
SELECT COUNT(*) INTO v_dr_table_exists
|
||||
@@ -339,8 +352,8 @@ BEGIN
|
||||
RAISE EXCEPTION '[mig 140] FAILED POST: paliad.deadlines.rule_id column still exists after DROP';
|
||||
END IF;
|
||||
|
||||
RAISE NOTICE '[mig 140] OK — deadline_rules dropped, snapshot=% rows, view=% rows, INSTEAD OF triggers active',
|
||||
v_snapshot_count, v_view_count;
|
||||
RAISE NOTICE '[mig 140] OK — deadline_rules dropped, snapshot=% rows, sequencing_rules=% rows, view (filtered)=% rows, INSTEAD OF triggers active',
|
||||
v_snapshot_count, v_sr_count, v_view_count;
|
||||
END $$;
|
||||
|
||||
-- ---------------------------------------------------------------
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
-- 151_dedupe_null_procedural_events (down) — t-paliad-319 / m/paliad#144
|
||||
--
|
||||
-- Best-effort restore from paliad.procedural_events_pre_151 and
|
||||
-- paliad.sequencing_rules_pre_151. Re-points the reparented
|
||||
-- sequencing_rules back at their original procedural_event_id and
|
||||
-- reactivates the archived duplicates with the lifecycle_state +
|
||||
-- is_active they had before the up migration.
|
||||
--
|
||||
-- Catastrophic-recovery path only; the normal revert is to leave the
|
||||
-- dedupe in place (it is purely cosmetic).
|
||||
|
||||
-- 1. Re-point sequencing_rules.procedural_event_id back to its
|
||||
-- pre-mig-151 value. The snapshot row is keyed by sr.id so the
|
||||
-- join is 1:1 and idempotent.
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET procedural_event_id = s.original_procedural_event_id,
|
||||
updated_at = now()
|
||||
FROM paliad.sequencing_rules_pre_151 s
|
||||
WHERE sr.id = s.id;
|
||||
|
||||
-- 2. Reactivate the archived duplicates with their snapshot lifecycle.
|
||||
UPDATE paliad.procedural_events pe
|
||||
SET is_active = s.is_active,
|
||||
lifecycle_state = s.lifecycle_state,
|
||||
updated_at = now()
|
||||
FROM paliad.procedural_events_pre_151 s
|
||||
WHERE pe.id = s.id;
|
||||
|
||||
-- 3. Drop the snapshot tables — the data is back in place.
|
||||
DROP TABLE IF EXISTS paliad.sequencing_rules_pre_151;
|
||||
DROP TABLE IF EXISTS paliad.procedural_events_pre_151;
|
||||
229
internal/db/migrations/151_dedupe_null_procedural_events.up.sql
Normal file
229
internal/db/migrations/151_dedupe_null_procedural_events.up.sql
Normal file
@@ -0,0 +1,229 @@
|
||||
-- 151_dedupe_null_procedural_events — t-paliad-319 / m/paliad#144
|
||||
--
|
||||
-- Purpose: ~14 paliad.procedural_events rows with synthetic null.<8hex>
|
||||
-- codes (minted by mig 136 from the legacy paliad.deadline_rules rows
|
||||
-- whose submission_code was NULL) share user-visible names. The
|
||||
-- /admin/procedural-events list shows multiple entries for the same legal
|
||||
-- concept (worst offender: "Mängelbeseitigung / Zahlung" × 6). This
|
||||
-- migration consolidates every name-group onto a single canonical row,
|
||||
-- reparents the sequencing_rules pointing at the duplicates, and archives
|
||||
-- the duplicates without deleting them.
|
||||
--
|
||||
-- Scope verified live before write (Supabase MCP, 2026-05-26):
|
||||
-- * 5 name-groups, 14 duplicate rows total (1 canonical + 1–5 dups per
|
||||
-- group). Every duplicate has exactly 1 sequencing_rule pointing at it.
|
||||
-- * 0 paliad.deadlines reference any duplicate.
|
||||
-- * 0 procedural_events.draft_of references any duplicate.
|
||||
-- * No audit trigger on procedural_events or sequencing_rules — only
|
||||
-- the INSTEAD OF triggers on deadline_rules_unified (mig 140), which
|
||||
-- do not fire on direct table writes. No set_config('paliad.audit_reason')
|
||||
-- needed.
|
||||
--
|
||||
-- Canonical selection: ROW_NUMBER() OVER (PARTITION BY name ORDER BY
|
||||
-- created_at, id::text). Every duplicate in current data shares the same
|
||||
-- created_at (mig 136 bulk insert), so the deterministic tiebreaker is
|
||||
-- the UUID's lexicographic order.
|
||||
--
|
||||
-- Hard constraints honoured:
|
||||
-- * No deletions. Duplicates flip to is_active=false +
|
||||
-- lifecycle_state='archived'. The rows stay in the table for audit.
|
||||
-- * Reparent sequencing_rules.procedural_event_id duplicate → canonical
|
||||
-- BEFORE archiving, so no FK ever points at an archived PE.
|
||||
-- * Snapshot the affected procedural_events + sequencing_rules into
|
||||
-- paliad.procedural_events_pre_151 / paliad.sequencing_rules_pre_151
|
||||
-- in the same TX, mirroring precedent (migs 091/093/095/098/140).
|
||||
--
|
||||
-- Down: best-effort restore from the snapshots. See .down.sql.
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 1. Build the dedupe mapping (duplicate_id → canonical_id) in a
|
||||
-- TEMP table used by every subsequent step.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE TEMP TABLE tmp_pe_dedupe ON COMMIT DROP AS
|
||||
WITH dupe_names AS (
|
||||
SELECT name
|
||||
FROM paliad.procedural_events
|
||||
WHERE code LIKE 'null.%'
|
||||
GROUP BY name
|
||||
HAVING COUNT(*) > 1
|
||||
),
|
||||
ranked AS (
|
||||
SELECT pe.id,
|
||||
pe.code,
|
||||
pe.name,
|
||||
pe.created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY pe.name
|
||||
ORDER BY pe.created_at, pe.id::text
|
||||
) AS rn
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.code LIKE 'null.%'
|
||||
AND pe.name IN (SELECT name FROM dupe_names)
|
||||
),
|
||||
canonicals AS (
|
||||
SELECT name,
|
||||
id AS canonical_id,
|
||||
code AS canonical_code
|
||||
FROM ranked
|
||||
WHERE rn = 1
|
||||
)
|
||||
SELECT r.id AS duplicate_id,
|
||||
r.code AS duplicate_code,
|
||||
r.name,
|
||||
c.canonical_id,
|
||||
c.canonical_code
|
||||
FROM ranked r
|
||||
JOIN canonicals c ON c.name = r.name
|
||||
WHERE r.rn > 1;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 2. Snapshot. Captures the rows that change so .down has a clean
|
||||
-- source of truth; mirrors the pre_091/093/095/098/140 precedent.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE TABLE paliad.procedural_events_pre_151 AS
|
||||
SELECT pe.*
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.id IN (SELECT duplicate_id FROM tmp_pe_dedupe);
|
||||
|
||||
COMMENT ON TABLE paliad.procedural_events_pre_151 IS
|
||||
'Snapshot (mig 151, t-paliad-319) of the null.* procedural_events '
|
||||
'duplicates that were archived in favour of their canonical name-mate. '
|
||||
'Read-only forensic + revert source. Mirrors precedent pre_091/093/'
|
||||
'095/098/140.';
|
||||
|
||||
CREATE TABLE paliad.sequencing_rules_pre_151 AS
|
||||
SELECT sr.id,
|
||||
sr.procedural_event_id AS original_procedural_event_id
|
||||
FROM paliad.sequencing_rules sr
|
||||
WHERE sr.procedural_event_id IN (SELECT duplicate_id FROM tmp_pe_dedupe);
|
||||
|
||||
COMMENT ON TABLE paliad.sequencing_rules_pre_151 IS
|
||||
'Snapshot (mig 151, t-paliad-319) of sequencing_rules.procedural_event_id '
|
||||
'before reparenting from null.* duplicates onto their canonical PE. '
|
||||
'Read-only forensic + revert source.';
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 3. Audit log — per-row NOTICE so the migration output captures
|
||||
-- exactly which duplicate folded into which canonical, including
|
||||
-- the sr_count for the duplicate (always 1 in current data, but
|
||||
-- the RAISE keeps the audit honest if the scope grows later).
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
rec record;
|
||||
v_dup_count int;
|
||||
v_grp_count int;
|
||||
BEGIN
|
||||
SELECT COUNT(*), COUNT(DISTINCT name)
|
||||
INTO v_dup_count, v_grp_count
|
||||
FROM tmp_pe_dedupe;
|
||||
|
||||
RAISE NOTICE '[mig 151] dedupe scope: % duplicate rows across % name-groups',
|
||||
v_dup_count, v_grp_count;
|
||||
|
||||
FOR rec IN
|
||||
SELECT d.duplicate_id,
|
||||
d.duplicate_code,
|
||||
d.name,
|
||||
d.canonical_id,
|
||||
d.canonical_code,
|
||||
(SELECT COUNT(*)
|
||||
FROM paliad.sequencing_rules sr
|
||||
WHERE sr.procedural_event_id = d.duplicate_id) AS sr_count
|
||||
FROM tmp_pe_dedupe d
|
||||
ORDER BY d.name, d.duplicate_id
|
||||
LOOP
|
||||
RAISE NOTICE '[mig 151] dup % (%) -> canonical % (%) — sr_count=%',
|
||||
rec.duplicate_id, rec.duplicate_code,
|
||||
rec.canonical_id, rec.canonical_code,
|
||||
rec.sr_count;
|
||||
RAISE NOTICE '[mig 151] name: %', rec.name;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 4. Reparent sequencing_rules.procedural_event_id duplicate → canonical.
|
||||
-- sequencing_rules_pe_proc_lifecycle_idx is non-unique, so collapsing
|
||||
-- multiple sr onto one PE is by design.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET procedural_event_id = d.canonical_id,
|
||||
updated_at = now()
|
||||
FROM tmp_pe_dedupe d
|
||||
WHERE sr.procedural_event_id = d.duplicate_id;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 5. Archive the duplicates. No deletion — audit trail preserved.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.procedural_events pe
|
||||
SET is_active = false,
|
||||
lifecycle_state = 'archived',
|
||||
updated_at = now()
|
||||
WHERE pe.id IN (SELECT duplicate_id FROM tmp_pe_dedupe);
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 6. POST assertions. Any failure rolls the migration back.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_surviving_groups int;
|
||||
v_expected_count int;
|
||||
v_archived_count int;
|
||||
v_orphan_sr int;
|
||||
BEGIN
|
||||
-- (a) Acceptance criterion 2: no name-group still has >1 active+
|
||||
-- published null.* row.
|
||||
SELECT COUNT(*) INTO v_surviving_groups
|
||||
FROM (
|
||||
SELECT name
|
||||
FROM paliad.procedural_events
|
||||
WHERE code LIKE 'null.%'
|
||||
AND is_active = true
|
||||
AND lifecycle_state = 'published'
|
||||
GROUP BY name
|
||||
HAVING COUNT(*) > 1
|
||||
) s;
|
||||
|
||||
IF v_surviving_groups > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'[mig 151] FAILED POST: % name-groups still have >1 active+published null.* rows',
|
||||
v_surviving_groups;
|
||||
END IF;
|
||||
|
||||
-- (b) Every targeted duplicate is now archived.
|
||||
SELECT COUNT(*) INTO v_expected_count FROM tmp_pe_dedupe;
|
||||
|
||||
SELECT COUNT(*) INTO v_archived_count
|
||||
FROM paliad.procedural_events pe
|
||||
WHERE pe.id IN (SELECT duplicate_id FROM tmp_pe_dedupe)
|
||||
AND pe.is_active = false
|
||||
AND pe.lifecycle_state = 'archived';
|
||||
|
||||
IF v_archived_count <> v_expected_count THEN
|
||||
RAISE EXCEPTION
|
||||
'[mig 151] FAILED POST: archived %/% duplicates',
|
||||
v_archived_count, v_expected_count;
|
||||
END IF;
|
||||
|
||||
-- (c) Acceptance criterion 4: no sequencing_rule still points at
|
||||
-- an archived duplicate.
|
||||
SELECT COUNT(*) INTO v_orphan_sr
|
||||
FROM paliad.sequencing_rules sr
|
||||
WHERE sr.procedural_event_id IN (SELECT duplicate_id FROM tmp_pe_dedupe);
|
||||
|
||||
IF v_orphan_sr > 0 THEN
|
||||
RAISE EXCEPTION
|
||||
'[mig 151] FAILED POST: % sequencing_rules still point at archived PE duplicates',
|
||||
v_orphan_sr;
|
||||
END IF;
|
||||
|
||||
RAISE NOTICE '[mig 151] OK — archived % duplicates across % name-groups; 0 orphan sequencing_rules',
|
||||
v_archived_count,
|
||||
(SELECT COUNT(DISTINCT name) FROM tmp_pe_dedupe);
|
||||
END $$;
|
||||
@@ -0,0 +1,17 @@
|
||||
-- 152_dedupe_identical_sequencing_rule_clones (down) — t-paliad-321
|
||||
--
|
||||
-- Best-effort revert from paliad.sequencing_rules_pre_152. Flips the
|
||||
-- archived rows back to is_active=true / lifecycle_state='published'.
|
||||
-- Does NOT undo the deadlines.sequencing_rule_id reparent — that would
|
||||
-- require remembering the previous pointer per row, which the snapshot
|
||||
-- on sequencing_rules doesn't carry. In live data the reparent was a
|
||||
-- no-op (zero deadlines pointed at duplicates), so this is fine.
|
||||
|
||||
UPDATE paliad.sequencing_rules sr
|
||||
SET is_active = true,
|
||||
lifecycle_state = 'published',
|
||||
updated_at = now()
|
||||
FROM paliad.sequencing_rules_pre_152 snap
|
||||
WHERE sr.id = snap.id;
|
||||
|
||||
DROP TABLE IF EXISTS paliad.sequencing_rules_pre_152;
|
||||
@@ -0,0 +1,240 @@
|
||||
-- 152_dedupe_identical_sequencing_rule_clones — t-paliad-321 / m/paliad#144 follow-up
|
||||
--
|
||||
-- Purpose: mig 151 archived 5 of 6 duplicate procedural_events for
|
||||
-- "Mängelbeseitigung / Zahlung" and reparented their sequencing_rules
|
||||
-- onto the canonical PE. The 6 sequencing_rules themselves remained
|
||||
-- active. Because every one of them is a byte-for-byte clone (same
|
||||
-- proceeding_type_id=NULL, rule_code=NULL, duration 14d, primary_party=NULL,
|
||||
-- everything else NULL, lifecycle_state='published') and only sequence_order
|
||||
-- differs, the admin shows six indistinguishable rows for one legal
|
||||
-- concept. This mig archives 5 of the 6 keeping the lexicographically
|
||||
-- lowest UUID as canonical.
|
||||
--
|
||||
-- Scope verified live before write (Supabase MCP, 2026-05-26):
|
||||
-- * Exactly 1 clone-group surfaces by the full-signature query
|
||||
-- below: 6 "Mängelbeseitigung / Zahlung" sequencing_rules with
|
||||
-- all-NULL discriminators and (duration_value=14, duration_unit='days').
|
||||
-- * 0 paliad.deadlines reference the 5 to-be-archived rows
|
||||
-- (verified via deadlines.sequencing_rule_id JOIN; the column
|
||||
-- formerly named deadlines.rule_id was dropped in mig 140 / B.4).
|
||||
-- * Other name-groups in the live corpus — "Antrag auf
|
||||
-- Patentänderung"×4, "Beginn des Hauptsacheverfahrens"×2,
|
||||
-- "Berufungsbegründung-R.220.1"×2, "Berufungsschrift-R.220.1"×2 —
|
||||
-- do NOT collapse under this signature because their
|
||||
-- proceeding_type_id / rule_code / duration / primary_party
|
||||
-- differ. They are legitimately distinct rules per proceeding;
|
||||
-- this mig leaves them alone.
|
||||
--
|
||||
-- Hard constraints honoured (mirrors mig 151):
|
||||
-- * No deletions. Archived rows flip to is_active=false +
|
||||
-- lifecycle_state='archived'. Rows stay in the table for audit.
|
||||
-- * Reparent paliad.deadlines.sequencing_rule_id duplicate →
|
||||
-- canonical BEFORE archiving, so no live deadline keeps pointing
|
||||
-- at an archived sequencing_rule. (deadlines.rule_id column
|
||||
-- dropped in mig 140; the back-link lives on sequencing_rule_id
|
||||
-- now — same UUID semantics.)
|
||||
-- * Snapshot the affected rows into paliad.sequencing_rules_pre_152
|
||||
-- in the same TX, mirroring precedent (migs 091/093/095/098/140/151).
|
||||
-- * set_config('paliad.audit_reason') is defensively called even
|
||||
-- though no audit trigger fires on sequencing_rules today (mig 151
|
||||
-- §comments documented this). Future audit trigger would inherit
|
||||
-- the reason automatically.
|
||||
--
|
||||
-- Generic-shape rationale: the audit query below uses the FULL
|
||||
-- signature paliadin specified — procedural_event_id, proceeding_type_id,
|
||||
-- rule_code, duration_value, duration_unit, primary_party, condition_expr,
|
||||
-- trigger_event_id, alt_*, anchor_alt, combine_op, parent_id, is_spawn,
|
||||
-- spawn_*. A NOTICE surfaces every group BEFORE the archive step so an
|
||||
-- operator running the deploy logs sees what's about to be touched.
|
||||
-- If new groups appear after future seeds, this mig is safe to re-run
|
||||
-- conceptually (it would archive any new clones) but only fires once
|
||||
-- via the applied_migrations protocol.
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 1. Build the dedupe mapping (duplicate_id → canonical_id) into a
|
||||
-- TEMP table used by every subsequent step.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE TEMP TABLE tmp_sr_dedupe ON COMMIT DROP AS
|
||||
WITH ranked AS (
|
||||
SELECT
|
||||
id, procedural_event_id, proceeding_type_id, rule_code,
|
||||
duration_value, duration_unit, primary_party,
|
||||
condition_expr, trigger_event_id, alt_duration_value,
|
||||
alt_duration_unit, alt_rule_code, anchor_alt, combine_op,
|
||||
parent_id, is_spawn, spawn_label, spawn_proceeding_type_id,
|
||||
created_at,
|
||||
ROW_NUMBER() OVER (
|
||||
PARTITION BY
|
||||
procedural_event_id, proceeding_type_id, rule_code,
|
||||
duration_value, duration_unit, primary_party,
|
||||
condition_expr::text, trigger_event_id,
|
||||
alt_duration_value, alt_duration_unit, alt_rule_code,
|
||||
anchor_alt, combine_op, parent_id, is_spawn, spawn_label,
|
||||
spawn_proceeding_type_id
|
||||
ORDER BY created_at, id::text
|
||||
) AS rn,
|
||||
COUNT(*) OVER (
|
||||
PARTITION BY
|
||||
procedural_event_id, proceeding_type_id, rule_code,
|
||||
duration_value, duration_unit, primary_party,
|
||||
condition_expr::text, trigger_event_id,
|
||||
alt_duration_value, alt_duration_unit, alt_rule_code,
|
||||
anchor_alt, combine_op, parent_id, is_spawn, spawn_label,
|
||||
spawn_proceeding_type_id
|
||||
) AS grp_size
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE is_active = true
|
||||
AND lifecycle_state = 'published'
|
||||
)
|
||||
SELECT
|
||||
r.id AS duplicate_id,
|
||||
canon.id AS canonical_id,
|
||||
r.procedural_event_id,
|
||||
(SELECT name FROM paliad.procedural_events WHERE id = r.procedural_event_id) AS pe_name
|
||||
FROM ranked r
|
||||
JOIN ranked canon
|
||||
ON canon.procedural_event_id IS NOT DISTINCT FROM r.procedural_event_id
|
||||
AND canon.proceeding_type_id IS NOT DISTINCT FROM r.proceeding_type_id
|
||||
AND canon.rule_code IS NOT DISTINCT FROM r.rule_code
|
||||
AND canon.duration_value IS NOT DISTINCT FROM r.duration_value
|
||||
AND canon.duration_unit IS NOT DISTINCT FROM r.duration_unit
|
||||
AND canon.primary_party IS NOT DISTINCT FROM r.primary_party
|
||||
AND canon.condition_expr::text IS NOT DISTINCT FROM r.condition_expr::text
|
||||
AND canon.trigger_event_id IS NOT DISTINCT FROM r.trigger_event_id
|
||||
AND canon.alt_duration_value IS NOT DISTINCT FROM r.alt_duration_value
|
||||
AND canon.alt_duration_unit IS NOT DISTINCT FROM r.alt_duration_unit
|
||||
AND canon.alt_rule_code IS NOT DISTINCT FROM r.alt_rule_code
|
||||
AND canon.anchor_alt IS NOT DISTINCT FROM r.anchor_alt
|
||||
AND canon.combine_op IS NOT DISTINCT FROM r.combine_op
|
||||
AND canon.parent_id IS NOT DISTINCT FROM r.parent_id
|
||||
AND canon.is_spawn IS NOT DISTINCT FROM r.is_spawn
|
||||
AND canon.spawn_label IS NOT DISTINCT FROM r.spawn_label
|
||||
AND canon.spawn_proceeding_type_id IS NOT DISTINCT FROM r.spawn_proceeding_type_id
|
||||
AND canon.rn = 1
|
||||
WHERE r.rn > 1 AND r.grp_size > 1;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 2. Surface every clone-group as a NOTICE before archiving.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
rec record;
|
||||
total_to_archive int;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO total_to_archive FROM tmp_sr_dedupe;
|
||||
RAISE NOTICE '[mig 152] PRE: % sequencing_rules row(s) will be archived', total_to_archive;
|
||||
FOR rec IN
|
||||
SELECT pe_name, canonical_id, COUNT(*) AS dup_count, array_agg(duplicate_id::text ORDER BY duplicate_id::text) AS dup_ids
|
||||
FROM tmp_sr_dedupe
|
||||
GROUP BY pe_name, canonical_id
|
||||
ORDER BY pe_name
|
||||
LOOP
|
||||
RAISE NOTICE '[mig 152] % canonical=% duplicates=% ids=%',
|
||||
rec.pe_name, rec.canonical_id, rec.dup_count, rec.dup_ids;
|
||||
END LOOP;
|
||||
END $$;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 3. Snapshot the rows about to be archived (only the duplicates;
|
||||
-- the canonicals stay in the live table). Matches precedent.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE TABLE paliad.sequencing_rules_pre_152 AS
|
||||
SELECT sr.*
|
||||
FROM paliad.sequencing_rules sr
|
||||
JOIN tmp_sr_dedupe d ON d.duplicate_id = sr.id;
|
||||
|
||||
COMMENT ON TABLE paliad.sequencing_rules_pre_152 IS
|
||||
'Snapshot of paliad.sequencing_rules rows archived by mig 152 '
|
||||
'(identical clones — Mängelbeseitigung / Zahlung × 5). Mirrors '
|
||||
'precedent pre_091/093/095/098/140/151. Read-only revert source. '
|
||||
't-paliad-321 / m/paliad#144 follow-up.';
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 4. Reparent paliad.deadlines.sequencing_rule_id duplicate → canonical
|
||||
-- BEFORE archiving. Today's live data has 0 deadlines pointing at
|
||||
-- any duplicate, but the statement is safe + defensive against a
|
||||
-- race between drift-check and apply.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.deadlines d
|
||||
SET sequencing_rule_id = m.canonical_id,
|
||||
procedural_event_id = (SELECT procedural_event_id
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE id = m.canonical_id),
|
||||
updated_at = now()
|
||||
FROM tmp_sr_dedupe m
|
||||
WHERE d.sequencing_rule_id = m.duplicate_id;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 5. Defensive audit-reason. Sequencing_rules has no audit trigger
|
||||
-- today (mig 151 §scope verified), but set_config is transactional
|
||||
-- and a future audit trigger inherits the reason automatically.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
SELECT set_config('paliad.audit_reason',
|
||||
'mig 152: archive identical sequencing_rule clones (mig 151 follow-up; t-paliad-321)',
|
||||
true);
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 6. Archive the duplicates.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.sequencing_rules
|
||||
SET is_active = false,
|
||||
lifecycle_state = 'archived',
|
||||
updated_at = now()
|
||||
WHERE id IN (SELECT duplicate_id FROM tmp_sr_dedupe);
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 7. POST assertions.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DO $$
|
||||
DECLARE
|
||||
v_archived int;
|
||||
v_remaining_dupes int;
|
||||
v_orphan_deadlines int;
|
||||
BEGIN
|
||||
-- a. Did the expected number of rows get archived?
|
||||
SELECT COUNT(*) INTO v_archived
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE id IN (SELECT duplicate_id FROM tmp_sr_dedupe)
|
||||
AND lifecycle_state = 'archived'
|
||||
AND is_active = false;
|
||||
IF v_archived <> (SELECT COUNT(*) FROM tmp_sr_dedupe) THEN
|
||||
RAISE EXCEPTION '[mig 152] FAILED POST: expected % rows archived, got %',
|
||||
(SELECT COUNT(*) FROM tmp_sr_dedupe), v_archived;
|
||||
END IF;
|
||||
|
||||
-- b. No clone group of size > 1 should remain in active+published.
|
||||
SELECT COUNT(*) INTO v_remaining_dupes FROM (
|
||||
SELECT 1
|
||||
FROM paliad.sequencing_rules
|
||||
WHERE is_active = true AND lifecycle_state = 'published'
|
||||
GROUP BY procedural_event_id, proceeding_type_id, rule_code,
|
||||
duration_value, duration_unit, primary_party,
|
||||
condition_expr::text, trigger_event_id,
|
||||
alt_duration_value, alt_duration_unit, alt_rule_code,
|
||||
anchor_alt, combine_op, parent_id, is_spawn, spawn_label,
|
||||
spawn_proceeding_type_id
|
||||
HAVING COUNT(*) > 1
|
||||
) g;
|
||||
IF v_remaining_dupes > 0 THEN
|
||||
RAISE EXCEPTION '[mig 152] FAILED POST: % clone group(s) still active+published after archive', v_remaining_dupes;
|
||||
END IF;
|
||||
|
||||
-- c. No deadline points at an archived sequencing_rule.
|
||||
SELECT COUNT(*) INTO v_orphan_deadlines
|
||||
FROM paliad.deadlines d
|
||||
JOIN paliad.sequencing_rules sr ON sr.id = d.sequencing_rule_id
|
||||
WHERE sr.lifecycle_state = 'archived';
|
||||
IF v_orphan_deadlines > 0 THEN
|
||||
RAISE EXCEPTION '[mig 152] FAILED POST: % live deadline(s) still point at an archived sequencing_rule', v_orphan_deadlines;
|
||||
END IF;
|
||||
|
||||
RAISE NOTICE '[mig 152] OK — archived=%, remaining clone groups=0, orphan deadlines=0',
|
||||
v_archived;
|
||||
END $$;
|
||||
53
internal/db/migrations/153_proceeding_types_kind.down.sql
Normal file
53
internal/db/migrations/153_proceeding_types_kind.down.sql
Normal file
@@ -0,0 +1,53 @@
|
||||
-- 153_proceeding_types_kind.down — t-paliad-325 / m/paliad#147
|
||||
--
|
||||
-- Best-effort rollback of mig 153. Restores the pre-mig state of
|
||||
-- paliad.proceeding_types from the same-TX snapshot, drops the kind
|
||||
-- column, drops the backstop trigger.
|
||||
|
||||
BEGIN;
|
||||
|
||||
SELECT set_config(
|
||||
'paliad.audit_reason',
|
||||
'mig 153 down: revert proceeding_types kind discriminator',
|
||||
true
|
||||
);
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 1. Drop the backstop trigger + function.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DROP TRIGGER IF EXISTS projects_proceeding_type_kind_check
|
||||
ON paliad.projects;
|
||||
|
||||
DROP FUNCTION IF EXISTS paliad.projects_proceeding_type_kind_check();
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 2. Restore is_active flags from the snapshot. We only touch rows
|
||||
-- whose is_active value diverged from the snapshot — i.e. the 23
|
||||
-- rows that mig 153 §4 deactivated.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.proceeding_types pt
|
||||
SET is_active = pre.is_active
|
||||
FROM paliad.proceeding_types_pre_153 pre
|
||||
WHERE pt.id = pre.id
|
||||
AND pt.is_active IS DISTINCT FROM pre.is_active;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 3. Drop the kind column (cascades the index).
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DROP INDEX IF EXISTS paliad.proceeding_types_kind_active_idx;
|
||||
|
||||
ALTER TABLE paliad.proceeding_types
|
||||
DROP COLUMN IF EXISTS kind;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 4. Drop the snapshot table.
|
||||
-- (The CHECK constraint on the kind column is dropped implicitly
|
||||
-- when the column is dropped.)
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
DROP TABLE IF EXISTS paliad.proceeding_types_pre_153;
|
||||
|
||||
COMMIT;
|
||||
201
internal/db/migrations/153_proceeding_types_kind.up.sql
Normal file
201
internal/db/migrations/153_proceeding_types_kind.up.sql
Normal file
@@ -0,0 +1,201 @@
|
||||
-- 153_proceeding_types_kind — t-paliad-325 / m/paliad#147
|
||||
--
|
||||
-- Purpose: tag every paliad.proceeding_types row with a structural
|
||||
-- classification so the Mode B R3 wizard (Fristenrechner overhaul,
|
||||
-- m/paliad#146), the projects.proceeding_type_id binding, and the
|
||||
-- pkg/litigationplanner snapshot can filter to primary proceedings
|
||||
-- only — separating self-contained matters from CFI phases,
|
||||
-- in-proceeding side-actions, and cross-cutting RoP/admin rows.
|
||||
--
|
||||
-- Design: docs/design-proceeding-types-taxonomy-2026-05-26.md
|
||||
-- §0–§10 (m ratified 2026-05-27 09:52 via 11-question AskUserQuestion
|
||||
-- batch; "proceed, sure" greenlight at 09:57).
|
||||
--
|
||||
-- This mig is purely additive: ALTER TABLE adds the kind column with
|
||||
-- a safe DEFAULT, UPDATEs reclassify the 23 non-primary rows, and a
|
||||
-- BEFORE INSERT/UPDATE trigger backstops the new
|
||||
-- "projects.proceeding_type_id must point at kind='proceeding'"
|
||||
-- invariant. The 23 rows being reclassified have zero downstream
|
||||
-- consumers today (0 active sequencing_rules anchor, 0 spawn, 0
|
||||
-- projects bind, 0 event_category_concepts reference) so no FK
|
||||
-- reparenting is needed — verified via Supabase MCP 2026-05-27
|
||||
-- before write.
|
||||
--
|
||||
-- Hard constraints honoured (mirrors precedent migs 091/093/095/098/
|
||||
-- 140/151/152):
|
||||
-- * No deletions. Non-primary rows flip is_active=false but stay in
|
||||
-- the table for audit + future re-activation.
|
||||
-- * Snapshot the affected proceeding_types into
|
||||
-- paliad.proceeding_types_pre_153 in the same TX.
|
||||
-- * set_config('paliad.audit_reason') is defensively called even
|
||||
-- though no audit trigger fires on proceeding_types today; a
|
||||
-- future audit trigger would inherit the reason automatically.
|
||||
-- * Idempotent on re-apply — the ADD COLUMN uses IF NOT EXISTS
|
||||
-- semantics through golang-migrate's tracker (mig only fires
|
||||
-- once); the UPDATEs only touch rows that match the explicit ID
|
||||
-- list from the ratified design §3.2 / §10.2.
|
||||
|
||||
BEGIN;
|
||||
|
||||
SELECT set_config(
|
||||
'paliad.audit_reason',
|
||||
'mig 153: proceeding_types kind discriminator (m/paliad#147)',
|
||||
true
|
||||
);
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 1. Snapshot the pre-mig state for audit + rollback safety.
|
||||
-- Mirrors precedent: sequencing_rules_pre_151/_pre_152,
|
||||
-- procedural_events_pre_151.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE TABLE paliad.proceeding_types_pre_153 AS
|
||||
SELECT * FROM paliad.proceeding_types;
|
||||
|
||||
COMMENT ON TABLE paliad.proceeding_types_pre_153 IS
|
||||
'Snapshot of paliad.proceeding_types taken in the same TX as '
|
||||
'mig 153 (kind discriminator). Audit + rollback safety per the '
|
||||
'precedent set by migs 091/093/095/098/140/151/152. Drop only '
|
||||
'when the kind taxonomy has held in prod for at least one '
|
||||
'release cycle and no rollback is anticipated.';
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 2. Add the kind column.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
ALTER TABLE paliad.proceeding_types
|
||||
ADD COLUMN kind text NOT NULL DEFAULT 'proceeding'
|
||||
CHECK (kind IN ('proceeding', 'phase', 'side_action', 'meta'));
|
||||
|
||||
COMMENT ON COLUMN paliad.proceeding_types.kind IS
|
||||
'Structural classification — see docs/design-proceeding-types-taxonomy-2026-05-26.md §1. '
|
||||
'proceeding = self-contained matter (own filing + deadline tree); '
|
||||
'phase = stage inside a primary CFI proceeding; '
|
||||
'side_action = application/order inside a proceeding; '
|
||||
'meta = RoP mechanics, court admin, cross-cutting remedies.';
|
||||
|
||||
CREATE INDEX proceeding_types_kind_active_idx
|
||||
ON paliad.proceeding_types(kind, is_active)
|
||||
WHERE is_active = true;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 3. Reclassify the 23 non-primary rows.
|
||||
-- IDs per ratified design §3.2 / §10.2. m's Q2 carve-out keeps
|
||||
-- upc.costs.cfi (176) as kind='proceeding' (defaults to that);
|
||||
-- Q3.b keeps upc.pl.cfi (188) as kind='proceeding' (defaults).
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
-- 3.1 Phases: 4 rows (Q2 carve-out drops upc.costs.cfi from the original 5).
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'phase'
|
||||
WHERE id IN (173, 174, 175, 185);
|
||||
|
||||
-- 3.2 Side-actions: 10 rows (§0.4 Group C).
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'side_action'
|
||||
WHERE id IN (178, 182, 177, 184, 165, 170, 180, 181, 187, 183);
|
||||
|
||||
-- 3.3 Meta / cross-cutting: 9 rows (§0.4 Group D incl. upc.reestablishment.rop).
|
||||
UPDATE paliad.proceeding_types
|
||||
SET kind = 'meta'
|
||||
WHERE id IN (162, 161, 163, 168, 164, 166, 167, 186, 169);
|
||||
|
||||
-- 3.4 Defensive integrity check — every reclassified ID must have been
|
||||
-- reached. If the live table drifted between design (2026-05-26)
|
||||
-- and apply, this raises before the trigger ships.
|
||||
DO $$
|
||||
DECLARE
|
||||
expected int := 23;
|
||||
actual int;
|
||||
BEGIN
|
||||
SELECT COUNT(*) INTO actual
|
||||
FROM paliad.proceeding_types
|
||||
WHERE kind <> 'proceeding';
|
||||
IF actual <> expected THEN
|
||||
RAISE EXCEPTION
|
||||
'[mig 153] expected % rows reclassified to non-proceeding kind, found % — '
|
||||
'live IDs drifted from the design. Abort.',
|
||||
expected, actual;
|
||||
END IF;
|
||||
RAISE NOTICE '[mig 153] reclassified % rows: 4 phase + 10 side_action + 9 meta', actual;
|
||||
END $$;
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 4. Per m's Q9: deactivate the non-primary rows so the admin list
|
||||
-- surfaces only primaries. The kind column carries the semantic
|
||||
-- info; is_active controls UI visibility. Reversible — flip
|
||||
-- is_active back on if a row gains corpus.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
UPDATE paliad.proceeding_types
|
||||
SET is_active = false
|
||||
WHERE kind IN ('phase', 'side_action', 'meta');
|
||||
|
||||
-- ----------------------------------------------------------------
|
||||
-- 5. Backstop trigger on projects.proceeding_type_id (§3.3 + Q8).
|
||||
-- Complements mig 088's category check; rejects any
|
||||
-- INSERT/UPDATE that would bind a project to a non-proceeding
|
||||
-- kind. Independent from the category trigger so each invariant
|
||||
-- can be dropped in isolation.
|
||||
-- ----------------------------------------------------------------
|
||||
|
||||
CREATE OR REPLACE FUNCTION paliad.projects_proceeding_type_kind_check()
|
||||
RETURNS trigger
|
||||
LANGUAGE plpgsql
|
||||
AS $$
|
||||
DECLARE
|
||||
v_kind text;
|
||||
BEGIN
|
||||
IF NEW.proceeding_type_id IS NULL THEN
|
||||
RETURN NEW;
|
||||
END IF;
|
||||
|
||||
SELECT kind INTO v_kind
|
||||
FROM paliad.proceeding_types
|
||||
WHERE id = NEW.proceeding_type_id;
|
||||
|
||||
IF v_kind IS NULL THEN
|
||||
-- FK should have caught this; defensive for any future FK relax.
|
||||
RAISE EXCEPTION
|
||||
'paliad.projects.proceeding_type_id = % does not resolve to a '
|
||||
'proceeding_types row — FK constraint should have caught this.',
|
||||
NEW.proceeding_type_id;
|
||||
END IF;
|
||||
|
||||
IF v_kind <> 'proceeding' THEN
|
||||
RAISE EXCEPTION
|
||||
'paliad.projects.proceeding_type_id must reference a kind=''proceeding'' '
|
||||
'proceeding_types row (got kind=''%''). '
|
||||
'Verfahrenstyp muss ein primäres Verfahren sein (kind=''%''). '
|
||||
'Phasen, Nebenanträge und RoP-Querschnittsregeln sind keine '
|
||||
'wählbaren Projekt-Verfahrenstypen.',
|
||||
v_kind, v_kind
|
||||
USING ERRCODE = '23514';
|
||||
END IF;
|
||||
|
||||
RETURN NEW;
|
||||
END;
|
||||
$$;
|
||||
|
||||
COMMENT ON FUNCTION paliad.projects_proceeding_type_kind_check() IS
|
||||
'BEFORE INSERT/UPDATE trigger function enforcing the mig 153 '
|
||||
'invariant: paliad.projects.proceeding_type_id may only '
|
||||
'reference kind=''proceeding'' proceeding_types rows. NULL is '
|
||||
'allowed. Complements mig 088''s category check.';
|
||||
|
||||
DROP TRIGGER IF EXISTS projects_proceeding_type_kind_check
|
||||
ON paliad.projects;
|
||||
|
||||
CREATE TRIGGER projects_proceeding_type_kind_check
|
||||
BEFORE INSERT OR UPDATE OF proceeding_type_id ON paliad.projects
|
||||
FOR EACH ROW
|
||||
EXECUTE FUNCTION paliad.projects_proceeding_type_kind_check();
|
||||
|
||||
COMMENT ON TRIGGER projects_proceeding_type_kind_check ON paliad.projects IS
|
||||
'mig 153 (t-paliad-325 / m/paliad#147) runtime guard — rejects '
|
||||
'any INSERT/UPDATE that would bind a project to a phase/'
|
||||
'side_action/meta proceeding_types row. The Go service layer '
|
||||
'also enforces this with a typed error; this trigger is the '
|
||||
'defence-in-depth backstop.';
|
||||
|
||||
COMMIT;
|
||||
@@ -41,14 +41,22 @@ import (
|
||||
// historical `submission_code` + `event_type` already on Rule's tags.
|
||||
// The embedded *models.DeadlineRule carries every existing tag through
|
||||
// json.Marshal unchanged; the wrapper only ADDS the two new keys.
|
||||
//
|
||||
// ProceedingTypeCode (t-paliad-321) is the joined paliad.proceeding_types.code
|
||||
// for the row's proceeding_type_id. NULL on event-rooted rules. Lets the
|
||||
// /admin/procedural-events list disambiguate same-named rules at a glance
|
||||
// (e.g. "Berufungsbegründung" rows differ only by proceeding code).
|
||||
type adminRuleResponse struct {
|
||||
*models.DeadlineRule
|
||||
Code *string `json:"code,omitempty"`
|
||||
EventKind *string `json:"event_kind,omitempty"`
|
||||
Code *string `json:"code,omitempty"`
|
||||
EventKind *string `json:"event_kind,omitempty"`
|
||||
ProceedingTypeCode *string `json:"proceeding_type_code,omitempty"`
|
||||
}
|
||||
|
||||
// wrapRuleResponse builds the dual-emit wrapper from a service result.
|
||||
// Same values, two keys per concept — no semantic change.
|
||||
// Same values, two keys per concept — no semantic change. Pass a non-nil
|
||||
// ptCode to populate the proceeding_type_code field; nil leaves it
|
||||
// absent (e.g. on event-rooted rules with NULL proceeding_type_id).
|
||||
func wrapRuleResponse(r *models.DeadlineRule) adminRuleResponse {
|
||||
if r == nil {
|
||||
return adminRuleResponse{}
|
||||
@@ -61,11 +69,20 @@ func wrapRuleResponse(r *models.DeadlineRule) adminRuleResponse {
|
||||
}
|
||||
|
||||
// wrapRuleListResponse maps a slice of service results into the
|
||||
// dual-emit wrapper. Used by the LIST endpoint.
|
||||
func wrapRuleListResponse(rows []models.DeadlineRule) []adminRuleResponse {
|
||||
// dual-emit wrapper. Used by the LIST endpoint. ptCodes is an
|
||||
// optional id → code lookup populated by handleAdminListRules from a
|
||||
// single batch query against paliad.proceeding_types; nil leaves
|
||||
// every row's proceeding_type_code empty (the LIST endpoint always
|
||||
// passes a populated map; other callers don't need it).
|
||||
func wrapRuleListResponse(rows []models.DeadlineRule, ptCodes map[int]string) []adminRuleResponse {
|
||||
out := make([]adminRuleResponse, len(rows))
|
||||
for i := range rows {
|
||||
out[i] = wrapRuleResponse(&rows[i])
|
||||
if ptCodes != nil && rows[i].ProceedingTypeID != nil {
|
||||
if code, ok := ptCodes[*rows[i].ProceedingTypeID]; ok {
|
||||
out[i].ProceedingTypeCode = &code
|
||||
}
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
@@ -128,8 +145,16 @@ func handleAdminListRules(w http.ResponseWriter, r *http.Request) {
|
||||
writeRuleEditorError(w, err)
|
||||
return
|
||||
}
|
||||
// t-paliad-321: batch-fetch proceeding_type.code for every rule
|
||||
// row that carries a non-NULL proceeding_type_id, so the LIST
|
||||
// response can show a Proceeding column without an N+1 join.
|
||||
ptCodes, err := dbSvc.ruleEditor.LoadProceedingTypeCodes(r.Context(), rows)
|
||||
if err != nil {
|
||||
writeRuleEditorError(w, err)
|
||||
return
|
||||
}
|
||||
adminRuleDeprecationHeaders(w)
|
||||
writeJSON(w, http.StatusOK, wrapRuleListResponse(rows))
|
||||
writeJSON(w, http.StatusOK, wrapRuleListResponse(rows, ptCodes))
|
||||
}
|
||||
|
||||
// GET /admin/api/rules/{id}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
@@ -204,6 +205,15 @@ func handleFristenrechnerCalculateRule(w http.ResponseWriter, r *http.Request) {
|
||||
// Returns 503 with an empty array when DATABASE_URL is unset so the page
|
||||
// still renders (buttons are server-rendered from tsx and don't depend on
|
||||
// this endpoint for existence, only for dynamic list updates).
|
||||
//
|
||||
// Optional query params (Fristenrechner overhaul S3, m/paliad#146):
|
||||
// jurisdiction - "UPC" | "DE" | "EPA" | "DPMA". Narrows the chip
|
||||
// pool to one jurisdiction. Empty = any.
|
||||
// kind - "proceeding" | "phase" | "side_action" | "meta".
|
||||
// Narrows to one structural kind from the taxonomy
|
||||
// cleanup (m/paliad#147, mig 153). Mode A passes
|
||||
// "proceeding" to exclude phase / side_action / meta
|
||||
// rows. Empty = any.
|
||||
func handleProceedingTypes(w http.ResponseWriter, r *http.Request) {
|
||||
if dbSvc == nil || dbSvc.fristenrechner == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
@@ -211,7 +221,12 @@ func handleProceedingTypes(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
return
|
||||
}
|
||||
types, err := dbSvc.fristenrechner.ListFristenrechnerTypes(r.Context())
|
||||
opts := services.ProceedingListOptions{
|
||||
Jurisdiction: strings.ToUpper(strings.TrimSpace(r.URL.Query().Get("jurisdiction"))),
|
||||
Kind: strings.TrimSpace(r.URL.Query().Get("kind")),
|
||||
EventKind: strings.TrimSpace(r.URL.Query().Get("event_kind")),
|
||||
}
|
||||
types, err := dbSvc.fristenrechner.ListProceedings(r.Context(), opts)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "konnte Verfahrenstypen nicht laden"})
|
||||
return
|
||||
|
||||
@@ -1,31 +0,0 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// GET /api/tools/fristenrechner/event-categories — returns the full
|
||||
// decision-tree taxonomy for the v3 Pathway B / B1 cascade UI
|
||||
// (t-paliad-133). Tree is small (~100 nodes) and mostly static; the
|
||||
// frontend ETag-caches it via localStorage.
|
||||
//
|
||||
// Returns 503 if the DB-backed services aren't wired (DATABASE_URL
|
||||
// unset).
|
||||
func handleFristenrechnerEventCategories(w http.ResponseWriter, r *http.Request) {
|
||||
if dbSvc == nil || dbSvc.eventCategory == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "Decision-tree-Taxonomie vorübergehend nicht verfügbar (keine Datenbank).",
|
||||
})
|
||||
return
|
||||
}
|
||||
tree, err := dbSvc.eventCategory.Tree(r.Context())
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{
|
||||
"error": "Decision-tree fehlgeschlagen: " + err.Error(),
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]any{
|
||||
"tree": tree,
|
||||
})
|
||||
}
|
||||
65
internal/handlers/fristenrechner_followups.go
Normal file
65
internal/handlers/fristenrechner_followups.go
Normal file
@@ -0,0 +1,65 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"mgit.msbls.de/m/paliad/internal/services"
|
||||
)
|
||||
|
||||
// GET /api/tools/fristenrechner/follow-ups — given a trigger event and
|
||||
// a trigger date, return the immediate follow-up sequencing rules with
|
||||
// their computed due dates (Fristenrechner overhaul S1, design §6.2).
|
||||
//
|
||||
// Query params:
|
||||
// event - procedural_events.code OR procedural_events.id
|
||||
// (uuid) OR sequencing_rules.id (uuid). Required.
|
||||
// trigger_date - YYYY-MM-DD. Defaults to today when omitted, so the
|
||||
// frontend can show a result preview before the user
|
||||
// commits a date.
|
||||
// party - "claimant" | "defendant" | "court" | "both".
|
||||
// Optional; narrows follow-ups by primary_party
|
||||
// (claimant/defendant filters keep "both" rules
|
||||
// visible — they're bilateral procedural moves).
|
||||
// court_id - paliad.courts.id (uuid); selects the holiday
|
||||
// calendar for date adjustment. Optional.
|
||||
func handleFristenrechnerFollowUps(w http.ResponseWriter, r *http.Request) {
|
||||
if dbSvc == nil || dbSvc.fristenrechner == nil {
|
||||
writeJSON(w, http.StatusServiceUnavailable, map[string]string{
|
||||
"error": "Fristenrechner ist vorübergehend nicht verfügbar (keine Datenbank).",
|
||||
})
|
||||
return
|
||||
}
|
||||
q := r.URL.Query()
|
||||
eventRef := q.Get("event")
|
||||
if eventRef == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{
|
||||
"error": "event ist erforderlich (procedural_events.code oder id)",
|
||||
})
|
||||
return
|
||||
}
|
||||
triggerDate := q.Get("trigger_date")
|
||||
if triggerDate == "" {
|
||||
triggerDate = time.Now().Format("2006-01-02")
|
||||
}
|
||||
|
||||
resp, err := dbSvc.fristenrechner.LookupFollowUps(
|
||||
r.Context(),
|
||||
eventRef,
|
||||
triggerDate,
|
||||
q.Get("party"),
|
||||
q.Get("court_id"),
|
||||
)
|
||||
if err != nil {
|
||||
if errors.Is(err, services.ErrUnknownProceduralEvent) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{
|
||||
"error": "Unbekanntes Ereignis: " + eventRef,
|
||||
})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
@@ -32,6 +32,10 @@ import (
|
||||
// dpma). Trigger pills bypass this filter.
|
||||
// limit - max cards (default 12, max 30; in browse
|
||||
// modes default 200, max 500)
|
||||
// kind - "events" switches to the events-shape
|
||||
// response (Fristenrechner overhaul S1,
|
||||
// design §6.1). The default concept-card
|
||||
// shape is unchanged when kind is empty.
|
||||
//
|
||||
// Returns an empty cards array (not 400) when q is empty — that lets
|
||||
// the frontend boot the search input without a server round-trip.
|
||||
@@ -42,6 +46,10 @@ func handleFristenrechnerSearch(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
return
|
||||
}
|
||||
if r.URL.Query().Get("kind") == "events" {
|
||||
handleFristenrechnerSearchEvents(w, r)
|
||||
return
|
||||
}
|
||||
q := r.URL.Query().Get("q")
|
||||
opts := services.SearchOptions{
|
||||
Party: r.URL.Query().Get("party"),
|
||||
@@ -60,6 +68,35 @@ func handleFristenrechnerSearch(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// handleFristenrechnerSearchEvents serves the ?kind=events shape of
|
||||
// /api/tools/fristenrechner/search (overhaul S1, design §6.1). Returns
|
||||
// one hit per (procedural_event × proceeding_type) tuple, with a
|
||||
// follow-up count and a trigram similarity score.
|
||||
//
|
||||
// Query params (additive to the legacy search params):
|
||||
// q - free-text search against name / name_en / code
|
||||
// jurisdiction - "UPC" | "DE" | "EPA" | "DPMA"
|
||||
// proc - proceeding_type code
|
||||
// event_kind - "filing" | "hearing" | "decision" | "order"
|
||||
// party - primary_party of the anchor rule
|
||||
// limit - max hits (default 50, max 200)
|
||||
func handleFristenrechnerSearchEvents(w http.ResponseWriter, r *http.Request) {
|
||||
q := r.URL.Query().Get("q")
|
||||
opts := services.EventSearchOptions{
|
||||
Jurisdiction: strings.ToUpper(strings.TrimSpace(r.URL.Query().Get("jurisdiction"))),
|
||||
ProceedingTypeCode: r.URL.Query().Get("proc"),
|
||||
EventKind: r.URL.Query().Get("event_kind"),
|
||||
PrimaryParty: r.URL.Query().Get("party"),
|
||||
Limit: parseLimit(r.URL.Query().Get("limit")),
|
||||
}
|
||||
resp, err := dbSvc.deadlineSearch.SearchEvents(r.Context(), q, opts)
|
||||
if err != nil {
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "Ereignis-Suche fehlgeschlagen: " + err.Error()})
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// parseCSV splits a comma-separated query-string value into a slice of
|
||||
// trimmed non-empty entries. Empty input → nil.
|
||||
func parseCSV(raw string) []string {
|
||||
|
||||
@@ -307,7 +307,14 @@ func Register(mux *http.ServeMux, client *auth.Client, giteaAPIToken string, svc
|
||||
protected.HandleFunc("POST /api/tools/event-trigger", handleEventTriggerCalculate)
|
||||
protected.HandleFunc("GET /api/tools/courts", handleCourtsList)
|
||||
protected.HandleFunc("GET /api/tools/fristenrechner/search", handleFristenrechnerSearch)
|
||||
protected.HandleFunc("GET /api/tools/fristenrechner/event-categories", handleFristenrechnerEventCategories)
|
||||
protected.HandleFunc("GET /api/tools/fristenrechner/follow-ups", handleFristenrechnerFollowUps)
|
||||
// t-paliad-323 Slice S6: the cascade endpoint /api/tools/fristenrechner/
|
||||
// event-categories is retired — the Fristenrechner overhaul Mode A
|
||||
// + wizard surfaces don't read the event_categories taxonomy. The
|
||||
// table itself stays for future tools (design doc §7). The
|
||||
// EventCategoryService still backs the /search endpoint's legacy
|
||||
// ?event_category_slug filter; that filter is dead-coded too but
|
||||
// removing the service is a separate follow-up.
|
||||
protected.HandleFunc("GET /downloads", handleDownloadsPage)
|
||||
protected.HandleFunc("GET /glossary", handleGlossaryPage)
|
||||
protected.HandleFunc("GET /api/glossary", handleGlossaryAPI)
|
||||
|
||||
@@ -82,13 +82,77 @@ func (s *FristenrechnerService) CalculateRule(ctx context.Context, params CalcRu
|
||||
// specific surface (the wire shape FristenrechnerType is owned by the
|
||||
// package but the SQL filter is paliad-side).
|
||||
func (s *FristenrechnerService) ListFristenrechnerTypes(ctx context.Context) ([]lp.FristenrechnerType, error) {
|
||||
rows, err := s.rules.db.QueryxContext(ctx, `
|
||||
SELECT code, name, name_en, jurisdiction
|
||||
FROM paliad.proceeding_types
|
||||
WHERE category = 'fristenrechner' AND is_active = true
|
||||
ORDER BY sort_order`)
|
||||
return s.ListProceedings(ctx, ProceedingListOptions{})
|
||||
}
|
||||
|
||||
// ProceedingListOptions narrows ListProceedings. Empty values = no
|
||||
// filter on that axis. Added for the Fristenrechner overhaul S3
|
||||
// (m/paliad#146): Mode A's "Verfahren" filter chip strip needs to scope
|
||||
// the proceeding pool by the user's Forum pick (jurisdiction) and by
|
||||
// kind='proceeding' to exclude the phase / side_action / meta rows
|
||||
// landed in the taxonomy cleanup (m/paliad#147, mig 153).
|
||||
type ProceedingListOptions struct {
|
||||
// Jurisdiction narrows to one jurisdiction code (UPC / DE / EPA /
|
||||
// DPMA). Empty = any.
|
||||
Jurisdiction string
|
||||
// Kind narrows to one structural kind (proceeding / phase /
|
||||
// side_action / meta). Mode A passes "proceeding" to exclude the
|
||||
// phase / side_action / meta rows from the chip strip. Empty = any.
|
||||
//
|
||||
// Filter referenced before mig 153 lands the column → callers
|
||||
// pre-mig get a "column kind does not exist" error from Postgres.
|
||||
// Sequenced per docs/design-proceeding-types-taxonomy-2026-05-26.md
|
||||
// §7 option (c): mig 153 merges to main before the S3 PR ships.
|
||||
Kind string
|
||||
// EventKind narrows to proceedings that have at least one published
|
||||
// sequencing rule anchored on a procedural event of the requested
|
||||
// kind ("filing" | "hearing" | "decision" | "order"). Powers the
|
||||
// Fristenrechner overhaul Mode B R3 wizard row (§3.2): after R1
|
||||
// picks an event_kind, R3 should only chip proceedings whose event
|
||||
// roster contains at least one event of that kind. Empty = no
|
||||
// event-kind narrowing.
|
||||
EventKind string
|
||||
}
|
||||
|
||||
// ListProceedings returns the proceeding_types chips the Fristenrechner
|
||||
// overhaul Mode A renders in its filter strip. Filters apply
|
||||
// progressively: pre-mig 153 Kind=="" is the safe default; post-mig 153
|
||||
// Mode A passes Kind="proceeding" to exclude the phase / side_action /
|
||||
// meta rows.
|
||||
func (s *FristenrechnerService) ListProceedings(ctx context.Context, opts ProceedingListOptions) ([]lp.FristenrechnerType, error) {
|
||||
where := []string{
|
||||
"category = 'fristenrechner'",
|
||||
"is_active = true",
|
||||
}
|
||||
args := []any{}
|
||||
add := func(clause string, val any) {
|
||||
args = append(args, val)
|
||||
where = append(where, fmt.Sprintf(clause, len(args)))
|
||||
}
|
||||
if opts.Jurisdiction != "" {
|
||||
add("jurisdiction = $%d", opts.Jurisdiction)
|
||||
}
|
||||
if opts.Kind != "" {
|
||||
add("kind = $%d", opts.Kind)
|
||||
}
|
||||
if opts.EventKind != "" {
|
||||
add(`EXISTS (
|
||||
SELECT 1 FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
WHERE sr.proceeding_type_id = paliad.proceeding_types.id
|
||||
AND sr.is_active = true AND sr.lifecycle_state = 'published'
|
||||
AND pe.is_active = true AND pe.lifecycle_state = 'published'
|
||||
AND pe.event_kind = $%d
|
||||
)`, opts.EventKind)
|
||||
}
|
||||
query := `SELECT code, name, name_en, jurisdiction
|
||||
FROM paliad.proceeding_types
|
||||
WHERE ` + strings.Join(where, " AND ") + `
|
||||
ORDER BY sort_order`
|
||||
|
||||
rows, err := s.rules.db.QueryxContext(ctx, query, args...)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list fristenrechner types: %w", err)
|
||||
return nil, fmt.Errorf("list proceedings: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
|
||||
404
internal/services/fristenrechner_followups.go
Normal file
404
internal/services/fristenrechner_followups.go
Normal file
@@ -0,0 +1,404 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
|
||||
lp "mgit.msbls.de/m/paliad/pkg/litigationplanner"
|
||||
)
|
||||
|
||||
// ErrUnknownProceduralEvent is returned by LookupFollowUps when the
|
||||
// requested procedural_event cannot be resolved (unknown id / unknown
|
||||
// code / not active+published). Distinct from ErrUnknownTriggerEvent
|
||||
// (which lives on the legacy Pipeline C / paliad.trigger_events path).
|
||||
var ErrUnknownProceduralEvent = errors.New("unknown procedural event")
|
||||
|
||||
// FollowUpsResponse is the wire shape for GET
|
||||
// /api/tools/fristenrechner/follow-ups (Fristenrechner overhaul S1,
|
||||
// design §6.2). Captures the locked trigger event + every immediate
|
||||
// follow-up rule with its computed due date.
|
||||
type FollowUpsResponse struct {
|
||||
Trigger FollowUpTrigger `json:"trigger"`
|
||||
TriggerDate string `json:"trigger_date"`
|
||||
Party *string `json:"party,omitempty"`
|
||||
FollowUps []FollowUpRule `json:"follow_ups"`
|
||||
}
|
||||
|
||||
// FollowUpTrigger is the locked trigger event identity returned by
|
||||
// LookupFollowUps.
|
||||
type FollowUpTrigger struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Code string `json:"code"`
|
||||
NameDE string `json:"name_de"`
|
||||
NameEN string `json:"name_en"`
|
||||
EventKind *string `json:"event_kind,omitempty"`
|
||||
ProceedingType EventSearchPT `json:"proceeding_type"`
|
||||
AnchorRuleID uuid.UUID `json:"anchor_rule_id"`
|
||||
}
|
||||
|
||||
// FollowUpRule is one follow-up deadline returned by LookupFollowUps.
|
||||
// Carries the rule metadata + the computed due date (or the
|
||||
// "wird vom Gericht bestimmt" / "abhängig von …" marker for rules whose
|
||||
// date is undefined).
|
||||
type FollowUpRule struct {
|
||||
RuleID uuid.UUID `json:"rule_id"`
|
||||
EventCode string `json:"event_code"`
|
||||
TitleDE string `json:"title_de"`
|
||||
TitleEN string `json:"title_en"`
|
||||
Priority string `json:"priority"`
|
||||
PrimaryParty *string `json:"primary_party,omitempty"`
|
||||
DurationValue *int `json:"duration_value,omitempty"`
|
||||
DurationUnit *string `json:"duration_unit,omitempty"`
|
||||
Timing *string `json:"timing,omitempty"`
|
||||
DueDate string `json:"due_date,omitempty"`
|
||||
OriginalDueDate string `json:"original_due_date,omitempty"`
|
||||
WasAdjusted bool `json:"was_adjusted,omitempty"`
|
||||
IsCourtSet bool `json:"is_court_set"`
|
||||
IsSpawn bool `json:"is_spawn"`
|
||||
IsBilateral bool `json:"is_bilateral"`
|
||||
HasCondition bool `json:"has_condition"`
|
||||
RuleCode *string `json:"rule_code,omitempty"`
|
||||
LegalSource *string `json:"legal_source,omitempty"`
|
||||
LegalSourceDisplay *string `json:"legal_source_display,omitempty"`
|
||||
LegalSourceURL *string `json:"legal_source_url,omitempty"`
|
||||
NotesDE *string `json:"notes_de,omitempty"`
|
||||
NotesEN *string `json:"notes_en,omitempty"`
|
||||
SpawnLabel *string `json:"spawn_label,omitempty"`
|
||||
SpawnProceedingCode *string `json:"spawn_proceeding_code,omitempty"`
|
||||
ConceptID *uuid.UUID `json:"concept_id,omitempty"`
|
||||
}
|
||||
|
||||
// LookupFollowUps returns the follow-up rules anchored on a single
|
||||
// procedural_event, with computed dates run through the holiday-aware
|
||||
// litigationplanner.CalculateRule. Identifies the anchor by either the
|
||||
// procedural_event.id (uuid) or its code; resolves the anchor rule
|
||||
// (the sequencing_rule with procedural_event_id matching), then walks
|
||||
// one hop down via parent_id to collect immediate follow-ups.
|
||||
//
|
||||
// When party is non-empty, follow-ups are filtered to rules whose
|
||||
// primary_party matches OR is "both" (so a defendant filter still
|
||||
// returns bilateral procedural moves like Vertraulichkeitsantrag-
|
||||
// Erwiderung).
|
||||
func (s *FristenrechnerService) LookupFollowUps(
|
||||
ctx context.Context,
|
||||
eventRef string,
|
||||
triggerDateStr string,
|
||||
party string,
|
||||
courtID string,
|
||||
) (*FollowUpsResponse, error) {
|
||||
if eventRef == "" {
|
||||
return nil, fmt.Errorf("eventRef required")
|
||||
}
|
||||
if triggerDateStr == "" {
|
||||
return nil, fmt.Errorf("triggerDate required")
|
||||
}
|
||||
|
||||
anchor, err := s.resolveTriggerEvent(ctx, eventRef)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
resp := &FollowUpsResponse{
|
||||
Trigger: anchor.Trigger,
|
||||
TriggerDate: triggerDateStr,
|
||||
FollowUps: []FollowUpRule{},
|
||||
}
|
||||
if party != "" {
|
||||
p := party
|
||||
resp.Party = &p
|
||||
}
|
||||
|
||||
// Pull the proceeding_type metadata once so we can pass it
|
||||
// downstream to populate the trigger card and to seed the
|
||||
// CalculateRule lookup (which uses RuleID anyway).
|
||||
rows, err := s.queryFollowUpRows(ctx, anchor.AnchorRuleID, party)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
for _, r := range rows {
|
||||
fr := FollowUpRule{
|
||||
RuleID: r.RuleID,
|
||||
EventCode: r.EventCode,
|
||||
TitleDE: r.NameDE,
|
||||
TitleEN: r.NameEN,
|
||||
Priority: r.Priority,
|
||||
IsCourtSet: r.IsCourtSet,
|
||||
IsSpawn: r.IsSpawn,
|
||||
IsBilateral: r.IsBilateral,
|
||||
HasCondition: r.HasCondition,
|
||||
}
|
||||
if r.PrimaryParty.Valid {
|
||||
v := r.PrimaryParty.String
|
||||
fr.PrimaryParty = &v
|
||||
}
|
||||
if r.DurationValue.Valid {
|
||||
v := int(r.DurationValue.Int32)
|
||||
fr.DurationValue = &v
|
||||
}
|
||||
if r.DurationUnit.Valid {
|
||||
v := r.DurationUnit.String
|
||||
fr.DurationUnit = &v
|
||||
}
|
||||
if r.Timing.Valid {
|
||||
v := r.Timing.String
|
||||
fr.Timing = &v
|
||||
}
|
||||
if r.RuleCode.Valid {
|
||||
v := r.RuleCode.String
|
||||
fr.RuleCode = &v
|
||||
}
|
||||
if r.LegalSource.Valid {
|
||||
v := r.LegalSource.String
|
||||
fr.LegalSource = &v
|
||||
display := lp.FormatLegalSourceDisplay(v)
|
||||
if display != "" {
|
||||
fr.LegalSourceDisplay = &display
|
||||
}
|
||||
url := lp.BuildLegalSourceURL(v)
|
||||
if url != "" {
|
||||
fr.LegalSourceURL = &url
|
||||
}
|
||||
}
|
||||
if r.NotesDE.Valid {
|
||||
v := r.NotesDE.String
|
||||
fr.NotesDE = &v
|
||||
}
|
||||
if r.NotesEN.Valid {
|
||||
v := r.NotesEN.String
|
||||
fr.NotesEN = &v
|
||||
}
|
||||
if r.SpawnLabel.Valid {
|
||||
v := r.SpawnLabel.String
|
||||
fr.SpawnLabel = &v
|
||||
}
|
||||
if r.SpawnProceedingCode.Valid {
|
||||
v := r.SpawnProceedingCode.String
|
||||
fr.SpawnProceedingCode = &v
|
||||
}
|
||||
if r.ConceptID != nil {
|
||||
fr.ConceptID = r.ConceptID
|
||||
}
|
||||
|
||||
// Skip date computation for court-set / spawn rules — they don't
|
||||
// project a calendar date here.
|
||||
if !r.IsCourtSet && !r.IsSpawn {
|
||||
calc, err := s.CalculateRule(ctx, lp.CalcRuleParams{
|
||||
RuleID: r.RuleID.String(),
|
||||
TriggerDate: triggerDateStr,
|
||||
CourtID: courtID,
|
||||
})
|
||||
if err == nil {
|
||||
fr.DueDate = calc.DueDate
|
||||
fr.OriginalDueDate = calc.OriginalDate
|
||||
fr.WasAdjusted = calc.WasAdjusted
|
||||
}
|
||||
// On error: leave the date fields empty — the frontend
|
||||
// already handles missing dates as "abhängig von ..." style
|
||||
// markers and a single bad rule shouldn't 500 the whole
|
||||
// follow-up list.
|
||||
}
|
||||
|
||||
resp.FollowUps = append(resp.FollowUps, fr)
|
||||
}
|
||||
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// anchorResolution carries the resolver output: the trigger card metadata
|
||||
// plus the anchor rule id (the sequencing_rule.id whose
|
||||
// procedural_event_id equals the trigger event).
|
||||
type anchorResolution struct {
|
||||
Trigger FollowUpTrigger
|
||||
AnchorRuleID uuid.UUID
|
||||
}
|
||||
|
||||
// resolveTriggerEvent looks up the trigger event by either uuid or code.
|
||||
// Returns ErrUnknownTriggerEvent when no published+active anchor row
|
||||
// matches.
|
||||
func (s *FristenrechnerService) resolveTriggerEvent(ctx context.Context, ref string) (*anchorResolution, error) {
|
||||
// Try uuid first; fall back to code lookup.
|
||||
type row struct {
|
||||
EventID uuid.UUID `db:"event_id"`
|
||||
Code string `db:"code"`
|
||||
NameDE string `db:"name_de"`
|
||||
NameEN string `db:"name_en"`
|
||||
EventKind sql.NullString `db:"event_kind"`
|
||||
AnchorRuleID uuid.UUID `db:"anchor_rule_id"`
|
||||
PTID int `db:"pt_id"`
|
||||
PTCode string `db:"pt_code"`
|
||||
PTNameDE string `db:"pt_name_de"`
|
||||
PTNameEN string `db:"pt_name_en"`
|
||||
PTJurisdiction sql.NullString `db:"pt_jurisdiction"`
|
||||
}
|
||||
|
||||
var r row
|
||||
queryBase := `
|
||||
SELECT pe.id AS event_id,
|
||||
pe.code,
|
||||
pe.name AS name_de,
|
||||
pe.name_en,
|
||||
pe.event_kind,
|
||||
sr.id AS anchor_rule_id,
|
||||
pt.id AS pt_id,
|
||||
pt.code AS pt_code,
|
||||
pt.name AS pt_name_de,
|
||||
pt.name_en AS pt_name_en,
|
||||
pt.jurisdiction AS pt_jurisdiction
|
||||
FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
JOIN paliad.proceeding_types pt ON pt.id = sr.proceeding_type_id
|
||||
WHERE sr.is_active = true
|
||||
AND sr.lifecycle_state = 'published'
|
||||
AND pe.is_active = true
|
||||
AND pe.lifecycle_state = 'published'
|
||||
AND pt.is_active = true
|
||||
AND %s
|
||||
ORDER BY pt.sort_order
|
||||
LIMIT 1`
|
||||
|
||||
if id, err := uuid.Parse(ref); err == nil {
|
||||
// Treat as a procedural_event id OR a sequencing_rule id (the
|
||||
// frontend may pass either — search returns event id but a
|
||||
// concept-card-derived flow may pass the rule id).
|
||||
err := s.rules.db.GetContext(ctx, &r, fmt.Sprintf(queryBase, "(pe.id = $1 OR sr.id = $1)"), id)
|
||||
if err == nil {
|
||||
goto found
|
||||
}
|
||||
if !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, fmt.Errorf("resolve trigger event by id: %w", err)
|
||||
}
|
||||
// fall through to code lookup
|
||||
}
|
||||
{
|
||||
err := s.rules.db.GetContext(ctx, &r, fmt.Sprintf(queryBase, "pe.code = $1"), ref)
|
||||
if err == nil {
|
||||
goto found
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrUnknownProceduralEvent
|
||||
}
|
||||
return nil, fmt.Errorf("resolve trigger event by code: %w", err)
|
||||
}
|
||||
|
||||
found:
|
||||
res := &anchorResolution{
|
||||
AnchorRuleID: r.AnchorRuleID,
|
||||
Trigger: FollowUpTrigger{
|
||||
ID: r.EventID,
|
||||
Code: r.Code,
|
||||
NameDE: r.NameDE,
|
||||
NameEN: r.NameEN,
|
||||
AnchorRuleID: r.AnchorRuleID,
|
||||
ProceedingType: EventSearchPT{
|
||||
ID: r.PTID,
|
||||
Code: r.PTCode,
|
||||
NameDE: r.PTNameDE,
|
||||
NameEN: r.PTNameEN,
|
||||
},
|
||||
},
|
||||
}
|
||||
if r.EventKind.Valid {
|
||||
v := r.EventKind.String
|
||||
res.Trigger.EventKind = &v
|
||||
}
|
||||
if r.PTJurisdiction.Valid {
|
||||
v := r.PTJurisdiction.String
|
||||
res.Trigger.ProceedingType.Jurisdiction = &v
|
||||
}
|
||||
return res, nil
|
||||
}
|
||||
|
||||
// followUpRow is the joined SELECT shape for follow-up rules.
|
||||
type followUpRow struct {
|
||||
RuleID uuid.UUID `db:"rule_id"`
|
||||
EventCode string `db:"event_code"`
|
||||
NameDE string `db:"name_de"`
|
||||
NameEN string `db:"name_en"`
|
||||
Priority string `db:"priority"`
|
||||
PrimaryParty sql.NullString `db:"primary_party"`
|
||||
DurationValue sql.NullInt32 `db:"duration_value"`
|
||||
DurationUnit sql.NullString `db:"duration_unit"`
|
||||
Timing sql.NullString `db:"timing"`
|
||||
IsCourtSet bool `db:"is_court_set"`
|
||||
IsSpawn bool `db:"is_spawn"`
|
||||
IsBilateral bool `db:"is_bilateral"`
|
||||
HasCondition bool `db:"has_condition"`
|
||||
RuleCode sql.NullString `db:"rule_code"`
|
||||
LegalSource sql.NullString `db:"legal_source"`
|
||||
NotesDE sql.NullString `db:"notes_de"`
|
||||
NotesEN sql.NullString `db:"notes_en"`
|
||||
SpawnLabel sql.NullString `db:"spawn_label"`
|
||||
SpawnProceedingCode sql.NullString `db:"spawn_proceeding_code"`
|
||||
ConceptID *uuid.UUID `db:"concept_id"`
|
||||
SequenceOrder int `db:"sequence_order"`
|
||||
}
|
||||
|
||||
// queryFollowUpRows pulls the immediate-children rules of an anchor.
|
||||
// Party filter is inclusive of "both" so bilateral moves stay visible
|
||||
// when the user picks claimant or defendant.
|
||||
func (s *FristenrechnerService) queryFollowUpRows(
|
||||
ctx context.Context,
|
||||
anchorRuleID uuid.UUID,
|
||||
party string,
|
||||
) ([]followUpRow, error) {
|
||||
where := []string{
|
||||
"sr.parent_id = $1",
|
||||
"sr.is_active = true",
|
||||
"sr.lifecycle_state = 'published'",
|
||||
"pe.is_active = true",
|
||||
"pe.lifecycle_state = 'published'",
|
||||
}
|
||||
args := []any{anchorRuleID}
|
||||
if party == "claimant" || party == "defendant" {
|
||||
args = append(args, party)
|
||||
where = append(where, fmt.Sprintf(
|
||||
"(sr.primary_party = $%d OR sr.primary_party = 'both' OR sr.primary_party IS NULL)",
|
||||
len(args)))
|
||||
} else if party != "" {
|
||||
// "court" / "both" — exact match
|
||||
args = append(args, party)
|
||||
where = append(where, fmt.Sprintf("sr.primary_party = $%d", len(args)))
|
||||
}
|
||||
|
||||
query := `
|
||||
SELECT sr.id AS rule_id,
|
||||
pe.code AS event_code,
|
||||
pe.name AS name_de,
|
||||
pe.name_en,
|
||||
sr.priority,
|
||||
sr.primary_party,
|
||||
sr.duration_value,
|
||||
sr.duration_unit,
|
||||
sr.timing,
|
||||
sr.is_court_set,
|
||||
sr.is_spawn,
|
||||
sr.is_bilateral,
|
||||
(sr.condition_expr IS NOT NULL) AS has_condition,
|
||||
sr.rule_code,
|
||||
ls.citation AS legal_source,
|
||||
sr.deadline_notes AS notes_de,
|
||||
sr.deadline_notes_en AS notes_en,
|
||||
sr.spawn_label,
|
||||
spt.code AS spawn_proceeding_code,
|
||||
pe.concept_id,
|
||||
sr.sequence_order
|
||||
FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
LEFT JOIN paliad.legal_sources ls ON ls.id = pe.legal_source_id
|
||||
LEFT JOIN paliad.proceeding_types spt ON spt.id = sr.spawn_proceeding_type_id
|
||||
WHERE ` + strings.Join(where, "\n AND ") + `
|
||||
ORDER BY sr.sequence_order, pe.code`
|
||||
|
||||
var rows []followUpRow
|
||||
if err := s.rules.db.SelectContext(ctx, &rows, query, args...); err != nil {
|
||||
return nil, fmt.Errorf("load follow-up rows: %w", err)
|
||||
}
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
205
internal/services/fristenrechner_followups_test.go
Normal file
205
internal/services/fristenrechner_followups_test.go
Normal file
@@ -0,0 +1,205 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"mgit.msbls.de/m/paliad/internal/db"
|
||||
)
|
||||
|
||||
// TestSearchEvents covers the ?kind=events response shape for the
|
||||
// Fristenrechner overhaul S1 (design §6.1). Verified against live data:
|
||||
// "Klageerhebung" must return upc.inf.cfi.soc (the canonical SoC
|
||||
// procedural event) as the top hit, with the proceeding metadata
|
||||
// populated and a non-zero follow_up_count.
|
||||
//
|
||||
// Skipped when TEST_DATABASE_URL is unset, mirroring the other live-DB
|
||||
// tests in this package.
|
||||
func TestSearchEvents(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()
|
||||
|
||||
svc := NewDeadlineSearchService(pool)
|
||||
|
||||
t.Run("Klageerhebung returns upc.inf.cfi.soc with follow-ups", func(t *testing.T) {
|
||||
resp, err := svc.SearchEvents(ctx, "Klageerhebung", EventSearchOptions{Limit: 30})
|
||||
if err != nil {
|
||||
t.Fatalf("search events: %v", err)
|
||||
}
|
||||
if len(resp.Events) == 0 {
|
||||
t.Fatalf("no events returned for Klageerhebung")
|
||||
}
|
||||
var soc *EventSearchHit
|
||||
for i := range resp.Events {
|
||||
if resp.Events[i].Code == "upc.inf.cfi.soc" {
|
||||
soc = &resp.Events[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if soc == nil {
|
||||
t.Fatalf("upc.inf.cfi.soc not in event hits (got %d hits)", len(resp.Events))
|
||||
}
|
||||
if soc.NameDE == "" {
|
||||
t.Errorf("expected name_de populated, got empty")
|
||||
}
|
||||
if soc.ProceedingType.Code != "upc.inf.cfi" {
|
||||
t.Errorf("expected proceeding upc.inf.cfi, got %q", soc.ProceedingType.Code)
|
||||
}
|
||||
if soc.FollowUpCount <= 0 {
|
||||
t.Errorf("expected follow_up_count > 0 for SoC, got %d", soc.FollowUpCount)
|
||||
}
|
||||
if soc.EventKind == nil || *soc.EventKind != "filing" {
|
||||
gotKind := "<nil>"
|
||||
if soc.EventKind != nil {
|
||||
gotKind = *soc.EventKind
|
||||
}
|
||||
t.Errorf("expected event_kind=filing, got %q", gotKind)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("jurisdiction filter narrows to UPC", func(t *testing.T) {
|
||||
resp, err := svc.SearchEvents(ctx, "", EventSearchOptions{
|
||||
Jurisdiction: "UPC",
|
||||
Limit: 200,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("search events UPC: %v", err)
|
||||
}
|
||||
if len(resp.Events) == 0 {
|
||||
t.Fatalf("expected UPC events, got 0")
|
||||
}
|
||||
for _, e := range resp.Events {
|
||||
if e.ProceedingType.Jurisdiction == nil || *e.ProceedingType.Jurisdiction != "UPC" {
|
||||
gotJ := "<nil>"
|
||||
if e.ProceedingType.Jurisdiction != nil {
|
||||
gotJ = *e.ProceedingType.Jurisdiction
|
||||
}
|
||||
t.Errorf("non-UPC event leaked: %s (jurisdiction=%q)", e.Code, gotJ)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("event_kind=filing narrows by kind", func(t *testing.T) {
|
||||
resp, err := svc.SearchEvents(ctx, "", EventSearchOptions{
|
||||
EventKind: "filing",
|
||||
Limit: 200,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("search events filing: %v", err)
|
||||
}
|
||||
if len(resp.Events) == 0 {
|
||||
t.Fatalf("expected filing events, got 0")
|
||||
}
|
||||
for _, e := range resp.Events {
|
||||
if e.EventKind == nil || *e.EventKind != "filing" {
|
||||
gotKind := "<nil>"
|
||||
if e.EventKind != nil {
|
||||
gotKind = *e.EventKind
|
||||
}
|
||||
t.Errorf("non-filing event leaked: %s (event_kind=%q)", e.Code, gotKind)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestLookupFollowUps covers the GET /api/tools/fristenrechner/follow-ups
|
||||
// endpoint contract (overhaul S1, design §6.2). Verified against live
|
||||
// data: looking up upc.inf.cfi.soc returns the four canonical follow-up
|
||||
// rules (Klageerwiderung, CCR, Einspruch, Vertraulichkeits-Erwiderung),
|
||||
// each with a computed due date or court-set marker.
|
||||
func TestLookupFollowUps(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()
|
||||
|
||||
holidays := NewHolidayService(pool)
|
||||
courts := NewCourtService(pool)
|
||||
rules := NewDeadlineRuleService(pool)
|
||||
fr := NewFristenrechnerService(rules, holidays, courts)
|
||||
|
||||
t.Run("SoC returns follow-ups with computed dates", func(t *testing.T) {
|
||||
resp, err := fr.LookupFollowUps(ctx, "upc.inf.cfi.soc", "2026-05-20", "", "")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup follow-ups: %v", err)
|
||||
}
|
||||
if resp.Trigger.Code != "upc.inf.cfi.soc" {
|
||||
t.Errorf("trigger code = %q, want upc.inf.cfi.soc", resp.Trigger.Code)
|
||||
}
|
||||
if len(resp.FollowUps) == 0 {
|
||||
t.Fatalf("expected follow-ups, got 0")
|
||||
}
|
||||
// At least the Klageerwiderung (sod) should be present and have a date.
|
||||
var sod *FollowUpRule
|
||||
for i := range resp.FollowUps {
|
||||
if resp.FollowUps[i].EventCode == "upc.inf.cfi.sod" {
|
||||
sod = &resp.FollowUps[i]
|
||||
break
|
||||
}
|
||||
}
|
||||
if sod == nil {
|
||||
t.Fatalf("Klageerwiderung (upc.inf.cfi.sod) not in follow-ups")
|
||||
}
|
||||
if sod.DueDate == "" {
|
||||
t.Errorf("expected due_date populated for sod, got empty")
|
||||
}
|
||||
if sod.Priority != "mandatory" {
|
||||
t.Errorf("expected priority=mandatory for sod, got %q", sod.Priority)
|
||||
}
|
||||
// 3 months after 2026-05-20 (then weekend-adjusted) — sanity check
|
||||
// only that something resembling 2026-08 came back.
|
||||
if len(sod.DueDate) < 7 || sod.DueDate[:7] != "2026-08" {
|
||||
t.Errorf("expected due_date in 2026-08, got %q", sod.DueDate)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("party=defendant narrows but keeps bilateral rules", func(t *testing.T) {
|
||||
resp, err := fr.LookupFollowUps(ctx, "upc.inf.cfi.soc", "2026-05-20", "defendant", "")
|
||||
if err != nil {
|
||||
t.Fatalf("lookup follow-ups (defendant): %v", err)
|
||||
}
|
||||
if len(resp.FollowUps) == 0 {
|
||||
t.Fatalf("expected defendant follow-ups, got 0")
|
||||
}
|
||||
for _, r := range resp.FollowUps {
|
||||
if r.PrimaryParty == nil {
|
||||
continue
|
||||
}
|
||||
p := *r.PrimaryParty
|
||||
if p == "claimant" {
|
||||
t.Errorf("claimant-only rule leaked under defendant filter: %s", r.EventCode)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("unknown event returns ErrUnknownProceduralEvent", func(t *testing.T) {
|
||||
_, err := fr.LookupFollowUps(ctx, "no.such.event", "2026-05-20", "", "")
|
||||
if err != ErrUnknownProceduralEvent {
|
||||
t.Errorf("expected ErrUnknownProceduralEvent, got %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
156
internal/services/fristenrechner_proceedings_test.go
Normal file
156
internal/services/fristenrechner_proceedings_test.go
Normal file
@@ -0,0 +1,156 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/jmoiron/sqlx"
|
||||
_ "github.com/lib/pq"
|
||||
|
||||
"mgit.msbls.de/m/paliad/internal/db"
|
||||
)
|
||||
|
||||
// TestListProceedings covers the proceeding chip-pool query that powers
|
||||
// the Fristenrechner overhaul Mode A "Verfahren" filter strip (S3,
|
||||
// design §3.1). The legacy callers go through ListFristenrechnerTypes
|
||||
// (no filters) — that path stays green here. The new ListProceedings
|
||||
// API accepts Jurisdiction + Kind filters; the Kind filter requires
|
||||
// mig 153 to have landed, so this test skips the Kind=proceeding case
|
||||
// when the column doesn't yet exist.
|
||||
func TestListProceedings(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()
|
||||
|
||||
rules := NewDeadlineRuleService(pool)
|
||||
holidays := NewHolidayService(pool)
|
||||
courts := NewCourtService(pool)
|
||||
fr := NewFristenrechnerService(rules, holidays, courts)
|
||||
|
||||
t.Run("no filters returns the legacy fristenrechner set", func(t *testing.T) {
|
||||
got, err := fr.ListProceedings(ctx, ProceedingListOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("list proceedings: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected non-empty proceeding list")
|
||||
}
|
||||
// Sanity — upc.inf.cfi should always be in the active set.
|
||||
found := false
|
||||
for _, p := range got {
|
||||
if p.Code == "upc.inf.cfi" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("upc.inf.cfi not in proceedings list")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("jurisdiction=UPC narrows to UPC-only", func(t *testing.T) {
|
||||
got, err := fr.ListProceedings(ctx, ProceedingListOptions{Jurisdiction: "UPC"})
|
||||
if err != nil {
|
||||
t.Fatalf("list proceedings UPC: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected UPC proceedings")
|
||||
}
|
||||
for _, p := range got {
|
||||
if p.Group != "UPC" {
|
||||
t.Errorf("non-UPC proceeding leaked: %s (group=%q)", p.Code, p.Group)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("jurisdiction=DE returns DE proceedings", func(t *testing.T) {
|
||||
got, err := fr.ListProceedings(ctx, ProceedingListOptions{Jurisdiction: "DE"})
|
||||
if err != nil {
|
||||
t.Fatalf("list proceedings DE: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected DE proceedings")
|
||||
}
|
||||
for _, p := range got {
|
||||
if p.Group != "DE" {
|
||||
t.Errorf("non-DE proceeding leaked: %s (group=%q)", p.Code, p.Group)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("ListFristenrechnerTypes legacy alias still works", func(t *testing.T) {
|
||||
got, err := fr.ListFristenrechnerTypes(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("list fristenrechner types: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected non-empty types")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("kind=proceeding narrows to primary proceedings only", func(t *testing.T) {
|
||||
got, err := fr.ListProceedings(ctx, ProceedingListOptions{Kind: "proceeding"})
|
||||
if err != nil {
|
||||
t.Fatalf("list proceedings kind=proceeding: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected non-empty primary-proceeding list")
|
||||
}
|
||||
// upc.inf.cfi is unambiguously a primary proceeding — must
|
||||
// survive the filter.
|
||||
found := false
|
||||
for _, p := range got {
|
||||
if p.Code == "upc.inf.cfi" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("upc.inf.cfi missing from kind=proceeding list")
|
||||
}
|
||||
// upc.cfi.interim is the canonical phase row (per mig 153 +
|
||||
// taxonomy doc §0.4 Group B) — must NOT appear.
|
||||
for _, p := range got {
|
||||
if p.Code == "upc.cfi.interim" {
|
||||
t.Errorf("phase row upc.cfi.interim leaked into kind=proceeding")
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("event_kind=filing narrows to proceedings with filing events", func(t *testing.T) {
|
||||
got, err := fr.ListProceedings(ctx, ProceedingListOptions{
|
||||
Jurisdiction: "UPC",
|
||||
Kind: "proceeding",
|
||||
EventKind: "filing",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("list proceedings UPC+filing: %v", err)
|
||||
}
|
||||
if len(got) == 0 {
|
||||
t.Fatalf("expected UPC proceedings with filing events")
|
||||
}
|
||||
// upc.inf.cfi has at least one rule anchored on a filing event
|
||||
// (Klageerhebung, SoD, etc.) — must survive.
|
||||
found := false
|
||||
for _, p := range got {
|
||||
if p.Code == "upc.inf.cfi" {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Errorf("upc.inf.cfi missing from UPC + event_kind=filing list")
|
||||
}
|
||||
})
|
||||
}
|
||||
257
internal/services/fristenrechner_search_events.go
Normal file
257
internal/services/fristenrechner_search_events.go
Normal file
@@ -0,0 +1,257 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
// EventSearchHit is one ranked hit in the events-shape search response.
|
||||
// Returned by FristenrechnerService.SearchEvents.
|
||||
//
|
||||
// One hit per (procedural_event, proceeding_type) tuple: a single event
|
||||
// can appear in multiple proceedings (the data carries handful of
|
||||
// procedural_event rows whose code is null.* and that are anchored by
|
||||
// rules in different proceedings — those legacy stragglers surface as
|
||||
// multiple hits, one per proceeding context).
|
||||
type EventSearchHit struct {
|
||||
EventID uuid.UUID `json:"id"`
|
||||
Code string `json:"code"`
|
||||
NameDE string `json:"name_de"`
|
||||
NameEN string `json:"name_en"`
|
||||
EventKind *string `json:"event_kind,omitempty"`
|
||||
Description *string `json:"description,omitempty"`
|
||||
PrimaryParty *string `json:"primary_party,omitempty"`
|
||||
ProceedingType EventSearchPT `json:"proceeding_type"`
|
||||
AnchorRuleID uuid.UUID `json:"anchor_rule_id"`
|
||||
FollowUpCount int `json:"follow_up_count"`
|
||||
ConceptID *uuid.UUID `json:"concept_id,omitempty"`
|
||||
Score float64 `json:"score"`
|
||||
}
|
||||
|
||||
// EventSearchPT is the proceeding-type slice embedded in an EventSearchHit.
|
||||
type EventSearchPT struct {
|
||||
ID int `json:"id"`
|
||||
Code string `json:"code"`
|
||||
NameDE string `json:"name_de"`
|
||||
NameEN string `json:"name_en"`
|
||||
Jurisdiction *string `json:"jurisdiction,omitempty"`
|
||||
}
|
||||
|
||||
// EventSearchOptions is the filter set for SearchEvents. Empty values
|
||||
// mean "no narrowing on this axis".
|
||||
type EventSearchOptions struct {
|
||||
// Jurisdiction filters by proceeding_types.jurisdiction
|
||||
// ("UPC" | "DE" | "EPA" | "DPMA"). Empty = any.
|
||||
Jurisdiction string
|
||||
// ProceedingTypeCode narrows to one proceeding. Empty = any.
|
||||
ProceedingTypeCode string
|
||||
// EventKind filters by procedural_events.event_kind
|
||||
// ("filing" | "hearing" | "decision" | "order"). Empty = any.
|
||||
EventKind string
|
||||
// PrimaryParty narrows by the anchor rule's primary_party
|
||||
// ("claimant" | "defendant" | "court" | "both"). Empty = any.
|
||||
PrimaryParty string
|
||||
// Limit caps the result set; defaults to 50, max 200.
|
||||
Limit int
|
||||
}
|
||||
|
||||
// EventSearchResponse is the wire shape for ?kind=events on the
|
||||
// /api/tools/fristenrechner/search endpoint (design §6.1).
|
||||
type EventSearchResponse struct {
|
||||
Query string `json:"query"`
|
||||
Filters EventSearchFilters `json:"filters"`
|
||||
Events []EventSearchHit `json:"events"`
|
||||
Total int `json:"total"`
|
||||
}
|
||||
|
||||
// EventSearchFilters is the filter echo returned to the client.
|
||||
type EventSearchFilters struct {
|
||||
Jurisdiction *string `json:"jurisdiction"`
|
||||
ProceedingTypeCode *string `json:"proceeding_type_code"`
|
||||
EventKind *string `json:"event_kind"`
|
||||
PrimaryParty *string `json:"primary_party"`
|
||||
}
|
||||
|
||||
// SearchEvents implements the ?kind=events response shape (Fristenrechner
|
||||
// overhaul S1, design §6.1). Returns one hit per (procedural_event ×
|
||||
// proceeding_type) tuple, ranked by trigram similarity against name /
|
||||
// name_en / code. Empty q returns the unranked catalog filtered by the
|
||||
// supplied facets.
|
||||
func (s *DeadlineSearchService) SearchEvents(ctx context.Context, q string, opts EventSearchOptions) (*EventSearchResponse, error) {
|
||||
limit := opts.Limit
|
||||
if limit <= 0 {
|
||||
limit = 50
|
||||
}
|
||||
if limit > 200 {
|
||||
limit = 200
|
||||
}
|
||||
|
||||
qNorm := normalizeQuery(q)
|
||||
|
||||
resp := &EventSearchResponse{
|
||||
Query: q,
|
||||
Filters: buildEventFilters(opts),
|
||||
Events: []EventSearchHit{},
|
||||
}
|
||||
|
||||
where := []string{
|
||||
"sr.is_active = true",
|
||||
"sr.lifecycle_state = 'published'",
|
||||
"pe.is_active = true",
|
||||
"pe.lifecycle_state = 'published'",
|
||||
"pt.is_active = true",
|
||||
}
|
||||
args := []any{}
|
||||
add := func(clause string, val any) {
|
||||
args = append(args, val)
|
||||
where = append(where, fmt.Sprintf(clause, len(args)))
|
||||
}
|
||||
if opts.Jurisdiction != "" {
|
||||
add("pt.jurisdiction = $%d", opts.Jurisdiction)
|
||||
}
|
||||
if opts.ProceedingTypeCode != "" {
|
||||
add("pt.code = $%d", opts.ProceedingTypeCode)
|
||||
}
|
||||
if opts.EventKind != "" {
|
||||
add("pe.event_kind = $%d", opts.EventKind)
|
||||
}
|
||||
if opts.PrimaryParty != "" {
|
||||
add("sr.primary_party = $%d", opts.PrimaryParty)
|
||||
}
|
||||
|
||||
// Trigram score over (name || name_en || code). Empty query collapses
|
||||
// the score to 0 — keeps the SQL identical regardless of input mode.
|
||||
scoreExpr := "0::float8"
|
||||
if qNorm != "" {
|
||||
args = append(args, qNorm)
|
||||
scoreExpr = fmt.Sprintf(
|
||||
`GREATEST(similarity(pe.name, $%[1]d), similarity(pe.name_en, $%[1]d), similarity(pe.code, $%[1]d))`,
|
||||
len(args))
|
||||
// Drop hits with zero similarity so a typo doesn't return the
|
||||
// whole catalog ranked at 0.
|
||||
where = append(where, fmt.Sprintf(
|
||||
`(pe.name %% $%[1]d OR pe.name_en %% $%[1]d OR pe.code %% $%[1]d)`,
|
||||
len(args)))
|
||||
}
|
||||
|
||||
// follow_up_count: rules whose parent_id points at this anchor rule.
|
||||
// Computed via correlated subquery; cheap at the 231-row scale.
|
||||
query := `
|
||||
SELECT pe.id AS event_id,
|
||||
pe.code,
|
||||
pe.name AS name_de,
|
||||
pe.name_en,
|
||||
pe.event_kind,
|
||||
pe.description,
|
||||
sr.primary_party,
|
||||
pe.concept_id,
|
||||
sr.id AS anchor_rule_id,
|
||||
pt.id AS pt_id,
|
||||
pt.code AS pt_code,
|
||||
pt.name AS pt_name_de,
|
||||
pt.name_en AS pt_name_en,
|
||||
pt.jurisdiction AS pt_jurisdiction,
|
||||
(SELECT COUNT(*)::int
|
||||
FROM paliad.sequencing_rules child
|
||||
WHERE child.parent_id = sr.id
|
||||
AND child.is_active = true
|
||||
AND child.lifecycle_state = 'published') AS follow_up_count,
|
||||
` + scoreExpr + ` AS score
|
||||
FROM paliad.sequencing_rules sr
|
||||
JOIN paliad.procedural_events pe ON pe.id = sr.procedural_event_id
|
||||
JOIN paliad.proceeding_types pt ON pt.id = sr.proceeding_type_id
|
||||
WHERE ` + strings.Join(where, "\n AND ") + `
|
||||
ORDER BY score DESC, pt.sort_order, pe.code
|
||||
LIMIT $` + fmt.Sprintf("%d", len(args)+1)
|
||||
|
||||
args = append(args, limit)
|
||||
|
||||
type row struct {
|
||||
EventID uuid.UUID `db:"event_id"`
|
||||
Code string `db:"code"`
|
||||
NameDE string `db:"name_de"`
|
||||
NameEN string `db:"name_en"`
|
||||
EventKind sql.NullString `db:"event_kind"`
|
||||
Description sql.NullString `db:"description"`
|
||||
PrimaryParty sql.NullString `db:"primary_party"`
|
||||
ConceptID *uuid.UUID `db:"concept_id"`
|
||||
AnchorRuleID uuid.UUID `db:"anchor_rule_id"`
|
||||
PTID int `db:"pt_id"`
|
||||
PTCode string `db:"pt_code"`
|
||||
PTNameDE string `db:"pt_name_de"`
|
||||
PTNameEN string `db:"pt_name_en"`
|
||||
PTJurisdiction sql.NullString `db:"pt_jurisdiction"`
|
||||
FollowUpCount int `db:"follow_up_count"`
|
||||
Score float64 `db:"score"`
|
||||
}
|
||||
|
||||
var rows []row
|
||||
if err := s.db.SelectContext(ctx, &rows, query, args...); err != nil {
|
||||
return nil, fmt.Errorf("search events: %w", err)
|
||||
}
|
||||
|
||||
hits := make([]EventSearchHit, 0, len(rows))
|
||||
for _, r := range rows {
|
||||
hit := EventSearchHit{
|
||||
EventID: r.EventID,
|
||||
Code: r.Code,
|
||||
NameDE: r.NameDE,
|
||||
NameEN: r.NameEN,
|
||||
AnchorRuleID: r.AnchorRuleID,
|
||||
FollowUpCount: r.FollowUpCount,
|
||||
ConceptID: r.ConceptID,
|
||||
Score: r.Score,
|
||||
ProceedingType: EventSearchPT{
|
||||
ID: r.PTID,
|
||||
Code: r.PTCode,
|
||||
NameDE: r.PTNameDE,
|
||||
NameEN: r.PTNameEN,
|
||||
},
|
||||
}
|
||||
if r.EventKind.Valid {
|
||||
v := r.EventKind.String
|
||||
hit.EventKind = &v
|
||||
}
|
||||
if r.Description.Valid {
|
||||
v := r.Description.String
|
||||
hit.Description = &v
|
||||
}
|
||||
if r.PrimaryParty.Valid {
|
||||
v := r.PrimaryParty.String
|
||||
hit.PrimaryParty = &v
|
||||
}
|
||||
if r.PTJurisdiction.Valid {
|
||||
v := r.PTJurisdiction.String
|
||||
hit.ProceedingType.Jurisdiction = &v
|
||||
}
|
||||
hits = append(hits, hit)
|
||||
}
|
||||
resp.Events = hits
|
||||
resp.Total = len(hits)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func buildEventFilters(opts EventSearchOptions) EventSearchFilters {
|
||||
f := EventSearchFilters{}
|
||||
if opts.Jurisdiction != "" {
|
||||
v := opts.Jurisdiction
|
||||
f.Jurisdiction = &v
|
||||
}
|
||||
if opts.ProceedingTypeCode != "" {
|
||||
v := opts.ProceedingTypeCode
|
||||
f.ProceedingTypeCode = &v
|
||||
}
|
||||
if opts.EventKind != "" {
|
||||
v := opts.EventKind
|
||||
f.EventKind = &v
|
||||
}
|
||||
if opts.PrimaryParty != "" {
|
||||
v := opts.PrimaryParty
|
||||
f.PrimaryParty = &v
|
||||
}
|
||||
return f
|
||||
}
|
||||
@@ -58,6 +58,14 @@ var (
|
||||
// surface this as a 400 with a bilingual friendly message; the
|
||||
// matching DB trigger (mig 088) is the defence-in-depth backstop.
|
||||
ErrInvalidProceedingTypeCategory = errors.New("proceeding_type_id must reference a fristenrechner-category proceeding_types row")
|
||||
// ErrInvalidProceedingTypeKind signals that the caller supplied a
|
||||
// proceeding_type_id pointing at a non-primary row — i.e. a
|
||||
// phase/side_action/meta row, or an inactive row. Mig 153
|
||||
// (t-paliad-325, design §1) carved the taxonomy so only
|
||||
// kind='proceeding' AND is_active=true rows may bind to a
|
||||
// project. Handlers surface this as a 400; the matching DB
|
||||
// trigger (mig 153) is the defence-in-depth backstop.
|
||||
ErrInvalidProceedingTypeKind = errors.New("proceeding_type_id must reference an active kind='proceeding' proceeding_types row")
|
||||
)
|
||||
|
||||
// ProjectType values enumerated on the projects.type CHECK constraint.
|
||||
@@ -1165,29 +1173,47 @@ func (s *ProjectService) Update(ctx context.Context, userID, id uuid.UUID, input
|
||||
return s.GetByID(ctx, userID, id)
|
||||
}
|
||||
|
||||
// validateProceedingTypeCategory enforces the Phase 3 Slice 5 invariant
|
||||
// (t-paliad-186, design §3.F + m's Q2 ruling): a project may only bind
|
||||
// to a fristenrechner-category proceeding_types row. NULL passes
|
||||
// through; the matching DB trigger (mig 088) is the defence-in-depth
|
||||
// backstop should this slip somehow.
|
||||
// validateProceedingTypeCategory enforces the project-binding invariants
|
||||
// on paliad.projects.proceeding_type_id:
|
||||
//
|
||||
// Surfaces ErrInvalidProceedingTypeCategory so handlers can map to a
|
||||
// 400 with a bilingual user-facing message.
|
||||
// 1. Phase 3 Slice 5 (t-paliad-186, design §3.F): row must be
|
||||
// category='fristenrechner'. DB-side backstop: mig 088 trigger.
|
||||
// Surfaces ErrInvalidProceedingTypeCategory.
|
||||
//
|
||||
// 2. Mig 153 (t-paliad-325, design §1 + m's Q8): row must be
|
||||
// kind='proceeding' AND is_active=true. DB-side backstop: mig 153
|
||||
// trigger. Surfaces ErrInvalidProceedingTypeKind. Rejects phase /
|
||||
// side_action / meta rows and any deactivated row.
|
||||
//
|
||||
// NULL passes through. The Go layer fires first so handlers get typed
|
||||
// errors; the DB triggers catch any writer that bypasses the service.
|
||||
func (s *ProjectService) validateProceedingTypeCategory(ctx context.Context, ptID *int) error {
|
||||
if ptID == nil {
|
||||
return nil
|
||||
}
|
||||
var category sql.NullString
|
||||
if err := s.db.GetContext(ctx, &category,
|
||||
`SELECT category FROM paliad.proceeding_types WHERE id = $1`, *ptID); err != nil {
|
||||
var row struct {
|
||||
Category sql.NullString `db:"category"`
|
||||
Kind sql.NullString `db:"kind"`
|
||||
IsActive bool `db:"is_active"`
|
||||
}
|
||||
if err := s.db.GetContext(ctx, &row,
|
||||
`SELECT category, kind, is_active FROM paliad.proceeding_types WHERE id = $1`, *ptID); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return fmt.Errorf("%w: proceeding_type_id=%d not found", ErrInvalidInput, *ptID)
|
||||
}
|
||||
return fmt.Errorf("lookup proceeding_type category: %w", err)
|
||||
return fmt.Errorf("lookup proceeding_type: %w", err)
|
||||
}
|
||||
if !category.Valid || category.String != "fristenrechner" {
|
||||
if !row.Category.Valid || row.Category.String != "fristenrechner" {
|
||||
return fmt.Errorf("%w: proceeding_type_id=%d has category=%q",
|
||||
ErrInvalidProceedingTypeCategory, *ptID, category.String)
|
||||
ErrInvalidProceedingTypeCategory, *ptID, row.Category.String)
|
||||
}
|
||||
if !row.Kind.Valid || row.Kind.String != "proceeding" {
|
||||
return fmt.Errorf("%w: proceeding_type_id=%d has kind=%q",
|
||||
ErrInvalidProceedingTypeKind, *ptID, row.Kind.String)
|
||||
}
|
||||
if !row.IsActive {
|
||||
return fmt.Errorf("%w: proceeding_type_id=%d is inactive",
|
||||
ErrInvalidProceedingTypeKind, *ptID)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -163,6 +163,162 @@ func TestProjectService_ProceedingTypeCategoryGuard(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestProjectService_ProceedingTypeKindGuard exercises the mig 153
|
||||
// (t-paliad-325 / m/paliad#147) "kind='proceeding' only" invariant on
|
||||
// paliad.projects.proceeding_type_id from three angles:
|
||||
//
|
||||
// 1. ProjectService.Create returns ErrInvalidProceedingTypeKind when
|
||||
// handed an id pointing at a kind='phase' / 'side_action' / 'meta'
|
||||
// row (the Go service guard fires before the DB trigger).
|
||||
//
|
||||
// 2. ProjectService.Create returns ErrInvalidProceedingTypeKind when
|
||||
// handed an id pointing at a row with is_active=false (mig 153 §4
|
||||
// deactivated all non-primary rows so this is the same set of IDs;
|
||||
// the test still independently asserts the is_active branch by
|
||||
// re-activating a phase row inside the test and confirming the kind
|
||||
// check still fires).
|
||||
//
|
||||
// 3. The mig 153 backstop trigger rejects a raw INSERT that bypasses
|
||||
// the Go service layer (defence-in-depth). Bypasses mig 088's
|
||||
// category trigger by also picking a fristenrechner-category row.
|
||||
//
|
||||
// 4. Passing a kind='proceeding' active id (upc.inf.cfi) still
|
||||
// succeeds — proves the new guard doesn't break the happy path.
|
||||
//
|
||||
// Skipped when TEST_DATABASE_URL is unset, mirroring the rest of this
|
||||
// file.
|
||||
func TestProjectService_ProceedingTypeKindGuard(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()
|
||||
|
||||
// A row that is fristenrechner-category but kind != 'proceeding'.
|
||||
// Picks the first phase row by id (deterministic). Falls back to any
|
||||
// non-proceeding kind if no phase rows are present (post-data-drift
|
||||
// hardening).
|
||||
var phaseID int
|
||||
if err := pool.GetContext(ctx, &phaseID,
|
||||
`SELECT id FROM paliad.proceeding_types
|
||||
WHERE category = 'fristenrechner' AND kind <> 'proceeding'
|
||||
ORDER BY (kind = 'phase') DESC, id
|
||||
LIMIT 1`); err != nil {
|
||||
t.Fatalf("look up non-proceeding kind id: %v", err)
|
||||
}
|
||||
|
||||
// A primary id for the happy-path case + raw-INSERT control.
|
||||
var proceedingID int
|
||||
if err := pool.GetContext(ctx, &proceedingID,
|
||||
`SELECT id FROM paliad.proceeding_types
|
||||
WHERE category = 'fristenrechner' AND kind = 'proceeding'
|
||||
AND is_active = true AND code = $1`,
|
||||
CodeUPCInfringement); err != nil {
|
||||
t.Fatalf("look up %s id: %v", CodeUPCInfringement, 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, 'mig153-guard-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, 'mig153-guard-test@hlc.com', 'Mig153 Guard', 'munich', 'associate', 'de')`,
|
||||
userID); err != nil {
|
||||
t.Fatalf("seed paliad.users: %v", err)
|
||||
}
|
||||
|
||||
// 1. Non-proceeding kind id → ErrInvalidProceedingTypeKind from the
|
||||
// service guard. (The row is also is_active=false post-mig-153,
|
||||
// but the kind check fires first.)
|
||||
_, err = svc.Create(ctx, userID, CreateProjectInput{
|
||||
Type: ProjectTypeProject,
|
||||
Title: "Mig 153 — non-proceeding-kind reject",
|
||||
ProceedingTypeID: &phaseID,
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("Create with kind!=proceeding proceeding_type_id should fail, but succeeded")
|
||||
} else if !errors.Is(err, ErrInvalidProceedingTypeKind) {
|
||||
t.Errorf("expected ErrInvalidProceedingTypeKind, got %v", err)
|
||||
}
|
||||
|
||||
// 2. Re-activate the phase row in a savepoint so the kind check
|
||||
// still fires (proves the kind branch isn't shadowed by the
|
||||
// is_active branch).
|
||||
if _, err := pool.ExecContext(ctx,
|
||||
`UPDATE paliad.proceeding_types SET is_active = true WHERE id = $1`, phaseID); err != nil {
|
||||
t.Fatalf("re-activate phase row: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
pool.ExecContext(ctx,
|
||||
`UPDATE paliad.proceeding_types SET is_active = false WHERE id = $1`, phaseID)
|
||||
})
|
||||
|
||||
_, err = svc.Create(ctx, userID, CreateProjectInput{
|
||||
Type: ProjectTypeProject,
|
||||
Title: "Mig 153 — active phase row still rejects on kind",
|
||||
ProceedingTypeID: &phaseID,
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("Create with active kind=phase row should still fail on kind check; got nil")
|
||||
} else if !errors.Is(err, ErrInvalidProceedingTypeKind) {
|
||||
t.Errorf("expected ErrInvalidProceedingTypeKind, got %v", err)
|
||||
}
|
||||
|
||||
// 3. mig 153 trigger — raw INSERT bypassing Go service must raise.
|
||||
// We use the active phase row (still re-activated from step 2)
|
||||
// so we don't trip mig 088's category check first. Both triggers
|
||||
// are independent; mig 153's must fire on a category=fristenrechner
|
||||
// kind!=proceeding row.
|
||||
rawID := uuid.New()
|
||||
defer pool.ExecContext(ctx, `DELETE FROM paliad.projects WHERE id = $1`, rawID)
|
||||
_, err = pool.ExecContext(ctx,
|
||||
`INSERT INTO paliad.projects
|
||||
(id, type, parent_id, path, title, status, created_by,
|
||||
proceeding_type_id, metadata, created_at, updated_at)
|
||||
VALUES ($1, 'project', NULL, $1::text, 'Mig 153 — trigger bypass', 'active', $2,
|
||||
$3, '{}'::jsonb, now(), now())`,
|
||||
rawID, userID, phaseID)
|
||||
if err == nil {
|
||||
t.Error("raw INSERT with kind!=proceeding proceeding_type_id should have raised; got nil")
|
||||
}
|
||||
|
||||
// 4. Happy path: kind='proceeding' active id → success.
|
||||
created, err := svc.Create(ctx, userID, CreateProjectInput{
|
||||
Type: ProjectTypeProject,
|
||||
Title: "Mig 153 — primary proceeding accept",
|
||||
ProceedingTypeID: &proceedingID,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("Create with kind=proceeding proceeding_type_id: %v", err)
|
||||
}
|
||||
if created.ProceedingTypeID == nil || *created.ProceedingTypeID != proceedingID {
|
||||
t.Errorf("created proceeding_type_id = %v, want %d", created.ProceedingTypeID, proceedingID)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProjectService_InstanceLevel_Roundtrip covers the Phase 3 Slice 8
|
||||
// (t-paliad-189) instance_level data path: Create + Update both accept
|
||||
// the four allowed shapes (first / appeal / cassation / NULL) and reject
|
||||
|
||||
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jmoiron/sqlx"
|
||||
"github.com/lib/pq"
|
||||
|
||||
"mgit.msbls.de/m/paliad/internal/models"
|
||||
lp "mgit.msbls.de/m/paliad/pkg/litigationplanner"
|
||||
@@ -677,6 +678,42 @@ func (s *RuleEditorService) ListRules(ctx context.Context, f ListRulesFilter) ([
|
||||
return rows, nil
|
||||
}
|
||||
|
||||
// LoadProceedingTypeCodes returns an id → code map for every distinct
|
||||
// non-NULL proceeding_type_id present in rows. Single SELECT against
|
||||
// paliad.proceeding_types (firm-wide reference data, no RLS). Used by
|
||||
// /admin/api/procedural-events to enrich the LIST response with a
|
||||
// proceeding_type_code field so the admin UI can disambiguate
|
||||
// same-named rules at a glance (t-paliad-321).
|
||||
func (s *RuleEditorService) LoadProceedingTypeCodes(ctx context.Context, rows []models.DeadlineRule) (map[int]string, error) {
|
||||
seen := map[int]bool{}
|
||||
var ids []int
|
||||
for _, r := range rows {
|
||||
if r.ProceedingTypeID != nil && !seen[*r.ProceedingTypeID] {
|
||||
seen[*r.ProceedingTypeID] = true
|
||||
ids = append(ids, *r.ProceedingTypeID)
|
||||
}
|
||||
}
|
||||
if len(ids) == 0 {
|
||||
return nil, nil
|
||||
}
|
||||
type pair struct {
|
||||
ID int `db:"id"`
|
||||
Code string `db:"code"`
|
||||
}
|
||||
var pairs []pair
|
||||
if err := s.db.SelectContext(ctx, &pairs,
|
||||
`SELECT id, code FROM paliad.proceeding_types WHERE id = ANY($1)`,
|
||||
pq.Array(ids),
|
||||
); err != nil {
|
||||
return nil, fmt.Errorf("load proceeding_type codes: %w", err)
|
||||
}
|
||||
out := make(map[int]string, len(pairs))
|
||||
for _, p := range pairs {
|
||||
out[p.ID] = p.Code
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
|
||||
// GetByID returns a single rule. Exported so the handler can call it
|
||||
// directly without round-tripping through ListRules.
|
||||
func (s *RuleEditorService) GetByID(ctx context.Context, id uuid.UUID) (*models.DeadlineRule, error) {
|
||||
|
||||
Reference in New Issue
Block a user