Skip to content

Commit

Permalink
Provide an Identity Key validation rule
Browse files Browse the repository at this point in the history
  • Loading branch information
cavalle committed Nov 22, 2023
1 parent f286dce commit f193b30
Showing 1 changed file with 27 additions and 2 deletions.
29 changes: 27 additions & 2 deletions org/identity.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org
import (
"context"
"fmt"
"strings"

"github.com/invopop/gobl/cbc"
"github.com/invopop/gobl/tax"
Expand Down Expand Up @@ -55,8 +56,15 @@ func HasIdentityType(typ cbc.Code) validation.Rule {
return validateIdentitySet{typ: typ}
}

// HasIdentityKey provides a validation rule that will determine if at least one
// of the identities defined includes one with the defined key.
func HasIdentityKey(key cbc.Key) validation.Rule {
return validateIdentitySet{key: key}
}

type validateIdentitySet struct {
typ cbc.Code
key cbc.Key
}

func (v validateIdentitySet) Validate(value interface{}) error {
Expand All @@ -65,11 +73,28 @@ func (v validateIdentitySet) Validate(value interface{}) error {
return nil
}
for _, row := range ids {
if row.Type == v.typ {
if v.matches(row) {
return nil
}
}
return fmt.Errorf("missing %s", v.typ)

return fmt.Errorf("missing %s", v)
}

func (v validateIdentitySet) matches(row *Identity) bool {
return (v.typ == cbc.CodeEmpty || row.Type == v.typ) &&
(v.key == cbc.KeyEmpty || row.Key == v.key)
}

func (v validateIdentitySet) String() string {
var parts []string
if v.typ != cbc.CodeEmpty {
parts = append(parts, fmt.Sprintf("type %s", v.typ))
}
if v.key != cbc.KeyEmpty {
parts = append(parts, fmt.Sprintf("key %s", v.key))
}
return strings.Join(parts, ", ")
}

// IdentityForType helps return the identity with a matching type code.
Expand Down

0 comments on commit f193b30

Please sign in to comment.