package governance import ( "context" "slices" "time" "github.com/samcharles93/archie-core/modules/governance/internal/store" ) // PathStep is one stop on the route an unanswered approval request takes: who // it is passed to, and how long it waits there. The first step is the target's // owner when there is one, otherwise the default owner, who may be nobody, and // then anyone with authority. type PathStep struct { // Person is the id of the person asked at this step, or empty. Person string `json:"person"` Name string `json:"name"` DeadlineMS int64 `json:"deadline_ms"` } // Deadline is how long the request waits at this step. func (p PathStep) Deadline() time.Duration { return time.Duration(p.DeadlineMS) * time.Millisecond } // HasDefaultOwner reports whether the organisation has a default owner. func (m *Module) HasDefaultOwner(ctx context.Context) (bool, error) { set, err := m.Settings(ctx) if err != nil { return false, err } return set.DefaultOwner != "", nil } // EscalationPath returns the route an approval request takes. owner is the // person who answers for the action's target, or empty when none is known. A // known owner is asked first and the default owner is the next step; an unknown // owner leaves the default owner first. Every later step is a person on the // escalation path. When the action needs authority, a step held by someone // without it is left out, so the request never moves to a person who could not // answer it. func (m *Module) EscalationPath(ctx context.Context, owner string, needAuthority bool) ([]PathStep, error) { set, err := m.Settings(ctx) if err != nil { return nil, err } people, err := m.store.People(ctx, m.orgID) if err != nil { return nil, err } return set.path(people, owner, needAuthority), nil } func (s Settings) path(people []store.Person, owner string, needAuthority bool) []PathStep { find := func(id string) (store.Person, bool) { i := slices.IndexFunc(people, func(p store.Person) bool { return p.ID.String() == id }) if i < 0 { return store.Person{}, false } return people[i], true } defaultOwner := PathStep{Person: s.DefaultOwner, DeadlineMS: s.ApprovalDeadline.Milliseconds()} if p, ok := find(s.DefaultOwner); ok { defaultOwner.Name = p.Name } var out []PathStep if p, ok := find(owner); ok && owner != "" && (p.Authority || !needAuthority) { out = append(out, PathStep{Person: owner, Name: p.Name, DeadlineMS: s.ApprovalDeadline.Milliseconds()}) } // With no owner to ask, the default owner leads even when nobody is set, // so the request still goes to anyone who may answer it. if len(out) == 0 || (s.DefaultOwner != "" && s.DefaultOwner != owner) { out = append(out, defaultOwner) } for _, st := range s.Escalation { p, ok := find(st.Person) if !ok || (needAuthority && !p.Authority) || slices.ContainsFunc(out, func(o PathStep) bool { return o.Person == st.Person }) { continue } out = append(out, PathStep{Person: st.Person, Name: p.Name, DeadlineMS: st.Deadline.Milliseconds()}) } return out }