Skip to content

Instantly share code, notes, and snippets.

@tom2strobl
Created August 14, 2025 12:28
Show Gist options
  • Save tom2strobl/708b15dd3bf997115c245281f052a7e4 to your computer and use it in GitHub Desktop.
Save tom2strobl/708b15dd3bf997115c245281f052a7e4 to your computer and use it in GitHub Desktop.
GOBL typescript types generation script
/** biome-ignore-all lint/suspicious/noConsole: we are scripting */
import { promises as fs } from "node:fs"
import path from "node:path"
import { fileURLToPath } from "node:url"
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
// we use the gobl repo as a submodule that we update through `git submodule update --remote --merge gobl`
const GOBL_SCHEMAS_DIR = path.join(__dirname, "..", "gobl", "data", "schemas")
const TYPES_OUTPUT = path.join(__dirname, "..", "types.ts")
async function generateTypes() {
try {
console.log("Loading all GOBL schemas...")
const allSchemas = await loadAllSchemas()
console.log(`Loaded ${allSchemas.length} schemas`)
console.log("Generating types using json-schema-to-ts...")
await generateTypesFile(allSchemas)
console.log("✅ Successfully generated types!")
} catch (error) {
console.error("Error generating types:", error)
process.exit(1)
}
}
async function loadAllSchemas() {
const schemaFiles = await getAllSchemaFiles(GOBL_SCHEMAS_DIR)
const allSchemas = []
for (const schemaFile of schemaFiles) {
const schemaContent = await fs.readFile(schemaFile, "utf-8")
const schema = JSON.parse(schemaContent)
const relativePath = path.relative(GOBL_SCHEMAS_DIR, schemaFile)
const { varName, typeName } = generateNames(relativePath)
allSchemas.push({
varName,
typeName,
schema,
relativePath,
$id: schema.$id // Keep the original $id for reference resolution
})
}
return allSchemas
}
async function generateTypesFile(allSchemas) {
let typesContent = `// Auto-generated TypeScript types from GOBL JSON schemas
// Generated on ${new Date().toISOString()}
// DO NOT EDIT MANUALLY - Run 'yarn generate-types' to regenerate
`
// Track generated type names to avoid duplicates
const generatedTypes = new Set()
// Generate TypeScript type definitions for all schemas
for (const schemaInfo of allSchemas) {
const typeDefinition = generateSimpleTypeDefinition(schemaInfo, generatedTypes)
typesContent += `${typeDefinition}\n\n`
}
// Write the types file
await fs.writeFile(TYPES_OUTPUT, typesContent.trim())
console.log(`✅ Generated types file: ${TYPES_OUTPUT}`)
}
function generateSimpleTypeDefinition(schemaInfo, generatedTypes = new Set()) {
const { schema, typeName, relativePath } = schemaInfo
let result = `// Schema: ${relativePath}\n`
// Generate type based on the main definition in $defs
const description = getSchemaDescription(schema)
if (description) {
result += `/**\n * ${description}\n */\n`
}
// Track the main type
generatedTypes.add(typeName)
if (schema.$defs && schema.$ref) {
const refPath = schema.$ref.replace("#/$defs/", "")
const mainDef = schema.$defs[refPath]
if (mainDef?.properties) {
// Complex object with properties - generate interface
result += `export interface ${typeName} {\n`
for (const [propName, propDef] of Object.entries(mainDef.properties)) {
const isOptional = !mainDef.required?.includes(propName)
const propType = getPropertyType(propDef, schema)
const comment = propDef.description ? ` /** ${propDef.description} */\n` : ""
result += `${comment} ${propName}${isOptional ? "?" : ""}: ${propType};\n`
}
result += "}"
} else if (mainDef) {
// Simple type definition - generate type alias
const simpleType = getSimpleTypeFromDef(mainDef, schema)
result += `export type ${typeName} = ${simpleType};`
} else {
// Fallback to any if we can't find the definition
result += `export type ${typeName} = any;`
}
// Generate additional internal type definitions from $defs
if (schema.$defs) {
for (const [defName, defSchema] of Object.entries(schema.$defs)) {
// Skip the main definition we already processed
if (defName === refPath) continue
// Skip if we've already generated this type name
if (generatedTypes.has(defName)) continue
generatedTypes.add(defName)
result += `\n\n// Internal type: ${defName}`
const internalDescription = defSchema.description
if (internalDescription) {
result += `\n/**\n * ${internalDescription}\n */`
}
if (defSchema.properties) {
// Complex object - generate interface
result += `\nexport interface ${defName} {\n`
for (const [propName, propDef] of Object.entries(defSchema.properties)) {
const isOptional = !defSchema.required?.includes(propName)
const propType = getPropertyType(propDef, schema)
const comment = propDef.description ? ` /** ${propDef.description} */\n` : ""
result += `${comment} ${propName}${isOptional ? "?" : ""}: ${propType};\n`
}
result += "}"
} else {
// Simple type - generate type alias
const simpleType = getSimpleTypeFromDef(defSchema, schema)
result += `\nexport type ${defName} = ${simpleType};`
}
}
}
} else {
// Fallback to any for schemas without $defs structure
result += `export type ${typeName} = any;`
}
return result
}
function getSimpleTypeFromDef(def, currentSchema = null) {
// Handle primitive types
if (def.type === "string") {
if (def.enum) {
return def.enum.map((val) => `"${val}"`).join(" | ")
}
if (def.const) {
return `"${def.const}"`
}
return "string"
}
if (def.type === "number" || def.type === "integer") return "number"
if (def.type === "boolean") return "boolean"
if (def.type === "array") {
if (def.items) {
const itemType = getPropertyType(def.items, currentSchema)
return `${itemType}[]`
}
return "any[]"
}
if (def.type === "object") {
if (def.properties) {
// This case should be handled by the interface generation above
return "Record<string, any>"
}
// Handle patternProperties for dynamic keys
if (def.patternProperties) {
const patterns = Object.values(def.patternProperties)
if (patterns.length === 1) {
const valueType = getPropertyType(patterns[0], currentSchema)
return `Record<string, ${valueType}>`
}
// Multiple patterns - use union type
const valueTypes = patterns.map((pattern) => getPropertyType(pattern, currentSchema))
const uniqueTypes = [...new Set(valueTypes)]
return `Record<string, ${uniqueTypes.join(" | ")}>`
}
// For generic objects (like SchemaObject), provide a more structured type
// if the description suggests it should have a $schema property
if (def.description?.includes("$schema")) {
return "Record<string, unknown> & { $schema?: string }"
}
return "Record<string, unknown>"
}
// Handle oneOf/anyOf as union types
if (def.oneOf || def.anyOf) {
const options = def.oneOf || def.anyOf
return options.map((opt) => getSimpleTypeFromDef(opt, currentSchema)).join(" | ")
}
// Handle const values
if (def.const !== undefined) {
return typeof def.const === "string" ? `"${def.const}"` : String(def.const)
}
return "any"
}
function getPropertyType(propDef, currentSchema = null) {
// Handle external references
if (propDef.$ref) {
if (propDef.$ref.startsWith("https://gobl.org/draft-0/")) {
// Extract type name from GOBL URL reference
const refPath = propDef.$ref.replace("https://gobl.org/draft-0/", "")
const { typeName } = generateNames(refPath)
return typeName
} else if (propDef.$ref.startsWith("#/$defs/") && currentSchema) {
// Handle internal references within the same schema
const refName = propDef.$ref.replace("#/$defs/", "")
const refDef = currentSchema.$defs?.[refName]
if (refDef) {
// For internal refs, create a sub-type name based on the reference
return refName // Use the ref name directly (e.g., "Tracking")
}
}
return "any" // Unknown reference
}
// Handle primitive types
if (propDef.type === "string") {
if (propDef.enum) {
return propDef.enum.map((val) => `"${val}"`).join(" | ")
}
if (propDef.const) {
return `"${propDef.const}"`
}
return "string"
}
if (propDef.type === "number" || propDef.type === "integer") return "number"
if (propDef.type === "boolean") return "boolean"
if (propDef.type === "array") {
if (propDef.items) {
const itemType = getPropertyType(propDef.items, currentSchema)
return `${itemType}[]`
}
return "any[]"
}
if (propDef.type === "object") return "Record<string, any>"
// Handle oneOf/anyOf as union types
if (propDef.oneOf || propDef.anyOf) {
const options = propDef.oneOf || propDef.anyOf
return options.map((opt) => getPropertyType(opt, currentSchema)).join(" | ")
}
// Handle const values
if (propDef.const !== undefined) {
return typeof propDef.const === "string" ? `"${propDef.const}"` : String(propDef.const)
}
return "any"
}
function getSchemaDescription(schema) {
// Try to get description from the main definition in $defs
if (schema.$defs && schema.$ref) {
const refPath = schema.$ref.replace("#/$defs/", "")
const mainDef = schema.$defs[refPath]
if (mainDef?.description) {
return mainDef.description
}
}
// Fallback to root description
return schema.description || null
}
async function getAllSchemaFiles(dir, files = []) {
const entries = await fs.readdir(dir, { withFileTypes: true })
for (const entry of entries) {
const fullPath = path.join(dir, entry.name)
if (entry.isDirectory()) {
await getAllSchemaFiles(fullPath, files)
} else if (entry.isFile() && entry.name.endsWith(".json")) {
files.push(fullPath)
}
}
return files
}
function generateNames(relativePath) {
// Remove .json extension
const pathWithoutExt = relativePath.replace(/\.json$/, "")
// Generate variable name (camelCase)
const varParts = pathWithoutExt.split(path.sep)
const varName = `${varParts
.map((part, index) => {
const words = part.split(/[-_]/)
if (index === 0) {
// First part in camelCase
return words.map((word, wordIndex) => (wordIndex === 0 ? word.toLowerCase() : capitalize(word))).join("")
}
// Rest in PascalCase
return words.map(capitalize).join("")
})
.join("")}Schema`
// Generate type name (PascalCase)
const typeParts = pathWithoutExt.split(path.sep)
const typeName = typeParts
.map((part) => {
const words = part.split(/[-_]/)
return words.map(capitalize).join("")
})
.join("")
return { varName, typeName }
}
function capitalize(str) {
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase()
}
// Run the generator
generateTypes()
// Auto-generated TypeScript types from GOBL JSON schemas
// Generated on 2025-08-14T12:24:29.567Z
// DO NOT EDIT MANUALLY - Run 'yarn generate-types' to regenerate
// Schema: bill/charge.json
/**
* Charge represents a surchange applied to the complete document independent from the individual lines.
*/
export interface BillCharge {
/** Universally Unique Identifier. */
uuid?: string;
/** Line number inside the list of charges (calculated). */
i: number;
/** Key for grouping or identifying charges for tax purposes. A suggested list of
keys is provided, but these may be extended by the issuer. */
key?: CbcKey;
/** Code to used to refer to the this charge by the issuer */
code?: CbcCode;
/** Text description as to why the charge was applied */
reason?: string;
/** Base represents the value used as a base for percent calculations instead
of the invoice's sum of lines. */
base?: NumAmount;
/** Percentage to apply to the sum of all lines */
percent?: NumPercentage;
/** Amount to apply (calculated if percent present) */
amount: NumAmount;
/** List of taxes to apply to the charge */
taxes?: TaxSet;
/** Extension codes that apply to the charge */
ext?: TaxExtensions;
/** Additional semi-structured information. */
meta?: CbcMeta;
}
// Schema: bill/correction-options.json
/**
* CorrectionOptions defines a structure used to pass configuration options to correct a previous invoice.
*/
export interface BillCorrectionOptions {
/** The type of corrective invoice to produce. */
type: CbcKey;
/** When the new corrective invoice's issue date should be set to. */
issue_date?: CalDate;
/** Series to assign to the new corrective invoice. */
series?: CbcCode;
/** Stamps of the previous document to include in the preceding data. */
stamps?: HeadStamp[];
/** Human readable reason for the corrective operation. */
reason?: string;
/** Extensions for region specific requirements that may be added in the preceding
or at the document level, according to the local rules. */
ext?: TaxExtensions;
/** CopyTax when true will copy the tax totals from the previous document to the
preceding document data. */
copy_tax?: boolean;
}
// Schema: bill/delivery-details.json
/**
* DeliveryDetails covers the details of the destination for the products described in the invoice body.
*/
export interface BillDeliveryDetails {
/** The party who will receive delivery of the goods defined in the invoice and is not responsible for taxes. */
receiver?: OrgParty;
/** Identities is used to define specific codes or IDs that may be used to
identify the delivery. */
identities?: OrgIdentity[];
/** When the goods should be expected. */
date?: CalDate;
/** Period of time in which to expect delivery if a specific date is not available. */
period?: CalPeriod;
/** Additional custom data. */
meta?: CbcMeta;
}
// Schema: bill/delivery.json
/**
* Delivery document used to describe the delivery of goods or potentially also services.
*/
export interface BillDelivery {
$regime?: L10nTaxCountryCode;
/** Addons defines a list of keys used to identify tax addons that apply special
normalization, scenarios, and validation rules to a document. */
$addons?: CbcKey[];
/** 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. */
$tags?: CbcKey[];
/** Universally Unique Identifier. */
uuid?: string;
/** Type of delivery document. */
type: CbcKey;
/** Series is used to identify groups of deliveries by date, business area, project,
type, customer, a combination of any, or other company specific data.
If the output format does not support the series as a separate field, it will be
prepended to the code for presentation with a dash (`-`) for separation. */
series?: CbcCode;
/** Code is a sequential identifier that uniquely identifies the delivery. The code can
be left empty initially, but is **required** to **sign** the document. */
code?: CbcCode;
/** When the delivery document is to be issued. */
issue_date: CalDate;
/** IssueTime is an optional field that may be useful to indicate the time of day when
the delivery was issued. Some regions and formats may require this field to be set.
An empty string will be automatically updated to reflect the current time, otherwise
the field can be left with a nil value. */
issue_time?: CalTime;
/** When the taxes of this delivery become accountable, if none set, the issue date is used. */
value_date?: CalDate;
/** Currency for all delivery totals. */
currency?: CurrencyCode;
/** Exchange rates to be used when converting the invoices monetary values into other currencies. */
exchange_rates?: CurrencyExchangeRate[];
/** Ordering details for the delivery, including links to other documents. */
ordering?: BillOrdering;
/** Key information regarding previous delivery documents that this one will either
extend or replace. */
preceding?: OrgDocumentRef[];
/** Tracking is used to define specific codes or IDs that may be used to
identify and track delivery. */
tracking?: Tracking;
/** DespatchDate is the date when the goods are expected to be despatched. */
despatch_date?: CalDate;
/** ReceiveDate is the date when the goods are expected to be received. */
receive_date?: CalDate;
/** Special tax configuration for calculating totals. */
tax?: BillTax;
/** The entity supplying the goods or services and usually responsible for paying taxes. */
supplier: OrgParty;
/** Legal entity receiving the goods or services, may be nil in certain circumstances such as simplified invoices. */
customer?: OrgParty;
/** The party who will despatch the goods defined in the invoice. */
despatcher?: OrgParty;
/** The party who will receive delivery of the goods defined in the invoice. */
receiver?: OrgParty;
/** The courier responsible for delivering the goods. */
courier?: OrgParty;
/** List of lines representing each of the items to be ordered. */
lines?: BillLine[];
/** Discounts or allowances applied to order totals */
discounts?: BillDiscount[];
/** Charges or surcharges applied to order totals */
charges?: BillCharge[];
/** Summary of all the order totals, including taxes (calculated). */
totals?: BillTotals;
/** Unstructured information that is relevant to the delivery, such as correction or additional
legal details. */
notes?: OrgNote[];
/** Additional complementary objects that add relevant information to the delivery. */
complements?: SchemaObject[];
/** Additional semi-structured data that doesn't fit into the body of the delivery. */
meta?: CbcMeta;
/** Attachments provide additional information or supporting documents that are not included
in the main document. It is important that attachments are not used for alternative
versions of the PDF, for that, see "links" inside the envelope headers. */
attachments?: OrgAttachment[];
}
// Internal type: Tracking
/**
* Tracking stores tracking information about a delivery.
*/
export interface Tracking {
/** Code used for tracking */
code?: CbcCode;
/** Website to access for more tracking details */
website?: OrgWebsite;
}
// Schema: bill/discount.json
/**
* Discount represents an allowance applied to the complete document independent from the individual lines.
*/
export interface BillDiscount {
/** Universally Unique Identifier. */
uuid?: string;
/** Line number inside the list of discounts (calculated) */
i: number;
/** Key for identifying the type of discount being applied. */
key?: CbcKey;
/** Code to used to refer to the this discount by the issuer */
code?: CbcCode;
/** Text description as to why the discount was applied */
reason?: string;
/** Base represents the value used as a base for percent calculations instead
of the invoice's sum of lines. */
base?: NumAmount;
/** Percentage to apply to the base or invoice's sum. */
percent?: NumPercentage;
/** Amount to apply (calculated if percent present). */
amount: NumAmount;
/** List of taxes to apply to the discount */
taxes?: TaxSet;
/** Extension codes that apply to the discount */
ext?: TaxExtensions;
/** Additional semi-structured information. */
meta?: CbcMeta;
}
// Schema: bill/invoice.json
/**
* Invoice represents a payment claim for goods or services supplied under conditions agreed between the supplier and the customer.
*/
export interface BillInvoice {
$regime?: L10nTaxCountryCode;
/** Addons defines a list of keys used to identify tax addons that apply special
normalization, scenarios, and validation rules to a document. */
$addons?: CbcKey[];
/** 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. */
$tags?: CbcKey[];
/** Universally Unique Identifier. */
uuid?: string;
/** Type of invoice document. May be restricted by local tax regime requirements. */
type: CbcKey;
/** Series is used to identify groups of invoices by date, business area, project,
type of document, customer type, a combination of any or other company specific data.
If the output format does not support the series as a separate field, it will be
prepended to the code for presentation with a dash (`-`) for separation. */
series?: CbcCode;
/** Code is a sequential identifier that uniquely identifies the invoice. The code can
be left empty initially, but is **required** to **sign** the invoice. */
code?: CbcCode;
/** Issue date for when the invoice was created and issued. Todays date is used if
none is set. There are often legal restrictions on how far back or in the future an
invoice can be issued. */
issue_date: CalDate;
/** IssueTime is an optional field that may be useful to indicate the time of day when
the invoice was issued. Some regions and formats may require this field to be set.
An empty string will be automatically updated to reflect the current time, otherwise
the field can be left with a nil value. */
issue_time?: CalTime;
/** Date when the operation defined by the invoice became effective. */
op_date?: CalDate;
/** When the taxes of this invoice become accountable, if none set, the issue date is used. */
value_date?: CalDate;
/** Currency for all invoice amounts and totals, unless explicitly stated otherwise. */
currency: CurrencyCode;
/** Exchange rates to be used when converting the invoices monetary values into other currencies. */
exchange_rates?: CurrencyExchangeRate[];
/** Document references for previous invoices that this document replaces or extends. */
preceding?: OrgDocumentRef[];
/** Special billing tax configuration options. */
tax?: BillTax;
/** The entity supplying the goods or services and usually responsible for paying taxes. */
supplier: OrgParty;
/** Legal entity receiving the goods or services, may be nil in certain circumstances
such as simplified invoices. */
customer?: OrgParty;
/** List of invoice lines representing each of the items sold to the customer. */
lines?: BillLine[];
/** Discounts or allowances applied to the complete invoice */
discounts?: BillDiscount[];
/** Charges or surcharges applied to the complete invoice */
charges?: BillCharge[];
/** Ordering details including document references and buyer or seller parties. */
ordering?: BillOrdering;
/** Information on when, how, and to whom the invoice should be paid. */
payment?: BillPaymentDetails;
/** Specific details on delivery of the goods referenced in the invoice. */
delivery?: BillDeliveryDetails;
/** Summary of all the invoice totals, including taxes (calculated). */
totals: BillTotals;
/** Unstructured information that is relevant to the invoice, such as correction or additional
legal details. */
notes?: OrgNote[];
/** Additional complementary objects that add relevant information to the invoice. */
complements?: SchemaObject[];
/** Additional semi-structured data that doesn't fit into the body of the invoice. */
meta?: CbcMeta;
/** Attachments provide additional information or supporting documents that are not included
in the main document. It is important that attachments are not used for alternative
versions of the PDF, for that, see "links" inside the envelope headers. */
attachments?: OrgAttachment[];
}
// Schema: bill/line.json
/**
* Line is a single row in an invoice.
*/
export interface BillLine {
/** Universally Unique Identifier. */
uuid?: string;
/** Line number inside the parent (calculated) */
i: number;
/** Number of items */
quantity: NumAmount;
/** Single identifier provided by the supplier for an object on which the
line item is based and is not considered a universal identity. Examples
include a subscription number, telephone number, meter point, etc.
Utilize the label property to provide a description of the identifier. */
identifier?: OrgIdentity;
/** A period of time relevant to when the service or item is delivered. */
period?: CalPeriod;
/** Order reference for a specific line within a purchase order provided by the buyer. */
order?: CbcCode;
/** Buyer accounting reference cost code to associate with the line. */
cost?: CbcCode;
/** Details about the item, service or good, that is being sold */
item: OrgItem;
/** Breakdown of the line item for more detailed information. The sum of all lines
will be used for the item price. */
breakdown?: SubLine[];
/** Result of quantity multiplied by the item's price (calculated) */
sum?: NumAmount;
/** Discounts applied to this line */
discounts?: LineDiscount[];
/** Charges applied to this line */
charges?: LineCharge[];
/** Map of taxes to be applied and used in the invoice totals */
taxes?: TaxSet;
/** Total line amount after applying discounts to the sum (calculated). */
total?: NumAmount;
/** List of substituted lines. Useful for deliveries or corrective documents in order
to indicate to the recipient which of the requested lines are being replaced.
This is for purely informative purposes, and will not be used for calculations. */
substituted?: SubLine[];
/** Set of specific notes for this line that may be required for
clarification. */
notes?: OrgNote[];
/** Extension codes that apply to the line */
ext?: TaxExtensions;
}
// Internal type: LineCharge
/**
* LineCharge represents an amount added to the line, and will be applied before taxes.
*/
export interface LineCharge {
/** Key for grouping or identifying charges for tax purposes. A suggested list of
keys is provided, but these are for reference only and may be extended by
the issuer. */
key?: CbcKey;
/** Reference or ID for this charge defined by the issuer */
code?: CbcCode;
/** Text description as to why the charge was applied */
reason?: string;
/** Base for percent calculations instead of the line's sum */
base?: NumAmount;
/** Percentage of base or parent line's sum */
percent?: NumPercentage;
/** Quantity of units to apply the charge to when using the rate instead of
the line's quantity. */
quantity?: NumAmount;
/** Unit to associate with the quantity when using the rate. */
unit?: OrgUnit;
/** Rate defines a price per unit to use instead of the percentage. */
rate?: NumAmount;
/** Fixed or resulting charge amount to apply (calculated if percent present). */
amount: NumAmount;
/** Extension codes that apply to the charge */
ext?: TaxExtensions;
}
// Internal type: LineDiscount
/**
* LineDiscount represents an amount deducted from the line, and will be applied before taxes.
*/
export interface LineDiscount {
/** Key for identifying the type of discount being applied. */
key?: CbcKey;
/** Code or reference for this discount defined by the issuer */
code?: CbcCode;
/** Text description as to why the discount was applied */
reason?: string;
/** Base for percent calculations instead of the line's sum. */
base?: NumAmount;
/** Percentage to apply to the base or line sum to calculate the discount amount */
percent?: NumPercentage;
/** Fixed discount amount to apply (calculated if percent present) */
amount: NumAmount;
/** Extension codes that apply to the discount */
ext?: TaxExtensions;
}
// Internal type: SubLine
/**
* SubLine provides a simplified line that can be embedded inside other lines to provide a more detailed breakdown of the items being sold or substituted.
*/
export interface SubLine {
/** Universally Unique Identifier. */
uuid?: string;
/** Line number inside the parent (calculated) */
i: number;
/** Number of items */
quantity: NumAmount;
/** Single identifier provided by the supplier for an object on which the
line item is based and is not considered a universal identity. Examples
include a subscription number, telephone number, meter point, etc.
Utilize the label property to provide a description of the identifier. */
identifier?: OrgIdentity;
/** A period of time relevant to when the service or item is delivered. */
period?: CalPeriod;
/** Order reference for a specific line within a purchase order provided by the buyer. */
order?: CbcCode;
/** Buyer accounting reference cost code to associate with the line. */
cost?: CbcCode;
/** Details about the item, service or good, that is being sold */
item: OrgItem;
/** Result of quantity multiplied by the item's price (calculated) */
sum?: NumAmount;
/** Discounts applied to this sub-line */
discounts?: LineDiscount[];
/** Charges applied to this sub-line */
charges?: LineCharge[];
/** Total sub-line amount after applying discounts to the sum (calculated). */
total?: NumAmount;
/** Set of specific notes for this sub-line that may be required for
clarification. */
notes?: OrgNote[];
}
// Schema: bill/order.json
/**
* Order documents are used for the initial part of a order-to-invoice process where the buyer requests goods or services from the seller.
*/
export interface BillOrder {
$regime?: L10nTaxCountryCode;
/** Addons defines a list of keys used to identify tax addons that apply special
normalization, scenarios, and validation rules to a document. */
$addons?: CbcKey[];
/** 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. */
$tags?: CbcKey[];
/** Universally Unique Identifier. */
uuid?: string;
/** Type of the order. */
type?: CbcKey;
/** Series is used to identify groups of orders by date, business area, project,
type, customer, a combination of any, or other company specific data.
If the output format does not support the series as a separate field, it will be
prepended to the code for presentation with a dash (`-`) for separation. */
series?: CbcCode;
/** Code is a sequential identifier that uniquely identifies the order. The code can
be left empty initially, but is **required** to **sign** the document. */
code?: CbcCode;
/** When the invoice was created. */
issue_date: CalDate;
/** IssueTime is an optional field that may be useful to indicate the time of day when
the order was issued. Some regions and formats may require this field to be set.
An empty string will be automatically updated to reflect the current time, otherwise
the field can be left with a nil value. */
issue_time?: CalTime;
/** Date when the operation defined by the invoice became effective. */
op_date?: CalDate;
/** When the taxes of this invoice become accountable, if none set, the issue date is used. */
value_date?: CalDate;
/** Currency for all invoice totals. */
currency: CurrencyCode;
/** Exchange rates to be used when converting the invoices monetary values into other currencies. */
exchange_rates?: CurrencyExchangeRate[];
/** The identification of contracts. */
contracts?: OrgDocumentRef[];
/** Key information regarding previous order documents. */
preceding?: OrgDocumentRef[];
/** Additional codes, IDs, SKUs, or other regional or custom identifiers that may be used to identify the order. */
identities?: OrgIdentity[];
/** Period of time in which the order is valid. */
period?: CalPeriod;
/** Special tax configuration for billing. */
tax?: BillTax;
/** The entity supplying the goods or services and usually responsible for paying taxes. */
supplier: OrgParty;
/** Legal entity receiving the goods or services, may be nil in certain circumstances such as simplified invoices. */
customer?: OrgParty;
/** Party who is responsible for issuing payment, if not the same as the customer. */
buyer?: OrgParty;
/** Seller is the party liable to pay taxes on the transaction if not the same as the supplier. */
seller?: OrgParty;
/** List of lines representing each of the items to be ordered. */
lines?: BillLine[];
/** Discounts or allowances applied to order totals */
discounts?: BillDiscount[];
/** Charges or surcharges applied to order totals */
charges?: BillCharge[];
/** Information on when, how, and to whom a final invoice would be paid. */
payment?: BillPaymentDetails;
/** Specific details on delivery of the goods to copy to the final invoice. */
delivery?: BillDeliveryDetails;
/** Summary of all the order totals, including taxes (calculated). */
totals?: BillTotals;
/** Unstructured information that is relevant to the order, such as correction or additional
legal details. */
notes?: OrgNote[];
/** Additional complementary objects that add relevant information to the order. */
complements?: SchemaObject[];
/** Additional semi-structured data that doesn't fit into the body of the order. */
meta?: CbcMeta;
/** Attachments provide additional information or supporting documents that are not included
in the main document. It is important that attachments are not used for alternative
versions of the PDF, for that, see "links" inside the envelope headers. */
attachments?: OrgAttachment[];
}
// Schema: bill/ordering.json
/**
* Ordering provides additional information about the ordering process including references to other documents and alternative parties involved in the order-to-delivery process.
*/
export interface BillOrdering {
/** Identifier assigned by the customer or buyer for internal routing purposes. */
code?: CbcCode;
/** Any additional Codes, IDs, SKUs, or other regional or custom
identifiers that may be used to identify the order. */
identities?: OrgIdentity[];
/** Buyer accounting reference cost code associated with the document. */
cost?: CbcCode;
/** Period of time that the invoice document refers to often used in addition to the details
provided in the individual line items. */
period?: CalPeriod;
/** Party who is responsible for issuing payment, if not the same as the customer. */
buyer?: OrgParty;
/** Seller is the party liable to pay taxes on the transaction if not the same as the supplier. */
seller?: OrgParty;
/** Issuer represents a third party responsible for issuing the invoice, but is not
responsible for tax. Some tax regimes and formats require this field. */
issuer?: OrgParty;
/** Projects this invoice refers to. */
projects?: OrgDocumentRef[];
/** The identification of contracts. */
contracts?: OrgDocumentRef[];
/** Purchase orders issued by the customer or buyer. */
purchases?: OrgDocumentRef[];
/** Sales orders issued by the supplier or seller. */
sales?: OrgDocumentRef[];
/** Receiving Advice. */
receiving?: OrgDocumentRef[];
/** Despatch advice. */
despatch?: OrgDocumentRef[];
/** Tender advice, the identification of the call for tender or lot the invoice relates to. */
tender?: OrgDocumentRef[];
}
// Schema: bill/payment-details.json
/**
* PaymentDetails contains details as to how the invoice should be paid.
*/
export interface BillPaymentDetails {
/** The party responsible for receiving payment of the invoice, if not the supplier. */
payee?: OrgParty;
/** Payment terms or conditions. */
terms?: PayTerms;
/** Any amounts that have been paid in advance and should be deducted from the amount due. */
advances?: PayAdvance[];
/** Details on how payment should be made. */
instructions?: PayInstructions;
}
// Schema: bill/payment.json
/**
* A Payment is used to link an invoice or invoices with a payment transaction.
*/
export interface BillPayment {
$regime?: L10nTaxCountryCode;
/** Addons defines a list of keys used to identify tax addons that apply special
normalization, scenarios, and validation rules to a document. */
$addons?: CbcKey[];
/** 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. */
$tags?: CbcKey[];
/** Universally Unique Identifier. */
uuid?: string;
/** Type of payment document being issued. */
type: CbcKey;
/** Details on how the payment was made based on the original instructions. */
method?: PayInstructions;
/** Series is used to identify groups of payments by date, business area, project,
type, customer, a combination of any, or other company specific data.
If the output format does not support the series as a separate field, it will be
prepended to the code for presentation with a dash (`-`) for separation. */
series?: CbcCode;
/** Code is a sequential identifier that uniquely identifies the payment. The code can
be left empty initially, but is **required** to **sign** the document. */
code?: CbcCode;
/** When the payment was issued. */
issue_date: CalDate;
/** IssueTime is an optional field that may be useful to indicate the time of day when
the payment was issued. */
issue_time?: CalTime;
/** When the taxes of this payment become accountable, if none set, the issue date is assumed. */
value_date?: CalDate;
/** Currency for all payment totals. */
currency: CurrencyCode;
/** Exchange rates to be used when converting the payment's monetary values into other currencies. */
exchange_rates?: CurrencyExchangeRate[];
/** Extensions for additional codes that may be required. */
ext?: TaxExtensions;
/** Key information regarding previous versions of this document. */
preceding?: OrgDocumentRef[];
/** The taxable entity who is responsible for supplying goods or services. */
supplier: OrgParty;
/** Legal entity that receives the goods or services. */
customer?: OrgParty;
/** Legal entity that receives the payment if not the supplier. */
payee?: OrgParty;
/** List of documents that are being paid for. */
lines: PaymentLine[];
/** Ordering allows for additional information about the ordering process including references
to other documents and alternative parties involved in the order-to-delivery process. */
ordering?: BillOrdering;
/** Total amount to be paid in this payment, either positive or negative according to the
line types and totals. Calculated automatically. */
total: NumAmount;
/** Unstructured information that is relevant to the payment, such as correction or additional
legal details. */
notes?: OrgNote[];
/** Additional complementary objects that add relevant information to the payment. */
complements?: SchemaObject[];
/** Additional semi-structured data that doesn't fit into the body of the invoice. */
meta?: CbcMeta;
}
// Internal type: PaymentLine
/**
* PaymentLine defines the details of a line item in a payment document.
*/
export interface PaymentLine {
/** Universally Unique Identifier. */
uuid?: string;
/** Line number within the parent document (automatically calculated) */
i: number;
/** Indicates whether this payment is a refund of a previous payment, effectively reversing
the flow of funds between the supplier and customer or their representatives. */
refund?: boolean;
/** Reference to the document being paid */
document?: OrgDocumentRef;
/** When making multiple payments for a single document, this specifies the
installment number for this payment line. */
installment?: number;
/** Additional human readable description of the payment line which may be useful for
explaining the purpose or special conditions. Notes should be used for more
formal comments. */
description?: string;
/** Payable reflects the amount of the document that is payable. This will be
calculated from the embedded document's amount automatically and converted
to the currency of the document. */
payable?: NumAmount;
/** Amount already paid in previous installments, which may be required
by some tax regimes or specific use cases. */
advances?: NumAmount;
/** Amount of the total payment allocated to the referenced document. */
amount: NumAmount;
/** Due reflects how much still needs to be paid */
due?: NumAmount;
/** Tax contains a breakdown of the taxes that will be applied to this payment line
after taking into account currency conversion and the relative amounts. */
tax?: TaxTotal;
/** Additional notes specific to this line item for clarification purposes */
notes?: OrgNote[];
}
// Schema: bill/tax.json
/**
* Tax defines a summary of the taxes which may be applied to an invoice.
*/
export interface BillTax {
/** Category of the tax already included in the line item prices, especially
useful for B2C retailers with customers who prefer final prices inclusive of
tax. */
prices_include?: CbcCode;
/** Rounding model used to perform tax calculations on the invoice. This
will be configured automatically based on the tax regime, or
`sum-then-round` by default, but you can override here if needed.
Use with caution, as some conversion tools may make assumptions about
the rounding model used. */
rounding?: CbcKey;
/** Additional extensions that are applied to the invoice as a whole as opposed to specific
sections. */
ext?: TaxExtensions;
/** Any additional data that may be required for processing, but should never
be relied upon by recipients. */
meta?: CbcMeta;
}
// Schema: bill/totals.json
/**
* Totals contains the summaries of all calculations for the invoice.
*/
export interface BillTotals {
/** Total of all line item amounts. */
sum: NumAmount;
/** Total of all discounts applied at the document level. */
discount?: NumAmount;
/** Total of all charges applied at the document level. */
charge?: NumAmount;
/** Total tax amount included in the prices, if prices are tax-inclusive. */
tax_included?: NumAmount;
/** Net total amount after subtracting discounts and adding charges, excluding tax. */
total: NumAmount;
/** Detailed breakdown of all taxes applied to the invoice. */
taxes?: TaxTotal;
/** Total indirect tax amount to be applied to the invoice. */
tax?: NumAmount;
/** Final total amount after applying indirect taxes. */
total_with_tax: NumAmount;
/** Total tax amount retained or withheld by the customer to be paid to the tax authority. */
retained_tax?: NumAmount;
/** Adjustment amount applied to the invoice totals to meet rounding rules or expectations. */
rounding?: NumAmount;
/** Final amount to be paid after retained taxes and rounding adjustments. */
payable: NumAmount;
/** Total amount already paid in advance by the customer. */
advance?: NumAmount;
/** Remaining amount that needs to be paid. */
due?: NumAmount;
}
// Schema: cal/date-time.json
/**
* Civil date time in simplified ISO format with no time zone
nor location information, for example: 2021-05-26T13:45:00
*/
export type CalDateTime = string;
// Schema: cal/date.json
/**
* Civil date in simplified ISO format, like 2021-05-26
*/
export type CalDate = string;
// Schema: cal/period.json
/**
* Period represents two dates with a start and finish.
*/
export interface CalPeriod {
/** Label is a short description of the period. */
label?: string;
/** Start indicates when this period starts. */
start: CalDate;
/** End indicates when the period ends, and must be after the start date. */
end: CalDate;
}
// Schema: cal/time.json
/**
* Civil time in simplified ISO format, like 13:45:30
*/
export type CalTime = string;
// Schema: cbc/code-map.json
/**
* CodeMap is a map of keys to specific codes, useful to determine regime specific codes from their key counterparts.
*/
export type CbcCodeMap = Record<string, CbcCode>;
// Schema: cbc/code.json
/**
* Alphanumerical text identifier with upper-case letters and limits on using
special characters or whitespace to separate blocks.
*/
export type CbcCode = string;
// Schema: cbc/definition.json
/**
* Definition defines properties of a key, code, or other value that has a specific meaning or utility.
*/
export interface CbcDefinition {
/** Key being defined. */
key?: CbcKey;
/** Code this definition represents. */
code?: CbcCode;
/** Short name for the key. */
name: I18nString;
/** Description offering more details about when the key should be used. */
desc?: I18nString;
/** Meta defines any additional details that may be useful or associated
with the key. */
meta?: CbcMeta;
/** Where the information was sourced from. */
sources?: CbcSource[];
/** Values defines the possible values associated with the key, which themselves will
either be keys or codes depending on the context. */
values?: CbcDefinition[];
/** Pattern is used to validate the key value instead of using a fixed value
from the code or key definitions. */
pattern?: string;
/** Map helps map local keys to specific codes, useful for converting the
described key into a local code. */
map?: CbcCodeMap;
}
// Schema: cbc/key.json
/**
* Text identifier to be used instead of a code for a more verbose but readable identifier.
*/
export type CbcKey = string;
// Schema: cbc/meta.json
/**
* Meta defines a structure for data about the data being defined.
*/
export type CbcMeta = Record<string, string>;
// Schema: cbc/source.json
/**
* Source is used to identify a specific source of data.
*/
export interface CbcSource {
/** Title stores the name of the source of information. */
title?: I18nString;
/** URL is the location of the source of information. */
url: string;
/** ContentType of the information expected at the URL. */
content_type?: string;
/** At is the date and time the information was retrieved. */
at?: CalDateTime;
}
// Schema: currency/amount.json
/**
* An Amount represents a monetary value in a specific currency.
*/
export interface CurrencyAmount {
/** Label allows for additional information to be added to the
currency Amount that may be useful. */
label?: string;
/** Code defines the currency for this amount. */
currency: CurrencyCode;
/** Value is the amount in the currency. */
value: NumAmount;
}
// Schema: currency/code.json
/**
* Currency Code as defined in the GOBL source which is expected to be ISO or commonly used alternative.
*/
export type CurrencyCode = string;
// Schema: currency/exchange-rate.json
/**
* ExchangeRate contains data on the rate to be used when converting amounts from one currency into another.
*/
export interface CurrencyExchangeRate {
/** Currency code this will be converted from. */
from: CurrencyCode;
/** Currency code this exchange rate will convert into. */
to: CurrencyCode;
/** At represents the effective date and time at which the exchange rate
is determined by the source. The time may be zero if referring to a
specific day only. */
at?: CalDateTime;
/** Source key provides a reference to the source the exchange rate was
obtained from. Typically this will be determined by an application
used to update exchange rates automatically. */
source?: CbcKey;
/** How much is 1 of the "from" currency worth in the "to" currency. */
amount: NumAmount;
}
// Schema: dsig/digest.json
/**
* Digest defines a structure to hold a digest value including the algorithm used to generate it.
*/
export interface DsigDigest {
/** Algorithm stores the algorithm key that was used to generate the value. */
alg: string;
/** Value contains the Hexadecimal representation of the resulting hash
generated by the algorithm. */
val: string;
}
// Schema: dsig/signature.json
/**
* JSON Web Signature in compact form.
*/
export type DsigSignature = string;
// Schema: envelope.json
/**
* Envelope wraps around a document adding headers and digital signatures.
*/
export interface Envelope {
/** Schema identifies the schema that should be used to understand this document */
$schema: string;
/** Details on what the contents are */
head: HeadHeader;
/** The data inside the envelope */
doc: SchemaObject;
/** JSON Web Signatures of the header */
sigs?: DsigSignature[];
}
// Schema: head/header.json
/**
* Header defines the metadata of the body.
*/
export interface HeadHeader {
/** Unique UUIDv1 identifier for the envelope. */
uuid: string;
/** Digest of the canonical JSON body. */
dig: DsigDigest;
/** Seals of approval from other organisations that can only be added to
non-draft envelopes. */
stamps?: HeadStamp[];
/** Links provide URLs to other resources that are related to this envelope
and unlike stamps can be added even in the draft state. */
links?: HeadLink[];
/** Set of labels that describe but have no influence on the data. */
tags?: string[];
/** Additional semi-structured information about this envelope. */
meta?: CbcMeta;
/** Any information that may be relevant to other humans about this envelope */
notes?: string;
}
// Schema: head/link.json
/**
* Link defines a link between this document and another resource.
*/
export interface HeadLink {
/** Key is a unique identifier for the link. */
key: CbcKey;
/** Title of the resource to use when presenting to users. */
title?: string;
/** Description of the resource to use when presenting to users. */
description?: string;
/** Expected MIME type of the link's content. */
mime?: string;
/** URL of the resource. */
url: string;
}
// Schema: head/stamp.json
/**
* Stamp defines an official seal of approval from a third party like a governmental agency or intermediary and should thus be included in any official envelopes.
*/
export interface HeadStamp {
/** Identity of the agency used to create the stamp usually defined by each region. */
prv: CbcKey;
/** The serialized stamp value generated for or by the external agency */
val: string;
}
// Schema: i18n/string.json
/**
* Map of 2-Letter language codes to their translations.
*/
export type I18nString = Record<string, string>;
// Schema: l10n/code.json
/**
* Code is used for short identifies like country or state codes.
*/
export type L10nCode = string;
// Schema: l10n/iso-country-code.json
/**
* Defines an ISO 3166-2 country code
*/
export type L10nIsoCountryCode = string;
// Schema: l10n/tax-country-code.json
/**
* Defines an ISO base country code used for tax purposes
*/
export type L10nTaxCountryCode = string;
// Schema: note/message.json
/**
* Message represents a simple message object with a title and some content meant.
*/
export interface NoteMessage {
/** Universally Unique Identifier. */
uuid?: string;
/** Summary of the message content */
title?: string;
/** Details of what exactly this message wants to communicate. */
content: string;
/** Any additional semi-structured data that might be useful. */
meta?: CbcMeta;
}
// Schema: num/amount.json
/**
* Quantity with optional decimal places that determine accuracy.
*/
export type NumAmount = string;
// Schema: num/percentage.json
/**
* Similar to an Amount, but designed for percentages and includes % symbol in JSON output.
*/
export type NumPercentage = string;
// Schema: org/address.json
/**
* Address defines a globally acceptable set of attributes that describes a postal or fiscal address.
*/
export interface OrgAddress {
/** Universally Unique Identifier. */
uuid?: string;
/** Useful identifier, such as home, work, etc. */
label?: string;
/** Box number or code for the post office box located at the address. */
po_box?: string;
/** House or building number in the street. */
num?: string;
/** Floor number within the building. */
floor?: string;
/** Block number within the building. */
block?: string;
/** Door number within the building. */
door?: string;
/** First line of street. */
street?: string;
/** Additional street address details. */
street_extra?: string;
/** Name of a village, town, district, or city, typically inside a region. */
locality?: string;
/** Name of a city, province, county, or state, inside a country. */
region?: string;
/** State or province code for countries that require it. */
state?: CbcCode;
/** Post or ZIP code. */
code?: CbcCode;
/** ISO country code. */
country?: L10nIsoCountryCode;
/** When the postal address is not sufficient, coordinates help locate the address more precisely. */
coords?: OrgCoordinates;
/** Any additional semi-structure details about the address. */
meta?: CbcMeta;
}
// Schema: org/attachment.json
/**
* An Attachment provides a structure to be used to attach documents inside a GOBL document, either as a reference via a URL, or directly as a base64 encoded string.
*/
export interface OrgAttachment {
/** Universally Unique Identifier. */
uuid?: string;
/** Key used to identify the attachment inside the document. */
key?: CbcKey;
/** Code used to identify the payload of the attachment. */
code?: CbcCode;
/** Filename of the attachment. */
name: string;
/** Details of why the attachment is being included and details on
what it contains. */
description?: string;
/** URL of where to find the attachment. Prefer using this field
over the Data field. */
url?: string;
/** Digest is used to verify the integrity of the attachment
when downloaded from the URL. */
digest?: DsigDigest;
/** MIME type of the attachment. */
mime?: string;
/** Data is the base64 encoded data of the attachment directly embedded
inside the GOBL document. This should only be used when the URL cannot
be used as it can dramatically increase the size of the JSON
document, thus effecting usability and performance. */
data?: string;
}
// Schema: org/coordinates.json
/**
* Coordinates describes an exact geographical location in the world.
*/
export interface OrgCoordinates {
/** Decimal latitude coordinate. */
lat?: number;
/** Decimal longitude coordinate. */
lon?: number;
/** What 3 Words text coordinates. */
w3w?: string;
/** Single string coordinate based on geohash standard. */
geohash?: string;
}
// Schema: org/document-ref.json
/**
* DocumentRef is used to describe an existing document or a specific part of it's contents.
*/
export interface OrgDocumentRef {
/** Universally Unique Identifier. */
uuid?: string;
/** Type of the document referenced. */
type?: CbcKey;
/** IssueDate reflects the date the document was issued. */
issue_date?: CalDate;
/** Series the referenced document belongs to. */
series?: CbcCode;
/** Source document's code or other identifier. */
code: CbcCode;
/** Currency used in the document, if different from the parent's currency. */
currency?: CurrencyCode;
/** Line index numbers inside the document, if relevant. */
lines?: number[];
/** List of additional codes, IDs, or SKUs which can be used to identify the document or its contents, agreed upon by the supplier and customer. */
identities?: OrgIdentity[];
/** Tax period in which the referred document had an effect required by some tax regimes and formats. */
period?: CalPeriod;
/** Human readable description on why this reference is here or needs to be used. */
reason?: string;
/** Additional details about the document. */
description?: string;
/** Seals of approval from other organizations that may need to be listed. */
stamps?: HeadStamp[];
/** Link to the source document. */
url?: string;
/** Tax total breakdown from the original document in the provided currency. Should
only be included if required by a specific tax regime or addon. */
tax?: TaxTotal;
/** Payable is the total amount that is payable in the referenced document. Only needed
for specific tax regimes or addons. This may also be used in some scenarios
to determine the proportion of the referenced document that has been paid, and
calculate the remaining amount due and taxes. */
payable?: NumAmount;
/** Extensions for additional codes that may be required. */
ext?: TaxExtensions;
/** Meta contains additional information about the document. */
meta?: CbcMeta;
}
// Schema: org/email.json
/**
* Email describes the electronic mailing details.
*/
export interface OrgEmail {
/** Universally Unique Identifier. */
uuid?: string;
/** Identifier for the email. */
label?: string;
/** Electronic mailing address. */
addr: string;
/** Additional fields. */
meta?: CbcMeta;
}
// Schema: org/identity.json
/**
* Identity is used to define a code for a specific context.
*/
export interface OrgIdentity {
/** Universally Unique Identifier. */
uuid?: string;
/** Optional label useful for non-standard identities to give a bit more context. */
label?: string;
/** Country from which the identity was issued. */
country?: L10nIsoCountryCode;
/** Uniquely classify this identity using a key instead of a type. */
key?: CbcKey;
/** The type of Code being represented and usually specific for
a particular context, country, or tax regime, and cannot be used
alongside the key. */
type?: CbcCode;
/** The actual value of the identity code. */
code: CbcCode;
/** Description adds details about what the code could mean or imply */
description?: string;
/** Ext provides a way to add additional information to the identity. */
ext?: TaxExtensions;
}
// Schema: org/image.json
/**
* Image describes a logo or photo that represents an entity.
*/
export interface OrgImage {
/** Universally Unique Identifier. */
uuid?: string;
/** Label to help identify the image. */
label?: string;
/** URL of the image */
url?: string;
/** As an alternative to the URL and only when the source data is small,
like an SVG, the raw data may be provided using Base64 encoding. */
data?: string;
/** Format of the image. */
mime?: string;
/** Details of what the image represents. */
description?: string;
/** Alternative text if the image cannot be shown. */
alt?: string;
/** Height of the image in pixels. */
height?: number;
/** Width of the image in pixels. */
width?: number;
/** Digest can be used to ensure the image contained at the URL
is the same one as originally intended. */
digest?: DsigDigest;
/** Meta contains additional information about the image. */
meta?: CbcMeta;
}
// Schema: org/inbox.json
/**
* Inbox is used to store data about a connection with a service that is responsible for automatically receiving copies of GOBL envelopes or other document formats.
*/
export interface OrgInbox {
/** Universally Unique Identifier. */
uuid?: string;
/** Label for the inbox. */
label?: string;
/** Type of inbox being defined if required for clarification between multiple
inboxes. */
key?: CbcKey;
/** Scheme ID of the code used to identify the inbox. This is context specific
and usually an ISO 6523 code or CEF (Connecting Europe Facility) code. */
scheme?: CbcCode;
/** Code or ID that identifies the Inbox. Mutually exclusive with URL and Email. */
code?: CbcCode;
/** URL of the inbox that includes the protocol, server, and path. May
be used instead of the Code to identify the inbox. Mutually exclusive with
Code and Email. */
url?: string;
/** Email address for the inbox. Mutually exclusive with Code and URL. */
email?: string;
}
// Schema: org/item.json
/**
* Item is used to describe a single product or service.
*/
export interface OrgItem {
/** Universally Unique Identifier. */
uuid?: string;
/** Primary reference code that identifies this item.
Additional codes can be provided in the 'identities' property. */
ref?: CbcCode;
/** Special key used to classify the item sometimes required by some regimes. */
key?: CbcKey;
/** Brief name of the item */
name: string;
/** List of additional codes, IDs, or SKUs which can be used to identify the item. They should be agreed upon between supplier and customer. */
identities?: OrgIdentity[];
/** Detailed description of the item. */
description?: string;
/** Currency used for the item's price. */
currency?: CurrencyCode;
/** Base price of a single unit to be sold. */
price?: NumAmount;
/** AltPrices defines a list of prices with their currencies that may be used
as an alternative to the item's base price. */
alt_prices?: CurrencyAmount[];
/** Unit of measure. */
unit?: OrgUnit;
/** Country code of where this item was from originally. */
origin?: L10nIsoCountryCode;
/** Extension code map for any additional regime specific codes that may be required. */
ext?: TaxExtensions;
/** Additional meta information that may be useful */
meta?: CbcMeta;
}
// Schema: org/name.json
/**
* Name represents what a human is called.
*/
export interface OrgName {
/** Universally Unique Identifier. */
uuid?: string;
/** What the person would like to be called */
alias?: string;
/** Additional prefix to add to name, like Mrs. or Mr. */
prefix?: string;
/** Person's given or first name */
given?: string;
/** Middle names or initials */
middle?: string;
/** Second or Family name. */
surname?: string;
/** Additional second of family name. */
surname2?: string;
/** Titles to include after the name. */
suffix?: string;
/** Any additional useful data. */
meta?: CbcMeta;
}
// Schema: org/note.json
/**
* Note represents a free text of additional information that may be added to a document.
*/
export interface OrgNote {
/** Universally Unique Identifier. */
uuid?: string;
/** Key specifying subject of the text */
key?: CbcKey;
/** Code used for additional data that may be required to identify the note. */
code?: CbcCode;
/** Source of this note, especially useful when auto-generated. */
src?: CbcKey;
/** The contents of the note */
text: string;
/** Additional information about the note */
meta?: CbcMeta;
/** Extension data */
ext?: TaxExtensions;
}
// Schema: org/party.json
/**
* Party represents a person or business entity.
*/
export interface OrgParty {
$regime?: L10nTaxCountryCode;
/** Universally Unique Identifier. */
uuid?: string;
/** Label can be used to provide a custom label for the party in a given
context in a single language, for example "Supplier", "Host", or similar. */
label?: string;
/** Legal name or representation of the organization. */
name?: string;
/** Alternate short name. */
alias?: string;
/** The entity's legal ID code used for tax purposes. They may have other numbers, but we're only interested in those valid for tax purposes. */
tax_id?: TaxIdentity;
/** Set of codes used to identify the party in other systems. */
identities?: OrgIdentity[];
/** Details of physical people who represent the party. */
people?: OrgPerson[];
/** Digital inboxes used for forwarding electronic versions of documents */
inboxes?: OrgInbox[];
/** Regular post addresses for where information should be sent if needed. */
addresses?: OrgAddress[];
/** Electronic mail addresses */
emails?: OrgEmail[];
/** Public websites that provide further information about the party. */
websites?: OrgWebsite[];
/** Regular telephone numbers */
telephones?: OrgTelephone[];
/** Additional registration details about the company that may need to be included in a document. */
registration?: OrgRegistration;
/** Images that can be used to identify the party visually. */
logos?: OrgImage[];
/** Extension code map for any additional regime specific codes that may be required. */
ext?: TaxExtensions;
/** Any additional semi-structured information that does not fit into the rest of the party. */
meta?: CbcMeta;
}
// Schema: org/person.json
/**
* Person represents a human, and how to contact them electronically.
*/
export interface OrgPerson {
/** Universally Unique Identifier. */
uuid?: string;
/** Label can be used to identify the person in a given context in a single
language, for example "Attn", "Contact", "Responsible", etc. */
label?: string;
/** Key used to identify the role of the person inside the context of the object. */
key?: CbcKey;
/** Complete details on the name of the person. */
name: OrgName;
/** Role or job title of the responsibilities of the person within an organization. */
role?: string;
/** Set of codes used to identify the person, such as ID numbers, social security,
driving licenses, etc. that can be attributed to the individual. */
identities?: OrgIdentity[];
/** Regular post addresses for where information should be sent if needed. */
addresses?: OrgAddress[];
/** Electronic mail addresses that belong to the person. */
emails?: OrgEmail[];
/** Regular phone or mobile numbers */
telephones?: OrgTelephone[];
/** Avatars provider links to images or photos or the person. */
avatars?: OrgImage[];
/** Data about the data. */
meta?: CbcMeta;
}
// Schema: org/registration.json
/**
* Registration is used in countries that require additional information to be associated with a company usually related to a specific registration office.
*/
export interface OrgRegistration {
/** Universally Unique Identifier. */
uuid?: string;
label?: string;
capital?: NumAmount;
currency?: CurrencyCode;
office?: string;
book?: string;
volume?: string;
sheet?: string;
section?: string;
page?: string;
entry?: string;
other?: string;
}
// Schema: org/telephone.json
/**
* Telephone describes what is expected for a telephone number.
*/
export interface OrgTelephone {
/** Universally Unique Identifier. */
uuid?: string;
/** Identifier for this number. */
label?: string;
/** Free-text string that represents the telephone number. */
num: string;
}
// Schema: org/unit.json
/**
* Unit defines how the quantity of the product should be interpreted either using a GOBL lower-case key (e.g. 'kg'), or UN/ECE code upper-case code (e.g. 'KGM').
*/
export type OrgUnit = string;
// Schema: org/website.json
/**
* Website describes what is expected for a web address.
*/
export interface OrgWebsite {
/** Universally Unique Identifier. */
uuid?: string;
/** Label for the website to show alongside the URL. */
label?: string;
/** Title of the website to help distinguish between this and other links. */
title?: string;
/** URL for the website. */
url: string;
}
// Schema: pay/advance.json
/**
* Advance represents a single payment that has been made already, such as a deposit on an intent to purchase, or as credit from a previous invoice which was later corrected or cancelled.
*/
export interface PayAdvance {
/** Universally Unique Identifier. */
uuid?: string;
/** When the advance was made. */
date?: CalDate;
/** The payment means used to make the advance. */
key?: CbcKey;
/** ID or reference for the advance. */
ref?: string;
/** If this "advance" payment has come from a public grant or subsidy, set this to true. */
grant?: boolean;
/** Details about the advance. */
description: string;
/** Percentage of the total amount payable that was paid. Note that
multiple advances with percentages may lead to rounding errors,
especially when the total advances sums to 100%. We recommend only
including one advance with a percent value per document. */
percent?: NumPercentage;
/** How much was paid. */
amount: NumAmount;
/** If different from the parent document's base currency. */
currency?: CurrencyCode;
/** Details of the payment that was made via a credit or debit card. */
card?: Card;
/** Details about how the payment was made by credit (bank) transfer. */
credit_transfer?: CreditTransfer;
/** Tax extensions required by tax regimes or addons. */
ext?: TaxExtensions;
/** Additional details useful for the parties involved. */
meta?: CbcMeta;
}
// Internal type: Card
/**
* Card contains simplified card holder data as a reference for the customer.
*/
export interface Card {
/** First 6 digits of the card's Primary Account Number (PAN). */
first6?: string;
/** Last 4 digits of the card's Primary Account Number (PAN). */
last4?: string;
/** Name of the person whom the card belongs to. */
holder?: string;
}
// Internal type: CreditTransfer
/**
* CreditTransfer contains fields that can be used for making payments via a bank transfer or wire.
*/
export interface CreditTransfer {
/** International Bank Account Number */
iban?: string;
/** Bank Identifier Code used for international transfers. */
bic?: string;
/** Account number, if IBAN not available. */
number?: string;
/** Name of the bank. */
name?: string;
/** Bank office branch address, not normally required. */
branch?: OrgAddress;
}
// Schema: pay/instructions.json
/**
* Instructions determine how the payment has or should be made.
*/
export interface PayInstructions {
/** The payment means expected or that have been arranged to be used to make the payment. */
key: CbcKey;
/** Optional text description of the payment method */
detail?: string;
/** Remittance information or concept, a code value used to link the payment with the invoice. */
ref?: CbcCode;
/** Instructions for sending payment via a bank transfer. */
credit_transfer?: CreditTransfer[];
/** Details of the payment that will be made via a credit or debit card. */
card?: Card;
/** A group of terms that can be used by the customer or payer to consolidate direct debit payments. */
direct_debit?: DirectDebit;
/** Array of online payment options */
online?: Online[];
/** Any additional instructions that may be required to make the payment. */
notes?: string;
/** Extension key-pairs values defined by a tax regime. */
ext?: TaxExtensions;
/** Non-structured additional data that may be useful. */
meta?: CbcMeta;
}
// Internal type: DirectDebit
/**
* DirectDebit defines the data that will be used to make the direct debit.
*/
export interface DirectDebit {
/** Unique identifier assigned by the payee for referencing the direct debit. */
ref?: string;
/** Unique banking reference that identifies the payee or seller assigned by the bank. */
creditor?: string;
/** Account identifier to be debited by the direct debit. */
account?: string;
}
// Internal type: Online
/**
* Online provides the details required to make a payment online using a website
*/
export interface Online {
/** Key identifier for this online payment method. */
key?: CbcKey;
/** Descriptive label for the online provider. */
label?: string;
/** URL to be used for payment. */
url: string;
}
// Schema: pay/terms.json
/**
* Terms defines when we expect the customer to pay, or have paid, for the contents of the document.
*/
export interface PayTerms {
/** Type of terms to be applied. */
key?: CbcKey;
/** Text detail of the chosen payment terms. */
detail?: string;
/** Set of dates for agreed payments. */
due_dates?: DueDate[];
/** Description of the conditions for payment. */
notes?: string;
/** Extensions to the terms for local codes. */
ext?: TaxExtensions;
}
// Internal type: DueDate
/**
* DueDate contains an amount that should be paid by the given date.
*/
export interface DueDate {
/** When the payment is due. */
date: CalDate;
/** Other details to take into account for the due date. */
notes?: string;
/** How much needs to be paid by the date. */
amount: NumAmount;
/** Percentage of the total that should be paid by the date. */
percent?: NumPercentage;
/** If different from the parent document's base currency. */
currency?: CurrencyCode;
}
// Schema: regimes/mx/food-vouchers.json
/**
* FoodVouchers carries the data to produce a CFDI's "Complemento de Vales de Despensa" (version 1.0) providing detailed information about food vouchers issued by an e-wallet supplier to its customer's employees.
*/
export interface RegimesMxFoodVouchers {
/** Customer's employer registration number (maps to `registroPatronal`). */
employer_registration?: string;
/** Customer's account number (maps to `numeroDeCuenta`). */
account_number: string;
/** Sum of all line amounts (calculated, maps to `total`). */
total: NumAmount;
/** List of food vouchers issued to the customer's employees (maps to `Conceptos`). */
lines: FoodVouchersLine[];
}
// Internal type: FoodVouchersEmployee
/**
* FoodVouchersEmployee represents an employee that received a food voucher.
*/
export interface FoodVouchersEmployee {
/** Employee's tax identity code (maps to `rfc`). */
tax_code: CbcCode;
/** Employee's CURP ("Clave Única de Registro de Población", maps to `curp`). */
curp: CbcCode;
/** Employee's name (maps to `nombre`). */
name: string;
/** Employee's Social Security Number (maps to `numSeguridadSocial`). */
social_security?: CbcCode;
}
// Internal type: FoodVouchersLine
/**
* FoodVouchersLine represents a single food voucher issued to the e-wallet of one of the customer's employees.
*/
export interface FoodVouchersLine {
/** Line number starting from 1 (calculated). */
i: number;
/** Identifier of the e-wallet that received the food voucher (maps to `Identificador`). */
e_wallet_id: CbcCode;
/** Date and time of the food voucher's issue (maps to `Fecha`). */
issue_date_time: CalDateTime;
/** Employee that received the food voucher. */
employee?: FoodVouchersEmployee;
/** Amount of the food voucher (maps to `importe`). */
amount: NumAmount;
}
// Schema: regimes/mx/fuel-account-balance.json
/**
* FuelAccountBalance carries the data to produce a CFDI's "Complemento de Estado de Cuenta de Combustibles para Monederos Electrónicos" (version 1.2 revision B) providing detailed information about fuel purchases made with electronic wallets.
*/
export interface RegimesMxFuelAccountBalance {
/** Customer's account number (maps to `NumeroDeCuenta`). */
account_number: string;
/** Sum of all line totals (i.e. taxes not included) (calculated, maps to `SubTotal`). */
subtotal: NumAmount;
/** Grand total after taxes have been applied (calculated, maps to `Total`). */
total: NumAmount;
/** List of fuel purchases made with the customer's e-wallets (maps to `Conceptos`). */
lines: FuelAccountLine[];
}
// Internal type: FuelAccountItem
/**
* FuelAccountItem provides the details of a fuel purchase.
*/
export interface FuelAccountItem {
/** Type of fuel (one of `c_ClaveTipoCombustible` codes, maps to `TipoCombustible`). */
type: CbcCode;
/** Reference unit of measure used in the price and the quantity (maps to `Unidad`). */
unit?: OrgUnit;
/** Name of the fuel (maps to `NombreCombustible`). */
name: string;
/** Base price of a single unit of the fuel without taxes (maps to `ValorUnitario`). */
price: NumAmount;
}
// Internal type: FuelAccountLine
/**
* FuelAccountLine represents a single fuel purchase made with an e-wallet issued by the invoice's supplier.
*/
export interface FuelAccountLine {
/** Index of the line starting from 1 (calculated) */
i: number;
/** Identifier of the e-wallet used to make the purchase (maps to `Identificador`). */
e_wallet_id: CbcCode;
/** Date and time of the purchase (maps to `Fecha`). */
purchase_date_time: CalDateTime;
/** Tax Identity Code of the fuel's vendor (maps to `Rfc`) */
vendor_tax_code: CbcCode;
/** Code of the service station where the purchase was made (maps to `ClaveEstacion`). */
service_station_code: CbcCode;
/** Amount of fuel units purchased (maps to `Cantidad`) */
quantity: NumAmount;
/** Details of the fuel purchased. */
item: FuelAccountItem;
/** Identifier of the purchase (maps to `FolioOperacion`). */
purchase_code: CbcCode;
/** Result of quantity multiplied by the unit price (maps to `Importe`). */
total: NumAmount;
/** Map of taxes applied to the purchase (maps to `Traslados`). */
taxes: FuelAccountTax[];
}
// Internal type: FuelAccountTax
/**
* FuelAccountTax represents a single tax applied to a fuel purchase.
*/
export interface FuelAccountTax {
/** Category that identifies the tax ("VAT" or "IEPS", maps to `Impuesto`) */
cat: CbcCode;
/** Percent applicable to the line total (tasa) to use instead of Rate (maps to `TasaoCuota`) */
percent?: NumPercentage;
/** Rate is a fixed fee to apply to the line quantity (cuota) (maps to `TasaOCuota`) */
rate?: NumAmount;
/** Total amount of the tax once the percent or rate has been applied (maps to `Importe`). */
amount: NumAmount;
}
// Schema: schema/object.json
/**
* Data object whose type is determined from the <code>$schema</code> property.
*/
export type SchemaObject = Record<string, unknown> & { $schema?: string };
// Schema: tax/addon-def.json
/**
* AddonDef is an interface that defines the methods that a tax add-on must implement.
*/
export interface TaxAddonDef {
/** Key that defines how to uniquely idenitfy the add-on. */
key: CbcKey;
/** Requires defines any additional addons that this one depends on to operate
correctly. */
requires?: CbcKey[];
/** Name of the add-on */
name: I18nString;
/** Description of the add-on */
description?: I18nString;
/** Sources is a list of sources that are used to provide the data for the add-on. */
sources?: CbcSource[];
/** Extensions defines the list of extensions that are associated with an add-on. */
extensions: CbcDefinition[];
/** Tags is slice of tag sets that define what can be assigned to each document schema. */
tags?: TagSet[];
/** Scenarios are applied to documents after normalization and before
validation to ensure that form specific extensions have been added
to the document. */
scenarios: ScenarioSet[];
/** Identities that are specific for the add-on and may be validated against or
used during conversion processes. */
identities?: CbcDefinition[];
/** Inboxes is a list of keys that are used to identify where copies of
documents can be sent. */
inboxes?: CbcDefinition[];
/** Corrections is used to provide a map of correction definitions that
are supported by the add-on. */
corrections: CorrectionSet;
}
// Internal type: CorrectionDefinition
/**
* CorrectionDefinition contains details about what can be defined in .
*/
export interface CorrectionDefinition {
/** Partial or complete schema URL for the document type supported by correction. */
schema: string;
/** The types of sub-documents supported by the regime */
types?: CbcKey[];
/** Extension keys that can be included */
extensions?: CbcKey[];
/** ReasonRequired when true implies that a reason must be provided */
reason_required?: boolean;
/** Stamps that must be copied from the preceding document. */
stamps?: CbcKey[];
/** Copy tax from the preceding document to the document ref. */
copy_tax?: boolean;
}
// Internal type: CorrectionSet
/**
* CorrectionSet defines a set of correction definitions for a selection of schemas.
*/
export type CorrectionSet = CorrectionDefinition[];
// Internal type: Scenario
/**
* Scenario is used to describe a tax scenario of a document based on the combination of document type and tag used.
*/
export interface Scenario {
/** Name of the scenario for further information. */
name?: I18nString;
/** Description of the scenario for documentation purposes. */
desc?: I18nString;
/** Type of document, if present. */
type?: CbcKey[];
/** Array of tags that have been applied to the document. */
tags?: CbcKey[];
/** Extension key that must be present in the document. */
ext_key?: CbcKey;
/** 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. */
ext_code?: CbcCode;
/** A note to be added to the document if the scenario is applied. */
note?: ScenarioNote;
/** Codes is used to define additional codes for regime specific
situations. */
codes?: CbcCodeMap;
/** Ext represents a set of tax extensions that should be applied to
the document in the appropriate "tax" context. */
ext?: TaxExtensions;
}
// Internal type: ScenarioNote
/**
* ScenarioNote represents the structure of the note that needs to be added to the document.
*/
export interface ScenarioNote {
/** Key specifying subject of the text */
key?: CbcKey;
/** Code used for additional data that may be required to identify the note. */
code?: CbcCode;
/** Source of this note, especially useful when auto-generated. */
src?: CbcKey;
/** The contents of the note */
text: string;
/** Extension data */
ext?: TaxExtensions;
}
// Internal type: ScenarioSet
/**
* 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.
*/
export interface ScenarioSet {
/** Partial or complete schema URL for the document type */
schema: string;
/** List of scenarios for the schema */
list: Scenario[];
}
// Internal type: TagSet
/**
* 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.
*/
export interface TagSet {
/** Schema that the tags are associated with. */
schema: string;
/** List of tags for the schema */
list: CbcDefinition[];
}
// Schema: tax/catalogue-def.json
/**
* A CatalogueDef contains a set of re-useable extensions, scenarios, and validators that can be used by addons or tax regimes.
*/
export interface TaxCatalogueDef {
/** Key defines a unique identifier for the catalogue. */
key: CbcKey;
/** Name is the name of the catalogue. */
name: I18nString;
/** Description is a human readable description of the catalogue. */
description?: I18nString;
/** Extensions defines all the extensions offered by the catalogue. */
extensions: CbcDefinition[];
}
// Schema: tax/extensions.json
/**
* Extensions is a map of extension keys to values.
*/
export type TaxExtensions = Record<string, CbcCode>;
// Schema: tax/identity.json
/**
* Identity stores the details required to identify an entity for tax purposes in a specific country.
*/
export interface TaxIdentity {
/** Tax country code for Where the tax identity was issued. */
country: L10nTaxCountryCode;
/** Normalized code shown on the original identity document. */
code?: CbcCode;
/** 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?: CbcCode;
/** 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?: CbcKey;
/** 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?: L10nCode;
}
// Schema: tax/regime-def.json
/**
* RegimeDef defines the holding structure for the definitions of taxes inside a country or territory.
*/
export interface TaxRegimeDef {
/** Name of the tax regime. */
name: I18nString;
/** Introductory details about the regime. */
description?: I18nString;
/** Location name for the country's central time zone. Accepted
values from IANA Time Zone Database (https://iana.org/time-zones). */
time_zone: string;
/** Country code for the region */
country: L10nTaxCountryCode;
/** Alternative localization codes that may be used to identify the tax regime
in specific circumstances. */
alt_country_codes?: L10nCode[];
/** Specific Locality, region, city, province, county, or similar code inside
the country, if needed. */
zone?: L10nCode;
/** Currency used by the country. */
currency: CurrencyCode;
/** 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. */
tax_scheme?: CbcCode;
/** Rounding rule to use when calculating the tax totals, default is always
`sum-then-round`. */
calculator_rounding_rule?: CbcKey;
/** Tags that can be applied at the document level to identify additional
considerations. */
tags?: TagSet[];
/** 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?: CbcDefinition[];
/** Identities used in addition to regular tax identities and specific for the
regime that may be validated against. */
identities?: CbcDefinition[];
/** PaymentMeansKeys specific for the regime that extend the original
base payment means keys. */
payment_means_keys?: CbcDefinition[];
/** InboxKeys specific to the regime that can be used to identify where a document
should be forwarded to. */
inbox_keys?: CbcDefinition[];
scenarios?: ScenarioSet[];
/** Configuration details for corrections to be used with correction options. */
corrections?: CorrectionSet;
/** List of tax categories. */
categories: CategoryDef[];
}
// Internal type: CategoryDef
/**
* CategoryDef contains the definition of a general type of tax inside a region.
*/
export interface CategoryDef {
/** Code to be used in documents */
code: CbcCode;
/** Short name of the category to be used instead of code in output */
name: I18nString;
/** Human name for the code to use for titles */
title?: I18nString;
/** Useful description of the category. */
desc?: I18nString;
/** 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?: boolean;
/** Specific tax definitions inside this category. Order is important. */
rates?: RateDef[];
/** 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?: CbcKey[];
/** Map defines a set of regime specific code mappings. */
map?: CbcCodeMap;
/** List of sources for the information contained in this category. */
sources?: CbcSource[];
/** Extension key-value pairs that will be copied to the tax combo if this
category is used. */
ext?: TaxExtensions;
/** Meta contains additional information about the category that is relevant
for local frequently used formats. */
meta?: CbcMeta;
}
// Internal type: RateDef
/**
* RateDef defines a single rate inside a category
*/
export interface RateDef {
/** Key identifies this rate within the system */
key: CbcKey;
/** Human name of the rate */
name: I18nString;
/** Useful description of the rate. */
desc?: I18nString;
/** Exempt when true implies that the rate when used in a tax Combo should
not define a percent value. */
exempt?: boolean;
/** 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[];
/** Extensions key-value pair that will be copied to the tax combo if this
rate is used. */
ext?: TaxExtensions;
/** Meta contains additional information about the rate that is relevant
for local frequently used implementations. */
meta?: CbcMeta;
}
// Internal type: RateValueDef
/**
* RateValueDef contains a percentage rate or fixed amount for a given date range.
*/
export interface RateValueDef {
/** Only apply this rate if one of the tags is present in the invoice. */
tags?: CbcKey[];
/** Ext map of keys that can be used to filter to determine if the rate applies. */
ext?: TaxExtensions;
/** Date from which this value should be applied. */
since?: CalDate;
/** Percent rate that should be applied */
percent: NumPercentage;
/** An additional surcharge to apply. */
surcharge?: NumPercentage;
/** When true, this value should no longer be used. */
disabled?: boolean;
}
// Schema: tax/set.json
/**
* Set defines a list of tax categories and their rates to be used alongside taxable items.
*/
export type TaxSet = Combo[];
// Internal type: Combo
/**
* Combo represents the tax combination of a category code and rate key.
*/
export interface Combo {
/** Tax category code from those available inside a region. */
cat: CbcCode;
/** Country code override when issuing with taxes applied from different countries. */
country?: L10nTaxCountryCode;
/** Rate within a category to apply. */
rate?: CbcKey;
/** 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?: NumPercentage;
/** Some countries require an additional surcharge (calculated if rate present). */
surcharge?: NumPercentage;
/** Local codes that apply for a given rate or percentage that need to be identified and validated. */
ext?: TaxExtensions;
}
// Schema: tax/total.json
/**
* Total contains a set of Category Totals which in turn contain all the accumulated taxes contained in the document.
*/
export interface TaxTotal {
/** Grouping of all the taxes by their category */
categories?: CategoryTotal[];
/** Total value of all non-retained or indirect taxes. */
sum: NumAmount;
/** Sum of retained or withheld tax amounts */
retained?: NumAmount;
}
// Internal type: CategoryTotal
/**
* CategoryTotal groups together all rates inside a given category.
*/
export interface CategoryTotal {
code: CbcCode;
retained?: boolean;
rates: RateTotal[];
amount: NumAmount;
surcharge?: NumAmount;
}
// Internal type: RateTotal
/**
* RateTotal contains a sum of all the tax rates in the document with a matching category and rate.
*/
export interface RateTotal {
/** Optional rate key is required when grouping. */
key?: CbcKey;
/** 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?: L10nTaxCountryCode;
/** If the rate is defined with extensions, they'll be used to group by also. */
ext?: TaxExtensions;
/** Base amount that the percentage is applied to. */
base: NumAmount;
/** Percentage of the rate. Will be nil when taxes are **exempt**. */
percent?: NumPercentage;
/** Surcharge applied to the rate. */
surcharge?: RateTotalSurcharge;
/** Total amount of rate, excluding surcharges */
amount: NumAmount;
}
// Internal type: RateTotalSurcharge
/**
* RateTotalSurcharge reflects the sum surcharges inside the rate.
*/
export interface RateTotalSurcharge {
percent: NumPercentage;
amount: NumAmount;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment