tax

package
v0.200.0-rc4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 25, 2024 License: Apache-2.0 Imports: 18 Imported by: 11

Documentation

Overview

Package tax encapsulates models related to taxation.

Index

Constants

View Source
const (
	CategoryST  cbc.Code = "ST"  // Sales Tax
	CategoryVAT cbc.Code = "VAT" // Value Added Tax
	CategoryGST cbc.Code = "GST" // Goods and Services Tax
)

Standard tax categories that may be shared between countries.

View Source
const (
	RateExempt       cbc.Key = "exempt"
	RateZero         cbc.Key = "zero"
	RateStandard     cbc.Key = "standard"
	RateIntermediate cbc.Key = "intermediate"
	RateReduced      cbc.Key = "reduced"
	RateSuperReduced cbc.Key = "super-reduced"
	RateSpecial      cbc.Key = "special"
	RateOther        cbc.Key = "other"
)

Most commonly used keys. Local regions may add their own rate keys or extend them.

View Source
const (
	TagSimplified    cbc.Key = "simplified"
	TagReverseCharge cbc.Key = "reverse-charge"
	TagCustomerRates cbc.Key = "customer-rates"
	TagSelfBilled    cbc.Key = "self-billed"
	TagPartial       cbc.Key = "partial"
	TagB2G           cbc.Key = "b2g"
)

Standard tax tags

Variables

View Source
var (
	// IdentityCodePattern is the regular expression pattern used to validate tax identity codes.
	IdentityCodePattern = `^[A-Z0-9]+$`

	// IdentityCodePatternRegexp is the regular expression used to validate tax identity codes.
	IdentityCodePatternRegexp = regexp.MustCompile(IdentityCodePattern)

	// ErrIdentityCodeInvalid is returned when the tax identity code is not valid.
	ErrIdentityCodeInvalid = errors.New("invalid tax identity code")

	// IdentityCodeBadCharsRegexp is used to remove any characters that are not valid in a tax code.
	IdentityCodeBadCharsRegexp = regexp.MustCompile(`[^A-Z0-9]+`)
)
View Source
var AddonRegistered = addonValidation{}

AddonRegistered will check that an add-on with the key to be validated has been registered.

View Source
var RequireIdentityCode = validateTaxID{/* contains filtered or unexported fields */}

RequireIdentityCode is an additional check to use alongside regular validation that will ensure the tax ID has a code value set.

Functions

func ExtensionForKey added in v0.200.0

func ExtensionForKey(key cbc.Key) *cbc.KeyDefinition

ExtensionForKey returns the extension definition for the given key or nil.

func ExtensionsHas added in v0.68.0

func ExtensionsHas(keys ...cbc.Key) validation.Rule

ExtensionsHas returns a validation rule that ensures the extension map's keys match those provided.

func ExtensionsRequires added in v0.68.0

func ExtensionsRequires(keys ...cbc.Key) validation.Rule

ExtensionsRequires returns a validation rule that ensures all the extension map's keys match those provided in the list.

func Normalize added in v0.200.0

func Normalize(list Normalizers, doc any)

Normalize will either run the "Normalize" method on the provided object, or directly go through the list of normalizers on the object. This supports arrays and slices, and will automatically normalize each element in the list.

func NormalizeIdentity added in v0.115.0

func NormalizeIdentity(tID *Identity, altCodes ...l10n.Code)

NormalizeIdentity removes any whitespace or separation characters and ensures all letters are uppercase.

func RegisterAddonDef added in v0.200.0

func RegisterAddonDef(addon *AddonDef)

RegisterAddonDef adds a new add-on to the shared global list of tax add-on definitions. This is expected to be called from module init functions.

func RegisterExtension added in v0.200.0

func RegisterExtension(kd *cbc.KeyDefinition)

RegisterExtension is used to add any extension definitions to the global register. This is not expected to be called directly, but rather will be used by the regimes and addons during their registration processes.

func RegisterRegimeDef added in v0.200.0

func RegisterRegimeDef(regime *RegimeDef)

RegisterRegimeDef adds a new regime to the shared global list of tax regimes.

func SetComboRule added in v0.200.0

func SetComboRule(cat cbc.Code, fields ...*validation.FieldRules) validation.Rule

SetComboRule provides a validation rule to apply to each combo with a matching tax category. This is useful for ensuring that tax combos contain the correct extensions.

func SetHasCategory added in v0.67.4

func SetHasCategory(categories ...cbc.Code) validation.Rule

SetHasCategory validates that the set contains the given category.

func TagsIn added in v0.200.0

func TagsIn(tags ...cbc.Key) validation.Rule

TagsIn provides a validation rule that will ensure the object's tags are contained inside the list.

func ValidateStructWithContext added in v0.200.0

func ValidateStructWithContext(ctx context.Context, obj any, fields ...*validation.FieldRules) error

ValidateStructWithContext wraps around the standard validation.ValidateStructWithContext method to add an additional check for the tax regime.

Types

type AddonDef added in v0.200.0

