Phase 3 Slice 7 Step G (design §6). Closes the half-finished
projection_service.go:896-901 spawn-skip from the t-178 audit.
What lands:
- DeadlineRuleService.ListByProceedingTypeIDs(ids): bulk-load
rules for a set of spawn-target proceedings in one round-trip.
Skips hydrateConceptDefaultEventTypes (SmartTimeline doesn't
need concept-default event_types on spawned rows). Pre-sorted
by (proceeding_type_id, sequence_order) so callers pick the
target's root rule via the first slot per proceeding.
- ProjectionService.expandCrossProceedingSpawns: walks the spawn
graph rooted at the project's source proceeding. For each rule
with is_spawn=true AND a non-NULL spawn_proceeding_type_id,
resolves the target proceeding's root rule and emits a
spawned-into TimelineEvent with:
Kind="projected", Track="spawn", Status="predicted",
DependsOnRuleCode=<source.code>, DependsOnRuleName=<source.name>,
DependsOnDate=<source's computed due date when available>.
SpawnLabel on the source rule, if set, is appended to the
target title as "<target name> (<spawn_label>)".
- Cycle guard: visited-set DFS keyed by proceeding_type_id. The
source proceeding is seeded into `visited` before the walk;
when any spawn's target is already in `visited`, the helper
returns ErrCyclicSpawn with rule + proceeding context. The
caller (computeProjections) catches the error and degrades to
"no spawned rows" — better than failing the whole projection.
ProjectionMeta.SpawnCycleDropped surfaces the degradation so
the caller can log + show a "Spawn-Auflösung übersprungen"
banner.
- Recursion: expandCrossProceedingSpawns recurses into the
target proceeding's spawn rules (depth+1) so a chain
A → B → C surfaces every hop. maxSpawnDepth (4) is a safety
belt on top of the visited-set guard.
Live data semantics: the live corpus has 6 active is_spawn=true
rules — AMD.ccr.amend, AMD.rev.amend, APP.ccr.appeal,
APP.inf.appeal, APP.rev.appeal, CCR.ccr.counterclaim. ALL six have
spawn_proceeding_type_id IS NULL today, so the live SmartTimeline
emits zero spawned-into rows. Slice 7 wires the code path; the
backfill of spawn_proceeding_type_id on these 6 rules is a
separate concern (the design doc's mig 093 was deferred — the
litigation-category proceedings these rules sit in were retired
from project-binding in Slice 5).
Calculator stays scoped (Option A, design §6.2): the unified
FristenrechnerService.Calculate does NOT follow spawns. The
SmartTimeline projection service is the sole consumer that chains
across proceedings. UIResponse.Deadlines for a proceeding only
contains rules from that proceeding; spawn resolution happens at
the projection layer.
projection_service.go:896-901 comment updated to reflect the new
post-Slice-7 reality (calculator stays scoped; spawned rules
arrive via expandCrossProceedingSpawns, not via the calculator's
Deadlines list).
357 lines
13 KiB
Go
357 lines
13 KiB
Go
package services
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jmoiron/sqlx"
|
|
|
|
"mgit.msbls.de/m/paliad/internal/models"
|
|
)
|
|
|
|
// DeadlineRuleService reads paliad.deadline_rules + paliad.proceeding_types.
|
|
// Rules are static reference data; no visibility check needed.
|
|
type DeadlineRuleService struct {
|
|
db *sqlx.DB
|
|
}
|
|
|
|
// NewDeadlineRuleService wires the service to the pool.
|
|
func NewDeadlineRuleService(db *sqlx.DB) *DeadlineRuleService {
|
|
return &DeadlineRuleService{db: db}
|
|
}
|
|
|
|
// ruleColumns lists every column scanned into models.DeadlineRule.
|
|
//
|
|
// Compat-mode (t-paliad-182 Phase 3 Slice 1): the SELECT reads BOTH
|
|
// the legacy shape (is_mandatory, is_optional, condition_flag,
|
|
// condition_rule_id) and the unified Phase 3 shape (trigger_event_id,
|
|
// spawn_proceeding_type_id, combine_op, condition_expr, priority,
|
|
// is_court_set, lifecycle_state, draft_of, published_at). Existing
|
|
// callers stay on the legacy fields; the new fields are NULL or carry
|
|
// their migration default until Slice 2 backfills them. Slice 4 cuts
|
|
// the calculator over to the new fields, Slice 9 drops the legacy
|
|
// columns.
|
|
const ruleColumns = `id, proceeding_type_id, parent_id, code, name, name_en,
|
|
description, primary_party, event_type, is_mandatory, duration_value,
|
|
duration_unit, timing, rule_code, deadline_notes, deadline_notes_en, sequence_order,
|
|
condition_rule_id, condition_flag, alt_duration_value, alt_duration_unit, alt_rule_code,
|
|
anchor_alt, concept_id, legal_source, is_spawn, spawn_label, is_optional, is_active,
|
|
created_at, updated_at,
|
|
trigger_event_id, spawn_proceeding_type_id, combine_op, condition_expr,
|
|
priority, is_court_set, lifecycle_state, draft_of, published_at`
|
|
|
|
const proceedingTypeColumns = `id, code, name, name_en, description, jurisdiction,
|
|
category, default_color, sort_order, is_active`
|
|
|
|
// List returns active rules, optionally filtered by proceeding type.
|
|
// Each row has ConceptDefaultEventTypeID hydrated from
|
|
// paliad.deadline_concept_event_types so the deadline-create form can
|
|
// auto-populate the Typ chip when the user picks a Regel.
|
|
func (s *DeadlineRuleService) List(ctx context.Context, proceedingTypeID *int) ([]models.DeadlineRule, error) {
|
|
var rules []models.DeadlineRule
|
|
var err error
|
|
|
|
if proceedingTypeID != nil {
|
|
err = s.db.SelectContext(ctx, &rules,
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE proceeding_type_id = $1 AND is_active = true
|
|
ORDER BY sequence_order`, *proceedingTypeID)
|
|
} else {
|
|
err = s.db.SelectContext(ctx, &rules,
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE is_active = true
|
|
ORDER BY proceeding_type_id, sequence_order`)
|
|
}
|
|
if err != nil {
|
|
return nil, fmt.Errorf("list deadline rules: %w", err)
|
|
}
|
|
if err := s.hydrateConceptDefaultEventTypes(ctx, rules); err != nil {
|
|
return nil, err
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// hydrateConceptDefaultEventTypes resolves each rule's (concept_id,
|
|
// proceeding_type.jurisdiction) pair to the canonical paliad.event_types
|
|
// row from paliad.deadline_concept_event_types (where is_default and
|
|
// jurisdiction matches), and assigns it to ConceptDefaultEventTypeID.
|
|
//
|
|
// One round-trip via JOIN to paliad.proceeding_types so we can match on
|
|
// the rule's jurisdiction without a per-rule second query. EPA→EPO
|
|
// canonicalisation is done in SQL because event_types use 'EPO' but
|
|
// proceeding_types use 'EPA' — the two columns disagreed before this
|
|
// mapping table existed (mig 074).
|
|
//
|
|
// Rules whose (concept, jurisdiction) has no default stay NULL —
|
|
// silent no-op on the form, better than a wrong-jurisdiction default.
|
|
func (s *DeadlineRuleService) hydrateConceptDefaultEventTypes(ctx context.Context, rules []models.DeadlineRule) error {
|
|
ruleIDs := make([]uuid.UUID, 0, len(rules))
|
|
for _, r := range rules {
|
|
if r.ConceptID == nil {
|
|
continue
|
|
}
|
|
ruleIDs = append(ruleIDs, r.ID)
|
|
}
|
|
if len(ruleIDs) == 0 {
|
|
return nil
|
|
}
|
|
query, args, err := sqlx.In(
|
|
`SELECT dr.id AS rule_id, j.event_type_id
|
|
FROM paliad.deadline_rules dr
|
|
JOIN paliad.proceeding_types pt ON pt.id = dr.proceeding_type_id
|
|
JOIN paliad.deadline_concept_event_types j
|
|
ON j.concept_id = dr.concept_id
|
|
AND j.is_default = true
|
|
AND j.jurisdiction = CASE WHEN pt.jurisdiction = 'EPA' THEN 'EPO' ELSE pt.jurisdiction END
|
|
WHERE dr.id IN (?)`, ruleIDs)
|
|
if err != nil {
|
|
return fmt.Errorf("build rule→event_type IN query: %w", err)
|
|
}
|
|
query = s.db.Rebind(query)
|
|
|
|
type row struct {
|
|
RuleID uuid.UUID `db:"rule_id"`
|
|
EventTypeID uuid.UUID `db:"event_type_id"`
|
|
}
|
|
var rows []row
|
|
if err := s.db.SelectContext(ctx, &rows, query, args...); err != nil {
|
|
return fmt.Errorf("load rule→event_type defaults: %w", err)
|
|
}
|
|
defaultByRule := make(map[uuid.UUID]uuid.UUID, len(rows))
|
|
for _, r := range rows {
|
|
defaultByRule[r.RuleID] = r.EventTypeID
|
|
}
|
|
for i := range rules {
|
|
if et, ok := defaultByRule[rules[i].ID]; ok {
|
|
etCopy := et
|
|
rules[i].ConceptDefaultEventTypeID = &etCopy
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// RuleTreeNode pairs a rule with its child rules in a parent_id hierarchy.
|
|
type RuleTreeNode struct {
|
|
models.DeadlineRule
|
|
Children []RuleTreeNode `json:"children,omitempty"`
|
|
}
|
|
|
|
// GetRuleTree returns rules for a proceeding type as a tree (same proceeding type only).
|
|
func (s *DeadlineRuleService) GetRuleTree(ctx context.Context, proceedingTypeCode string) ([]RuleTreeNode, error) {
|
|
var pt models.ProceedingType
|
|
if err := s.db.GetContext(ctx, &pt,
|
|
`SELECT `+proceedingTypeColumns+`
|
|
FROM paliad.proceeding_types
|
|
WHERE code = $1 AND is_active = true`, proceedingTypeCode); err != nil {
|
|
return nil, fmt.Errorf("resolve proceeding type %q: %w", proceedingTypeCode, err)
|
|
}
|
|
|
|
var rules []models.DeadlineRule
|
|
if err := s.db.SelectContext(ctx, &rules,
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE proceeding_type_id = $1 AND is_active = true
|
|
ORDER BY sequence_order`, pt.ID); err != nil {
|
|
return nil, fmt.Errorf("list rules for %q: %w", proceedingTypeCode, err)
|
|
}
|
|
return buildTree(rules), nil
|
|
}
|
|
|
|
// GetFullTimeline returns all rules in the tree starting at the given proceeding
|
|
// type, following parent_id even across proceeding types (for cross-type spawns
|
|
// like "Appeal" hanging off an INF Decision).
|
|
func (s *DeadlineRuleService) GetFullTimeline(ctx context.Context, proceedingTypeCode string) ([]models.DeadlineRule, *models.ProceedingType, error) {
|
|
var pt models.ProceedingType
|
|
if err := s.db.GetContext(ctx, &pt,
|
|
`SELECT `+proceedingTypeColumns+`
|
|
FROM paliad.proceeding_types
|
|
WHERE code = $1 AND is_active = true`, proceedingTypeCode); err != nil {
|
|
return nil, nil, fmt.Errorf("resolve proceeding type %q: %w", proceedingTypeCode, err)
|
|
}
|
|
|
|
var rules []models.DeadlineRule
|
|
err := s.db.SelectContext(ctx, &rules, `
|
|
WITH RECURSIVE tree AS (
|
|
SELECT * FROM paliad.deadline_rules
|
|
WHERE proceeding_type_id = $1 AND parent_id IS NULL AND is_active = true
|
|
UNION ALL
|
|
SELECT dr.* FROM paliad.deadline_rules dr
|
|
JOIN tree t ON dr.parent_id = t.id
|
|
WHERE dr.is_active = true
|
|
)
|
|
SELECT `+ruleColumns+` FROM tree ORDER BY sequence_order`, pt.ID)
|
|
if err != nil {
|
|
return nil, nil, fmt.Errorf("fetch timeline for %q: %w", proceedingTypeCode, err)
|
|
}
|
|
return rules, &pt, nil
|
|
}
|
|
|
|
// GetByIDs fetches a set of rules by UUID.
|
|
func (s *DeadlineRuleService) GetByIDs(ctx context.Context, ids []uuid.UUID) ([]models.DeadlineRule, error) {
|
|
if len(ids) == 0 {
|
|
return nil, nil
|
|
}
|
|
query, args, err := sqlx.In(
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE id IN (?) AND is_active = true
|
|
ORDER BY sequence_order`, ids)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build IN query: %w", err)
|
|
}
|
|
query = s.db.Rebind(query)
|
|
|
|
var rules []models.DeadlineRule
|
|
if err := s.db.SelectContext(ctx, &rules, query, args...); err != nil {
|
|
return nil, fmt.Errorf("fetch rules by IDs: %w", err)
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// ListByTriggerEvent returns active rules scoped to a single trigger
|
|
// event — the Pipeline-C surface added by Phase 3 Slice 3 (mig 085).
|
|
// These rules carry proceeding_type_id IS NULL (event-rooted) and have
|
|
// no parent_id chain.
|
|
//
|
|
// Distinct from List: List filters by proceeding_type_id and runs
|
|
// hydrateConceptDefaultEventTypes (which assumes a proceeding-type FK).
|
|
// Pipeline-C rules don't have that FK, so hydration is skipped here.
|
|
//
|
|
// Order by sequence_order so the data-move's (1000 + ed.id) offset
|
|
// preserves the original event_deadlines.id ordering.
|
|
func (s *DeadlineRuleService) ListByTriggerEvent(ctx context.Context, triggerEventID int64) ([]models.DeadlineRule, error) {
|
|
var rules []models.DeadlineRule
|
|
if err := s.db.SelectContext(ctx, &rules,
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE trigger_event_id = $1
|
|
AND is_active = true
|
|
ORDER BY sequence_order`, triggerEventID); err != nil {
|
|
return nil, fmt.Errorf("list deadline rules by trigger_event_id=%d: %w", triggerEventID, err)
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// ListByProceedingTypeIDs returns active rules across a set of
|
|
// proceeding types, ordered by (proceeding_type_id, sequence_order) so
|
|
// callers can group + pick the "first rule" (lowest sequence_order)
|
|
// per proceeding without a second sort. Phase 3 Slice 7 (t-paliad-188)
|
|
// uses this for cross-proceeding spawn target expansion: given a list
|
|
// of spawn_proceeding_type_id values, bulk-load every target
|
|
// proceeding's rules in one round-trip.
|
|
//
|
|
// Empty input returns nil, nil (no SELECT issued). Distinct from
|
|
// List(proceedingTypeID) which scopes to a single proceeding + runs
|
|
// hydrateConceptDefaultEventTypes — this method skips hydration since
|
|
// the SmartTimeline doesn't need concept-default event types on
|
|
// spawned rules.
|
|
func (s *DeadlineRuleService) ListByProceedingTypeIDs(ctx context.Context, ids []int) ([]models.DeadlineRule, error) {
|
|
if len(ids) == 0 {
|
|
return nil, nil
|
|
}
|
|
query, args, err := sqlx.In(
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE proceeding_type_id IN (?)
|
|
AND is_active = true
|
|
ORDER BY proceeding_type_id, sequence_order`, ids)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("build IN query for proceeding ids: %w", err)
|
|
}
|
|
query = s.db.Rebind(query)
|
|
|
|
var rules []models.DeadlineRule
|
|
if err := s.db.SelectContext(ctx, &rules, query, args...); err != nil {
|
|
return nil, fmt.Errorf("list deadline rules by proceeding_type_ids %v: %w", ids, err)
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// ListByConcept returns active rules linked to a single
|
|
// paliad.deadline_concepts row via the concept_id FK. Used by the
|
|
// Phase 3 Slice 6 event-trigger endpoint (t-paliad-187) to discover
|
|
// the rules a cascade leaf produces.
|
|
//
|
|
// Distinct from ListByTriggerEvent (Pipeline-C): this is the
|
|
// Pipeline-A concept-keyed path. A concept may have rules across
|
|
// multiple proceeding_types — the caller may want to narrow further
|
|
// via event_category_concepts.proceeding_type_code, but the Slice 6
|
|
// service does no narrowing in v1 (returns every active rule on
|
|
// the concept).
|
|
//
|
|
// Order by sequence_order so rules within a proceeding stay in their
|
|
// canonical order. proceeding_type_id is a secondary sort so a
|
|
// multi-proceeding concept doesn't interleave its constituent rules.
|
|
func (s *DeadlineRuleService) ListByConcept(ctx context.Context, conceptID uuid.UUID) ([]models.DeadlineRule, error) {
|
|
var rules []models.DeadlineRule
|
|
if err := s.db.SelectContext(ctx, &rules,
|
|
`SELECT `+ruleColumns+`
|
|
FROM paliad.deadline_rules
|
|
WHERE concept_id = $1
|
|
AND is_active = true
|
|
ORDER BY proceeding_type_id NULLS LAST, sequence_order`, conceptID); err != nil {
|
|
return nil, fmt.Errorf("list deadline rules by concept_id=%s: %w", conceptID, err)
|
|
}
|
|
return rules, nil
|
|
}
|
|
|
|
// ListProceedingTypes returns active proceeding types ordered by sort_order.
|
|
func (s *DeadlineRuleService) ListProceedingTypes(ctx context.Context) ([]models.ProceedingType, error) {
|
|
return s.ListProceedingTypesByCategory(ctx, "")
|
|
}
|
|
|
|
// ListProceedingTypesByCategory returns active proceeding types
|
|
// ordered by sort_order, optionally filtered to a single category. An
|
|
// empty category returns every active row (preserves the legacy
|
|
// ListProceedingTypes behaviour).
|
|
//
|
|
// Phase 3 Slice 5 (t-paliad-186): the project-create / project-edit
|
|
// pickers pass category='fristenrechner' so users never see retired
|
|
// litigation codes when binding a project to a proceeding (design §3.F).
|
|
func (s *DeadlineRuleService) ListProceedingTypesByCategory(ctx context.Context, category string) ([]models.ProceedingType, error) {
|
|
var types []models.ProceedingType
|
|
if category == "" {
|
|
if err := s.db.SelectContext(ctx, &types,
|
|
`SELECT `+proceedingTypeColumns+`
|
|
FROM paliad.proceeding_types
|
|
WHERE is_active = true
|
|
ORDER BY sort_order`); err != nil {
|
|
return nil, fmt.Errorf("list proceeding types: %w", err)
|
|
}
|
|
return types, nil
|
|
}
|
|
if err := s.db.SelectContext(ctx, &types,
|
|
`SELECT `+proceedingTypeColumns+`
|
|
FROM paliad.proceeding_types
|
|
WHERE is_active = true
|
|
AND category = $1
|
|
ORDER BY sort_order`, category); err != nil {
|
|
return nil, fmt.Errorf("list proceeding types by category %q: %w", category, err)
|
|
}
|
|
return types, nil
|
|
}
|
|
|
|
// buildTree converts a flat rule slice into a parent_id-rooted tree.
|
|
func buildTree(rules []models.DeadlineRule) []RuleTreeNode {
|
|
nodeMap := make(map[uuid.UUID]*RuleTreeNode, len(rules))
|
|
var roots []RuleTreeNode
|
|
|
|
for _, r := range rules {
|
|
nodeMap[r.ID] = &RuleTreeNode{DeadlineRule: r}
|
|
}
|
|
for _, r := range rules {
|
|
node := nodeMap[r.ID]
|
|
if r.ParentID != nil {
|
|
if parent, ok := nodeMap[*r.ParentID]; ok {
|
|
parent.Children = append(parent.Children, *node)
|
|
continue
|
|
}
|
|
}
|
|
roots = append(roots, *node)
|
|
}
|
|
return roots
|
|
}
|