// Package rules applies the ordered glob rules from rules.toml to // transactions, deciding their automatic tag and whether they are a transfer // between the user's own accounts. // // Only the rule_* columns are ever written. Manual edits made in the TUI live // in separate columns and survive any number of re-runs. package rules import ( "git.petrovv.com/nikola/money/internal/config" "git.petrovv.com/nikola/money/internal/glob" "git.petrovv.com/nikola/money/internal/model" "git.petrovv.com/nikola/money/internal/store" ) // Engine evaluates rules in file order; the first match wins. type Engine struct { rules []config.Rule } // New builds an engine from the parsed rules file. func New(r *config.Rules) *Engine { return &Engine{rules: r.Rule} } // Match returns the first rule matching a transaction on the given account, or // nil if none does. Every pattern a rule sets must match: a rule with both // match and counterparty is an "and", not an "or". func (e *Engine) Match(accountSlug string, t model.Transaction) *config.Rule { var ( description = model.NormalizeDescription(t.Description) counterparty = model.NormalizeDescription(t.Counterparty) kind = model.NormalizeDescription(t.Type) ) for i := range e.rules { r := &e.rules[i] if r.Account != "" && r.Account != accountSlug { continue } if r.Match != "" && !glob.Match(r.Match, description) { continue } if r.Counterparty != "" && !glob.Match(r.Counterparty, counterparty) { continue } if r.Type != "" && !glob.Match(r.Type, kind) { continue } return r } return nil } // ApplyTxn returns the tag and transfer flag for a transaction. An unmatched // transaction gets an empty tag and is not a transfer. func (e *Engine) ApplyTxn(accountSlug string, t model.Transaction) (tag string, transfer bool) { if r := e.Match(accountSlug, t); r != nil { return r.Tag, r.Transfer } return "", false } // Apply is the description-only shorthand, for callers that have nothing else. func (e *Engine) Apply(accountSlug, description string) (tag string, transfer bool) { return e.ApplyTxn(accountSlug, model.Transaction{Description: description}) } // Retag recomputes rule verdicts for every transaction in the index and // writes them back. It returns how many rows changed. func (e *Engine) Retag(db *store.DB) (int, error) { txns, err := db.Transactions(store.Filter{}) if err != nil { return 0, err } var changed []store.RuleAssignment for _, t := range txns { tag, transfer := e.ApplyTxn(t.AccountSlug, t) if tag == t.RuleTag && transfer == t.RuleTransfer { continue } changed = append(changed, store.RuleAssignment{ID: t.ID, Tag: tag, Transfer: transfer}) } if len(changed) == 0 { return 0, nil } if err := db.ApplyRuleResults(changed); err != nil { return 0, err } return len(changed), nil }