type AddonDef struct {
	// Key that defines how to uniquely idenitfy the add-on.
	Key cbc.Key `json:"key" jsonschema:"title=Key"`

	// Name of the add-on
	Name i18n.String `json:"name" jsonschema:"title=Name"`

	// Description of the add-on
	Description i18n.String `json:"description,omitempty" jsonschema:"title=Description"`

	// Extensions defines the list of extensions that are associated with an add-on.
	Extensions []*cbc.KeyDefinition `json:"extensions" jsonschema:"title=Extensions"`

	// Tags is slice of tag sets that define what can be assigned to each document schema.
	Tags []*TagSet `json:"tags,omitempty" jsonschema:"title=Tags"`

	// Scenarios are applied to documents after normalization and before
	// validation to ensure that form specific extensions have been added
	// to the document.
	Scenarios []*ScenarioSet `json:"scenarios" jsonschema:"title=Scenarios"`

	// Inboxes is a list of keys that are used to identify where copies of
	// documents can be sent.
	Inboxes []*cbc.KeyDefinition `json:"inboxes,omitempty" jsonschema:"title=Inboxes"`

	// Normalizer performs the normalization rules for the add-on.
	Normalizer func(doc any) `json:"-"`

	// Validator performs the validation rules for the add-on.
	Validator func(doc any) error `json:"-"`

	// Corrections is used to provide a map of correction definitions that
	// are supported by the add-on.
	Corrections CorrectionSet `json:"corrections" jsonschema:"title=Corrections"`
}

AddonDef is an interface that defines the methods that a tax add-on must implement.

func AddonForKey added in v0.200.0

func AddonForKey(key cbc.Key) *AddonDef

AddonForKey provides the add-on for the given key.

func AllAddons

func AllAddons() []*AddonDef

AllAddons provides a slice of all the addons defined.

func (*AddonDef) Validate added in v0.200.0

func (ad *AddonDef) Validate() error

Validate checks that the add-on has been defined correctly.

func (*AddonDef) WithContext added in v0.200.0

func (ad *AddonDef) WithContext(ctx context.Context) context.Context

WithContext adds this addon to the given context, alongside its validator.

type Addons added in v0.200.0

type Addons struct {
	// Addons defines a list of keys used to identify tax addons that apply special
	// normalization, scenarios, and validation rules to a document.
	List []cbc.Key `json:"$addons,omitempty" jsonschema:"title=Addons"`
}

Addons adds functionality to the owner to be able to handle addons.

func WithAddons added in v0.200.0

func WithAddons(addons ...cbc.Key) Addons

WithAddons prepares the Addons struct with the provided list of keys.

func (Addons) GetAddonDefs added in v0.200.0

func (as Addons) GetAddonDefs() []*AddonDef

GetAddonDefs provides a slice of Addon Definition instances.

func (*Addons) GetAddons added in v0.200.0

func (as *Addons) GetAddons() []cbc.Key

GetAddons provides the list of addon keys in use.

func (*Addons) SetAddons added in v0.200.0

func (as *Addons) SetAddons(addons ...cbc.Key)

SetAddons is a helper method to set the list of addons

func (Addons) Validate added in v0.200.0

func (as Addons) Validate() error

Validate ensures that the list of addons is valid. This struct is designed to be embedded, so we don't perform a regular validation on the struct itself.

type CalculatorRoundingRule added in v0.115.0

type CalculatorRoundingRule string

CalculatorRoundingRule defines the available methods for calculating the totals in the tax calculator.

const (
	// CalculatorSumThenRound is the default method of calculating the totals
	// in GOBL, and provides the best results for most cases as the precision
	// is maintained to the maximum amount possible. The tradeoff however is
	// that sometimes the totals may not sum exactly based on what is visible.
	CalculatorSumThenRound CalculatorRoundingRule = "sum-then-round"
	// CalculatorRoundThenSum is the alternative method of calculating the totals
	// that will first round all the amounts to the currency's precision before
	// making the sums. Totals using this approach can always be recalculated using
	// the amounts presented, but can lead to rounding errors in the case of
	// pre-payments and when line item prices include tax.
	CalculatorRoundThenSum CalculatorRoundingRule = "round-then-sum"
)

type CategoryDef added in v0.200.0

type CategoryDef struct {
	// Code to be used in documents
	Code cbc.Code `json:"code" jsonschema:"title=Code"`

	// Short name of the category to be used instead of code in output
	Name i18n.String `json:"name" jsonschema:"title=Name"`

	// Human name for the code to use for titles
	Title i18n.String `json:"title,omitempty" jsonschema:"title=Title"`

	// Useful description of the category.
	Description *i18n.String `json:"desc,omitempty" jsonschema:"title=Description"`

	// Retained when true implies that the tax amount will be retained
	// by the buyer on behalf of the supplier, and thus subtracted from
	// the invoice taxable base total. Typically used for taxes related to
	// income.
	Retained bool `json:"retained,omitempty" jsonschema:"title=Retained"`

	// Specific tax definitions inside this category.
	Rates []*RateDef `json:"rates,omitempty" jsonschema:"title=Rates"`

	// Extensions defines a list of extension keys that may be used or required
	// as an alternative or alongside choosing a rate for the tax category.
	// Every key must be defined in the Regime's extensions table.
	Extensions []cbc.Key `json:"extensions,omitempty" jsonschema:"title=Extensions"`

	// Map defines a set of regime specific code mappings.
	Map cbc.CodeMap `json:"map,omitempty" jsonschema:"title=Map"`

	// List of sources for the information contained in this category.
	Sources []*Source `json:"sources,omitempty" jsonschema:"title=Sources"`

	// Extensions key-value pairs that will be copied to the tax combo if this
	// category is used.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`

	// Meta contains additional information about the category that is relevant
	// for local frequently used formats.
	Meta cbc.Meta `json:"meta,omitempty" jsonschema:"title=Meta"`
}

CategoryDef contains the definition of a general type of tax inside a region.

func (*CategoryDef) RateDef added in v0.200.0

func (c *CategoryDef) RateDef(key cbc.Key) *RateDef

RateDef provides the rate definition with a matching key for the category.

