feat(collections): smart (dynamic) collections — rules evaluated live at render

Type is DERIVED, not stored: a saved ruleset makes a collection SMART,
no rules = STATIC (stored collection_items links, unchanged behavior).
No schema change — collections.auto_assign_rules JSONB already carried
the config; user's decision 2026-10-14 (handoff: live-at-render, not
refresh-on-scan; create-time Static/Smart toggle; v1 NO hybrid).

- Rule gains an enabled flag (absent = enabled, legacy rules unaffected).
- Rule CRUD: POST/PUT(DELETE) /api/collections/:id/rules[/:ruleId] — the
  survivor dead effort of the rules-builder UI finally has real
  endpoints (rules were never editable after creation; nothing ever
  re-evaluated them). First rule converts a user collection to smart;
  removing the last reverts it to static. UpdateCollectionRulesJSON
  edits ONLY the rules doc so rule CRUD cannot clobber metadata.
- Live evaluation: candidates from GetVisibleLiveMediaForRules —
  visible-library set (family lens enforced at source) + archived IS
  NULL AND missing_scan_count = 0 — any enabled rule matches, title
  order. Zero refresh hooks by design: always current by construction.
- Membership mutations (add/remove/bulk-add) are 400 on smart — v1 no
  hybrid; collection_items.excluded stays the reserved future hook.
- Rules builder page (/collections/:id/rules) first time ever routable;
  templ whole-attribute interpolation ("{ expr }" inside a quoted attr
  value is literal text, as theme-{ user.Theme } silently proved).
- UI: create modal Static/⚡Smart cards (smart create redirects into the
  rules builder), ⚡ badge + real per-card counts on the grid (smart =
  live matches, static = stored-link count), smart detail renders
  matched books with no hand-pick actions + an Edit Rules button.
- API: GET /:id gains is_smart + live books; GET /: keeps the Android
  app's default exclusion, include_auto=true surfaces smart rows with
  live counts; TestRules previews against the SAME candidates the live
  render uses (visible + live, was raw first-1000).
- FIXED pre-existing regression from 7ce7321: static collection detail
  with NO library_id returned zero books — QueryType != '' caught user
  rows ('filter' default) and routed them to dashboard sections that
  never contain them; now only real system query types go there
  (handlers + SSR). App-visible symptom: /api/collections/:id without
  library_id came back books:[] for every static collection.

Tests: collections_smart_test.go (conversion, disabled rules, mutation
guards, revert-to-static, validation, system-collection prohibition,
include_auto semantics). Full offline integration suite PASS.
This commit is contained in:
John O'Keefe committed 2026-10-14 11:59:38 -04:00
1 parent df556d8208
commit 0a7fbd6f48
17 files changed
+1766 -440

No files matched your search

