Documentation
¶
Overview ¶
Package tax encapsulates models related to taxation.
Index ¶
- Constants
- Variables
- func AddonContext(keys ...cbc.Key) rules.WithContext
- func AddonIn(keys ...cbc.Key) rules.Test
- func ApplyRoundingRule(rr cbc.Key, cur currency.Code, amount num.Amount) num.Amount
- func ExtensionForKey(key cbc.Key) *cbc.Definition
- func ExtensionHasValidCode(key cbc.Key) rules.Test
- func HasAddon(key cbc.Key) rules.Test
- func IdentityIn(codes ...l10n.TaxCountryCode) rules.Test
- func NormalizeIdentity(tID *Identity, altCodes ...l10n.Code)
- func RegimeContext(codes ...l10n.TaxCountryCode) rules.WithContext
- func RegimeIn(codes ...l10n.TaxCountryCode) rules.Test
- func RegisterAddonDef(addon *AddonDef)
- func RegisterApprovedAddon(ea *ExternalAddon)
- func RegisterCatalogueDef(filename string)
- func RegisterExtension(kd *cbc.Definition)
- func RegisterRegimeDef(regime *RegimeDef)
- func TagsIn(tags ...cbc.Key) rules.Test
- type AddonDef
- type AddonList
- type Addons
- type CatalogueDef
- type CategoryDef
- type CategoryTotal
- type Combo
- type CorrectionDefinition
- type CorrectionNormalizer
- type CorrectionSet
- type Error
- type Extensions
- func (e Extensions) All() iter.Seq2[cbc.Key, cbc.Code]
- func (e Extensions) Clean() Extensions
- func (e Extensions) Clone() Extensions
- func (e Extensions) Contains(other Extensions) bool
- func (e Extensions) Delete(key cbc.Key) Extensions
- func (e Extensions) Equals(other Extensions) bool
- func (e Extensions) Get(k cbc.Key) cbc.Code
- func (e Extensions) Has(keys ...cbc.Key) bool
- func (e Extensions) IsZero() bool
- func (Extensions) JSONSchemaExtend(s *jsonschema.Schema)
- func (e Extensions) Keys() []cbc.Key
- func (e Extensions) Len() int
- func (e Extensions) Lookup(val cbc.Code) cbc.Key
- func (e Extensions) MarshalJSON() ([]byte, error)
- func (e Extensions) Merge(other Extensions) Extensions
- func (e Extensions) Set(key cbc.Key, code cbc.Code) Extensions
- func (e Extensions) SetIfEmpty(key cbc.Key, code cbc.Code) Extensions
- func (e Extensions) SetOneOf(key cbc.Key, code cbc.Code, codes ...cbc.Code) Extensions
- func (e *Extensions) UnmarshalJSON(data []byte) error
- func (e Extensions) Values() []cbc.Code
- type ExtensionsRule
- func ExtensionsAllowOneOf(keys ...cbc.Key) ExtensionsRule
- func ExtensionsExclude(keys ...cbc.Key) ExtensionsRule
- func ExtensionsExcludeCodes(key cbc.Key, codes ...cbc.Code) ExtensionsRule
- func ExtensionsHasCodes(key cbc.Key, codes ...cbc.Code) ExtensionsRule
- func ExtensionsRequire(keys ...cbc.Key) ExtensionsRule
- func ExtensionsRequireAllOrNone(keys ...cbc.Key) ExtensionsRule
- type ExternalAddon
- type Identity
- type KeyDef
- type Note
- type RateDef
- type RateTotal
- type RateTotalSurcharge
- type RateValueDef
- type Regime
- type RegimeCode
- type RegimeDef
- func (r *RegimeDef) CategoryDef(code cbc.Code) *CategoryDef
- func (r *RegimeDef) Code() cbc.Code
- func (r *RegimeDef) CurrencyDef() *currency.Def
- func (r *RegimeDef) GetCountry() l10n.TaxCountryCode
- func (r *RegimeDef) GetCurrency() currency.Code
- func (r *RegimeDef) GetRoundingRule() cbc.Key
- func (r *RegimeDef) ScenarioSet(schema string) *ScenarioSet
- func (r *RegimeDef) TimeLocation() *time.Location
- type RegimeDefCollection
- type Scenario
- type ScenarioDocument
- type ScenarioSet
- type ScenarioSummary
- type Set
- type SetTest
- type TagSet
- type Tags
- type TaxableLine
- type Total
- func (t *Total) Calculate(cur currency.Code, rr cbc.Key)
- func (t *Total) Category(code cbc.Code) *CategoryTotal
- func (t *Total) Clone() *Total
- func (t *Total) Exchange(rate *currency.ExchangeRate, rr cbc.Key)
- func (t *Total) Merge(t2 *Total) *Total
- func (t *Total) Negate() *Total
- func (t *Total) Round(zero num.Amount)
- func (t *Total) Scale(factor num.Amount, cur currency.Code, rr cbc.Key)
- type TotalCalculator
Constants ¶
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.
const ( KeyStandard cbc.Key = "standard" KeyZero cbc.Key = "zero" KeyReverseCharge cbc.Key = "reverse-charge" KeyExempt cbc.Key = "exempt" KeyExport cbc.Key = "export" KeyIntraCommunity cbc.Key = "intra-community" KeyOutsideScope cbc.Key = "outside-scope" )
Standard tax combo keys used to identify different tax situations.
const ( RateZero cbc.Key = "zero" RateGeneral cbc.Key = "general" RateIntermediate cbc.Key = "intermediate" RateReduced cbc.Key = "reduced" RateSuperReduced cbc.Key = "super-reduced" RateSpecial cbc.Key = "special" RateOther cbc.Key = "other" )
Most commonly used rates. Local regions may add their own rate keys or extend them.
const ( TagSimplified cbc.Key = "simplified" TagReverseCharge cbc.Key = "reverse-charge" TagCustomerRates cbc.Key = "customer-rates" TagSelfBilled cbc.Key = "self-billed" TagReplacement cbc.Key = "replacement" TagPartial cbc.Key = "partial" TagBypass cbc.Key = "bypass" TagB2G cbc.Key = "b2g" TagExport cbc.Key = "export" TagEEA cbc.Key = "eea" // European Economic Area TagPrepayment cbc.Key = "prepayment" TagFactoring cbc.Key = "factoring" )
Standard tax tags that can be used to indicate special circumstances at the level of the document.
const ( // PointIssue indicates tax is due on the invoice issue date. // Corresponds to UNCL 2005 code 3. PointIssue cbc.Key = "issue" // PointDelivery indicates tax is due on the delivery date. // Corresponds to UNCL 2005 code 35. PointDelivery cbc.Key = "delivery" // PointPayment indicates tax is due when payment is received. // Corresponds to UNCL 2005 code 432. PointPayment cbc.Key = "payment" )
Point keys define when the tax point occurs, i.e. when the tax liability is triggered. These correspond to UNCL 2005 date/time/period function codes used in BT-8 of the EN 16931 standard.
const ( // RoundingRulePrecise is the default method of performing calculations // in GOBL, and provides the best results for most cases. Before calculations // are made, item and line prices are calculated with at least the currency's // precision plus 2 significant digits. In the case of Euros, all calculations // would be made with at least 4 decimal places. The tradeoff however is // that sometimes the totals may not sum exactly based on what is visible in the // document, which can cause problems with some electronic invoice formats or // regional requirements. RoundingRulePrecise cbc.Key = "precise" // RoundingRuleCurrency is the alternative method of performing calculations // whereby the currency's precision or subunits are used to round the amounts // **before** performing the sums. This is a common approach in other digital // invoicing formats. When prices include tax, the tax amount is determined // from the sum of each rate's tax-inclusive line totals and shared back over // the lines, so that the resulting bases and amounts always sum precisely. RoundingRuleCurrency cbc.Key = "currency" )
Variables ¶
var ( // IdentityCodePattern is the regular expression pattern used to validate tax identity codes. // Includes special exception letters used in some regions such as MX. 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Ñ\&]+`) )
var PointDefs = []*cbc.Definition{ { Key: PointIssue, Name: i18n.String{ i18n.EN: "Issue Date", }, Desc: i18n.String{ i18n.EN: here.Doc(` Tax point is the invoice issue date. Corresponds to UNCL 2005 code 3. `), }, }, { Key: PointDelivery, Name: i18n.String{ i18n.EN: "Delivery Date", }, Desc: i18n.String{ i18n.EN: here.Doc(` Tax point is the actual delivery date. Corresponds to UNCL 2005 code 35. `), }, }, { Key: PointPayment, Name: i18n.String{ i18n.EN: "Payment Date", }, Desc: i18n.String{ i18n.EN: here.Doc(` Tax point is the date on which payment is made. Corresponds to UNCL 2005 code 432. `), }, }, }
PointDefs lists the supported tax point keys and their descriptions.
var RoundingRules = []*cbc.Definition{ { Key: RoundingRulePrecise, Name: i18n.String{ i18n.EN: "Precise", }, Desc: i18n.String{ i18n.EN: here.Doc(` 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. `), }, }, { Key: RoundingRuleCurrency, Name: i18n.String{ i18n.EN: "Currency", }, Desc: i18n.String{ i18n.EN: here.Doc(` 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. When prices include tax, the tax amounts are calculated from each rate's sum of tax-inclusive line totals so that the bases and amounts always add up, though recalculating a tax amount from its base alone may occasionally differ by a single subunit of the currency. `), }, }, }
RoundingRules defines the list of supported rounding rules.
Functions ¶
func AddonContext ¶ added in v0.400.0
func AddonContext(keys ...cbc.Key) rules.WithContext
AddonContext returns a rules.WithContext option that injects the given addon key(s) into the validation context. Useful for testing rules against specific addons without a fully calculated document.
func AddonIn ¶ added in v0.400.0
AddonIn returns a Test that checks whether the context contains the given addon key. It is symmetric with RegimeIn and works with addon definitions stored in the validation context via InContext(AddonIn(key)).
func ApplyRoundingRule ¶ added in v0.212.0
ApplyRoundingRule applies the given rounding rule to the amount using the currency's base precision as a reference.
func ExtensionForKey ¶ added in v0.200.0
func ExtensionForKey(key cbc.Key) *cbc.Definition
ExtensionForKey returns the extension definition for the given key or nil.
func ExtensionHasValidCode ¶ added in v0.400.0
ExtensionHasValidCode returns a validation rule that ensures that if the provided key is present in the extensions map, that it's code matches the underlying extension's definition. Unlike other tests, if the extension key is not present, the test will still pass.
func HasAddon ¶ added in v0.400.0
HasAddon provides a test to check that an object provided to the test responds to the GetAddons method and that the addon key provided is supported.
func IdentityIn ¶ added in v0.400.0
func IdentityIn(codes ...l10n.TaxCountryCode) rules.Test
IdentityIn provides a rules test that checks if a tax identity's country code is one of the provided codes.
func NormalizeIdentity ¶ added in v0.115.0
NormalizeIdentity removes any whitespace or separation characters and ensures all letters are uppercase.
func RegimeContext ¶ added in v0.400.0
func RegimeContext(codes ...l10n.TaxCountryCode) rules.WithContext
RegimeContext returns a rules.WithContext option that injects the given regime code(s) into the validation context. Useful for testing rules against specific regimes without a fully calculated document.
func RegimeIn ¶ added in v0.400.0
func RegimeIn(codes ...l10n.TaxCountryCode) rules.Test
RegimeIn checks if the regime's country code is in the provided list of codes.
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 RegisterApprovedAddon ¶ added in v0.500.0
func RegisterApprovedAddon(ea *ExternalAddon)
RegisterApprovedAddon adds an external addon to the curated list of addons recognised by GOBL. See ExternalAddon for the semantics. The curated list is maintained in the addons package (addons/external.go); adding an entry there is the approval step, reviewed via pull request.
func RegisterCatalogueDef ¶ added in v0.204.0
func RegisterCatalogueDef(filename string)
RegisterCatalogueDef will register the catalogue in the global list of catalogues and ensure the extensions it contains are available in GOBL.
Unlike other sources, catalogues are loaded from JSON files in the `catalogues` directory of the embedded data filesystem.
func RegisterExtension ¶ added in v0.200.0
func RegisterExtension(kd *cbc.Definition)
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.
Types ¶
type AddonDef ¶ added in v0.200.0
type AddonDef struct {
// Key that defines how to uniquely identify the add-on.
Key cbc.Key `json:"key" jsonschema:"title=Key"`
// Requires defines any additional addons that this one depends on to operate
// correctly.
Requires []cbc.Key `json:"requires,omitempty" jsonschema:"title=Requires"`
// 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"`
// Sources is a list of sources that are used to provide the data for the add-on.
Sources []*cbc.Source `json:"sources,omitempty" jsonschema:"title=Sources"`
// Extensions defines the list of extensions that are associated with an add-on.
Extensions []*cbc.Definition `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"`
// Identities that are specific for the add-on and may be validated against or
// used during conversion processes.
Identities []*cbc.Definition `json:"identities,omitempty" jsonschema:"title=Identities"`
// Inboxes is a list of keys that are used to identify where copies of
// documents can be sent.
Inboxes []*cbc.Definition `json:"inboxes,omitempty" jsonschema:"title=Inboxes"`
// 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
AddonForKey provides the add-on for the given key.
func AllAddonDefs ¶ added in v0.200.0
func AllAddonDefs() []*AddonDef
AllAddonDefs provides a slice of all the addons defined.
type AddonList ¶ added in v0.304.0
AddonList defines the slice of keys to use for addons.
func (AddonList) JSONSchemaExtend ¶ added in v0.304.0
func (AddonList) JSONSchemaExtend(js *jsonschema.Schema)
JSONSchemaExtend will add the addon options to the JSON list. The enum is the union of the runtime-registered addons and the curated list of approved external addons (see ApprovedAddons), so a key whose implementation lives in a separate module is still a recognised `$addons` value. A registered definition takes precedence over an approved stub of the same key. Note that being listed here does not relax the runtime "$addons must be registered" check — the module must still be imported for validation to succeed.
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 AddonList `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
WithAddons prepares the Addons struct with the provided list of keys.
func (*Addons) AddAddons ¶ added in v0.500.0
AddAddons appends the given keys to the addon list, skipping any that are empty or already present. Use it to declare addons programmatically before calculating a document; addons cannot be added during normalization.
func (Addons) AddonDefs ¶ added in v0.204.0
AddonDefs provides a slice of Addon Definition instances including any dependencies.
func (*Addons) PrepareNormalization ¶ added in v0.500.0
func (as *Addons) PrepareNormalization()
PrepareNormalization expands the addon list to include the dependencies (Requires) of every declared addon, transitively, dropping any keys that are not registered. The norm engine calls this once before normalizing so that the required addons' normalizers are applied in a single pass.
func (Addons) RulesContext ¶ added in v0.400.0
func (as Addons) RulesContext() rules.WithContext
RulesContext implements rules.ContextAdder so that any struct embedding Addons automatically injects each addon definition into the validation context. This allows guards like is.InContext(tax.AddonIn(key)) to work on nested objects without needing access to the root document.
type CatalogueDef ¶ added in v0.204.0
type CatalogueDef struct {
// Key defines a unique identifier for the catalogue.
Key cbc.Key `json:"key"`
// Name is the name of the catalogue.
Name i18n.String `json:"name"`
// Description is a human readable description of the catalogue.
Description i18n.String `json:"description,omitempty"`
// Extensions defines all the extensions offered by the catalogue.
Extensions []*cbc.Definition `json:"extensions"`
}
A CatalogueDef contains a set of re-useable extensions, scenarios, and validators that can be used by addons or tax regimes. This structure is useful for serializing the data into JSON for use in external libraries.
func AllCatalogueDefs ¶ added in v0.204.0
func AllCatalogueDefs() []*CatalogueDef
AllCatalogueDefs provides a slice of all the addons defined.
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"`
// Informative when true implies that the tax amount will be calculated
// and reported but will not affect the invoice totals. Typically used
// for taxes that are embedded in the base amount or don't impact the
// final payable amount.
Informative bool `json:"informative,omitempty" jsonschema:"title=Informative"`
// Specific tax definitions inside this category.
Keys []*KeyDef `json:"keys,omitempty" jsonschema:"title=Keys"`
// Rates defines the set of rates that can be used with 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 and most importantly,
// an official source where the tax rates can be reviewed and updated in the future.
Sources []*cbc.Source `json:"sources,omitempty" jsonschema:"title=Sources"`
// Extension key-value pairs that will be copied to the tax combo if this
// category is used.
Ext Extensions `json:"ext,omitzero" 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 Category ¶
func Category(code cbc.Code) *CategoryDef
Category returns a global category definition by its code.
func GlobalGST ¶ added in v0.302.0
func GlobalGST() *CategoryDef
GlobalGST returns a global GST category definition that can be use in other regimes.
func GlobalVAT ¶ added in v0.300.0
func GlobalVAT() *CategoryDef
GlobalVAT returns a global VAT category definition that can be use in other regimes.
type CategoryTotal ¶
type CategoryTotal struct {
Code cbc.Code `json:"code" jsonschema:"title=Code"`
Retained bool `json:"retained,omitempty" jsonschema:"title=Retained"`
Informative bool `json:"informative,omitempty" jsonschema:"title=Informative"`
Rates []*RateTotal `json:"rates" jsonschema:"title=Rates"`
Amount num.Amount `json:"amount" jsonschema:"title=Amount"`
Surcharge *num.Amount `json:"surcharge,omitempty" jsonschema:"title=Surcharge"`
}
CategoryTotal groups together all rates inside a given category.
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"`
// Key helps determine the tax situation within the category.
Key cbc.Key `json:"key,omitempty"`
// Rate within a category and for a given key to apply.
Rate cbc.Key `json:"rate,omitempty" jsonschema:"title=Rate"`
// Percent defines the percentage set manually or determined from the
// key. A nil percent implies that this tax combo is either exempt or not-subject.
Percent *num.Percentage `json:"percent,omitempty" jsonschema:"title=Percent" jsonschema_extras:"calculated=true"`
// Some countries require an additional surcharge (may be determined if key 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,omitzero" 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) JSONSchemaExtend ¶ added in v0.300.0
func (c Combo) JSONSchemaExtend(s *jsonschema.Schema)
JSONSchemaExtend will extend the JSON schema for the Combo object with global tax category keys.
func (*Combo) UnmarshalJSON ¶ added in v0.50.0
UnmarshalJSON is a migration helper that will prepare the Combo's key from either the old tags or rate fields.
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"`
// Copy tax from the preceding document to the document ref.
CopyTax bool `json:"copy_tax,omitempty" jsonschema:"title=Copy Tax Totals"`
// Normalizer is an optional implementation of the CorrectionNormalizer to allow
// addon/regime-specific logic to route extensions between the document
// and the preceding reference.
Normalizer CorrectionNormalizer `json:"-"`
}
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
func (cd *CorrectionDefinition) Merge(other *CorrectionDefinition) *CorrectionDefinition
Merge combines two correction definitions into a new definition without mutating either input.
type CorrectionNormalizer ¶ added in v0.403.0
type CorrectionNormalizer interface {
Normalize(doc any)
}
CorrectionNormalizer defines an object that can be used to normalize a document during the correction process.
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
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" ErrInvalid Error = "invalid" ErrInvalidCategory Error = "invalid-category" ErrInvalidTag Error = "invalid-tag" ErrInvalidDate Error = "invalid-date" ErrInvalidPricesInclude Error = "invalid-prices-include" )
Standard list of tax errors
func (Error) WithMessage ¶ added in v0.22.1
WithMessage wraps around the original error so we can use if for matching and adds a human message.
type Extensions ¶ added in v0.68.0
type Extensions struct {
// contains filtered or unexported fields
}
Extensions are a key component of GOBL that are used to include additional structured data in documents that doesn't fit into any of the common or universal fields. They're typically defined by local tax agencies that will use the data for tax reports or classification. Civil law countries have a far greater tendancy to require these than common law countries.
Naming of extension keys is important and should be kept short and descriptive. There are three key components to an extension key separated by dashes:
- An ISO country code e.g. `mx`, `es`, `gb`, etc.
- Short abreviation of the platform or format the extension will be used with, e.g. `cfdi` for Mexico's CFDI defined by the SAT, `facturae` for Spain's FacturaE format, `sdi` for the Italian SDI (document interchange system), etc. This is important, as it helps avoid potential conflicts in the future with new or alternative formats that may appear.
- A short descriptive name of the extension, e.g. `exception`, `fiscal-regime`, `vat-cat`, `incoming-typ`, etc. The aim should be to avoid using obvious names like `code` or `key` in the name, as these are already implied through usage.
Please look at the regimes package and other country specific implementations for examples of how to define and use extensions.
Extensions is immutable: every mutation method (Set, Delete, Merge, etc.) returns a new Extensions instance with its own underlying map. Chaining is supported for ergonomic construction:
ext := tax.MakeExtensions().
Set("es-sii-doc-type", "F1").
Set("untdid-document-type", "380")
Extensions wraps a map of extension keys to values. The internal map is unexported so that all access goes through the type's methods, which guarantee copy-on-write semantics and deterministic (alphabetical) JSON output.
func ExtensionsFromValue ¶ added in v0.402.0
func ExtensionsFromValue(value any) (Extensions, bool)
ExtensionsFromValue extracts an Extensions from an any, accepting either an Extensions value or a *Extensions pointer (which the rules framework produces when validating struct-typed fields). It is intended for use inside custom validation-guard functions such as those passed to is.Func:
func myGuard(val any) bool {
ext, ok := tax.ExtensionsFromValue(val)
return ok && ext.Has("some-key")
}
func ExtensionsOf ¶ added in v0.402.0
func ExtensionsOf(m cbc.CodeMap) Extensions
ExtensionsOf builds a new Extensions from the provided map. The map is copied so later mutations of the source do not affect the Extensions.
func MakeExtensions ¶ added in v0.402.0
func MakeExtensions() Extensions
MakeExtensions returns an empty Extensions ready to be populated via chained Set calls.
func (Extensions) All ¶ added in v0.402.0
All returns an iterator over the Extensions entries in alphabetical order of the keys. Intended for use with Go 1.23+ range-over-func:
for k, v := range ext.All() {
// ...
}
func (Extensions) Clean ¶ added in v0.402.0
func (e Extensions) Clean() Extensions
Clean returns a new Extensions with empty-code entries removed. If the result has no entries, a zero Extensions is returned.
func (Extensions) Clone ¶ added in v0.402.0
func (e Extensions) Clone() Extensions
Clone returns an independent copy of the Extensions. Mutations to the returned value will not affect the receiver. A zero Extensions clones to another zero Extensions (no allocation).
func (Extensions) Contains ¶ added in v0.72.0
func (e Extensions) Contains(other Extensions) bool
Contains returns true if this Extensions contains all the key/value pairs of the other Extensions. It may contain additional keys that are not in the other. Always returns false if the receiver is empty.
func (Extensions) Delete ¶ added in v0.300.0
func (e Extensions) Delete(key cbc.Key) Extensions
Delete returns a new Extensions without the provided key. If the key is not present, the returned Extensions has the same content as the receiver.
func (Extensions) Equals ¶ added in v0.68.0
func (e Extensions) Equals(other Extensions) bool
Equals returns true if the other Extensions has exactly the same keys and values as this one.
func (Extensions) Get ¶ added in v0.207.0
func (e Extensions) Get(k cbc.Key) cbc.Code
Get returns the value for the provided key or an empty code if not found. If the key is composed of sub-keys and no exact match is found, the key is progressively shortened until a match is found or the key is empty.
func (Extensions) Has ¶ added in v0.68.0
func (e Extensions) Has(keys ...cbc.Key) bool
Has returns true if the Extensions contains entries for all the provided keys.
func (Extensions) IsZero ¶ added in v0.402.0
func (e Extensions) IsZero() bool
IsZero returns true when the Extensions has no entries. Used by encoding/json with the "omitzero" tag so that empty extension maps are omitted from JSON output.
func (Extensions) JSONSchemaExtend ¶ added in v0.68.0
func (Extensions) JSONSchemaExtend(s *jsonschema.Schema)
JSONSchemaExtend replaces the struct-reflection artefacts (empty `properties`, `additionalProperties: false`) with a pattern-properties schema that reproduces the shape Extensions had as a map type: keys must match the cbc.Key pattern, and values are references to the cbc.Code schema. The ref target is resolved via `schema.Lookup` so we don't hardcode the URL.
func (Extensions) Keys ¶ added in v0.402.0
func (e Extensions) Keys() []cbc.Key
Keys returns all the keys of the Extensions sorted alphabetically.
func (Extensions) Len ¶ added in v0.402.0
func (e Extensions) Len() int
Len returns the number of entries in the Extensions.
func (Extensions) Lookup ¶ added in v0.200.0
func (e Extensions) Lookup(val cbc.Code) cbc.Key
Lookup returns the first key whose value matches the provided code, or an empty key if no match is found. Note: if multiple keys share the value, the returned key is not deterministic (depends on map iteration order).
func (Extensions) MarshalJSON ¶ added in v0.402.0
func (e Extensions) MarshalJSON() ([]byte, error)
MarshalJSON emits the Extensions as a JSON object with keys sorted alphabetically for deterministic output. An empty Extensions marshals to "null".
func (Extensions) Merge ¶ added in v0.72.0
func (e Extensions) Merge(other Extensions) Extensions
Merge returns a new Extensions combining the entries of the receiver with those of the other Extensions. Keys in both maps take the value from other.
func (Extensions) Set ¶ added in v0.300.0
func (e Extensions) Set(key cbc.Key, code cbc.Code) Extensions
Set returns a new Extensions with the provided key set to the given code. If the code is empty, the key is removed from the returned Extensions.
func (Extensions) SetIfEmpty ¶ added in v0.300.0
func (e Extensions) SetIfEmpty(key cbc.Key, code cbc.Code) Extensions
SetIfEmpty returns a new Extensions where the given key is set to the provided code only if the key was not already present.
func (Extensions) SetOneOf ¶ added in v0.300.0
func (e Extensions) SetOneOf(key cbc.Key, code cbc.Code, codes ...cbc.Code) Extensions
SetOneOf returns a new Extensions where the given key is set to the first code unless the current value for that key is already one of the additional codes provided.
func (*Extensions) UnmarshalJSON ¶ added in v0.402.0
func (e *Extensions) UnmarshalJSON(data []byte) error
UnmarshalJSON reads a JSON object into the Extensions. A JSON null is treated as an empty Extensions.
func (Extensions) Values ¶ added in v0.300.0
func (e Extensions) Values() []cbc.Code
Values returns all the values of the Extensions sorted alphabetically.
type ExtensionsRule ¶ added in v0.400.0
type ExtensionsRule struct {
// contains filtered or unexported fields
}
ExtensionsRule is a validation rule for extension maps. It implements the rules.Test interface (Check + String), so it can be used in rules.When conditions and rules.Assert tests. It also provides a Validate method that returns detailed per-key errors.
func ExtensionsAllowOneOf ¶ added in v0.305.0
func ExtensionsAllowOneOf(keys ...cbc.Key) ExtensionsRule
ExtensionsAllowOneOf returns a validation rule that ensures at most one of the provided keys is present in the extensions map. This is useful for mutually exclusive options where none or one is allowed.
func ExtensionsExclude ¶ added in v0.207.0
func ExtensionsExclude(keys ...cbc.Key) ExtensionsRule
ExtensionsExclude returns a validation rule that ensures that an extensions map does **not** include the provided keys.
func ExtensionsExcludeCodes ¶ added in v0.216.0
func ExtensionsExcludeCodes(key cbc.Key, codes ...cbc.Code) ExtensionsRule
ExtensionsExcludeCodes returns a validation rule that ensures the extension map's key does not have any of the provided **codes**.
func ExtensionsHasCodes ¶ added in v0.207.0
func ExtensionsHasCodes(key cbc.Key, codes ...cbc.Code) ExtensionsRule
ExtensionsHasCodes returns a validation rule that ensures the extension map's key has one of the provided **codes**.
func ExtensionsRequire ¶ added in v0.207.0
func ExtensionsRequire(keys ...cbc.Key) ExtensionsRule
ExtensionsRequire returns a validation rule that ensures that all of the provided keys are present.
func ExtensionsRequireAllOrNone ¶ added in v0.215.0
func ExtensionsRequireAllOrNone(keys ...cbc.Key) ExtensionsRule
ExtensionsRequireAllOrNone returns a validation rule that performs an XNOR operation on the provided keys. If one of the keys is present, then all of them must be present. If none of the keys are present, then all of them must be absent.
func (ExtensionsRule) Check ¶ added in v0.400.0
func (v ExtensionsRule) Check(val any) bool
Check implements the rules.Test interface. It returns true when the extensions map satisfies the rule (i.e. validation passes).
func (ExtensionsRule) String ¶ added in v0.400.0
func (v ExtensionsRule) String() string
String implements the rules.Test interface, returning the human-readable description set when the rule was constructed.
func (ExtensionsRule) Validate ¶ added in v0.400.0
func (v ExtensionsRule) Validate(value any) error
Validate returns an error when the extensions map does not satisfy the rule.
type ExternalAddon ¶ added in v0.500.0
type ExternalAddon struct {
// Key is the addon key, e.g. "fr-ctc-v1".
Key cbc.Key
// Name is a human-readable description, surfaced in the JSON Schema enum.
Name i18n.String
// Module is the Go module path that implements the addon, kept as the
// approval record, e.g. "github.com/invopop/gobl.fr.ctc".
Module string
}
ExternalAddon describes an addon whose implementation lives in a separate, optional Go module rather than in GOBL core (for example github.com/invopop/gobl.fr.ctc).
Registering an addon here does NOT make it functional at runtime. It only records that the key is a recognised, *approved* addon so that:
- the key is accepted in the JSON Schema `$addons` enum (see AddonList.JSONSchemaExtend), and
- GOBL keeps a curated, reviewed list of the external addons it endorses.
At Validate/Calculate time the addon must still be actually loaded — its module must have been imported so its init() called RegisterAddonDef — otherwise the "$addons must be registered" rule fails. The approved list is recognition and governance, never a runtime bypass: a document is never silently processed without the addon's normalizers and rules.
func ApprovedAddons ¶ added in v0.500.0
func ApprovedAddons() []*ExternalAddon
ApprovedAddons returns the curated list of approved external addons, ordered by key. Being on this list does not imply the addon is loaded at runtime.
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"`
// Scheme is an optional field that may be used to override the tax regime's
// default tax scheme. Many electronic formats such as UBL or CII define an
// equivalent field. Examples: `VAT`, `GST`, `ST`, etc.
Scheme cbc.Code `json:"scheme,omitempty" jsonschema:"title=Scheme"`
// 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"`
}
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 scheme like VAT or GST. Some countries, such as the US, do not have an official tax scheme and should omit the `code` field.
Other fiscal identities should be defined in a party identities array with their own validation rules and country specific handling.
func ParseIdentity ¶ added in v0.113.0
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) GetScheme ¶ added in v0.213.0
GetScheme can be used to determine the tax identities Scheme either from the value defined directly in the identity, or from the tax regime.
func (*Identity) InEU ¶ added in v0.220.3
InEU checks if the tax identity is from a country that is part of the EU on the given date.
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 are normalized by their own country's tax regime, never by the document regime or an addon.
type KeyDef ¶ added in v0.300.0
type KeyDef struct {
// Key identifies this rate within the system
Key cbc.Key `json:"key,omitempty" jsonschema:"title=Key"`
// Human name of the rate set
Name i18n.String `json:"name,omitempty" jsonschema:"title=Name"`
// Useful description of the rate.
Description i18n.String `json:"desc,omitempty" jsonschema:"title=Description"`
// NoPercent when true implies that the rate when used in a tax Combo should
// not define a percent value.
NoPercent bool `json:"no_percent,omitempty" jsonschema:"title=No Percent"`
}
KeyDef defines a key that can be used inside a tax category. Rates may also be defined in addition to the key, and reference them for filtering purposes.
func GlobalGSTKeys ¶ added in v0.302.0
func GlobalGSTKeys() []*KeyDef
GlobalGSTKeys returns the keys that are defined for the global GST category, which can be re-used in other regimes subject to GST.
func GlobalVATKeys ¶ added in v0.300.0
func GlobalVATKeys() []*KeyDef
GlobalVATKeys returns the keys that are defined for the global VAT category, which can be re-used in other regimes subject to VAT.
type Note ¶ added in v0.309.0
type Note struct {
// Tax category code from those available inside a region.
Category cbc.Code `json:"cat,omitempty" jsonschema:"title=Category"`
// Key usually identifies the tax rate key this note applies to (e.g. "exempt",
// "reverse-charge"), but may also be used for other identifiers depending on context.
Key cbc.Key `json:"key,omitempty" jsonschema:"title=Key"`
// Text contains the exemption reason or explanation.
Text string `json:"text" jsonschema:"title=Text"`
// Extensions for additional structured data.
Ext Extensions `json:"ext,omitzero" jsonschema:"title=Extensions"`
}
Note represents a tax-related note, typically used for exemption reasons or other tax-specific explanations that need to be associated with a particular tax category.
type RateDef ¶ added in v0.200.0
type RateDef struct {
// Rate defines the key for which this rate applies.
Rate cbc.Key `json:"rate" jsonschema:"title=Rate"`
// Keys identifies the set of tax keys defined in the category that this
// rate can be used with.
Keys []cbc.Key `json:"keys,omitempty" jsonschema:"title=Keys"`
// 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"`
// 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"`
// 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) HasKey ¶ added in v0.300.0
HasKey returns true if we make a match for the provided key, or if rate has no keys and the provided key is empty.
func (*RateDef) Value ¶ added in v0.200.0
func (r *RateDef) Value(date cal.Date, ext Extensions) *RateValueDef
Value determines the tax rate value for the provided date and zone, if applicable.
type RateTotal ¶
type RateTotal struct {
// 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"`
// Tax key if supported by the category.
Key cbc.Key `json:"key,omitempty" jsonschema:"title=Key"`
// If the rate is defined with extensions, they'll be used to group by also.
Ext Extensions `json:"ext,omitzero" 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,omitzero" 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.
type Regime ¶ added in v0.34.0
type Regime struct {
// Country code that identifies the tax regime applicable to the document.
// It determines which country-specific tax rules, normalizations, and validations are applied.
// It may be determined automatically via normalization of a supplier or issuer tax identity
// country code.
Country RegimeCode `json:"$regime,omitempty" jsonschema:"title=Tax 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) RulesContext ¶ added in v0.400.0
func (r Regime) RulesContext() rules.WithContext
RulesContext implements rules.ContextAdder so that any struct embedding Regime automatically injects the regime code into the validation context. This allows guards like is.InContext(tax.RegimeIn("ES")) to work on nested objects without needing access to the root document.
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 RegimeCode ¶ added in v0.304.0
type RegimeCode l10n.TaxCountryCode
RegimeCode defines the tax country code available for use as a regime identifier.
func (RegimeCode) Code ¶ added in v0.304.0
func (rc RegimeCode) Code() l10n.Code
Code provides the regime code as an l10n.Code.
func (RegimeCode) JSONSchema ¶ added in v0.309.0
func (RegimeCode) JSONSchema() *jsonschema.Schema
JSONSchema provides a representation of the type for usage in Schema.
func (RegimeCode) String ¶ added in v0.304.0
func (rc RegimeCode) String() string
String provides the string representation of the regime code.
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"`
// Sources is a list of references to tax authority or other relevant documentation that
// can be used to validate the regime's data and be used in the future to check for updates
// and changes.
Sources []*cbc.Source `json:"sources,omitempty" jsonschema:"title=Sources"`
// Location name for the country's central time zone. Accepted
// values from IANA Time Zone Database (https://iana.org/time-zones). If a country has multiple
// time zones, the most common or central one should be used.
TimeZone string `json:"time_zone" jsonschema:"title=Time Zone"`
// Country code for tax purposes which usually coincides with the ISO 3166-1 alpha-2 code, but not
// always.
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"`
// TaxScheme defines the principal scheme of consumption tax that should be
// applied to the regime and associated with Tax IDs in some export formats
// such as UBL or CII. Some regimes may not have a Tax Scheme and as a
// consequence will not use tax identities, like the US.
TaxScheme cbc.Code `json:"tax_scheme,omitempty" jsonschema:"title=Tax Scheme"`
// Rounding rule to use when calculating the tax totals. See the RoundingRule
// constants for more details. If not provided, the default is RoundingRulePrecise.
CalculatorRoundingRule cbc.Key `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.Definition `json:"extensions,omitempty" jsonschema:"title=Extensions"`
// Identities used in addition to regular tax identities and specific for the
// regime that may be validated against.
Identities []*cbc.Definition `json:"identities,omitempty" jsonschema:"title=Identities"`
// PaymentMeansKeys specific for the regime that extend the original
// base payment means keys.
PaymentMeansKeys []*cbc.Definition `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.Definition `json:"inbox_keys,omitempty" jsonschema:"title=Inbox Keys"`
// Scenarios are used to describe a specific set of conditions and rules that apply to a specific
// document schema. These provide a more generic solution for normalization and validation of documents
// in regimes with specific requirements.
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"`
}
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
RegimeDefFor returns the regime definition for country and locality combination or nil if no match was found.
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
Code provides a unique code for this tax regime based on the country.
func (*RegimeDef) CurrencyDef ¶ added in v0.200.0
CurrencyDef provides the currency definition object for the region.
func (*RegimeDef) GetCountry ¶ added in v0.211.0
func (r *RegimeDef) GetCountry() l10n.TaxCountryCode
GetCountry provides the country code for the regime, or an empty string.
func (*RegimeDef) GetCurrency ¶ added in v0.209.0
GetCurrency is a convenience method that will always return a code, even if the RegimeDef is nil.
func (*RegimeDef) GetRoundingRule ¶ added in v0.209.0
GetRoundingRule provides the regime's rounding rule, or the default.
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
TimeLocation returns the time.Location for the regime.
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.
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"`
// Description of the scenario for documentation purposes.
Desc i18n.String `json:"desc,omitempty" jsonschema:"title=Description"`
// 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"`
// Categories is an optional list of tax category codes that acts as a filter.
// When set, at least one of the specified categories must be present in the
// document's line taxes for the scenario to match.
Categories []cbc.Code `json:"cat,omitempty" jsonschema:"title=Tax Categories"`
// Extension key that must be present in the document.
ExtKey cbc.Key `json:"ext_key,omitempty" jsonschema:"title=Extension Key"`
// Extension code that along side the key must be present for a match
// to happen. This cannot be used without an `cbc.Code`. The value will
// be copied to the note code if needed.
ExtCode cbc.Code `json:"ext_code,omitempty" jsonschema:"title=Extension Code"`
// 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 *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,omitzero" 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.
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
// GetTaxCategories returns a list of tax categories used in the document's lines,
// charges, and discounts.
GetTaxCategories() []cbc.Code
}
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() []*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.
type ScenarioSummary ¶ added in v0.38.0
type ScenarioSummary struct {
Notes []*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.
type SetTest ¶ added in v0.400.0
type SetTest struct {
// contains filtered or unexported fields
}
SetTest defines a validation rule for tax sets, checking for the presence of certain categories.
func SetHasCategory ¶ added in v0.67.4
SetHasCategory validates that the set contains the given category.
func SetHasOneOf ¶ added in v0.304.0
SetHasOneOf checks that the tax set has at least one of the provided categories.
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.Definition `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
TagSetForSchema will return the tag set for the provided schema, or nil if it does not exist.
type Tags ¶ added in v0.200.0
type Tags struct {
// Tags are used to help identify specific tax scenarios or requirements that may
// apply changes to the contents of the document or imply a specific meaning.
// Converters may use tags to help identify specific situations that do not have
// a specific extension, for example; self-billed or partial invoices may be
// identified by their respective 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 (Tags) GetTags ¶ added in v0.200.0
GetTags returns the list of tags that have been assigned to the object.
func (Tags) HasTags ¶ added in v0.200.0
HasTags returns true if the list of tags contains all of the provided tags.
func (Tags) JSONSchemaExtendWithDefs ¶ added in v0.220.0
func (ts Tags) JSONSchemaExtendWithDefs(js *jsonschema.Schema, defs []*cbc.Definition)
JSONSchemaExtendWithDefs will add the provided set of tags to the JSON schema as default options for the `$tags` property. A default catch-all will also be available.
func (*Tags) RemoveTags ¶ added in v0.304.0
RemoveTags removes the specified tags from the list.
type TaxableLine ¶
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 non-retained or indirect taxes.
Sum num.Amount `json:"sum" jsonschema:"title=Sum"`
// Sum of retained or withheld tax amounts
Retained *num.Amount `json:"retained,omitempty" jsonschema:"title=Retained"`
}
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) Calculate ¶
Calculate will go through all the categories and rates to recalculate the final tax amounts and sums from the accumulated bases according to the rounding rule. When source lines are available, use the TotalCalculator instead; recalculations from the bases alone cannot take into account any taxes included in prices.
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) Clone ¶ added in v0.209.0
Clone creates a new total with the same values as the original, but in an independent object.
func (*Total) Exchange ¶ added in v0.218.0
func (t *Total) Exchange(rate *currency.ExchangeRate, rr cbc.Key)
Exchange will recalculate the total with the same values, but in a different currency. This is used in scenarios where tax totals are embedded into sub-documents and need to be combined. If either the rate ot total is nil, nothing will be done. The rounding rule will be used for re-calculations.
func (*Total) Merge ¶ added in v0.209.0
Merge will combine two totals objects into a new one, summing up the values of the categories and rates. The original totals will not be modified. The totals may contain zero amounts if the amounts in the second total are negative.
func (*Total) Negate ¶ added in v0.209.0
Negate provides a new total with all the values inverted (positive to negative and vice versa). Will return nil if total is nil.
func (*Total) Round ¶ added in v0.216.0
Round will go through all the values generated and round them to the currency's preferred precision.
type TotalCalculator ¶ added in v0.35.0
type TotalCalculator struct {
Country l10n.TaxCountryCode
Rounding cbc.Key
Currency currency.Code
Date cal.Date
Lines []TaxableLine
Includes cbc.Code // Tax included in price
// contains filtered or unexported fields
}
TotalCalculator defines the base structure with the available data for calculating tax totals from TaxableLines.
func (*TotalCalculator) Calculate ¶ added in v0.35.0
func (tc *TotalCalculator) Calculate(t *Total) error
Calculate the totals according to the rounding rule, either using the currency's precision for every step, or maintaining precision until the final sums.
Source Files
¶
- addons.go
- addons_external.go
- catalogue.go
- category_def.go
- combo.go
- constants.go
- corrections.go
- errors.go
- extensions.go
- identity.go
- key_def.go
- norm.go
- note.go
- point.go
- rate_def.go
- regime.go
- regime_def.go
- regimes.go
- rounding_rules.go
- scenario.go
- set.go
- tags.go
- tax.go
- totals.go
- totals_calculator.go
- totals_calculator_currency.go
- totals_calculator_precise.go