func (*CategoryDef) ValidateWithContext added in v0.200.0

func (c *CategoryDef) ValidateWithContext(ctx context.Context) error

ValidateWithContext ensures the Category's contents are correct.

type CategoryTotal

type CategoryTotal struct {
	Code      cbc.Code     `json:"code" jsonschema:"title=Code"`
	Retained  bool         `json:"retained,omitempty" jsonschema:"title=Retained"`
	Rates     []*RateTotal `json:"rates" jsonschema:"title=Rates"`
	Amount    num.Amount   `json:"amount" jsonschema:"title=Amount"`
	Surcharge *num.Amount  `json:"surcharge,omitempty" jsonschema:"title=Surcharge"`
	// contains filtered or unexported fields
}

CategoryTotal groups together all rates inside a given category.

func (*CategoryTotal) PreciseAmount added in v0.65.1

func (ct *CategoryTotal) PreciseAmount() num.Amount

PreciseAmount contains the intermediary amount generated from the calculator with the original precision. This is useful when a Category Total needs to be used for further calculations, such as when an invoice includes taxes.

type Combo added in v0.21.0

type Combo struct {
	// Tax category code from those available inside a region.
	Category cbc.Code `json:"cat" jsonschema:"title=Category"`
	// Country code override when issuing with taxes applied from different countries.
	Country l10n.TaxCountryCode `json:"country,omitempty" jsonschema:"title=Country"`
	// Rate within a category to apply.
	Rate cbc.Key `json:"rate,omitempty" jsonschema:"title=Rate"`
	// Percent defines the percentage set manually or determined from the rate
	// key (calculated if rate present). A nil percent implies that this tax combo
	// is **exempt** from tax.
	Percent *num.Percentage `json:"percent,omitempty" jsonschema:"title=Percent" jsonschema_extras:"calculated=true"`
	// Some countries require an additional surcharge (calculated if rate present).
	Surcharge *num.Percentage `json:"surcharge,omitempty" jsonschema:"title=Surcharge" jsonschema_extras:"calculated=true"`
	// Local codes that apply for a given rate or percentage that need to be identified and validated.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`
	// contains filtered or unexported fields
}

Combo represents the tax combination of a category code and rate key. The percent and retained attributes will be determined automatically from the Rate key if set during calculation.

func (*Combo) Normalize added in v0.200.0

func (c *Combo) Normalize(normalizers Normalizers)

Normalize tries to normalize the data inside the tax combo.

func (*Combo) UnmarshalJSON added in v0.50.0

func (c *Combo) UnmarshalJSON(data []byte) error

UnmarshalJSON is a temporary migration helper that will move the first of the "tags" array used in earlier versions of GOBL into the rate field.

func (*Combo) ValidateWithContext added in v0.38.0

func (c *Combo) ValidateWithContext(ctx context.Context) error

ValidateWithContext ensures the Combo has the correct details.

type CorrectionDefinition added in v0.57.0

type CorrectionDefinition struct {
	// Partial or complete schema URL for the document type supported by correction.
	Schema string `json:"schema" jsonschema:"title=Schema"`
	// The types of sub-documents supported by the regime
	Types []cbc.Key `json:"types,omitempty" jsonschema:"title=Types"`
	// Extension keys that can be included
	Extensions []cbc.Key `json:"extensions,omitempty" jsonschema:"title=Extensions"`
	// ReasonRequired when true implies that a reason must be provided
	ReasonRequired bool `json:"reason_required,omitempty" jsonschema:"title=Reason Required"`
	// Stamps that must be copied from the preceding document.
	Stamps []cbc.Key `json:"stamps,omitempty" jsonschema:"title=Stamps"`
}

CorrectionDefinition contains details about what can be defined in .

func (*CorrectionDefinition) HasExtension added in v0.67.0

func (cd *CorrectionDefinition) HasExtension(key cbc.Key) bool

HasExtension returns true if the correction definition has the change key provided.

func (*CorrectionDefinition) HasType added in v0.57.0

func (cd *CorrectionDefinition) HasType(t cbc.Key) bool

HasType returns true if the correction definition has a type that matches the one provided.

func (*CorrectionDefinition) Merge added in v0.200.0

Merge combines two correction definitions into a single one.

func (*CorrectionDefinition) Validate added in v0.57.0

func (cd *CorrectionDefinition) Validate() error

Validate ensures the key definition looks correct in the context of the regime.

type CorrectionSet added in v0.200.0

type CorrectionSet []*CorrectionDefinition

CorrectionSet defines a set of correction definitions for a selection of schemas.

func (CorrectionSet) Def added in v0.200.0

func (cs CorrectionSet) Def(schema string) *CorrectionDefinition

Def provides the correction definition in the set for the schema provided.

type Error added in v0.22.1

type Error cbc.Key

Error is a general wrapper around tax errors produced during run time, typically during calculations. Not to be confused with errors produced from definition validation.

const (
	ErrMissingRegime        Error = "missing-regime"
	ErrInvalidCategory      Error = "invalid-category"
	ErrInvalidTag           Error = "invalid-tag"
	ErrInvalidRate          Error = "invalid-rate"
	ErrInvalidDate          Error = "invalid-date"
	ErrInvalidPricesInclude Error = "invalid-prices-include"
)

Standard list of tax errors

func (Error) Error added in v0.22.1

func (e Error) Error() string

Error serializes the error's message.

func (Error) WithMessage added in v0.22.1

func (e Error) WithMessage(msg string, s ...interface{}) error

WithMessage wraps around the original error so we can use if for matching and adds a human message.

type ExtValue added in v0.68.0

type ExtValue string