+269
View File
@@ -24,8 +24,30 @@ type Rule struct {
Operator string `json:"operator"` // "equals", "contains", "starts_with", "ends_with", "greater_than", "less_than"
Value string `json:"value"`
Priority int `json:"priority"` // 1-10, higher values take precedence
// Enabled gates the rule in the LIVE evaluation used by smart
// collections; absent (JSON omitempty) means enabled — rules written
// before the field existed keep matching.
Enabled *bool `json:"enabled,omitempty"`
}
// Known rule fields and operators — the rules builder UI and the
// persisted JSONB documents must agree with this vocabulary.
var ruleFields = map[string]bool{
"genre": true, "series": true, "author": true, "language": true,
"publisher": true, "copyright_year": true, "tags": true,
}
var ruleOperators = map[string]bool{
"equals": true, "not_equals": true, "contains": true, "not_contains": true,
"starts_with": true, "ends_with": true, "greater_than": true, "less_than": true,
}
// RuleValidationError reports a rule payload the evaluator could never
// honor (unknown field/operator, empty value).
type RuleValidationError struct{ Msg string }
func (e *RuleValidationError) Error() string { return e.Msg }
// RuleEvaluation represents the result of evaluating a rule
type RuleEvaluation struct {
RuleID string `json:"rule_id"`
@@ -244,6 +266,248 @@ func (s *CollectionService) GetBookCollections(ctx context.Context, mediaItemID
return collections, nil
}
// ParseRules decodes a collection's auto_assign_rules JSONB into typed
// rules. "null", empty, and malformed docs mean "no rules".
func (s *CollectionService) ParseRules(raw []byte) []Rule {
if len(raw) == 0 {
return nil
}
var rules []Rule
if err := json.Unmarshal(raw, &rules); err != nil {
return nil
}
return rules
}
// IsSmartCollection derives the collection type: a non-empty ruleset
// makes it SMART (live-matched), an empty/absent ruleset makes it STATIC
// (stored collection_items links).
func (s *CollectionService) IsSmartCollection(raw []byte) bool {
return len(s.ParseRules(raw)) > 0
}
// EnabledRules filters a ruleset down to the rules that participate in
// live evaluation (absent enabled = enabled for backward compatibility).
func (s *CollectionService) EnabledRules(rules []Rule) []Rule {
enabled := make([]Rule, 0, len(rules))
for _, rule := range rules {
if rule.Enabled == nil || *rule.Enabled {
enabled = append(enabled, rule)
}
}
return enabled
}
// validateRule checks a rule payload the evaluator will have to honor.
func (s *CollectionService) validateRule(rule Rule) error {
if !ruleFields[rule.Field] {
return &RuleValidationError{Msg: "unknown rule field: " + rule.Field}
}
if !ruleOperators[rule.Operator] {
return &RuleValidationError{Msg: "unknown rule operator: " + rule.Operator}
}
if strings.TrimSpace(rule.Value) == "" {
return &RuleValidationError{Msg: "rule value is required"}
}
if rule.Priority < 0 || rule.Priority > 10 {
return &RuleValidationError{Msg: "priority must be between 0 and 10"}
}
return nil
}
// AddRule appends a rule to the collection's ruleset, generating an id
// when the caller did not supply one. Adding the first rule CONVERTS a
// static collection to smart (type is derived from rules presence).
func (s *CollectionService) AddRule(ctx context.Context, collectionID uuid.UUID, rule Rule) (database.Collections, Rule, error) {
if err := s.validateRule(rule); err != nil {
return database.Collections{}, Rule{}, err
}
collection, err := s.GetCollection(ctx, collectionID)
if err != nil {
return database.Collections{}, Rule{}, err
}
rules := s.ParseRules(collection.AutoAssignRules)
if rule.ID == "" {
rule.ID = uuid.NewString()
}
rules = append(rules, rule)
rulesJSON, marshalErr := json.Marshal(rules)
if marshalErr != nil {
return database.Collections{}, Rule{}, fmt.Errorf("failed to marshal rules: %w", marshalErr)
}
updated, err := s.db.UpdateCollectionRulesJSON(ctx, database.UpdateCollectionRulesJSONParams{
ID: pgtype.UUID{Bytes: collectionID, Valid: true},
AutoAssignRules: rulesJSON,
})
if err != nil {
return database.Collections{}, Rule{}, fmt.Errorf("failed to save rules: %w", err)
}
return updated, rule, nil
}
// SetRuleEnabled flips a single rule's enabled flag in place.
func (s *CollectionService) SetRuleEnabled(ctx context.Context, collectionID uuid.UUID, ruleID string, enabled bool) (database.Collections, error) {
collection, err := s.GetCollection(ctx, collectionID)
if err != nil {
return database.Collections{}, err
}
rules := s.ParseRules(collection.AutoAssignRules)
found := false
for i := range rules {
if rules[i].ID == ruleID {
rules[i].Enabled = &enabled
found = true
break
}
}
if !found {
return database.Collections{}, fmt.Errorf("rule not found: %s", ruleID)
}
rulesJSON, marshalErr := json.Marshal(rules)
if marshalErr != nil {
return database.Collections{}, fmt.Errorf("failed to marshal rules: %w", marshalErr)
}
updated, err := s.db.UpdateCollectionRulesJSON(ctx, database.UpdateCollectionRulesJSONParams{
ID: pgtype.UUID{Bytes: collectionID, Valid: true},
AutoAssignRules: rulesJSON,
})
if err != nil {
return database.Collections{}, fmt.Errorf("failed to save rules: %w", err)
}
return updated, nil
}
// RemoveRule deletes a single rule from the ruleset. Removing the LAST
// rule converts the collection back to static (type is derived).
func (s *CollectionService) RemoveRule(ctx context.Context, collectionID uuid.UUID, ruleID string) (database.Collections, error) {
collection, err := s.GetCollection(ctx, collectionID)
if err != nil {
return database.Collections{}, err
}
rules := s.ParseRules(collection.AutoAssignRules)
kept := make([]Rule, 0, len(rules))
found := false
for _, rule := range rules {
if rule.ID == ruleID {
found = true
continue
}
kept = append(kept, rule)
}
if !found {
return database.Collections{}, fmt.Errorf("rule not found: %s", ruleID)
}
rulesJSON, marshalErr := json.Marshal(kept)
if marshalErr != nil {
return database.Collections{}, fmt.Errorf("failed to marshal rules: %w", marshalErr)
}
updated, err := s.db.UpdateCollectionRulesJSON(ctx, database.UpdateCollectionRulesJSONParams{
ID: pgtype.UUID{Bytes: collectionID, Valid: true},
AutoAssignRules: rulesJSON,
})
if err != nil {
return database.Collections{}, fmt.Errorf("failed to save rules: %w", err)
}
return updated, nil
}
// SmartEvalOptions scopes a smart collection's live evaluation.
type SmartEvalOptions struct {
// LibraryID, when valid, restricts matching to one library (the
// detail page's library switcher).
LibraryID pgtype.UUID
// VisibleIDs is the requesting user's visible-library set (family
// lens). Empty means no visible-library filter.
VisibleIDs []pgtype.UUID
}
// EvaluateSmartCollection resolves a smart collection's membership LIVE:
// every visible live book matched by at least one enabled rule is in.
// No stored links are consulted — "truly dynamic," always current.
func (s *CollectionService) EvaluateSmartCollection(ctx context.Context, rules []Rule, opts SmartEvalOptions) ([]database.MediaItems, error) {
enabled := s.EnabledRules(rules)
if len(enabled) == 0 {
return []database.MediaItems{}, nil
}
var visibleArg []pgtype.UUID
if len(opts.VisibleIDs) > 0 {
visibleArg = opts.VisibleIDs
}
items, err := s.db.GetVisibleLiveMediaForRules(ctx, database.GetVisibleLiveMediaForRulesParams{
LibraryID: opts.LibraryID,
VisibleLibraryIds: visibleArg,
})
if err != nil {
return nil, fmt.Errorf("failed to load candidate books: %w", err)
}
matches := make([]database.MediaItems, 0, len(items))
for _, item := range items {
if s.mediaItemMatchesAnyRule(item, enabled) {
matches = append(matches, item)
}
}
return matches, nil
}
func (s *CollectionService) mediaItemMatchesAnyRule(item database.MediaItems, rules []Rule) bool {
for _, rule := range rules {
if s.mediaItemMatchesRule(item, rule) {
return true
}
}
return false
}
func (s *CollectionService) mediaItemMatchesRule(item database.MediaItems, rule Rule) bool {
if rule.Enabled != nil && !*rule.Enabled {
return false
}
var fieldValue string
switch rule.Field {
case "genre":
if item.Genre.Valid {
fieldValue = item.Genre.String
}
case "series":
if item.Series.Valid {
fieldValue = item.Series.String
}
case "author":
if item.Author.Valid {
fieldValue = item.Author.String
}
case "language":
if item.Language.Valid {
fieldValue = item.Language.String
}
case "publisher":
if item.Publisher.Valid {
fieldValue = item.Publisher.String
}
case "copyright_year":
if item.CopyrightYear.Valid {
fieldValue = fmt.Sprintf("%d", item.CopyrightYear.Int32)
}
case "tags":
if len(item.Tags) > 0 {
fieldValue = strings.Join(item.Tags, ", ")
}
}
return s.evaluateRule(fieldValue, rule.Operator, rule.Value)
}
// EvaluateRules evaluates auto-assign rules for a media item
func (s *CollectionService) EvaluateRules(mediaItem database.ListMediaItemsRow, rules []Rule) []RuleEvaluation {
var evaluations []RuleEvaluation
@@ -260,6 +524,11 @@ func (s *CollectionService) EvaluateRules(mediaItem database.ListMediaItemsRow,
}
for _, rule := range sortedRules {
// Disabled rules never match (kept for context in the UI only).
if rule.Enabled != nil && !*rule.Enabled {
evaluations = append(evaluations, RuleEvaluation{RuleID: rule.ID, Matches: false})
continue
}
eval := RuleEvaluation{
RuleID: rule.ID,
Matches: false,