ksef

package module
v0.42.0 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2026 License: Apache-2.0 Imports: 19 Imported by: 0

README

GOBL ↔ KSeF Conversion

Bidirectional conversion between GOBL and the Polish FA_VAT XML format (KSeF).

Main Conversion Entrypoints

GOBL → KSeF:

  • ksef.BuildFavat(env *gobl.Envelope) (*Invoice, error) - Converts a GOBL envelope to a KSeF FA_VAT invoice model
  • (*Invoice).Bytes() ([]byte, error) - Returns the XML representation as bytes

KSeF → GOBL:

  • ksef.ParseKSeF(xmlData []byte) (*gobl.Envelope, error) - Converts KSeF FA_VAT XML to a GOBL envelope

Copyright Invopop Ltd. 2023. Released publicly under the Apache License Version 2.0. For commercial licenses please contact the dev team at invopop. In order to accept contributions to this library we will require transferring copyrights to Invopop Ltd.

Supported Features

The converter handles the following invoice types and features:

Invoice types (GOBL → KSeF):

  • VAT - Standard invoices
  • ZAL - Advance/prepayment invoices (tag: partial)
  • ROZ - Settlement invoices (tag: settlement)
  • UPR - Simplified invoices (tag: simplified)
  • KOR - Correction invoices (credit notes)
  • KOR_ZAL - Correction of advance invoices
  • KOR_ROZ - Correction of settlement invoices

Parties:

  • Seller (Podmiot1) with Polish NIP, address, contact details, and EU VAT prefix
  • Buyer (Podmiot2) with Polish NIP, EU VAT number, or non-EU tax ID
  • Third parties (Podmiot3) for JST (local government units) and Group VAT scenarios

Tax rates:

  • Standard (23%), reduced (8%), super-reduced (5%), and other percentage rates
  • Zero-rated (0 KR), intra-community (0 WDT), export (0 EX)
  • Tax exempt (zw), outside scope (np I), reverse charge (np II), domestic reverse charge (oo)
  • OSS (One Stop Shop) rates
  • Margin scheme rates

Annotations:

  • Cash accounting, self-billing, reverse charge, split payment mechanism
  • Tax exemption with legal basis (Polish law, EU directive, or other)
  • Margin scheme (travel agency, used goods, art works, collectibles/antiques)

Other features:

  • Line item discounts
  • Invoice periods (P_6_Od / P_6_Do)
  • Correction/credit note references with KSeF numbers
  • Payment details: means of payment, bank accounts, due dates, advance payments
  • Additional description lines (DodatkowyOpis)
  • Ordering data with order references and order lines (Zamowienie / WarunkiTransakcji)
  • Rounding adjustments to reconcile KSeF and GOBL totals
  • Gross pricing (P_9B) support in KSeF → GOBL direction
  • Credit notes with before/after correction lines (StanPrzed)
  • Prepayment invoices without line items (bypass mode with totals from tax summaries)

CLI

The gobl.ksef CLI provides two commands:

  • convert - Convert a GOBL JSON envelope into a FA_VAT XML document:

    gobl.ksef convert input.json output.xml
    
  • send - Convert and send a GOBL JSON envelope to the KSeF API:

    gobl.ksef send input.json [nip] [token] [keyPath]
    

Testing

The test suite includes tests for both conversion directions and round-trip validation.

Running Tests

Run all tests:

go test ./test -v

Update golden files:

go test ./test --update -v

With XSD schema validation (requires libxml2):

# Using the helper script (sets LD_LIBRARY_PATH automatically)
./test/test.sh -v
./test/test.sh --update -v

# Or manually
LD_LIBRARY_PATH=/home/linuxbrew/.linuxbrew/opt/libxml2/lib:$LD_LIBRARY_PATH go test -tags xsdvalidate ./test -v
Test Data