ExtValue is a string value that has helper methods to help determine if it is a code, key, or regular string.

func (ExtValue) Code added in v0.68.0

func (ev ExtValue) Code() cbc.Code

Code returns the code value or empty if the value is a Key.

func (ExtValue) Key added in v0.68.0

func (ev ExtValue) Key() cbc.Key

Key returns the key value or empty if the value is a Code.

func (ExtValue) String added in v0.68.0

func (ev ExtValue) String() string

String provides the string representation.

type Extensions added in v0.68.0

type Extensions map[cbc.Key]ExtValue

Extensions is a map of extension keys to values.

func CleanExtensions added in v0.200.0

func CleanExtensions(em Extensions) Extensions

CleanExtensions will try to clean the extension map removing empty values and will potentially return a nil if there only keys with no values.

func (Extensions) Contains added in v0.72.0

func (em Extensions) Contains(other Extensions) bool

Contains returns true if the extension map contains the same keys and values as the provided map, but may have additional keys.

func (Extensions) Equals added in v0.68.0

func (em Extensions) Equals(other Extensions) bool

Equals returns true if the extension map has the same keys and values as the provided map.

func (Extensions) Has added in v0.68.0

func (em Extensions) Has(keys ...cbc.Key) bool

Has returns true if the code map has values for all the provided keys.

func (Extensions) JSONSchemaExtend added in v0.68.0

func (Extensions) JSONSchemaExtend(schema *jsonschema.Schema)

JSONSchemaExtend provides extra details about the extension map which are not automatically determined. In this case we add validation for the map's keys.

func (Extensions) Lookup added in v0.200.0

func (em Extensions) Lookup(val ExtValue) cbc.Key

Lookup returns the key for the provided value or an empty key if not found. This is useful for reverse lookups.

func (Extensions) Merge added in v0.72.0

func (em Extensions) Merge(other Extensions) Extensions

Merge will merge the provided extensions map with the current one generating a new map. Duplicate keys will be overwritten by the other map's values.

func (Extensions) Validate added in v0.200.0

func (em Extensions) Validate() error

Validate ensures the extension map data looks correct and that all keys have been registered globally.

type Identity added in v0.34.0

type Identity struct {
	// Tax country code for Where the tax identity was issued.
	Country l10n.TaxCountryCode `json:"country" jsonschema:"title=Country Code"`

	// Normalized code shown on the original identity document.
	Code cbc.Code `json:"code,omitempty" jsonschema:"title=Code"`

	// Type is set according to the requirements of each regime, some have a single
	// tax document type code, others require a choice to be made.
	//
	// Deprecated: Tax Identities should only be used for VAT or similar codes
	// for companies. Use the identities array for other types of identification.
	Type cbc.Key `json:"type,omitempty" jsonschema:"title=Type"`

	// Zone identifies a sub-locality within a country.
	//
	// Deprecated: Removed 2024-03-14 in favour of using tax tags
	// and extensions with local data when required. Maintained here to support
	// data migration.
	Zone l10n.Code `json:"zone,omitempty" jsonschema:"title=Zone"`
}

Identity stores the details required to identify an entity for tax purposes in a specific country. Typically this would be a code related to a specific indirect tax like VAT or GST. Some countries, such as the US, do not have a VAT system so will not have a code here.

Other fiscal identities should be defined in a parties identities array with their own validation rules and country specific handling.

func ParseIdentity added in v0.113.0

func ParseIdentity(tin string) (*Identity, error)

ParseIdentity will attempt to parse a tax identity from a string making the assumption that the first two characters are the country code and the rest is the tax code. If the country code is identified by a tax regime, the code will be normalized and validated.

func (Identity) JSONSchemaExtend added in v0.38.0

func (Identity) JSONSchemaExtend(js *jsonschema.Schema)

JSONSchemaExtend adds extra details to the schema.

func (*Identity) Normalize added in v0.113.0

func (id *Identity) Normalize()

Normalize will attempt to perform a regional tax normalization on the tax identity. Identities are an exception to the normal normalization rules as they cannot be normalized using addons.

func (*Identity) Regime added in v0.34.0

func (id *Identity) Regime() *RegimeDef

Regime provides the regime object for this tax identity.

func (*Identity) String added in v0.35.1

func (id *Identity) String() string

String provides a string representation of the tax identity.

func (*Identity) Validate added in v0.34.0

func (id *Identity) Validate() error

Validate checks to ensure the tax ID contains all the required fields and performs any regime specific validation based on the ID's country and zone properties.

type Normalizer added in v0.200.0

type Normalizer func(doc any)

Normalizer is used for functions that will normalize the provided object ensuring that all the data is aligned with expected values, and adding any additional data tha may be required.

Normalizer cannot fail by design, they should always be designed to fail silently in case of issues and depend on the Validator to pick up on any issues.

type Normalizers added in v0.200.0

type Normalizers []Normalizer

Normalizers defines a list of normalizer methods with some helpers for execution.

func (Normalizers) Append added in v0.200.0

func (ns Normalizers) Append(n Normalizer) Normalizers

Append adds the normalizer, but only if it is not nil.

func (Normalizers) Each added in v0.200.0

func (ns Normalizers) Each(doc any)

Each will run a simple loop over the normalizers on the provided object.

type RateDef added in v0.200.0

