Documentation
¶
Overview ¶
Package stackin is the official Go SDK for the stackin fiscal document API — issue, consult, and cancel Brazilian NF-e and NFS-e electronic invoices with a single API key, no certificates or XML handling required.
See https://docs.stackin.io for the REST API reference and https://docs.stackin.io/blog/go-sdk for the Go SDK guide.
Index ¶
- Constants
- Variables
- type APIError
- type Address
- type AuthorizedCompanies
- type AuthorizedCompany
- type CityQuery
- type ClassifyRequest
- type ClientAlreadyExistsError
- type ClientChanges
- type ClientFields
- type ClientInactiveError
- type ClientNotFoundError
- type ClientQuery
- type Clients
- func (c *Clients) Create(fields ClientFields) (map[string]any, error)
- func (c *Clients) Deactivate(clientID string) error
- func (c *Clients) ForCompany(company string) *Clients
- func (c *Clients) Get(clientID string) (map[string]any, error)
- func (c *Clients) List(query ClientQuery) (map[string]any, error)
- func (c *Clients) Reactivate(clientID string) (map[string]any, error)
- func (c *Clients) Update(clientID string, changes ClientChanges) (map[string]any, error)
- type Company
- type CompanyAddress
- type CompanyNotInScopeError
- type CompanyRequiredError
- type CompanyUpdate
- type ConnectionFailedError
- type Direction
- type DocumentType
- type Environment
- type Export
- type FiscalFields
- type FiscalReference
- func (r *FiscalReference) CalculateIbsCbs(request IbsCbsCalculationRequest) (*IbsCbsCalculation, error)
- func (r *FiscalReference) Cities(name string, query CityQuery) ([]map[string]any, error)
- func (r *FiscalReference) Kind(name string, country ...string) *Kind
- func (r *FiscalReference) Kinds(country ...string) ([]string, error)
- func (r *FiscalReference) Search(query SearchQuery) (map[string]any, error)
- type HistoryQuery
- type IbsCbsAmounts
- type IbsCbsAppliedRates
- type IbsCbsCalculatedItem
- type IbsCbsCalculation
- type IbsCbsCalculationItem
- type IbsCbsCalculationRequest
- type IbsCbsIndicators
- type IbsCbsRates
- type InsufficientPermissionError
- type Intermediary
- type InvalidationRequest
- type Invoice
- func (inv *Invoice) Cancel(accessKey string, documentType DocumentType, reason string, ...) (map[string]any, error)
- func (inv *Invoice) Classify(req ClassifyRequest) (map[string]any, error)
- func (inv *Invoice) Companies() (*AuthorizedCompanies, error)
- func (inv *Invoice) Consult(accessKey string, documentType DocumentType) (map[string]any, error)
- func (inv *Invoice) ConsultByDPS(dpsID string) (map[string]any, error)
- func (inv *Invoice) Correct(accessKey string, documentType DocumentType, correction string) (map[string]any, error)
- func (inv *Invoice) ForCompany(company string) *Invoice
- func (inv *Invoice) History(query HistoryQuery) (map[string]any, error)
- func (inv *Invoice) Invalidate(req InvalidationRequest) (map[string]any, error)
- func (inv *Invoice) Invalidations(query PageQuery) (map[string]any, error)
- func (inv *Invoice) Issue(req IssueRequest) (map[string]any, error)
- func (inv *Invoice) Manifest(accessKey string, manifestation Manifestation, reason string) (map[string]any, error)
- func (inv *Invoice) Pdf(accessKey string, documentType DocumentType) ([]byte, error)
- func (inv *Invoice) Readiness() (map[string]any, error)
- func (inv *Invoice) Received(limit, offset int) (map[string]any, error)
- func (inv *Invoice) ReceivedXML(accessKey string) ([]byte, error)
- func (inv *Invoice) Reissue(invoiceID string, opts ...RequestOption) (map[string]any, error)
- func (inv *Invoice) Rejection(invoiceID string) (map[string]any, error)
- func (inv *Invoice) Stats(days int) (map[string]any, error)
- func (inv *Invoice) Submissions(invoiceID string) ([]map[string]any, error)
- func (inv *Invoice) SyncReceived() (*SyncResult, error)
- func (inv *Invoice) Usage() (*Usage, error)
- func (inv *Invoice) Validate(req IssueRequest) (*ValidationResult, error)
- type InvoiceError
- type IssueRequest
- type ItemAlreadyExistsError
- type ItemChanges
- type ItemFields
- type ItemInactiveError
- type ItemKindMismatchError
- type ItemNotFoundError
- type ItemQuery
- type ItemTaxRegimeMismatchError
- type ItemTaxRequiredError
- type Items
- func (i *Items) Create(fields ItemFields) (map[string]any, error)
- func (i *Items) Deactivate(itemID string) error
- func (i *Items) ForCompany(company string) *Items
- func (i *Items) Get(itemID string) (map[string]any, error)
- func (i *Items) List(query ItemQuery) (map[string]any, error)
- func (i *Items) Reactivate(itemID string) (map[string]any, error)
- func (i *Items) Update(itemID string, changes ItemChanges) (map[string]any, error)
- func (i *Items) Upsert(fields ItemFields) (item map[string]any, created bool, err error)
- type Kind
- type Manifestation
- type Option
- type PageQuery
- type Payment
- type PaymentCard
- type PaymentRequiredError
- type Purpose
- type RateLimitedError
- type RequestOption
- type SaleTerms
- type SearchQuery
- type SyncResult
- type Taxpayer
- type Transport
- type TransportVolume
- type Usage
- type ValidationFinding
- type ValidationResult
- type ValidationWarning
- type WebhookEndpoint
- type Webhooks
- func (w *Webhooks) Create(endpoint WebhookEndpoint) (map[string]any, error)
- func (w *Webhooks) Delete(endpointID string) error
- func (w *Webhooks) Deliveries(query PageQuery) (map[string]any, error)
- func (w *Webhooks) ForCompany(company string) *Webhooks
- func (w *Webhooks) List() ([]map[string]any, error)
Constants ¶
const AbroadState = "EX"
AbroadState is the State of a buyer abroad on an NF-e. Such an address may leave ZipCode and CityCode out and names its country with CountryCode (BACEN code) and CountryName instead.
const DefaultBaseURL = "https://sdk.stackin.io"
Variables ¶
var Kinds = []string{
"cfop",
"ncm",
"cest",
"cst",
"csosn",
"iss_service",
"icms_fuel",
"ibs_cbs_class",
}
Kinds are the classifications with a named accessor on FiscalReference. It is not the whole truth and is not meant to be: ask Kinds() for what the API actually has, because a classification published after this release is reachable through Kind() with no release at all.
var WebhookEvents = []string{
"invoice.authorized",
"invoice.rejected",
"invoice.cancelled",
"invoice.corrected",
"received_invoice.stored",
"received_invoice.full_document",
}
WebhookEvents are the event names an endpoint can subscribe to.
Functions ¶
This section is empty.
Types ¶
type APIError ¶
type APIError struct {
StatusCode int
Detail string
Code string
Field string
Retryable *bool
DocumentID string
SefazRejection string
Expected string
Received string
// contains filtered or unexported fields
}
APIError is any non-2xx answer. Detail is the human message. Code, Field, Retryable, DocumentID, SefazRejection, Expected and Received are filled from the body when it carries them and are zero (nil for Retryable) otherwise. A nil Retryable means the API did not say.
type Address ¶
type Address struct {
State string `json:"state,omitempty"`
CityCode string `json:"city_code,omitempty"`
Street string `json:"street,omitempty"`
Number string `json:"number,omitempty"`
Neighborhood string `json:"neighborhood,omitempty"`
City string `json:"city,omitempty"`
ZipCode string `json:"zip_code,omitempty"`
CountryCode string `json:"country_code,omitempty"`
CountryName string `json:"country_name,omitempty"`
}
type AuthorizedCompanies ¶ added in v0.15.0
type AuthorizedCompanies struct {
Environment string `json:"environment"`
Companies []AuthorizedCompany `json:"companies"`
}
AuthorizedCompanies is every company a credential covers, in one environment.
type AuthorizedCompany ¶ added in v0.15.0
type AuthorizedCompany struct {
CompanyID string `json:"company_id"`
Name string `json:"name"`
TaxID string `json:"tax_id"`
Permissions []string `json:"permissions"`
}
AuthorizedCompany is one company a credential may act on, and the permissions it holds there.
type CityQuery ¶ added in v0.19.0
type CityQuery struct {
// State is one UF, two letters.
State string
// Country overrides the client's own, ISO 3166-1 alpha-2.
Country string
}
CityQuery narrows a city lookup. Both fields are optional.
type ClassifyRequest ¶ added in v0.19.0
type ClassifyRequest struct {
// Description is the item as the shop names it, 3 to 500 characters.
Description string
// DocumentType is NFE or NFSE. Required.
DocumentType DocumentType
// RecipientState is the buyer's UF, two letters. Omitted when empty.
RecipientState string
// Answers settle what the last suggestion listed in
// missing_information: operation_scope, purpose, contains_alcohol,
// service_city_code, tax_retained. Omitted when empty.
Answers map[string]any
}
ClassifyRequest is one item's description and the context that changes its codes.
type ClientAlreadyExistsError ¶ added in v0.17.0
ClientAlreadyExistsError is the API's 409 CLIENT_EXISTS: the company already has a client with this tax id or foreign id. ClientID names it, to read or reactivate instead of searching for it. errors.As still finds the *APIError inside.
func (*ClientAlreadyExistsError) Unwrap ¶ added in v0.17.0
func (e *ClientAlreadyExistsError) Unwrap() error
type ClientChanges ¶ added in v0.17.0
type ClientChanges struct {
Name *string
TaxID *string
ForeignID *string
StateRegistration *string
MunicipalRegistration *string
Email *string
Phone *string
Address *Address
ClearAddress bool
Notes *string
// IsActive pointing at true brings a deactivated client back; see
// Reactivate.
IsActive *bool
}
ClientChanges is what Update changes. A nil field is not sent; a field pointing at "" is sent as null, which clears it. Address replaces the whole address; ClearAddress removes it.
type ClientFields ¶ added in v0.17.0
type ClientFields struct {
Name string `json:"name"`
TaxID string `json:"tax_id,omitempty"`
ForeignID string `json:"foreign_id,omitempty"`
StateRegistration string `json:"state_registration,omitempty"`
MunicipalRegistration string `json:"municipal_registration,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
Address *Address `json:"address,omitempty"`
Notes string `json:"notes,omitempty"`
}
ClientFields is a client as Create takes it. TaxID is required except for a buyer abroad (Address.State EX), who has a ForeignID instead. Empty fields are left out of the request.
type ClientInactiveError ¶ added in v0.18.0
ClientInactiveError is the API's 422 CLIENT_INACTIVE: the saved client named by ClientID is deactivated. Reactivate it, or issue without it. errors.As still finds the *APIError inside.
func (*ClientInactiveError) Unwrap ¶ added in v0.18.0
func (e *ClientInactiveError) Unwrap() error
type ClientNotFoundError ¶ added in v0.18.0
ClientNotFoundError is the API's 404 CLIENT_NOT_FOUND: no saved client of this company has that id. errors.As still finds the *APIError inside.
func (*ClientNotFoundError) Unwrap ¶ added in v0.18.0
func (e *ClientNotFoundError) Unwrap() error
type ClientQuery ¶ added in v0.17.0
type ClientQuery struct {
// Search matches part of the name, the tax id (masked or not) or the
// foreign id.
Search string
// Source is manual, issued or issuance.
Source string
// IsActive left nil lists the active clients, as the API does;
// pointing at false lists the deactivated ones.
IsActive *bool
Limit int
Offset int
// SortBy takes name, last_used_at, created_at or uses_count.
SortBy string
OrderBy string
}
ClientQuery narrows the client listing. Every field is optional; the zero value asks for the first page of active clients, by name.
type Clients ¶ added in v0.17.0
type Clients struct {
// contains filtered or unexported fields
}
Clients reads and edits the company's saved clients: the recipients it issues to again. A successful issuance saves a new recipient on its own, and IssueRequest.ClientID issues to a saved one.
It is company data, like everything on Invoice: WithCompany and ForCompany pick the company. Reading needs invoice:read; creating, editing and deactivating need invoice:issue. The rules on a client's fields are the issuance's own and they are the API's: a refusal comes back as an *APIError 422.
func NewClients ¶ added in v0.17.0
func (*Clients) Create ¶ added in v0.17.0
func (c *Clients) Create(fields ClientFields) (map[string]any, error)
Create saves a client by hand. A TaxID or ForeignID the company already holds is a *ClientAlreadyExistsError, whose ClientID names it.
func (*Clients) Deactivate ¶ added in v0.17.0
Deactivate deactivates a client. It is kept, left out of List by default and refused on issue until Reactivate brings it back.
func (*Clients) ForCompany ¶ added in v0.17.0
ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.
func (*Clients) Get ¶ added in v0.17.0
Get returns one client, deactivated or not. Another company's client is a 404.
func (*Clients) List ¶ added in v0.17.0
func (c *Clients) List(query ClientQuery) (map[string]any, error)
List returns a page of the company's clients.
func (*Clients) Reactivate ¶ added in v0.17.0
Reactivate brings a deactivated client back, and returns it.
type Company ¶ added in v0.20.0
type Company struct {
// contains filtered or unexported fields
}
Company fixes the issuer itself: its address and, for the owner, its fiscal fields (PATCH /company). It fixes what Invoice.Readiness reports missing; reading stays Readiness.
It is company data: WithCompany and ForCompany pick the company. On an OAuth credential Update needs company:write; an API key acts for the member who created it.
func NewCompany ¶ added in v0.20.0
func (*Company) ForCompany ¶ added in v0.20.0
ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.
func (*Company) Update ¶ added in v0.20.0
func (c *Company) Update(update CompanyUpdate) (map[string]any, error)
Update fixes the issuer's address and, for the owner, its fiscal fields, and answers what GET /company does — ready, missing, by_document_type, fix_url, ... — plus the stored address and fiscal_fields, so no second call is needed.
A municipality the IBGE table cannot be read for right now is an *APIError 503 with Retry-After: nothing was written. A member limited to homologation, or a non-owner sending FiscalFields, is an *APIError 403.
type CompanyAddress ¶ added in v0.20.0
type CompanyAddress struct {
Street string `json:"street,omitempty"`
Number string `json:"number,omitempty"`
Neighborhood string `json:"neighborhood,omitempty"`
// MunicipalityCode is the 7-digit IBGE code of a city in the company's
// state. MunicipalityName is derived from it when left out.
MunicipalityCode string `json:"municipality_code,omitempty"`
// MunicipalityName is resolved to its code when sent alone, and must be
// the code's city when both are sent.
MunicipalityName string `json:"municipality_name,omitempty"`
// ZipCode is the 8-digit CEP; a mask (01310-100) is stripped.
ZipCode string `json:"zip_code,omitempty"`
}
CompanyAddress is the issuer address Update may fix. There is no complement, and the state changes only in the dashboard: it decides the authorizer. Empty fields are left out.
type CompanyNotInScopeError ¶ added in v0.15.0
type CompanyNotInScopeError struct {
APIError
Description string
Companies []AuthorizedCompany
}
CompanyNotInScopeError is the API's 403 company_not_in_scope: the company named is not one this credential covers. Companies lists the ones it does. Retrying the same request cannot succeed. errors.As still finds the *APIError inside.
func (*CompanyNotInScopeError) Unwrap ¶ added in v0.15.0
func (e *CompanyNotInScopeError) Unwrap() error
type CompanyRequiredError ¶ added in v0.15.0
type CompanyRequiredError struct {
APIError
Description string
Companies []AuthorizedCompany
}
CompanyRequiredError is the API's 422 company_required: the credential covers several companies and the request named none. Companies lists them; name one with WithCompany or ForCompany. Retrying the same request cannot succeed. errors.As still finds the *APIError inside.
func (*CompanyRequiredError) Unwrap ¶ added in v0.15.0
func (e *CompanyRequiredError) Unwrap() error
type CompanyUpdate ¶ added in v0.20.0
type CompanyUpdate struct {
Address *CompanyAddress
// FiscalFields are the company owner's alone: anyone else gets an
// *APIError 403, even when the address in the same call would pass.
FiscalFields *FiscalFields
BlockActivityMismatch *bool
}
CompanyUpdate is what Update sends. A nil group, or one with nothing set, is left out; an empty CompanyUpdate changes nothing and answers the company as it is.
type ConnectionFailedError ¶
type ConnectionFailedError struct {
Message string
}
func (*ConnectionFailedError) Error ¶
func (e *ConnectionFailedError) Error() string
type Direction ¶ added in v0.14.0
type Direction string
Direction is whether an NF-e is outgoing or an incoming one the company issues itself (tpNF). The API defaults to DirectionOut when it is left out.
type DocumentType ¶
type DocumentType string
const ( NFE DocumentType = "nfe" NFSE DocumentType = "nfse" )
type Environment ¶
type Environment string
const ( Local Environment = "local" Test Environment = "test" Production Environment = "production" )
type Export ¶ added in v0.14.0
type Export struct {
ExitState string `json:"exit_state"`
Place string `json:"place"`
DispatchPlace string `json:"dispatch_place,omitempty"`
}
Export is where the goods of an NF-e to a buyer abroad leave Brazil (the exporta group): ExitState is a Brazilian state (UFSaidaPais, never EX), Place the place of shipment or border crossing (xLocExporta) and DispatchPlace the optional customs facility of dispatch (xLocDespacho).
type FiscalFields ¶ added in v0.20.0
type FiscalFields struct {
// TaxRegime is the CRT: 1 Simples, 2 Simples excesso, 3 normal, 4 MEI.
TaxRegime string `json:"tax_regime,omitempty"`
// SimplesNacional is the NFS-e opSimpNac: 1 no, 2 MEI, 3 ME/EPP.
SimplesNacional string `json:"simples_nacional,omitempty"`
// SimplesApuracao is the NFS-e regApTribSN for ME/EPP, 1 to 3.
SimplesApuracao string `json:"simples_apuracao,omitempty"`
// SimplesApuracaoIbsCbs is the apuração of the IBS/CBS for an ME/EPP,
// 1 or 3; 3 is what the NFS-e IBS/CBS group needs.
SimplesApuracaoIbsCbs string `json:"simples_apuracao_ibs_cbs,omitempty"`
// StateRegistration is the inscrição estadual (IE), or ISENTO.
StateRegistration string `json:"state_registration,omitempty"`
// ServiceCode is the default cTribNac, e.g. 1.07 or 01.07.00.
ServiceCode string `json:"service_code,omitempty"`
}
FiscalFields are the fiscal fields the owner may set. Empty fields are left out.
type FiscalReference ¶ added in v0.10.0
type FiscalReference struct {
CFOP *Kind
NCM *Kind
CEST *Kind
CST *Kind
CSOSN *Kind
IssService *Kind
IcmsFuel *Kind
IbsCbsClass *Kind
// contains filtered or unexported fields
}
FiscalReference reads the published classification tables. Nothing here is the company's own data and nothing here is writable.
func NewFiscalReference ¶ added in v0.10.0
func NewFiscalReference(opts ...Option) *FiscalReference
func (*FiscalReference) CalculateIbsCbs ¶ added in v0.23.0
func (r *FiscalReference) CalculateIbsCbs(request IbsCbsCalculationRequest) (*IbsCbsCalculation, error)
CalculateIbsCbs simulates the IBS and CBS of up to 990 items (POST /ibs-cbs/calculate). The amounts are the NF-e's: the simulation does not compute an NFS-e's, which the Sefin Nacional does. It needs no company and writes nothing. A refusal by the API, such as IBS_CBS_RATES_REQUIRED, is an *APIError with its code and field.
func (*FiscalReference) Cities ¶ added in v0.19.0
Cities lists the municipalities whose name starts with name, with their code. Each row is {country, code, name, state}; for Brazil code is the 7-digit IBGE code an Address's CityCode takes. Issuing resolves it from City and State by itself, so this is for the name that matches more than one. The API answers at most 20 rows.
func (*FiscalReference) Kind ¶ added in v0.10.0
func (r *FiscalReference) Kind(name string, country ...string) *Kind
Kind reaches any classification by name, including one with no accessor on this struct.
func (*FiscalReference) Kinds ¶ added in v0.10.0
func (r *FiscalReference) Kinds(country ...string) ([]string, error)
Kinds asks which classifications this country has rows for. The only honest answer to "what else is there" — a hard-coded list goes stale the next time the ETL grows one.
func (*FiscalReference) Search ¶ added in v0.10.0
func (r *FiscalReference) Search(query SearchQuery) (map[string]any, error)
Search spans every classification at once, which no accessor can express. It is the most expensive call the endpoint accepts: the whole country's tables, not one of them.
type HistoryQuery ¶ added in v0.5.0
type HistoryQuery struct {
DocumentType DocumentType
Status string
Limit int
Offset int
SortBy string
OrderBy string
// ExternalReference finds the documents issued with exactly this
// IssueRequest.ExternalReference.
ExternalReference string
// Fields set to "summary" returns a lighter item per invoice.
Fields string
}
HistoryQuery filters the issuance history. Every field is optional; the zero value asks for the newest page with the API's own defaults.
type IbsCbsAmounts ¶ added in v0.23.0
type IbsCbsAmounts struct {
Base string `json:"base"`
IbsState string `json:"ibs_state"`
IbsCity string `json:"ibs_city"`
Ibs string `json:"ibs"`
Cbs string `json:"cbs"`
DeferredIbsState string `json:"deferred_ibs_state"`
DeferredIbsCity string `json:"deferred_ibs_city"`
DeferredCbs string `json:"deferred_cbs"`
}
IbsCbsAmounts are money values as the API sends them, decimal strings such as "1.00", so nothing is rounded through a float.
type IbsCbsAppliedRates ¶ added in v0.23.0
type IbsCbsAppliedRates struct {
RateState string `json:"rate_state"`
RateCity string `json:"rate_city"`
RateFederal string `json:"rate_federal"`
}
IbsCbsAppliedRates are rates in percent, as decimal strings.
type IbsCbsCalculatedItem ¶ added in v0.23.0
type IbsCbsCalculatedItem struct {
CST string `json:"cst"`
Classification string `json:"classification"`
Indicators IbsCbsIndicators `json:"indicators"`
HasGroup bool `json:"has_group"`
Rates *IbsCbsAppliedRates `json:"rates"`
RatesSource *string `json:"rates_source"`
ReductionIbs *string `json:"reduction_ibs"`
ReductionCbs *string `json:"reduction_cbs"`
EffectiveRates *IbsCbsAppliedRates `json:"effective_rates"`
Deferral *string `json:"deferral"`
Amounts IbsCbsAmounts `json:"amounts"`
}
IbsCbsCalculatedItem is one simulated item. RatesSource is "caller" or "official_2026"; Rates and EffectiveRates are nil when the item has none.
type IbsCbsCalculation ¶ added in v0.23.0
type IbsCbsCalculation struct {
Simulated bool `json:"simulated"`
Notice string `json:"notice"`
DocumentType string `json:"document_type"`
OperationDate string `json:"operation_date"`
Items []IbsCbsCalculatedItem `json:"items"`
Total IbsCbsAmounts `json:"total"`
}
IbsCbsCalculation is the simulation. Simulated is always true: nothing is issued or stored.
type IbsCbsCalculationItem ¶ added in v0.23.0
type IbsCbsCalculationItem struct {
CST string
Classification string
Amount *float64
Base *float64
RateState *float64
RateCity *float64
RateFederal *float64
ReductionIbs *float64
ReductionCbs *float64
}
IbsCbsCalculationItem is one item of the simulation. CST (3 digits) and Classification (cClassTrib, 6 digits) are required, and so is Amount or Base. Fields left nil are not sent.
type IbsCbsCalculationRequest ¶ added in v0.23.0
type IbsCbsCalculationRequest struct {
DocumentType string
OperationDate string
Rates *IbsCbsRates
Items []IbsCbsCalculationItem
}
IbsCbsCalculationRequest is what CalculateIbsCbs sends. OperationDate is YYYY-MM-DD and required. DocumentType is "nfe" (the default when empty), "nfce" or "nfse": it only picks the model the cClassTrib is checked for.
type IbsCbsIndicators ¶ added in v0.23.0
type IbsCbsIndicators struct {
Group *int `json:"group"`
Reduction *int `json:"reduction"`
Deferral *int `json:"deferral"`
}
IbsCbsIndicators are the cClassTrib's group, reduction and deferral indicators; nil when the classification does not carry one.
type IbsCbsRates ¶ added in v0.23.0
IbsCbsRates are the caller's rates for the whole simulation, in percent (0 to 100): pIBSUF, pIBSMun and pCBS. Each is sent only when set, and an item's own rate wins over it. A nil IbsCbsCalculationRequest.Rates in 2026 makes the official 2026 rates apply (CBS 0.9%, IBS UF 0.1%, IBS Mun 0%); outside 2026 the API refuses it with IBS_CBS_RATES_REQUIRED.
type InsufficientPermissionError ¶ added in v0.15.0
InsufficientPermissionError is the API's 403 INSUFFICIENT_PERMISSION: the credential reaches the company but lacks the permission the call needs. Description reads "needs X, has Y, company=<id>". Retrying the same request cannot succeed. errors.As still finds the *APIError inside.
func (*InsufficientPermissionError) Unwrap ¶ added in v0.15.0
func (e *InsufficientPermissionError) Unwrap() error
type Intermediary ¶ added in v0.25.0
Intermediary is the marketplace or platform an NF-e sale went through (infIntermed). TaxID is its CNPJ and Identifier the seller's user name or profile id there.
type InvalidationRequest ¶ added in v0.2.0
type Invoice ¶
type Invoice struct {
// contains filtered or unexported fields
}
func NewInvoice ¶
func (*Invoice) Cancel ¶
func (inv *Invoice) Cancel(accessKey string, documentType DocumentType, reason string, opts ...RequestOption) (map[string]any, error)
Cancel voids an authorized document. Pass WithIdempotencyKey to make a retry safe: repeating the same key with the same body replays the first answer instead of cancelling twice. This is the one irreversible operation here, with a legal window and no undo.
func (*Invoice) Classify ¶ added in v0.19.0
func (inv *Invoice) Classify(req ClassifyRequest) (map[string]any, error)
Classify suggests a fiscal classification for one item's description.
A suggestion, never a decision: primary_candidate and alternative_candidates carry the NCM, CFOP, CST/CSOSN, CEST or service code, each read from the published tables, with a confidence, and missing_information lists what would settle it (pass those back in Answers). Someone confirms it before it goes on an item; the codes decide the tax owed.
func (*Invoice) Companies ¶ added in v0.15.0
func (inv *Invoice) Companies() (*AuthorizedCompanies, error)
Companies lists the companies this credential reaches, with the permissions it holds on each: the ids WithCompany and ForCompany accept. An API key lists as its one company with every permission.
func (*Invoice) ConsultByDPS ¶ added in v0.24.0
ConsultByDPS reads an NFS-e by the DPS id the authority was sent, the document_id of an OUTCOME_UNKNOWN error. It answers like Consult and may carry status "cancelled". The API answers 400 when the id is not this company's and 404 when the authority holds no note for it, meaning nothing was issued.
func (*Invoice) Correct ¶ added in v0.2.0
func (inv *Invoice) Correct(accessKey string, documentType DocumentType, correction string) (map[string]any, error)
Correct files a correction letter (CC-e). NF-e only: a key that is not an NF-e access key is refused before the call. A well-formed key sent with NFSE, or one for a document the API does not hold, is answered 409 by the API and comes back as an *APIError.
func (*Invoice) ForCompany ¶ added in v0.15.0
ForCompany returns a copy of the client bound to another company, for the calls chained on it: inv.ForCompany("00.000.000/0001-91").Issue(req). The receiver is left as it was and the copy shares its HTTP client. An empty company sends no header at all.
func (*Invoice) History ¶ added in v0.5.0
func (inv *Invoice) History(query HistoryQuery) (map[string]any, error)
History lists what this company issued, newest first.
The counterpart of Received: that one lists what was issued against the company, this one what the company issued.
func (*Invoice) Invalidate ¶ added in v0.2.0
func (inv *Invoice) Invalidate(req InvalidationRequest) (map[string]any, error)
func (*Invoice) Invalidations ¶ added in v0.19.0
Invalidations lists the numbering ranges this company already invalidated, a page. Each row carries the range, the reason, the SEFAZ status and its protocol. Read it before Invalidate to avoid reporting the same range twice.
func (*Invoice) Manifest ¶ added in v0.3.1
func (inv *Invoice) Manifest(accessKey string, manifestation Manifestation, reason string) (map[string]any, error)
Manifest files the recipient's formal answer to a received document.
Only OperacaoNaoRealizada takes a reason, and it requires one. Both are fixed rules, checked here rather than spending a round trip to be told.
func (*Invoice) Pdf ¶ added in v0.3.0
func (inv *Invoice) Pdf(accessKey string, documentType DocumentType) ([]byte, error)
Pdf returns the printable rendering of an authorized document, as raw bytes — the only method that does not return a parsed object. The API draws it itself from the authorized XML: the DANFE for an NF-e, the DANFSe for an NFS-e. The XML stays the legally valid document.
func (*Invoice) Readiness ¶ added in v0.19.0
Readiness says whether the company can issue right now, and if not, why (GET /company).
ready is true when at least one document type can be issued; when false, missing names why: certificate, certificate_expired, certificate_unreadable, address, state_registration (NF-e) or plan. by_document_type breaks it down per nfe/nfse (ready, missing, warnings, each issue a code plus, for address, the fields at fault) and fix_url is the dashboard screen for the first blocker (nil when nothing blocks). Also has_certificate, certificate_expires_at, tax_regime (CRT), state, default_series per document type and suggested_fiscal_fields, what the CNPJ registry suggests where it differs — never applied. The map keeps whatever the API adds. Company.Update fixes the address and fiscal fields. Ask before a first document instead of failing it.
func (*Invoice) Received ¶ added in v0.3.1
Received lists documents other companies issued against this one.
Reads what the API already collected; it does not call the authorizer. Collecting runs on a schedule there, every six hours, and SyncReceived asks for it now. After a read that finds nothing more the SEFAZ makes the CNPJ wait an hour before the next one.
The first 50 received documents a month are included in every plan; each one after that takes R$ 0,05 from the account credit. Some accounts are exempt: Usage().ReceivedFree tells.
func (*Invoice) ReceivedXML ¶ added in v0.24.0
ReceivedXML returns the full XML (procNFe) of a received document as raw bytes. A document held only as a summary answers 409 with code RECEIVED_XML_NOT_AVAILABLE until it is manifested; 402 is a *PaymentRequiredError. Downloading is never billed.
func (*Invoice) Rejection ¶ added in v0.19.0
Rejection explains why a rejected document was refused, and what to change. Submissions has the authorizer's own answer; this reads it for someone who does not speak SEFAZ: code, message, explanation, steps, the field to fix and, when there is one, a suggested value. It takes the invoiceID, like Submissions. A document that is not rejected is an *APIError 409.
func (*Invoice) Stats ¶ added in v0.19.0
Stats counts this company's documents, and the last days of them.
total, by_document_type and by_status cover every document; current_period/previous_period compare the last days (1 to 365) with the ones before, and daily_series has one row per day. Zero days sends nothing and the API answers for 30.
func (*Invoice) Submissions ¶ added in v0.6.0
Submissions returns every attempt made for one invoice, with what the authorizer answered to each.
Consult gives the status; this gives the reason. It takes the invoiceID, like Reissue and unlike everything else, because a rejected document has no access key to look it up by.
func (*Invoice) SyncReceived ¶ added in v0.18.0
func (inv *Invoice) SyncReceived() (*SyncResult, error)
SyncReceived asks the SEFAZ now for the documents issued against this company since the last read, instead of waiting for the scheduled collection, which runs every six hours. After a read that finds nothing more the SEFAZ makes the CNPJ wait an hour; a call inside that wait is a *RateLimitedError with Code DISTRIBUTION_COOLDOWN, RetryAt and RetryAfter.
func (*Invoice) Usage ¶ added in v0.18.0
Usage reads the plan behind this company and how much of it the current period has used (GET /company/usage).
func (*Invoice) Validate ¶ added in v0.24.0
func (inv *Invoice) Validate(req IssueRequest) (*ValidationResult, error)
Validate dry-runs an issuance: the same request as Issue, checked by the API without transmitting, numbering or charging. The rules failing is a result with Valid false, not an error; any other refusal (malformed body, unknown client or item, credentials, rate limit) is returned as the error Issue would return.
type InvoiceError ¶
type InvoiceError struct {
Message string
}
func (*InvoiceError) Error ¶
func (e *InvoiceError) Error() string
type IssueRequest ¶
type IssueRequest struct {
DocumentType DocumentType
ClientName string
TaxID string
Items []br.Product
RecipientAddress *Address
Series string
Number string
// ExternalReference is the caller's own id for the document, an order
// number say. The API stores it as sent (at most 255 characters) and
// returns it on every read and webhook. Omitted when empty.
ExternalReference string
// IdempotencyKey makes a retry safe: the same key with the same body
// replays the first response instead of issuing a second document.
// Keys live 24 hours. Never generated for you — only the caller knows
// which two requests are meant to be the same one.
IdempotencyKey string
AcceptLanguage string `json:"-"`
// Discount is a discount on the whole document, in BRL, zero or more.
// The API spreads it over the lines. Omitted when nil.
Discount *float64
// IssuedAt is the emission moment (dhEmi), sent as RFC 3339 in the
// offset of its own Location. NF-e: at most 30 days back and 5 minutes
// ahead; NFS-e: never ahead. The API defaults it to now. Omitted when
// nil.
IssuedAt *time.Time
// Purpose is why the NF-e is issued; Direction whether it is outgoing
// or incoming. NF-e only, omitted when empty.
Purpose Purpose
Direction Direction
// ReferencedKeys are the 44-character access keys of the NF-e, NFC-e
// or CF-e this NF-e refers to: required for PurposeComplementary and,
// but for a few CFOPs, PurposeReturn. NF-e only, omitted when empty.
ReferencedKeys []string
// ForeignID identifies a buyer abroad (idEstrangeiro, 5 to 20
// characters), for an NF-e whose RecipientAddress.State is EX. TaxID
// is then left out. Omitted when empty.
ForeignID string
// Export is where the goods leave Brazil, required for an outgoing
// NF-e to a buyer abroad. Omitted when nil.
Export *Export
// ClientID names a saved client of the company (see Clients). Its
// name, tax id, foreign id and address fill whichever of ClientName,
// TaxID, ForeignID and RecipientAddress are left empty; the ones set
// win, and the empty ones are left out of the request. Its e-mail and
// phone likewise fill ClientEmail and ClientPhone when empty. The address
// checks then apply only to a RecipientAddress that is set: the API
// checks the merged request. Omitted when empty.
ClientID string
// Presence is indPres, how the buyer took part: 0, 1, 2, 3, 4, 5 or 9.
// NF-e only, omitted when empty.
Presence string
// Intermediary is the marketplace or platform the sale went through.
// NF-e only, omitted when nil.
Intermediary *Intermediary
// Transport is the freight mode and the volumes. NF-e only, omitted
// when nil.
Transport *Transport
// Payments are the detPag entries, 1 to 100 (an empty non-nil slice is refused); Amount and Change take at most 2 decimal places. NF-e only, omitted when
// empty.
Payments []Payment
// Change is vTroco in BRL, what the payments exceed the total by. A
// pointer so a 0 can be sent. NF-e only, omitted when nil.
Change *float64
// Contingency sends an NF-e through the UF's contingency authorizer
// (SVC-AN or SVC-RS, tpEmis 6/7) for when its own is down. Sent only
// when true.
Contingency bool
// UpdateClient rewrites an existing client with this request's
// recipient data after a successful issuance; a new recipient is
// saved as a client either way. Sent only when true.
UpdateClient bool
// ClientEmail is the recipient's e-mail, saved on the Stackin client
// created after a successful issuance, or on an existing one only with
// UpdateClient. It is also kept on the invoice and sent again on a
// reissue (which does not touch the client), and written into the
// fiscal document: NF-e dest/email (up to 60 characters), NFS-e
// toma/email (up to 80). A value the layout cannot carry (too long,
// characters beyond Latin-1) is left out of the document and the
// issuance goes on. Omitted when empty.
ClientEmail string
// ClientPhone is the recipient's phone, 8 to 15 digits with an optional
// leading + (the API drops spaces, dots, dashes and parentheses). Saved
// on the client like ClientEmail, and written into the fiscal document:
// NF-e dest/enderDest/fone (digits only, up to 14, only with a
// RecipientAddress), NFS-e toma/fone (up to 20 digits). Digits only,
// area code first; a +55 is dropped unless the recipient is abroad. A
// value the layout cannot carry is left out of the document. Omitted
// when empty.
ClientPhone string
}
type ItemAlreadyExistsError ¶ added in v0.21.0
ItemAlreadyExistsError is the API's 409 ITEM_EXISTS: the company already has an item with this code or external reference (a deactivated item still holds its code). ItemID names it and Field is "code" or "external_reference". errors.As still finds the *APIError inside.
func (*ItemAlreadyExistsError) Unwrap ¶ added in v0.21.0
func (e *ItemAlreadyExistsError) Unwrap() error
type ItemChanges ¶ added in v0.21.0
type ItemChanges struct {
Kind *string
Description *string
Code *string
// UnitPrice is sent as a decimal string. UnitPriceText (up to 10
// places) wins over it and keeps every digit; pointing it at "" clears
// the price.
UnitPrice *float64
UnitPriceText *string
Unit *string
ExternalReference *string
Notes *string
NCM *string
CFOP *string
TaxSituation *string
Origin *string
CEST *string
GTIN *string
ServiceCode *string
NBS *string
ISSRetained *bool
NetWeight *float64
GrossWeight *float64
// ClearNetWeight and ClearGrossWeight send null, clearing the weight;
// a NetWeight or GrossWeight set alongside wins.
ClearNetWeight bool
ClearGrossWeight bool
IbsCbsCST *string
IbsCbsClass *string
// IsActive pointing at true brings a deactivated item back; see
// Reactivate.
IsActive *bool
}
ItemChanges is what Update changes. A nil field is not sent; a text field pointing at "" is sent as null, which clears it. The API checks the item as a whole, so changing Kind while a field of the old kind is still set is a 422.
type ItemFields ¶ added in v0.21.0
type ItemFields struct {
Kind string `json:"kind"`
Description string `json:"description"`
Code string `json:"code,omitempty"`
// UnitPrice is a pointer so a price of 0 can be sent, and goes out as a
// decimal string. UnitPriceText (such as "18.9000000001", up to 10
// places) wins over it and keeps every digit a float64 would round.
UnitPrice *float64 `json:"-"`
UnitPriceText string `json:"-"`
Unit string `json:"unit,omitempty"`
ExternalReference string `json:"external_reference,omitempty"`
Notes string `json:"notes,omitempty"`
// Source is how the item came to be (manual, import, nuvemshop or
// invoice). Upsert only, and only when it creates; the API defaults it
// to manual.
Source string `json:"source,omitempty"`
NCM string `json:"ncm,omitempty"`
CFOP string `json:"cfop,omitempty"`
TaxSituation string `json:"tax_situation,omitempty"`
Origin string `json:"origin,omitempty"`
CEST string `json:"cest,omitempty"`
GTIN string `json:"gtin,omitempty"`
ServiceCode string `json:"service_code,omitempty"`
NBS string `json:"nbs,omitempty"`
ISSRetained *bool `json:"iss_retained,omitempty"`
// NetWeight and GrossWeight are one unit's weight in kg (a product);
// pointers so a real 0 can be sent.
NetWeight *float64 `json:"net_weight,omitempty"`
GrossWeight *float64 `json:"gross_weight,omitempty"`
// IbsCbsCST (3 digits) and IbsCbsClass (cClassTrib, 6 digits) go
// together; the API checks them.
IbsCbsCST string `json:"ibs_cbs_cst,omitempty"`
IbsCbsClass string `json:"ibs_cbs_class,omitempty"`
}
ItemFields is an item as Create and Upsert take it. Kind and Description are required. The NCM, CFOP, TaxSituation, Origin, CEST and GTIN fields belong to a product and ServiceCode and ISSRetained to a service; the other kind's is a 422. Empty text fields and nil pointers are left out of the request; UnitPrice and ISSRetained are pointers so a price of 0 and ISSRetained false (turning retention off) can be sent.
func (ItemFields) MarshalJSON ¶ added in v0.21.0
func (f ItemFields) MarshalJSON() ([]byte, error)
MarshalJSON writes the unit price as a decimal string.
type ItemInactiveError ¶ added in v0.21.0
ItemInactiveError is the API's 422 ITEM_INACTIVE: the catalog item named by ItemID is deactivated. Reactivate it, or issue without it. errors.As still finds the *APIError inside.
func (*ItemInactiveError) Unwrap ¶ added in v0.21.0
func (e *ItemInactiveError) Unwrap() error
type ItemKindMismatchError ¶ added in v0.21.0
ItemKindMismatchError is the API's 422 ITEM_KIND_MISMATCH: a service item on an NF-e or a product item on an NFS-e. Index is the line. errors.As still finds the *APIError inside.
func (*ItemKindMismatchError) Unwrap ¶ added in v0.21.0
func (e *ItemKindMismatchError) Unwrap() error
type ItemNotFoundError ¶ added in v0.21.0
ItemNotFoundError is the API's 404 ITEM_NOT_FOUND: no item of this company has that id, also the answer for another company's item. errors.As still finds the *APIError inside.
func (*ItemNotFoundError) Unwrap ¶ added in v0.21.0
func (e *ItemNotFoundError) Unwrap() error
type ItemQuery ¶ added in v0.21.0
type ItemQuery struct {
// Kind is product or service.
Kind string
// Search matches part of the description, code or external reference;
// digits also match the NCM and the GTIN.
Search string
// Source is manual, import, nuvemshop or invoice.
Source string
// IsActive left nil lists the active items, as the API does; pointing
// at false lists the deactivated ones.
IsActive *bool
Limit int
Offset int
// SortBy takes description, code, unit_price, last_used_at,
// created_at or uses_count.
SortBy string
OrderBy string
}
ItemQuery narrows the item listing. Every field is optional; the zero value asks for the first page of active items, by description.
type ItemTaxRegimeMismatchError ¶ added in v0.21.0
ItemTaxRegimeMismatchError is the API's 422 ITEM_TAX_REGIME_MISMATCH: the item's CST/CSOSN does not fit the company's tax regime (a CSOSN is for Simples Nacional, a CST for the rest), or is not allowed on an export CFOP. Send the line's own Tax, or fix the item. Index is the line. errors.As still finds the *APIError inside.
func (*ItemTaxRegimeMismatchError) Unwrap ¶ added in v0.21.0
func (e *ItemTaxRegimeMismatchError) Unwrap() error
type ItemTaxRequiredError ¶ added in v0.21.0
ItemTaxRequiredError is the API's 422 ITEM_TAX_REQUIRED: the item's tax situation needs an ICMS base and rate the catalog does not keep, so the line at Index must send its own tax. errors.As still finds the *APIError inside.
func (*ItemTaxRequiredError) Unwrap ¶ added in v0.21.0
func (e *ItemTaxRequiredError) Unwrap() error
type Items ¶ added in v0.21.0
type Items struct {
// contains filtered or unexported fields
}
Items reads and edits the company's catalog of products and services, and Product.ItemID issues a line from one. The catalog is one table told apart by Kind: "product" for goods (NF-e) and "service" for services (NFS-e).
It is company data, like everything on Invoice: WithCompany and ForCompany pick the company. Reading needs invoice:read; creating, editing and deactivating need invoice:issue. The rules on an item's fields are the API's: a refusal comes back as an *APIError 422.
func (*Items) Create ¶ added in v0.21.0
func (i *Items) Create(fields ItemFields) (map[string]any, error)
Create is Upsert without the created flag.
func (*Items) Deactivate ¶ added in v0.21.0
Deactivate deactivates an item. It is kept, still holds its code, is left out of List by default and refused on issue until Reactivate brings it back. The API answers 204 with no body.
func (*Items) ForCompany ¶ added in v0.21.0
ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.
func (*Items) Get ¶ added in v0.21.0
Get returns one item, deactivated or not. Another company's item is a 404 (*ItemNotFoundError).
func (*Items) Reactivate ¶ added in v0.21.0
Reactivate brings a deactivated item back, and returns it.
func (*Items) Update ¶ added in v0.21.0
Update changes only the fields set in changes. The API checks the item as a whole; taking a code another item holds is a *ItemAlreadyExistsError.
func (*Items) Upsert ¶ added in v0.21.0
Upsert saves an item by its ExternalReference, or by its Code when no reference is sent: the company's matching item is updated with the fields sent (it keeps its source and its active flag), otherwise a new one is created. created is true for the API's 201 and false for its 200, so sending the same fields twice never makes two items. A Code the company holds on another item is a *ItemAlreadyExistsError.
type Kind ¶ added in v0.10.0
Kind is one classification, bound to a country.
func (*Kind) Get ¶ added in v0.10.0
Get returns one code. A code that does not exist is a 404, which arrives as *APIError — there is no separate not-found type.
func (*Kind) Search ¶ added in v0.10.0
func (k *Kind) Search(query SearchQuery) (map[string]any, error)
Search returns a page of this classification, filtered by the query's term when it has one. An empty term is no term: the route rejects search="" with a 422, and sending it would invent a failure the caller cannot read.
type Manifestation ¶ added in v0.3.1
type Manifestation string
Manifestation is the recipient's answer to a document issued against it.
const ( Confirmacao Manifestation = "210200" Ciencia Manifestation = "210210" Desconhecimento Manifestation = "210220" OperacaoNaoRealizada Manifestation = "210240" )
type Option ¶
type Option func(*transport)
func WithAPIKey ¶
func WithBaseURL ¶
func WithCompany ¶ added in v0.15.0
WithCompany names the company every request acts on, by its id (UUID) or its CNPJ, punctuated or not. It is sent as the X-Stackin-Company header. Only a credential covering several companies needs it; an API key is one company already. Left empty, nothing is sent.
func WithCountry ¶ added in v0.10.0
WithCountry sets the ISO 3166-1 alpha-2 code FiscalReference and Taxpayer look codes up under. Defaults to BR.
func WithEnvironment ¶
func WithEnvironment(env Environment) Option
func WithTimeout ¶
type PageQuery ¶ added in v0.19.0
PageQuery is the API's pagination for a listing. Every field is optional; a zero value is left out and the API's own default applies.
type Payment ¶ added in v0.25.0
type Payment struct {
Method string
Amount float64
Description string
Card *PaymentCard
}
Payment is one detPag. Method is the national tPag code, such as "01" or "17"; Amount is in BRL and is always sent, so a 0 (method "90") goes out. Description is required for method "99" and sent only then.
func (Payment) MarshalJSON ¶ added in v0.25.0
func (*Payment) UnmarshalJSON ¶ added in v0.25.0
type PaymentCard ¶ added in v0.25.0
type PaymentCard struct {
Integration string `json:"integration"`
TaxID string `json:"tax_id,omitempty"`
Brand string `json:"brand,omitempty"`
Authorization string `json:"authorization,omitempty"`
}
PaymentCard is the electronic payment's processor and authorization (card). Integration is 1 (integrated with the seller's system) or 2.
type PaymentRequiredError ¶ added in v0.18.0
type PaymentRequiredError struct {
APIError
}
PaymentRequiredError is any 402: the plan's allowance is spent and neither an overage price nor the account credit covers the call. Detail says why. errors.As still finds the *APIError inside.
func (*PaymentRequiredError) Unwrap ¶ added in v0.18.0
func (e *PaymentRequiredError) Unwrap() error
type Purpose ¶ added in v0.14.0
type Purpose string
Purpose is why an NF-e is issued (finNFe). The API defaults to PurposeNormal when it is left out.
type RateLimitedError ¶ added in v0.18.0
RateLimitedError is any 429. RetryAfter is the Retry-After header in seconds; without the header it is derived from RetryAt, and zero when neither is there. RetryAt and Code come from the body when it carries them: DISTRIBUTION_COOLDOWN is the SEFAZ's one-hour wait after a received-invoices read that found nothing more. errors.As still finds the *APIError inside.
func (*RateLimitedError) Unwrap ¶ added in v0.18.0
func (e *RateLimitedError) Unwrap() error
type RequestOption ¶ added in v0.2.0
type RequestOption func(*requestConfig)
RequestOption tunes a single call, as opposed to Option, which tunes the client.
func WithIdempotencyKey ¶ added in v0.2.0
func WithIdempotencyKey(key string) RequestOption
WithIdempotencyKey attaches an Idempotency-Key to one call. See IssueRequest.IdempotencyKey for what the API does with it.
type SaleTerms ¶ added in v0.25.0
type SaleTerms struct {
Presence *string `json:"presence"`
Intermediary *Intermediary `json:"intermediary"`
Transport *Transport `json:"transport"`
Payments []Payment `json:"payments"`
Change *float64 `json:"-"`
}
SaleTerms are the NF-e sale terms an invoice was issued with, as the invoice detail returns them. Every field is nil or empty when the issuance did not send it. Change is in BRL.
func SaleTermsOf ¶ added in v0.25.0
SaleTermsOf reads the stored sale terms out of an invoice detail, as returned by the API: presence, intermediary, transport, payments and change at the top level of the object (or of its "result"). Fields the detail does not carry stay nil.
func (*SaleTerms) UnmarshalJSON ¶ added in v0.25.0
type SearchQuery ¶ added in v0.10.0
SearchQuery narrows a classification listing.
There is no SortBy or OrderBy: the route accepts both and discards them, so rows always come back ordered by kind then code. History on Invoice does honour them, which is why the difference is spelled out here rather than left to be discovered.
type SyncResult ¶ added in v0.18.0
SyncResult is what one read of the SEFAZ distribution brought back. NextSyncAt is set when the SEFAZ had nothing more to deliver: no read is allowed before it.
func (*SyncResult) UnmarshalJSON ¶ added in v0.18.0
func (s *SyncResult) UnmarshalJSON(raw []byte) error
type Taxpayer ¶ added in v0.10.0
type Taxpayer struct {
// contains filtered or unexported fields
}
Taxpayer reads the taxpayer registry, one tax id at a time.
One method, and it stays one method. The registry names and addresses real people and companies: an exact lookup answers the question an issuer has — who is this CNPJ I am about to invoice — and answers nothing else. A prefix or wildcard search over the same table is a bulk export wearing the costume of a query. Do not add one, not for parity with FiscalReference, not "just by name", not "just within one state".
func NewTaxpayer ¶ added in v0.10.0
func (*Taxpayer) Get ¶ added in v0.10.0
Get returns one taxpayer, by exact tax id.
A 404 arrives as *APIError and does not mean the taxpayer does not exist: the registry reloads monthly, so a company registered in the last few weeks is simply not in it yet. Never build a validation rule on top of it.
type Transport ¶ added in v0.25.0
type Transport struct {
FreightMode string
Volumes []TransportVolume
}
Transport is the freight mode (modFrete) and the volumes carried. Volumes left nil lets the API derive one from the lines' weights; an empty non-nil slice is sent as [] and writes none.
func (Transport) MarshalJSON ¶ added in v0.25.0
func (*Transport) UnmarshalJSON ¶ added in v0.25.0
type TransportVolume ¶ added in v0.25.0
type TransportVolume struct {
Quantity *int `json:"quantity,omitempty"`
Species string `json:"species,omitempty"`
Brand string `json:"brand,omitempty"`
Numbering string `json:"numbering,omitempty"`
NetWeight *float64 `json:"net_weight,omitempty"`
GrossWeight *float64 `json:"gross_weight,omitempty"`
}
TransportVolume is one transp/vol group. Every field is optional and sent only when set; the pointers let a real 0 go out. Weights are in kg with at most 3 decimal places.
func (*TransportVolume) UnmarshalJSON ¶ added in v0.25.0
func (v *TransportVolume) UnmarshalJSON(data []byte) error
type Usage ¶ added in v0.18.0
type Usage struct {
PlanName string
PlanSlug string
IncludedInvoices int
UsedInvoices int
OveragePriceCents *int
IncludedReceived int
UsedReceived int
ReceivedPriceCents int
ReceivedFree bool
CurrentPeriodStart time.Time
CurrentPeriodEnd *time.Time
CreditBalance int
CompaniesOnAccount int
}
Usage is the plan behind the company and how much of it the current period has used. The numbers are the paying account's, shared by every company it holds; CompaniesOnAccount says whether that sharing is real. Prices and CreditBalance are in cents.
Received invoices: the first IncludedReceived a month come with every plan, then each costs ReceivedPriceCents from the account credit. ReceivedFree is true for the accounts exempt from that charge.
func (*Usage) UnmarshalJSON ¶ added in v0.18.0
type ValidationFinding ¶ added in v0.24.0
type ValidationFinding struct {
Code string `json:"code"`
Field string `json:"field"`
Message string `json:"message"`
SefazRejection string `json:"sefaz_rejection"`
Expected string `json:"expected"`
Received string `json:"received"`
FixURL string `json:"fix_url"`
}
ValidationFinding is one refusal or blocker found by Validate. Field is the request path of the offending value, empty for a blocker of the company itself.
type ValidationResult ¶ added in v0.24.0
type ValidationResult struct {
Valid bool `json:"valid"`
Errors []ValidationFinding `json:"errors"`
Warnings []ValidationWarning `json:"warnings"`
}
ValidationResult is what Validate answers. Valid is false when Errors is not empty.
type ValidationWarning ¶ added in v0.24.0
type ValidationWarning struct {
Code string `json:"code"`
Message string `json:"message"`
Field string `json:"field"`
}
ValidationWarning is a default the issuance would declare for the company.
type WebhookEndpoint ¶ added in v0.19.0
type WebhookEndpoint struct {
// URL must be https://, at most 500 characters. The API also refuses
// one that points at a private network.
URL string
// Secret signs every delivery, 16 to 255 characters. It is never
// returned again, so keep it.
Secret string
// Events narrows what is sent, from WebhookEvents. Left nil, the
// endpoint receives every event.
Events []string
}
WebhookEndpoint is an endpoint as Create takes it.
type Webhooks ¶ added in v0.19.0
type Webhooks struct {
// contains filtered or unexported fields
}
Webhooks manages where the company's events are delivered (/webhooks).
It is company data: WithCompany and ForCompany pick the company. An endpoint receives the events of the credential's own environment only. On an OAuth credential every call needs webhook:manage; an API key has it.
func NewWebhooks ¶ added in v0.19.0
func (*Webhooks) Create ¶ added in v0.19.0
func (w *Webhooks) Create(endpoint WebhookEndpoint) (map[string]any, error)
Create registers an HTTPS endpoint for this company's events.
func (*Webhooks) Delete ¶ added in v0.19.0
Delete stops delivery to one endpoint, keeping what was already sent. An id this company does not have is an *APIError 404.
func (*Webhooks) Deliveries ¶ added in v0.19.0
Deliveries lists every delivery attempt in the credential's environment, a page. Each row has the event, its status, attempts, the endpoint's response_status, last_error and when it was delivered or will be tried again.
func (*Webhooks) ForCompany ¶ added in v0.19.0
ForCompany returns a copy of the client bound to another company, for the calls chained on it. The receiver is left as it was.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cancel_invoice
command
|
|
|
consult_invoice
command
|
|
|
lookup_fiscal_reference
command
|
|
|
lookup_taxpayer
command
|
|
|
nfe/basic
command
|
|
|
nfe/full
command
|
|
|
nfe/icms_isento
command
|
|
|
nfe/imported
command
|
|
|
nfe/interstate_with_icms_dest
command
|
|
|
nfe/scale_manufactured
command
|
|
|
nfe/taxed_icms
command
|
|
|
nfe/unit_price
command
|
|
|
nfe/used_asset
command
|
|
|
nfe/with_barcode
command
|
|
|
nfe/with_extra_charges
command
|
|
|
nfe/with_purchase_order
command
|
|
|
nfe/with_quantity
command
|
|
|
nfe/with_tax_benefit
command
|
|
|
nfse/basic
command
|
|
|
nfse/full
command
|
|
|
nfse/with_discount
command
|
|
|
nfse/with_observations
command
|
|
|
nfse/with_service_code
command
|
|
|
nfse/with_tax_retained
command
|
|
|
reissue_invoice
command
|