GOBL → KSeF conversion:

  • Input: GOBL JSON files in test/data/gobl.ksef/*.json
  • Output: KSeF XML files in test/data/gobl.ksef/out/*.xml

KSeF → GOBL conversion:

  • Input: KSeF XML files in test/data/ksef.gobl/*.xml
  • Output: GOBL JSON files in test/data/ksef.gobl/out/*.json

Schema validation:

  • Schema: FA3 XSD and dependencies in test/data/schema/

Unsupported fields

See unsupported-fields.md for the list of unsupported fields.

FA_VAT documentation

FA_VAT is the Polish electronic invoice format. The format uses XML.

Parsing (KSeF → GOBL)

The parsing functionality converts KSeF FA_VAT XML documents back into GOBL format. The implementation includes:

  • Party conversion: Converts seller (Podmiot1), buyer (Podmiot2), and third parties (Podmiot3) to GOBL parties
  • Invoice data: Parses invoice metadata including type, codes, dates, currency, and annotations
  • Line items: Converts FA_VAT line items (FaWiersz) to GOBL invoice lines, including discounts and tax combos
  • Credit notes: Handles line inversion for correction invoices, including before/after correction lines (StanPrzed)
  • Gross pricing: Supports invoices using gross unit prices (P_9B) by setting PricesInclude = VAT
  • Ordering data: Maps Zamowienie (order) and WarunkiTransakcji (transaction conditions) to GOBL ordering purchases
  • Payment details: Extracts payment means, bank accounts, due dates, and advance payments
  • Prepayment invoices: Handles advance invoices without line items (ZAL/KOR_ZAL) using bypass mode with totals from tax summary fields
  • Settlement invoices: Derives advance payments for ROZ/KOR_ROZ invoices (see below)
  • Rounding adjustments: Handles rounding differences between KSeF and GOBL calculation methods
  • Round-trip validation: All GOBL → KSeF conversions are validated through round-trip tests (GOBL → KSeF → GOBL)

Settlement Invoices (ROZ)

Settlement invoices (ROZ) finalize orders that had advance payments (ZAL invoices). Per Art. 106f sec. 3 of the Polish VAT Act, they must show the full order value in line items (FaWiersz) while P_15 contains only the remaining amount after advance deductions. The advance invoice references appear in FakturaZaliczkowa elements.

This creates a structural mismatch: GOBL calculates Payable from line items (full amount), but P_15 is the remaining balance. For example, an order worth 68,363.40 PLN with a 13,672.68 PLN advance would have lines totalling 68,363.40 but P_15 = 54,690.72.

KSeF → GOBL: The converter detects settlement invoices with FakturaZaliczkowa references and no explicit ZaplataCzesciowa (partial payment) entries, and derives the advance amount as Payable - P_15. This produces a natural GOBL invoice where lines represent the full order, advances represent prepaid amounts, and Due equals the remaining balance. When explicit ZaplataCzesciowa entries are present (as in some ERP systems), those are used directly and no derivation occurs.

GOBL → KSeF: When a settlement invoice has advances, the converter prorates the tax summary fields (P_13_X/P_14_X) by the ratio Due / Payable so they reflect only the remaining amounts. Advance ref values are mapped to FakturaZaliczkowa elements. Lines and ZaplataCzesciowa entries are emitted unchanged.

KSeF API

KSeF is the Polish system for submitting electronic invoices to the Polish authorities. The system uses API version 2.0, which introduced JWT-based authentication, mandatory invoice encryption, and a unified session model.

Useful links:

KSeF provides three environments:

Environment Description API Documentation
Test (Release Candidate) For testing integration, contains RC versions api-test.ksef.mf.gov.pl
Demo (Pre-production) Matches production configuration, for final validation api-demo.ksef.mf.gov.pl
Production Full legal validity, production data api.ksef.mf.gov.pl

The OpenAPI specification is available at each environment's /docs/v2/openapi.json endpoint.

Authentication

See authentication.md.

Documentation

Overview

Package ksef implements the conversion from GOBL to FA_VAT XML

Package ksef implements conversion between GOBL documents and KSeF formats, including the Polish FA_VAT XML invoice document.

Index

Constants

View Source
const (
	XSINamespace    = "http://www.w3.org/2001/XMLSchema-instance"
	XSDNamespace    = "http://www.w3.org/2001/XMLSchema"
	XMLNamespace    = "http://crd.gov.pl/wzor/2025/06/25/13775/"
	RootElementName = "Faktura"
)

Constants for KSeF XML

Variables

This section is empty.

Functions

func AdjustRounding added in v0.9.0

func AdjustRounding(inv *bill.Invoice, ksefTotalDue string) error

AdjustRounding checks and, if needed, adjusts the rounding in the GOBL invoice to match the KSEF total amount. KSEF calculates totals by rounding each line and then summing, which can lead to a mismatch with the total amount in GOBL.

func MaxRoundingError added in v0.9.0

func MaxRoundingError(inv *bill.Invoice) num.Amount

MaxRoundingError returns the maximum error that can be attributed to rounding in an invoice. It calculates 1 of the smallest subunit of the currency per line.

func ParseKSeF added in v0.9.0

func ParseKSeF(xmlData []byte) (*gobl.Envelope, error)

ParseKSeF converts a KSeF FA_VAT XML document into a GOBL envelope.

func ParsePaymentMeansCode added in v0.9.0

func ParsePaymentMeansCode(code string) cbc.Key

ParsePaymentMeansCode converts KSEF payment means code to GOBL payment key.

func SetTimeNow added in v0.12.0

func SetTimeNow(fn func() time.Time)

SetTimeNow overrides the function used to get the current time. This is intended for use in tests to produce deterministic output.

Types

type AdditionalDescriptionLine added in v0.6.0

type AdditionalDescriptionLine struct {
	LineNumber string `xml:"NrWiersza,omitempty"`
	Key        string `xml:"Klucz"`
	Value      string `xml:"Wartosc"`
}

AdditionalDescriptionLine defines the XML structure for KSeF additional description line (`DodatkowyOpis`)

type Address

type Address struct {
	CountryCode string `xml:"KodKraju"`
	AddressL1   string `xml:"AdresL1,omitempty"`
	AddressL2   string `xml:"AdresL2,omitempty"`
	GLN         string `xml:"GLN,omitempty"` // Global Location Number
}

Address defines the XML structure for KSeF addresses

type AdvanceInvoiceRef added in v0.8.0

type AdvanceInvoiceRef struct {
	KSeFMarker           int    `xml:"NrKSeFZN,omitempty"`
	AdvanceInvoiceNo     string `xml:"NrFaZaliczkowej,omitempty"`
	KSeFAdvanceInvoiceNo string `xml:"NrKSeFFaZaliczkowej,omitempty"`
}

AdvanceInvoiceRef defines the XML structure for advance invoice reference

type AdvancePayment

type AdvancePayment struct {
	PaymentAmount          string `xml:"KwotaZaplatyCzesciowej,omitempty"`
	PaymentDate            string `xml:"DataZaplatyCzesciowej,omitempty"`
	PaymentMean            string `xml:"FormaPlatnosci,omitempty"`
	OtherPaymentMeanMarker int    `xml:"PlatnoscInna,omitempty"`
	OtherPaymentMean       string `xml:"OpisPlatnosci,omitempty"`
}

AdvancePayment defines the XML structure for KSeF advance payments

type Annotations

type Annotations struct {
	CashAccounting                      string             `xml:"P_16"`
	SelfBilling                         string             `xml:"P_17"`
	ReverseCharge                       string             `xml:"P_18"`
	SplitPaymentMechanism               string             `xml:"P_18A"`
	TaxExemption                        *TaxExemption      `xml:"Zwolnienie,omitempty"`
	NewTransportMeans                   *NewTransportMeans `xml:"NoweSrodkiTransportu,omitempty"`
	SimplifiedProcedureBySecondTaxpayer string             `xml:"P_23"`
	MarginScheme                        *MarginScheme      `xml:"PMarzy,omitempty"`
}

Annotations defines the XML structure for KSeF annotations

type AuthorizedEntity added in v0.8.0

type AuthorizedEntity struct {
	EORI                  string   `xml:"NrEORI,omitempty"`
	NIP                   string   `xml:"DaneIdentyfikacyjne>NIP"`
	Name                  string   `xml:"DaneIdentyfikacyjne>Nazwa"`
	Address               *Address `xml:"Adres"`
	CorrespondenceAddress *Address `xml:"AdresKoresp,omitempty"`
	Email                 string   `xml:"DaneKontaktowe>EmailPU,omitempty"`
	Phone                 string   `xml:"DaneKontaktowe>TelefonPU,omitempty"`
	Role                  int      `xml:"RolaPU"` // 1=enforcement authority, 2=court bailiff, 3=tax representative
}

AuthorizedEntity defines the XML structure for KSeF authorized entity (PodmiotUpowazniony)

type BankAccount

type BankAccount struct {
	AccountNumber         string `xml:"NrRB"`
	SWIFT                 string `xml:"SWIFT,omitempty"`
	BankSelfAccountMarker int    `xml:"RachunekWlasnyBanku,omitempty"` // enum - 1,2,3, not sure what exactly they mean
	BankName              string `xml:"NazwaBanku,omitempty"`
	AccountDescription    string `xml:"OpisRachunku,omitempty"`
}

BankAccount defines the XML structure for KSeF bank accounts

type Buyer

type Buyer struct {
	NIP string `xml:"DaneIdentyfikacyjne>NIP,omitempty"`
	// or
	UECode      string `xml:"DaneIdentyfikacyjne>KodUE,omitempty"`   // Country code when in European Union
	UEVatNumber string `xml:"DaneIdentyfikacyjne>NrVatUE,omitempty"` // EU VAT number
	// or
	CountryCode string `xml:"DaneIdentyfikacyjne>KodKraju,omitempty"` // Country code outside European Union
	IDNumber    string `xml:"DaneIdentyfikacyjne>NrID,omitempty"`     // Tax ID number outside European Union
	// or
	NoID int `xml:"DaneIdentyfikacyjne>BrakID,omitempty"`

	Name                  string          `xml:"DaneIdentyfikacyjne>Nazwa,omitempty"`
	BuyerID               string          `xml:"IDNabywcy,omitempty"`
	EORI                  string          `xml:"NrEORI,omitempty"`
	Address               *Address        `xml:"Adres,omitempty"`
	CorrespondenceAddress *Address        `xml:"AdresKoresp,omitempty"`
	Contact               *ContactDetails `xml:"DaneKontaktowe,omitempty"`
	CustomerNumber        string          `xml:"NrKlienta,omitempty"`

	JST string `xml:"JST"` // JST (Jednostka Samorządu Terytorialnego = local government unit) 1 = Yes, 2 = No
	GV  string `xml:"GV"`  // GV (Group VAT) 1 = Yes, 2 = No
}

Buyer defines the XML structure for KSeF buyer

func NewFavatBuyer added in v0.8.0

func NewFavatBuyer(customer *org.Party) *Buyer

NewFavatBuyer converts a GOBL Party into a KSeF buyer

func (*Buyer) ToGOBL added in v0.9.0

func (b *Buyer) ToGOBL() *org.Party

ToGOBL converts a KSEF Buyer to a GOBL Party (customer).

type Carrier added in v0.8.0

type Carrier struct {
	IdentificationData *Buyer   `xml:"DaneIdentyfikacyjne"`
	Address            *Address `xml:"AdresPrzewoznika"`
}

Carrier defines the XML structure for carrier information

type ChargeOrDeduction added in v0.8.0

type ChargeOrDeduction struct {
	Amount string `xml:"Kwota"`
	Reason string `xml:"Powod"`
}

ChargeOrDeduction defines the XML structure for a single charge or deduction

type ContactDetails

type ContactDetails struct {
	Email string `xml:"Email,omitempty"`
	Phone string `xml:"Telefon,omitempty"`
}

ContactDetails defines the XML structure for KSeF contact

type Contract added in v0.8.0

type Contract struct {
	Date   string `xml:"DataUmowy"`
	Number string `xml:"NrUmowy"`
}

Contract defines the XML structure for contract reference

type CorrectedInv

type CorrectedInv struct {
	IssueDate           string   `xml:"DataWystFaKorygowanej,omitempty"`
	SequentialNumber    string   `xml:"NrFaKorygowanej,omitempty"`
	CorrectionPeriod    string   `xml:"OkresFaKorygowanej,omitempty"`
	CorrectedInvoiceNo  string   `xml:"NrFaKorygowany,omitempty"`
	KsefNumberPresent   int      `xml:"NrKSeF,omitempty"`
	NoKsefNumberPresent int      `xml:"NrKSeFN,omitempty"`
	KsefNumber          string   `xml:"NrKSeFFaKorygowanej,omitempty"`
	CorrectedSeller     *Seller  `xml:"Podmiot1K,omitempty"`
	CorrectedBuyer      []*Buyer `xml:"Podmiot2K,omitempty"`
}

CorrectedInv defines the XML structure for KSeF correction invoice

func NewCorrectedInv

func NewCorrectedInv(prc *org.DocumentRef) *CorrectedInv

NewCorrectedInv gets credit note data from GOBL invoice

type Discount

type Discount struct {
	Conditions string `xml:"WarunkiSkonta,omitempty"`
	Amount     string `xml:"WysokoscSkonta,omitempty"`
}

Discount defines the XML structure for KSeF early payment discount

type DueDate

type DueDate struct {
	Date            string           `xml:"Termin,omitempty"`
	TermDescription *TermDescription `xml:"TerminOpis,omitempty"`
}

DueDate defines the XML structure for KSeF due date

type FormCode

type FormCode struct {
	SystemCode    string `xml:"kodSystemowy,attr"`
	SchemaVersion string `xml:"wersjaSchemy,attr"`
	FormCode      string `xml:",chardata"`
}

FormCode defines the XML structure for KSeF schema versioning

type Header struct {
	FormCode     *FormCode `xml:"KodFormularza"`
	FormVariant  int       `xml:"WariantFormularza"`
	CreationDate string    `xml:"DataWytworzeniaFa"`
	SystemInfo   string    `xml:"SystemInfo,omitempty"`
}

Header defines the XML structure for KSeF header

func NewFavatHeader added in v0.8.0

func NewFavatHeader() *Header

NewFavatHeader gets header data from GOBL invoice

type Inv

type Inv struct {
	CurrencyCode                       string                       `xml:"KodWaluty"`
	IssueDate                          string                       `xml:"P_1"`
	IssuePlace                         string                       `xml:"P_1M,omitempty"`
	SequentialNumber                   string                       `xml:"P_2"`
	WarehouseDocuments                 []string                     `xml:"WZ,omitempty"`
	CompletionDate                     string                       `xml:"P_6,omitempty"`
	Period                             *InvoicePeriod               `xml:"OkresFa,omitempty"`
	StandardRateNetSale                string                       `xml:"P_13_1,omitempty"`
	StandardRateTax                    string                       `xml:"P_14_1,omitempty"`
	StandardRateTaxConvertedToPln      string                       `xml:"P_14_1W,omitempty"`
	ReducedRateNetSale                 string                       `xml:"P_13_2,omitempty"`
	ReducedRateTax                     string                       `xml:"P_14_2,omitempty"`
	ReducedRateTaxConvertedToPln       string                       `xml:"P_14_2W,omitempty"`
	SuperReducedRateNetSale            string                       `xml:"P_13_3,omitempty"`
	SuperReducedRateTax                string                       `xml:"P_14_3,omitempty"`
	SuperReducedRateTaxConvertedToPln  string                       `xml:"P_14_3W,omitempty"`
	TaxiRateNetSale                    string                       `xml:"P_13_4,omitempty"`
	TaxiRateTax                        string                       `xml:"P_14_4,omitempty"`
	TaxiRateTaxConvertedToPln          string                       `xml:"P_14_4W,omitempty"`
	OSSNetSale                         string                       `xml:"P_13_5,omitempty"`
	OSSTax                             string                       `xml:"P_14_5,omitempty"`
	ZeroTaxExceptIntraCommunityNetSale string                       `xml:"P_13_6_1,omitempty"`
	IntraCommunityNetSale              string                       `xml:"P_13_6_2,omitempty"`
	ExportNetSale                      string                       `xml:"P_13_6_3,omitempty"`
	TaxExemptNetSale                   string                       `xml:"P_13_7,omitempty"`
	OutsideScopeNetSale                string                       `xml:"P_13_8,omitempty"`
	ReverseChargeNetSale               string                       `xml:"P_13_9,omitempty"`
	DomesticReverseChargeNetSale       string                       `xml:"P_13_10,omitempty"`
	MarginNetSale                      string                       `xml:"P_13_11,omitempty"`
	TotalAmountDue                     string                       `xml:"P_15"`
	ExchangeRate                       string                       `xml:"KursWalutyZ,omitempty"`
	AmountBeforeCorrection             string                       `xml:"P_15ZK,omitempty"`
	Annotations                        *Annotations                 `xml:"Adnotacje"`
	InvoiceType                        string                       `xml:"RodzajFaktury"`
	CorrectionReason                   string                       `xml:"PrzyczynaKorekty,omitempty"`
	CorrectionType                     string                       `xml:"TypKorekty,omitempty"`
	CorrectedInv                       []*CorrectedInv              `xml:"DaneFaKorygowanej,omitempty"`
	AdvanceInvoices                    []*AdvanceInvoiceRef         `xml:"FakturaZaliczkowa,omitempty"`
	PartialAdvancePayments             []*PartialAdvancePayment     `xml:"ZaliczkaCzesciowa,omitempty"`
	FP                                 int                          `xml:"FP,omitempty"`
	TP                                 int                          `xml:"TP,omitempty"`
	ExciseTaxRefund                    int                          `xml:"ZwrotAkcyzy,omitempty"`
	AdditionalDescription              []*AdditionalDescriptionLine `xml:"DodatkowyOpis,omitempty"`
	Lines                              []*Line                      `xml:"FaWiersz,omitempty"` // empty for ZAL and KOR_ZAL, use Order instead
	Settlement                         *Settlement                  `xml:"Rozliczenie,omitempty"`
	Payment                            *Payment                     `xml:"Platnosc,omitempty"`
	TransactionConditions              *TransactionConditions       `xml:"WarunkiTransakcji,omitempty"`
	Order                              *Order                       `xml:"Zamowienie,omitempty"` // for ZAL and KOR_ZAL types
}

Inv defines the XML structure for KSeF invoice

func NewFavatInv added in v0.8.0

func NewFavatInv(invoice *bill.Invoice) *Inv

NewFavatInv gets invoice data from GOBL invoice

type Invoice

type Invoice struct {
	XMLName      xml.Name
	XSINamespace string        `xml:"xmlns:xsi,attr"`
	XSDNamespace string        `xml:"xmlns:xsd,attr"`
	XMLNamespace string        `xml:"xmlns,attr"`
	Header       *Header       `xml:"Naglowek"`
	Seller       *Seller       `xml:"Podmiot1"`
	Buyer        *Buyer        `xml:"Podmiot2"`
	ThirdParties []*ThirdParty `xml:"Podmiot3,omitempty"` // third party (up to 100)
	Inv          *Inv          `xml:"Fa"`
}

Invoice is a pseudo-model for containing the XML document being created

func BuildFavat added in v0.8.0

func BuildFavat(env *gobl.Envelope) (*Invoice, error)

BuildFavat converts a GOBL envelope into a KSeF FA_VAT invoice document.

func (*Invoice) Bytes

func (d *Invoice) Bytes() ([]byte, error)

Bytes returns the XML representation of the document in bytes

func (*Invoice) ToGOBL added in v0.9.0

func (d *Invoice) ToGOBL() (*bill.Invoice, error)

ToGOBL converts the KSeF Invoice to a GOBL invoice. If an error occurs during parsing, the invoice is still returned with any successfully parsed fields populated, allowing callers to access partial data.

type InvoicePeriod added in v0.7.0

type InvoicePeriod struct {
	StartDate string `xml:"P_6_Od,omitempty"`
	EndDate   string `xml:"P_6_Do,omitempty"`
}

type Line

type Line struct {
	LineNumber              int    `xml:"NrWierszaFa"`
	UniqueID                string `xml:"UU_ID,omitempty"`
	CompletionDate          string `xml:"P_6A,omitempty"`
	Name                    string `xml:"P_7,omitempty"`
	InternalCode            string `xml:"Indeks,omitempty"`
	GTIN                    string `xml:"GTIN,omitempty"`
	PKWiU                   string `xml:"PKWiU,omitempty"`
	CN                      string `xml:"CN,omitempty"`
	PKOB                    string `xml:"PKOB,omitempty"`
	Measure                 string `xml:"P_8A,omitempty"`
	Quantity                string `xml:"P_8B,omitempty"`
	NetUnitPrice            string `xml:"P_9A,omitempty"`
	GrossUnitPrice          string `xml:"P_9B,omitempty"`
	Discount                string `xml:"P_10,omitempty"`
	NetPriceTotal           string `xml:"P_11,omitempty"`
	GrossPriceTotal         string `xml:"P_11A,omitempty"`
	VATAmount               string `xml:"P_11Vat,omitempty"`
	VATRate                 string `xml:"P_12,omitempty"`
	OSSTaxRate              string `xml:"P_12_XII,omitempty"` // one stop shop
	Attachment15GoodsMarker int    `xml:"P_12_Zal_15,omitempty"`
	ExciseDuty              string `xml:"KwotaAkcyzy,omitempty"`
	SpecialGoodsCode        string `xml:"GTU,omitempty"` // values GTU_01 to GTU_13
	Procedure               string `xml:"Procedura,omitempty"`
	CurrencyRate            string `xml:"KursWaluty,omitempty"`
	BeforeCorrectionMarker  int    `xml:"StanPrzed,omitempty"`
}

Line defines the XML structure for KSeF item line (element type FaWiersz, for VAT and KOR type invoices)

func NewLines deprecated

func NewLines(lines []*bill.Line) []*Line

NewLines generates lines for the KSeF invoice assuming net-priced lines (P_9A/P_11).

Deprecated: prefer NewLinesForInvoice, which honors tax.prices_include=VAT and emits gross fields (P_9B/P_11A, art. 106e(7)-(8)) for gross-priced invoices.

func NewLinesForInvoice added in v0.35.0

func NewLinesForInvoice(invoice *bill.Invoice) []*Line

NewLinesForInvoice generates KSeF lines from a GOBL invoice, choosing between net (P_9A/P_11) and gross (P_9B/P_11A) line fields based on invoice.Tax.PricesInclude.

func (*Line) ToGOBL added in v0.9.0

func (l *Line) ToGOBL() (*bill.Line, error)

ToGOBL converts a KSEF Line to a GOBL Line.

type MarginScheme added in v0.8.0

type MarginScheme struct {
	Marker                        string `xml:"P_PMarzy,omitempty"`
	TravelAgencyMargin            string `xml:"P_PMarzy_2,omitempty"`
	UsedGoodsMargin               string `xml:"P_PMarzy_3_1,omitempty"`
	ArtWorksMargin                string `xml:"P_PMarzy_3_2,omitempty"`
	CollectiblesAndAntiquesMargin string `xml:"P_PMarzy_3_3,omitempty"`
	NoMarginScheme                string `xml:"P_PMarzyN,omitempty"`
}

MarginScheme defines the XML structure for margin scheme

type NewTransportMeans added in v0.8.0

type NewTransportMeans struct {
	Marker                 int                      `xml:"P_22,omitempty"`
	Art42Obligation        string                   `xml:"P_42_5,omitempty"`
	NewTransportMeansItems []*NewTransportMeansItem `xml:"NowySrodekTransportu,omitempty"`
	NoNewTransportMeans    string                   `xml:"P_22N,omitempty"`
}

NewTransportMeans defines the XML structure for new means of transport

type NewTransportMeansItem added in v0.8.0

type NewTransportMeansItem struct {
	FirstUseDate       string `xml:"P_22A"`
	LineNumber         int    `xml:"P_NrWierszaNST"`
	Brand              string `xml:"P_22BMK,omitempty"`
	Model              string `xml:"P_22BMD,omitempty"`
	Color              string `xml:"P_22BK,omitempty"`
	RegistrationNumber string `xml:"P_22BNR,omitempty"`
	ProductionYear     string `xml:"P_22BRP,omitempty"`
	// For land vehicles
	Mileage       string `xml:"P_22B,omitempty"`
	VIN           string `xml:"P_22B1,omitempty"`
	BodyNumber    string `xml:"P_22B2,omitempty"`
	ChassisNumber string `xml:"P_22B3,omitempty"`
	FrameNumber   string `xml:"P_22B4,omitempty"`
	VehicleType   string `xml:"P_22BT,omitempty"`
	// For watercraft
	OperatingHoursWater string `xml:"P_22C,omitempty"`
	HullNumber          string `xml:"P_22C1,omitempty"`
	// For aircraft
	OperatingHoursAir string `xml:"P_22D,omitempty"`
	FactoryNumber     string `xml:"P_22D1,omitempty"`
}

NewTransportMeansItem defines details for a single new transport means item

type Order added in v0.6.0

type Order struct {
	OrderAmount string       `xml:"WartoscZamowienia"`
	LineItems   []*OrderLine `xml:"ZamowienieWiersz,omitempty"`
}

Order defines the XML structure for KSeF "Zamowienie" (order) field, required for ZAL and KOR_ZAL types

type OrderLine added in v0.6.0

type OrderLine struct {
	LineNumber              int    `xml:"NrWierszaZam"`
	UniqueID                string `xml:"UU_IDZ,omitempty"`
	Name                    string `xml:"P_7Z,omitempty"`
	InternalCode            string `xml:"IndeksZ,omitempty"`
	GTIN                    string `xml:"GTINZ,omitempty"`
	PKWiU                   string `xml:"PKWiUZ,omitempty"`
	CN                      string `xml:"CNZ,omitempty"`
	PKOB                    string `xml:"PKOBZ,omitempty"`
	Measure                 string `xml:"P_8AZ,omitempty"`
	Quantity                string `xml:"P_8BZ,omitempty"`
	NetUnitPrice            string `xml:"P_9AZ,omitempty"`
	NetPriceTotal           string `xml:"P_11NettoZ,omitempty"`
	TaxValue                string `xml:"P_11VatZ,omitempty"`
	VATRate                 string `xml:"P_12Z,omitempty"`
	OSSTaxRate              string `xml:"P_12Z_XII,omitempty"` // one stop shop
	Attachment15GoodsMarker int    `xml:"P_12Z_Zal_15,omitempty"`
	SpecialGoodsCode        string `xml:"GTUZ,omitempty"` // values GTU_01 to GTU_13
	Procedure               string `xml:"ProceduraZ,omitempty"`
	ExciseDuty              string `xml:"KwotaAkcyzyZ,omitempty"`
	BeforeCorrectionMarker  int    `xml:"StanPrzedZ,omitempty"`
}

OrderLine defines the XML structure for KSeF item line (element type ZamowienieWiersz, for ZAL and KOR_ZAL type invoices)

type OrderRef added in v0.8.0

type OrderRef struct {
	Date   string `xml:"DataZamowienia,omitempty"`
	Number string `xml:"NrZamowienia"`
}

OrderRef defines the XML structure for order reference

type PartialAdvancePayment added in v0.8.0

type PartialAdvancePayment struct {
	PaymentDate          string `xml:"P_6Z"`
	PaymentAmount        string `xml:"P_15Z"`
	CurrencyExchangeRate string `xml:"KursWalutyZW,omitempty"`
}

PartialAdvancePayment defines the XML structure for partial advance payment (ZaliczkaCzesciowa)

type Payment

type Payment struct {
	PaidMarker             string            `xml:"Zaplacono,omitempty"`
	PaymentDate            string            `xml:"DataZaplaty,omitempty"`
	PartiallyPaidMarker    string            `xml:"ZnacznikZaplatyCzesciowej,omitempty"`
	AdvancePayments        []*AdvancePayment `xml:"ZaplataCzesciowa,omitempty"`
	DueDates               []*DueDate        `xml:"TerminPlatnosci,omitempty"`
	PaymentMean            string            `xml:"FormaPlatnosci,omitempty"` // enum: 1 = cash, 2 = card etc. (see KSeF documentation)
	OtherPaymentMeanMarker string            `xml:"PlatnoscInna,omitempty"`
	OtherPaymentMean       string            `xml:"OpisPlatnosci,omitempty"`
	BankAccounts           []*BankAccount    `xml:"RachunekBankowy,omitempty"`
	FactorBankAccounts     []*BankAccount    `xml:"RachunekBankowyFaktora,omitempty"`
	Discount               *Discount         `xml:"Skonto,omitempty"`
	PaymentLink            string            `xml:"LinkDoPlatnosci,omitempty"`
	KSeFPaymentID          string            `xml:"IPKSeF,omitempty"`
}

Payment defines the XML structure for KSeF payment

func NewPayment

func NewPayment(pay *bill.PaymentDetails, totals *bill.Totals) *Payment

NewPayment gets payment data from GOBL invoice

type RoundingError added in v0.10.0

type RoundingError struct {
	Calculated num.Amount
	Expected   num.Amount
	Diff       num.Amount
	MaxAllowed num.Amount
}

RoundingError indicates that the total calculated from the GOBL invoice does not match the total reported by KSeF, and the difference is larger than what can be attributed to rounding. When this error is returned, the inv parameter passed to AdjustRounding has had the difference applied as a rounding adjustment anyway, allowing callers to use it despite the warning.

func (*RoundingError) Error added in v0.10.0

func (e *RoundingError) Error() string

type Seller

type Seller struct {
	VATPrefix             string          `xml:"PrefiksPodatnika,omitempty"`
	NIP                   string          `xml:"DaneIdentyfikacyjne>NIP"`
	Name                  string          `xml:"DaneIdentyfikacyjne>Nazwa"`
	EORI                  string          `xml:"NrEORI,omitempty"`
	Address               *Address        `xml:"Adres"`
	CorrespondenceAddress *Address        `xml:"AdresKoresp,omitempty"`
	Contact               *ContactDetails `xml:"DaneKontaktowe,omitempty"`
	TaxpayerStatus        int             `xml:"StatusInfoPodatnika,omitempty"` // 1=liquidation, 2=restructuring, 3=bankruptcy, 4=inheritance
}

Seller defines the XML structure for KSeF seller

func NewFavatSeller added in v0.8.0

func NewFavatSeller(supplier *org.Party) *Seller

NewFavatSeller converts a GOBL Party into a KSeF seller

func (*Seller) ToGOBL added in v0.9.0

func (s *Seller) ToGOBL() *org.Party

ToGOBL converts a KSEF Seller to a GOBL Party (supplier).

type Settlement added in v0.8.0

type Settlement struct {
	Charges         []*ChargeOrDeduction `xml:"Obciazenia,omitempty"`
	TotalCharges    string               `xml:"SumaObciazen,omitempty"`
	Deductions      []*ChargeOrDeduction `xml:"Odliczenia,omitempty"`
	TotalDeductions string               `xml:"SumaOdliczen,omitempty"`
	AmountToPay     string               `xml:"DoZaplaty,omitempty"`
	AmountToSettle  string               `xml:"DoRozliczenia,omitempty"`
}

Settlement defines the XML structure for the additional charges and deductions block (Rozliczenie). Per the FA(3) schema, each <Obciazenia> and <Odliczenia> is itself a single entry (with <Kwota>/<Powod> children, maxOccurs=100), and <SumaObciazen>/<SumaOdliczen> are siblings of those entries — not nested wrappers.

type TaxExemption added in v0.8.0

type TaxExemption struct {
	Marker           string `xml:"P_19,omitempty"`
	PolishLawBasis   string `xml:"P_19A,omitempty"`
	EUDirectiveBasis string `xml:"P_19B,omitempty"`
	OtherLegalBasis  string `xml:"P_19C,omitempty"`
	NoExemption      string `xml:"P_19N,omitempty"`
}

TaxExemption defines the XML structure for tax exemption details

type TaxRateInfo added in v0.9.0

type TaxRateInfo struct {
	Key         cbc.Key
	Rate        cbc.Key
	Percent     *num.Percentage
	TaxCategory cbc.Code
}

TaxRateInfo contains the parsed tax rate information

type TermDescription added in v0.8.0

type TermDescription struct {
	Quantity      int    `xml:"Ilosc"`
	Unit          string `xml:"Jednostka"`
	StartingEvent string `xml:"ZdarzeniePoczatkowe"`
}

TermDescription defines alternative payment term description

type ThirdParty added in v0.8.0

type ThirdParty struct {
	BuyerID               string          `xml:"IDNabywcy,omitempty"`
	EORI                  string          `xml:"NrEORI,omitempty"`
	NIP                   string          `xml:"DaneIdentyfikacyjne>NIP,omitempty"`
	InternalID            string          `xml:"DaneIdentyfikacyjne>IDWew,omitempty"`
	UECode                string          `xml:"DaneIdentyfikacyjne>KodUE,omitempty"`
	UEVatNumber           string          `xml:"DaneIdentyfikacyjne>NrVatUE,omitempty"`
	CountryCode           string          `xml:"DaneIdentyfikacyjne>KodKraju,omitempty"`
	IDNumber              string          `xml:"DaneIdentyfikacyjne>NrID,omitempty"`
	NoID                  int             `xml:"DaneIdentyfikacyjne>BrakID,omitempty"`
	Name                  string          `xml:"DaneIdentyfikacyjne>Nazwa,omitempty"`
	Address               *Address        `xml:"Adres,omitempty"`
	CorrespondenceAddress *Address        `xml:"AdresKoresp,omitempty"`
	Contact               *ContactDetails `xml:"DaneKontaktowe,omitempty"`
	Role                  string          `xml:"Rola,omitempty"`     // TRolaPodmiotu3: 1-11
	OtherRole             int             `xml:"RolaInna,omitempty"` // 1 for other role
	OtherRoleDescription  string          `xml:"OpisRoli,omitempty"` // description when OtherRole=1
	Share                 string          `xml:"Udzial,omitempty"`   // percentage share
	CustomerNumber        string          `xml:"NrKlienta,omitempty"`
}

ThirdParty defines the XML structure for KSeF third party (Podmiot3)

func NewThirdParties added in v0.8.0

func NewThirdParties(invoice *bill.Invoice) []*ThirdParty

type TransactionConditions added in v0.8.0

type TransactionConditions struct {
	Contracts         []*Contract  `xml:"Umowy,omitempty"`
	Orders            []*OrderRef  `xml:"Zamowienia,omitempty"`
	BatchNumbers      []string     `xml:"NrPartiiTowaru,omitempty"`
	DeliveryTerms     string       `xml:"WarunkiDostawy,omitempty"`
	ContractRate      string       `xml:"KursUmowny,omitempty"`
	ContractCurrency  string       `xml:"WalutaUmowna,omitempty"`
	Transport         []*Transport `xml:"Transport,omitempty"`
	IntermediaryParty int          `xml:"PodmiotPosredniczacy,omitempty"`
}

TransactionConditions defines the XML structure for transaction conditions

type Transport added in v0.8.0

type Transport struct {
	TransportType        string     `xml:"RodzajTransportu,omitempty"`
	OtherTransportType   int        `xml:"TransportInny,omitempty"`
	OtherTransportDesc   string     `xml:"OpisInnegoTransportu,omitempty"`
	Carrier              *Carrier   `xml:"Przewoznik,omitempty"`
	TransportOrderNumber string     `xml:"NrZleceniaTransportu,omitempty"`
	CargoType            string     `xml:"OpisLadunku,omitempty"`
	OtherCargoType       int        `xml:"LadunekInny,omitempty"`
	OtherCargoDesc       string     `xml:"OpisInnegoLadunku,omitempty"`
	PackagingUnit        string     `xml:"JednostkaOpakowania,omitempty"`
	TransportStartTime   string     `xml:"DataGodzRozpTransportu,omitempty"`
	TransportEndTime     string     `xml:"DataGodzZakTransportu,omitempty"`
	ShipFrom             *Address   `xml:"WysylkaZ,omitempty"`
	ShipVia              []*Address `xml:"WysylkaPrzez,omitempty"`
	ShipTo               *Address   `xml:"WysylkaDo,omitempty"`
}

Transport defines the XML structure for transport information

Directories

Path Synopsis
api
Package api used for communication with the KSeF API
Package api used for communication with the KSeF API
cmd
gobl.ksef command
Package main provides a CLI interface for the library
Package main provides a CLI interface for the library
Package test provides tools for testing the library
Package test provides tools for testing the library

Jump to

Keyboard shortcuts

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