type RateDef struct {
	// Key identifies this rate within the system
	Key cbc.Key `json:"key" jsonschema:"title=Key"`

	// Human name of the rate
	Name i18n.String `json:"name" jsonschema:"title=Name"`
	// Useful description of the rate.
	Description i18n.String `json:"desc,omitempty" jsonschema:"title=Description"`

	// Exempt when true implies that the rate when used in a tax Combo should
	// not define a percent value.
	Exempt bool `json:"exempt,omitempty" jsonschema:"title=Exempt"`

	// Values contains a list of Value objects that contain the
	// current and historical percentage values for the rate and
	// additional filters.
	// Order is important, newer values should come before
	// older values.
	Values []*RateValueDef `json:"values,omitempty" jsonschema:"title=Values"`

	// Extensions key-value pair that will be copied to the tax combo if this
	// rate is used.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`

	// Meta contains additional information about the rate that is relevant
	// for local frequently used implementations.
	Meta cbc.Meta `json:"meta,omitempty" jsonschema:"title=Meta"`
}

RateDef defines a single rate inside a category

func (*RateDef) ValidateWithContext added in v0.200.0

func (r *RateDef) ValidateWithContext(ctx context.Context) error

ValidateWithContext checks that our tax definition is valid. This is only really meant to be used when testing new regional tax definitions.

func (*RateDef) Value added in v0.200.0

func (r *RateDef) Value(date cal.Date, tags []cbc.Key, ext Extensions) *RateValueDef

Value determines the tax rate value for the provided date and zone, if applicable.

type RateTotal

type RateTotal struct {
	// Optional rate key is required when grouping.
	Key cbc.Key `json:"key,omitempty" jsonschema:"title=Key"`
	// Country code override when issuing with taxes applied from different countries,
	// it'd be very strange to mix rates from different countries, but in theory
	// this would be possible.
	Country l10n.TaxCountryCode `json:"country,omitempty" jsonschema:"title=Country"`
	// If the rate is defined with extensions, they'll be used to group by also.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`
	// Base amount that the percentage is applied to.
	Base num.Amount `json:"base" jsonschema:"title=Base"`
	// Percentage of the rate. Will be nil when taxes are **exempt**.
	Percent *num.Percentage `json:"percent,omitempty" jsonschema:"title=Percent"`
	// Surcharge applied to the rate.
	Surcharge *RateTotalSurcharge `json:"surcharge,omitempty" jsonschema:"title=Surcharge"`
	// Total amount of rate, excluding surcharges
	Amount num.Amount `json:"amount" jsonschema:"title=Amount"`
}

RateTotal contains a sum of all the tax rates in the document with a matching category and rate. The Key is optional as we may be using the percentage to group rates.

type RateTotalSurcharge added in v0.25.0

type RateTotalSurcharge struct {
	Percent num.Percentage `json:"percent" jsonschema:"title=Percent"`
	Amount  num.Amount     `json:"amount" jsonschema:"title=Amount"`
}

RateTotalSurcharge reflects the sum surcharges inside the rate.

type RateValueDef added in v0.200.0

type RateValueDef struct {
	// Only apply this rate if one of the tags is present in the invoice.
	Tags []cbc.Key `json:"tags,omitempty" jsonschema:"title=Tags"`
	// Ext map of keys that can be used to filter to determine if the rate applies.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`
	// Date from which this value should be applied.
	Since *cal.Date `json:"since,omitempty" jsonschema:"title=Since"`
	// Percent rate that should be applied
	Percent num.Percentage `json:"percent" jsonschema:"title=Percent"`
	// An additional surcharge to apply.
	Surcharge *num.Percentage `json:"surcharge,omitempty" jsonschema:"title=Surcharge"`
	// When true, this value should no longer be used.
	Disabled bool `json:"disabled,omitempty" jsonschema:"title=Disabled"`
}

RateValueDef contains a percentage rate or fixed amount for a given date range. Fiscal policy changes mean that rates are not static so we need to be able to apply the correct rate for a given period.

func (*RateValueDef) HasATag added in v0.200.0

func (rv *RateValueDef) HasATag(tags []cbc.Key) bool

HasATag returns true if the rate value has a tag that matches one of those provided.

func (*RateValueDef) Validate added in v0.200.0

func (rv *RateValueDef) Validate() error

Validate ensures the tax rate contains all the required fields.

type Regime added in v0.34.0

type Regime struct {
	Country l10n.TaxCountryCode `json:"$regime,omitempty" jsonschema:"title=Regime"`
}

Regime defines a structure that can be embedded inside another structure to enable methods and the `$regime` attribute to be able to determine a tax regime definition to associate with the document.

func WithRegime added in v0.200.0

func WithRegime(country l10n.TaxCountryCode) Regime

WithRegime prepares a Regime struct with the provided country code.

func (Regime) GetRegime added in v0.200.0

func (r Regime) GetRegime() l10n.TaxCountryCode

GetRegime returns the regime country code.

func (Regime) IsEmpty added in v0.200.0

func (r Regime) IsEmpty() bool

IsEmpty returns true if the regime is empty.

func (Regime) RegimeDef added in v0.200.0

func (r Regime) RegimeDef() *RegimeDef

RegimeDef provides the associated regime definition.

func (*Regime) SetRegime added in v0.200.0

func (r *Regime) SetRegime(country l10n.TaxCountryCode)

SetRegime updates the current regime country code, after first checking to ensure that the regime is actually defined. Missing regimes will silently replace the current regime with an empty value.

type RegimeDef added in v0.200.0

type RegimeDef struct {
	// Name of the tax regime.
	Name i18n.String `json:"name" jsonschema:"title=Name"`

	// Introductory details about the regime.
	Description i18n.String `json:"description,omitempty" jsonschema:"title=Description"`

	// Location name for the country's central time zone. Accepted
	// values from IANA Time Zone Database (https://iana.org/time-zones).
	TimeZone string `json:"time_zone" jsonschema:"title=Time Zone"`

	// Country code for the region
	Country l10n.TaxCountryCode `json:"country" jsonschema:"title=Code"`

	// Alternative localization codes that may be used to identify the tax regime
	// in specific circumstances.
	AltCountryCodes []l10n.Code `json:"alt_country_codes,omitempty" jsonschema:"title=Alternative Country Codes"`

	// Specific Locality, region, city, province, county, or similar code inside
	// the country, if needed.
	Zone l10n.Code `json:"zone,omitempty" jsonschema:"title=Zone"`

	// Currency used by the country.
	Currency currency.Code `json:"currency" jsonschema:"title=Currency"`

	// Rounding rule to use when calculating the tax totals, default is always
	// `sum-then-round`.
	CalculatorRoundingRule CalculatorRoundingRule `json:"calculator_rounding_rule,omitempty" jsonschema:"title=Calculator Rounding Rule"`

	// Tags that can be applied at the document level to identify additional
	// considerations.
	Tags []*TagSet `json:"tags,omitempty" jsonschema:"title=Tags"`

	// Extensions defines the keys that can be used for extended or extra data inside the regime that
	// is specific to the regime and cannot be easily determined from other GOBL structures.
	// Typically these are used to define local codes for suppliers, customers, products, or tax rates.
	Extensions []*cbc.KeyDefinition `json:"extensions,omitempty" jsonschema:"title=Extensions"`

	// Tax Identity types specific for the regime and may be validated
	// against.
	TaxIdentityTypeKeys []*cbc.KeyDefinition `json:"tax_identity_type_keys,omitempty" jsonschema:"title=Tax Identity Type Keys"`

	// Identity keys used in addition to regular tax identities and specific for the
	// regime that may be validated against.
	IdentityKeys []*cbc.KeyDefinition `json:"identity_keys,omitempty" jsonschema:"title=Identity Keys"`

	// Charge keys specific for the regime and may be validated or used in the UI as suggestions
	ChargeKeys []*cbc.KeyDefinition `json:"charge_keys,omitempty" jsonschema:"title=Charge Keys"`

	// PaymentMeansKeys specific for the regime that extend the original
	// base payment means keys.
	PaymentMeansKeys []*cbc.KeyDefinition `json:"payment_means_keys,omitempty" jsonschema:"title=Payment Means Keys"`

	// InboxKeys specific to the regime that can be used to identify where a document
	// should be forwarded to.
	InboxKeys []*cbc.KeyDefinition `json:"inbox_keys,omitempty" jsonschema:"title=Inbox Keys"`

	Scenarios []*ScenarioSet `json:"scenarios,omitempty" jsonschema:"title=Scenarios"`

	// Configuration details for corrections to be used with correction options.
	Corrections CorrectionSet `json:"corrections,omitempty" jsonschema:"title=Corrections"`

	// List of tax categories.
	Categories []*CategoryDef `json:"categories" jsonschema:"title=Categories"`

	// Validator is a method to use to validate a document in a given region.
	Validator Validator `json:"-"`

	// Normalizer is used to perform regime specific normalizations on data,
	// that might need to take place such as with tax codes and removing white-space.
	Normalizer Normalizer `json:"-"`
}

RegimeDef defines the holding structure for the definitions of taxes inside a country or territory.

func AllRegimeDefs added in v0.200.0

func AllRegimeDefs() []*RegimeDef

AllRegimeDefs provides an array of all the regime codes to definitions.

func RegimeDefFor added in v0.200.0

func RegimeDefFor(country l10n.Code) *RegimeDef

RegimeDefFor returns the regime definition for country and locality combination or nil if no match was found.

func RegimeDefFromContext added in v0.200.0

func RegimeDefFromContext(ctx context.Context) *RegimeDef

RegimeDefFromContext returns the regime from the given context, or nil.

func (*RegimeDef) CategoryDef added in v0.200.0

func (r *RegimeDef) CategoryDef(code cbc.Code) *CategoryDef

CategoryDef provides the requested category definition by its code.

func (*RegimeDef) Code added in v0.200.0

func (r *RegimeDef) Code() cbc.Code

Code provides a unique code for this tax regime based on the country.

func (*RegimeDef) CurrencyDef added in v0.200.0

func (r *RegimeDef) CurrencyDef() *currency.Def

CurrencyDef provides the currency definition object for the region.

func (*RegimeDef) ExtensionDef added in v0.200.0

func (r *RegimeDef) ExtensionDef(key cbc.Key) *cbc.KeyDefinition

ExtensionDef provides the extension definition with a matching key.

func (*RegimeDef) InCategories added in v0.200.0

func (r *RegimeDef) InCategories() validation.Rule

InCategories returns a validation rule to ensure the category code is inside the list of known codes.

func (*RegimeDef) InCategoryRates added in v0.200.0

func (r *RegimeDef) InCategoryRates(cat cbc.Code) validation.Rule

InCategoryRates is used to provide a validation rule that will ensure a rate key is defined inside a category.

func (*RegimeDef) NormalizeObject added in v0.200.0

func (r *RegimeDef) NormalizeObject(obj interface{})

NormalizeObject performs any regime specific normalizations on the provided object.

func (*RegimeDef) RateDef added in v0.200.0

func (r *RegimeDef) RateDef(cat cbc.Code, key cbc.Key) *RateDef

RateDef provides the rate definition for the provided category code and rate key.

func (*RegimeDef) ScenarioSet added in v0.200.0

func (r *RegimeDef) ScenarioSet(schema string) *ScenarioSet

ScenarioSet returns a single scenario set instance for the provided document schema.

func (*RegimeDef) TimeLocation added in v0.200.0

func (r *RegimeDef) TimeLocation() *time.Location

TimeLocation returns the time.Location for the regime.

func (*RegimeDef) Validate added in v0.200.0

func (r *RegimeDef) Validate() error

Validate enures the region definition is valid, including all subsequent categories.

func (*RegimeDef) ValidateObject added in v0.200.0

func (r *RegimeDef) ValidateObject(value interface{}) error

ValidateObject performs validation on the provided object in the context of the regime.

func (*RegimeDef) ValidateWithContext added in v0.200.0

func (r *RegimeDef) ValidateWithContext(ctx context.Context) error

ValidateWithContext enures the region definition is valid, including all subsequent categories, and passes through the context.

func (*RegimeDef) WithContext added in v0.200.0

func (r *RegimeDef) WithContext(ctx context.Context) context.Context

WithContext adds this regime to the given context, alongside its validator and tags in the contexts.

type RegimeDefCollection added in v0.200.0

type RegimeDefCollection struct {
	// contains filtered or unexported fields
}

RegimeDefCollection defines how to access details about all the regimes currently stored. Currently only a single tax regime per country is supported as we've not yet come across situations where multiple regimes exist within a single country.

func Regimes added in v0.34.0

func Regimes() *RegimeDefCollection

Regimes provides the current global regime collection object.

func (*RegimeDefCollection) All added in v0.200.0

func (c *RegimeDefCollection) All() []*RegimeDef

All provides a list of all the registered Regimes.

func (*RegimeDefCollection) For added in v0.200.0

func (c *RegimeDefCollection) For(country l10n.Code) *RegimeDef

For provides a single matching regime from the collection, or nil if no match is found.

type Scenario added in v0.38.0

type Scenario struct {
	// Name of the scenario for further information.
	Name i18n.String `json:"name,omitempty" jsonschema:"title=Name"`

	// Type of document, if present.
	Types []cbc.Key `json:"type,omitempty" jsonschema:"title=Type"`

	// Array of tags that have been applied to the document.
	Tags []cbc.Key `json:"tags,omitempty" jsonschema:"title=Tags"`

	// Extension key that must be present in the document.
	ExtKey cbc.Key `json:"ext_key,omitempty" jsonschema:"title=Extension Key"`

	// Extension value that along side the key must be present for a match
	// to happen. This cannot be used without an `ExtKey`. The value will
	// be copied to the note code if needed.
	ExtValue ExtValue `json:"ext_value,omitempty" jsonschema:"title=Extension Value"`

	// Filter defines a custom filter method for when the regular basic filters
	// are not sufficient.
	Filter func(doc any) bool `json:"-"`

	// A note to be added to the document if the scenario is applied.
	Note *cbc.Note `json:"note,omitempty" jsonschema:"title=Note"`

	// Codes is used to define additional codes for regime specific
	// situations.
	Codes cbc.CodeMap `json:"codes,omitempty" jsonschema:"title=Codes"`

	// Ext represents a set of tax extensions that should be applied to
	// the document in the appropriate "tax" context.
	Ext Extensions `json:"ext,omitempty" jsonschema:"title=Extensions"`
}

Scenario is used to describe a tax scenario of a document based on the combination of document type and tag used.

There are effectively two parts to a scenario, the filters that are used to determine if the scenario is applicable to a document and the output that is applied or data to be used by conversion processes.

func (*Scenario) ValidateWithContext added in v0.65.0

func (s *Scenario) ValidateWithContext(ctx context.Context) error

ValidateWithContext checks the scenario for errors, using the regime in the context to validate the list of tags.

type ScenarioDocument added in v0.200.0

type ScenarioDocument interface {
	// GetType returns a type associated with the document.
	GetType() cbc.Key
	// GetTags returns a list of the tags used in the document.
	GetTags() []cbc.Key
	// GetExtensions an array of extensions that used in the document.
	GetExtensions() []Extensions
}

ScenarioDocument is used to determine if scenarios can be applied to a document.

type ScenarioSet added in v0.38.0

type ScenarioSet struct {
	// Partial or complete schema URL for the document type
	Schema string `json:"schema" jsonschema:"title=Schema"`

	// List of scenarios for the schema
	List []*Scenario `json:"list" jsonschema:"title=List"`
}

ScenarioSet is a collection of tax scenarios for a given schema that can be used to determine special codes or notes that need to be included in the final document.

func NewScenarioSet added in v0.200.0

func NewScenarioSet(schema string) *ScenarioSet

NewScenarioSet creates a new scenario set with the given schema.

func (*ScenarioSet) ExtensionKeys added in v0.200.0

func (ss *ScenarioSet) ExtensionKeys() []cbc.Key

ExtensionKeys extracts all the possible extension keys that could be applied to a document.

func (*ScenarioSet) Merge added in v0.200.0

func (ss *ScenarioSet) Merge(other []*ScenarioSet)

Merge appends the scenarios from the other set to the current set.

func (*ScenarioSet) Notes added in v0.200.0

func (ss *ScenarioSet) Notes() []*cbc.Note

Notes extracts all the possible notes that could be applied to a document.

func (*ScenarioSet) SummaryFor added in v0.38.0

func (ss *ScenarioSet) SummaryFor(doc ScenarioDocument) *ScenarioSummary

SummaryFor returns a summary by applying the scenarios to the supplied document.

func (*ScenarioSet) ValidateWithContext added in v0.65.0

func (ss *ScenarioSet) ValidateWithContext(ctx context.Context) error

ValidateWithContext checks the scenario set for errors.

type ScenarioSummary added in v0.38.0

type ScenarioSummary struct {
	Notes []*cbc.Note
	Codes cbc.CodeMap
	Ext   Extensions
}

ScenarioSummary is the result after running through a set of scenarios and determining which combinations of Notes, Codes, Meta, and extensions are viable.

type Set added in v0.21.0

type Set []*Combo

Set defines a list of tax categories and their rates to be used alongside taxable items.

func CleanSet added in v0.200.0

func CleanSet(s Set) Set

CleanSet removes any nil values from the set.

func (Set) Equals added in v0.21.0

func (s Set) Equals(s2 Set) bool

Equals returns true if the sets match, regardless of order.

func (Set) Get added in v0.21.0

func (s Set) Get(cat cbc.Code) *Combo

Get the Rate key for the given category

func (Set) Rate added in v0.21.0

func (s Set) Rate(cat cbc.Code) cbc.Key

Rate returns the rate from the matching category, if set.

func (Set) ValidateWithContext added in v0.38.0

func (s Set) ValidateWithContext(ctx context.Context) error

ValidateWithContext ensures the set of tax combos looks correct

type Source added in v0.56.0

type Source struct {
	// Title of the linked source to help distinguish between this and other links.
	Title i18n.String `json:"title,omitempty" jsonschema:"title=Title"`
	// URL for the website.
	URL string `json:"url" jsonschema:"title=URL,format=uri"`
}

Source describes where the information for the taxes comes from.

func (*Source) Validate added in v0.56.0

func (s *Source) Validate() error

Validate ensures the Source's contents are correct.

type TagSet added in v0.200.0

type TagSet struct {
	// Schema that the tags are associated with.
	Schema string `json:"schema" jsonschema:"title=Schema"`

	// List of tags for the schema
	List []*cbc.KeyDefinition `json:"list" jsonschema:"title=List"`
}

TagSet defines a set of tags and their descriptions that can be used for a specific schema in the context of a Regime or Addon.

Tags between multiple sets may be duplicated. In this case, the definition of the first tag will be used.

func TagSetForSchema added in v0.200.0

func TagSetForSchema(sets []*TagSet, schema string) *TagSet

TagSetForSchema will return the tag set for the provided schema, or nil if it does not exist.

func (*TagSet) Keys added in v0.200.0

func (ts *TagSet) Keys() []cbc.Key

Keys returns the list of keys that are available in the tag set.

func (*TagSet) Merge added in v0.200.0

func (ts *TagSet) Merge(other *TagSet) *TagSet

Merge will combine the tags from the current set with the tags from the other set, ensuring that any duplicates are not overwritten from the original list.

type Tags added in v0.200.0

type Tags struct {
	// Tags are used to help identify specific tax scenarios or requirements that will
	// apply changes to the contents of the invoice. Tags by design should always be optional,
	// it should always be possible to build a valid invoice without any tags.
	List []cbc.Key `json:"$tags,omitempty" jsonschema:"title=Tags"`
}

Tags defines the structure to use for allowing an object to be assigned tags for use in determining how the content should be handled.

func WithTags added in v0.200.0

func WithTags(tags ...cbc.Key) Tags

WithTags prepares a tags struct

func (Tags) GetTags added in v0.200.0

func (ts Tags) GetTags() []cbc.Key

GetTags returns the list of tags that have been assigned to the object.

func (Tags) HasTags added in v0.200.0

func (ts Tags) HasTags(keys ...cbc.Key) bool

HasTags returns true if the list of tags contains all of the provided tags.

func (*Tags) SetTags added in v0.200.0

func (ts *Tags) SetTags(tags ...cbc.Key)

SetTags is a helper method to set the list of tags.

type TaxableLine

type TaxableLine interface {
	GetTaxes() Set
	GetTotal() num.Amount
}

TaxableLine defines what we expect from a line in order to subsequently calculate the taxes that need to be added or retained.

type Total

type Total struct {
	// Grouping of all the taxes by their category
	Categories []*CategoryTotal `json:"categories,omitempty" jsonschema:"title=Categories"`
	// Total value of all the taxes applied.
	Sum num.Amount `json:"sum" jsonschema:"title=Sum"`
	// contains filtered or unexported fields
}

Total contains a set of Category Totals which in turn contain all the accumulated taxes contained in the document. The resulting `sum` is that value that should be added to the payable total.

func (*Total) Category added in v0.13.0

func (t *Total) Category(code cbc.Code) *CategoryTotal

Category provides the category total for the matching code.

func (*Total) PreciseSum added in v0.57.0

func (t *Total) PreciseSum() num.Amount

PreciseSum contains an intermediary sum generated from the calculator with the original precision. If no calculations were made on the totals, such as when loading, the original sum will be provided instead.

type TotalCalculator added in v0.35.0

type TotalCalculator struct {
	Country  l10n.TaxCountryCode
	Tags     []cbc.Key
	Zero     num.Amount
	Date     cal.Date
	Lines    []TaxableLine
	Includes cbc.Code // Tax included in price
}

TotalCalculator defines the base structure with the available data for calculating tax totals.

func (*TotalCalculator) Calculate added in v0.35.0

func (tc *TotalCalculator) Calculate(t *Total) error

Calculate the totals

type Validator added in v0.200.0

type Validator func(doc any) error

Validator is used for functions that will validate the provided object and provide an error if the object is not valid.

func Validators added in v0.200.0

func Validators(ctx context.Context) []Validator

Validators provides the list of validators that have been added to the current context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL