diff --git a/ChangeLog.md b/ChangeLog.md
new file mode 100644
--- /dev/null
+++ b/ChangeLog.md
@@ -0,0 +1,23 @@
+# Changelog for exchangealgebra-einvoice
+
+## 0.1.0.0 - 2026-11-27
+
+### Added
+
+- First version. `parseInvoice` reads one UBL 2.1 `Invoice` in the JP PINT 1.1
+  billing profile and checks what a journal entry needs: the document totals,
+  the tax categories and rates, the tax amount of each category, and the form of
+  the seller registration number. It is not a full JP PINT validator. An invoice
+  outside the version 0.1 scope (a currency other than JPY, document-level
+  allowances or charges, prepaid or rounding amounts, tax-inclusive line prices,
+  or a `BillingReference`) is rejected, never read in part. Structural errors
+  stop reading; consistency errors are reported together.
+- `invoiceTerms` lists the terms of one invoice for the buyer's or the seller's
+  books, under tax-exclusive or tax-inclusive accounting. A function supplied by
+  the caller builds the base of each term, so the base may carry the tax rate or
+  the counterparty besides the account. A negative amount becomes a term on the
+  opposite side, so every value is non-negative, and terms with the same base
+  are kept as separate terms.
+- `invoiceJournal` builds one balanced entry from those terms. It rejects an
+  amount that the value type cannot hold exactly and an account that does not
+  accept an ordinary journal posting.
diff --git a/LICENSE.txt b/LICENSE.txt
new file mode 100644
--- /dev/null
+++ b/LICENSE.txt
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2026 Kaya Akagi
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/exchangealgebra-einvoice.cabal b/exchangealgebra-einvoice.cabal
new file mode 100644
--- /dev/null
+++ b/exchangealgebra-einvoice.cabal
@@ -0,0 +1,70 @@
+cabal-version: 1.18
+
+-- This file has been generated from package.yaml by hpack version 0.39.6.
+--
+-- see: https://github.com/sol/hpack
+
+name:           exchangealgebra-einvoice
+version:        0.1.0.0
+synopsis:       Read UBL e-invoices (JP PINT) into exchange algebra journals
+description:    Reads Japanese qualified invoices in the JP PINT profile of UBL 2.1 and turns each invoice into one balanced exchange algebra entry. The caller supplies the function that builds the base of each term, so the base may have elements other than the account, such as the tax rate or the counterparty. Tax-exclusive and tax-inclusive accounting are both supported.
+category:       Accounting, Finance
+homepage:       https://github.com/yakagika/ExchangeAlgebra#readme
+bug-reports:    https://github.com/yakagika/ExchangeAlgebra/issues
+author:         Kaya Akagi
+maintainer:     yakagika@icloud.com
+copyright:      2026 Kaya Akagi
+license:        MIT
+license-file:   LICENSE.txt
+build-type:     Simple
+extra-doc-files:
+    ChangeLog.md
+
+source-repository head
+  type: git
+  location: https://github.com/yakagika/ExchangeAlgebra
+
+library
+  exposed-modules:
+      ExchangeAlgebra.IO.Input.EInvoice
+      ExchangeAlgebra.IO.Input.EInvoice.Document
+      ExchangeAlgebra.IO.Input.EInvoice.Journal
+  other-modules:
+      Paths_exchangealgebra_einvoice
+  hs-source-dirs:
+      src
+  ghc-options: -Wall
+  build-depends:
+      base >=4.19 && <5
+    , bytestring >=0.11 && <0.13
+    , containers >=0.6 && <0.8
+    , exchangealgebra ==0.7.*
+    , text >=2.0 && <2.2
+    , time >=1.12 && <1.15
+    , xml-conduit >=1.9.1 && <1.11
+  default-language: Haskell2010
+
+test-suite exchangealgebra-einvoice-test
+  type: exitcode-stdio-1.0
+  main-is: Spec.hs
+  other-modules:
+      DocumentSpec
+      InvoiceFixture
+      JournalSpec
+      TestSupport
+      Paths_exchangealgebra_einvoice
+  hs-source-dirs:
+      test
+  ghc-options: -Wall
+  build-depends:
+      QuickCheck >=2.14 && <3
+    , base >=4.19 && <5
+    , bytestring >=0.11 && <0.13
+    , containers >=0.6 && <0.8
+    , exchangealgebra ==0.7.*
+    , exchangealgebra-einvoice
+    , hashable >=1.4 && <1.6
+    , text >=2.0 && <2.2
+    , time >=1.12 && <1.15
+    , xml-conduit >=1.9.1 && <1.11
+  default-language: Haskell2010
diff --git a/src/ExchangeAlgebra/IO/Input/EInvoice.hs b/src/ExchangeAlgebra/IO/Input/EInvoice.hs
new file mode 100644
--- /dev/null
+++ b/src/ExchangeAlgebra/IO/Input/EInvoice.hs
@@ -0,0 +1,59 @@
+{- |
+Module      : ExchangeAlgebra.IO.Input.EInvoice
+Description : Read JP PINT e-invoices into exchange algebra entries.
+
+Role: the entry point of the package. Reading an invoice and building its
+entry are separate steps, so the checked 'Invoice' can be inspected or used
+with several base functions.
+
+Layer: IO (input), outside the core package @exchangealgebra@, which this
+package depends on through public modules only.
+
+What a user writes: a base type with an @ExBaseClass (HatBase k)@ instance
+whose account type has an @AccountVocabulary@ instance, and one function
+@Invoice -> TermRole -> k@ for the side of the books in use. Then:
+
+> case parseInvoice bytes of
+>     Left errors   -> reportInvoiceErrors errors
+>     Right invoice -> either reportJournalError useEntry (invoiceJournal spec invoice)
+-}
+module ExchangeAlgebra.IO.Input.EInvoice
+    ( -- * Reading
+      Invoice
+    , InvoiceError(..)
+    , parseInvoice
+      -- * Invoice contents used by a base function
+    , InvoiceLine(..)
+    , TaxSubtotal(..)
+    , TaxCategory(..)
+    , TaxCategoryCode(..)
+    , Percent(..)
+    , Amount(..)
+      -- * Building entries
+    , InvoiceJournalSpec(..)
+    , BookSide(..)
+    , TaxAccounting(..)
+    , TermRole(..)
+    , InvoiceJournalError(..)
+    , invoiceJournal
+    ) where
+
+import ExchangeAlgebra.IO.Input.EInvoice.Document
+    ( Amount(..)
+    , Invoice
+    , InvoiceError(..)
+    , InvoiceLine(..)
+    , Percent(..)
+    , TaxCategory(..)
+    , TaxCategoryCode(..)
+    , TaxSubtotal(..)
+    , parseInvoice
+    )
+import ExchangeAlgebra.IO.Input.EInvoice.Journal
+    ( BookSide(..)
+    , InvoiceJournalError(..)
+    , InvoiceJournalSpec(..)
+    , TaxAccounting(..)
+    , TermRole(..)
+    , invoiceJournal
+    )
diff --git a/src/ExchangeAlgebra/IO/Input/EInvoice/Document.hs b/src/ExchangeAlgebra/IO/Input/EInvoice/Document.hs
new file mode 100644
--- /dev/null
+++ b/src/ExchangeAlgebra/IO/Input/EInvoice/Document.hs
@@ -0,0 +1,690 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+{- |
+Module      : ExchangeAlgebra.IO.Input.EInvoice.Document
+Description : Checked invoice documents read from JP PINT UBL XML.
+
+Role: the reading boundary for e-invoices. 'parseInvoice' reads one UBL 2.1
+@Invoice@ in the JP PINT 1.1 profile and checks the conditions that a journal
+entry needs; an 'Invoice' value exists only after these checks, so later
+stages do not repeat them. It is not a full JP PINT validator: conformance to
+every rule of the profile is the job of the official validation artifacts.
+
+Layer: IO (input). Depends on xml-conduit and on no exchange algebra module.
+"ExchangeAlgebra.IO.Input.EInvoice.Journal" turns an 'Invoice' into terms.
+
+Read order: 'parseInvoice', then 'InvoiceError' for what is rejected, then the
+accessors of 'Invoice'.
+
+Scope of version 0.1 (an invoice outside it is rejected, never read in part):
+
+* root element @Invoice@, @CustomizationID@ and @ProfileID@ of the JP PINT
+  billing profile (aligned-ibrp-001-jp, -002-jp), @InvoiceTypeCode@ 380
+  (aligned-ibrp-cl-02-jp);
+* document currency JPY, so one @TaxTotal@ suffices (a foreign-currency
+  qualified invoice needs a second @TaxTotal@ in JPY);
+* no @TaxIncludedIndicator@ true, no document-level @AllowanceCharge@, and
+  @AllowanceTotalAmount@, @ChargeTotalAmount@, @PrepaidAmount@ and
+  @PayableRoundingAmount@ absent or zero (line-level allowances and charges are
+  inside the line amount);
+* no @BillingReference@. An invoice that refers to a preceding invoice either
+  replaces it (a corrected invoice issued in full, JP PINT specification,
+  Example 6) or adds to it (a negative invoice, specification 2.3.8), and the
+  document has no element that tells which. Booking a replacement as an
+  independent entry counts the purchase twice; reversing the preceding entry
+  needs the preceding invoice, which one document does not contain. A negative
+  invoice without a reference is read;
+* the seller tax identifier (the @CompanyID@ of the @PartyTaxScheme@ whose
+  scheme is @VAT@) present as @T@ and 13 ASCII digits. aligned-ibr-jp-01
+  requires this form only for periods from 2023-10-01; version 0.1 requires it
+  always. The form is checked, not the registration itself.
+
+Amounts are signed: a negative invoice (specification 1.4, 1.5.2) keeps its
+signs here. The sign becomes the debit or credit side in the journal stage, so
+no negative value reaches an exchange algebra term.
+-}
+module ExchangeAlgebra.IO.Input.EInvoice.Document
+    ( -- * Checked invoices
+      Invoice
+    , invoiceIdentifier
+    , invoiceIssueDate
+    , invoicePeriod
+    , invoiceSeller
+    , invoiceBuyer
+    , invoiceLines
+    , invoiceTaxSubtotals
+    , invoiceTotals
+      -- * Components
+    , Seller(..)
+    , Buyer(..)
+    , Period(..)
+    , InvoiceLine(..)
+    , TaxSubtotal(..)
+    , TaxCategory(..)
+    , TaxCategoryCode(..)
+    , MonetaryTotal(..)
+    , Amount(..)
+    , Percent(..)
+    , RegistrationNumber
+    , registrationNumberText
+      -- * Reading UBL XML
+    , InvoiceError(..)
+    , ElementPath(..)
+    , TotalRule(..)
+    , parseInvoice
+    ) where
+
+import           Control.Monad (guard, unless, when)
+import qualified Data.ByteString.Lazy as LBS
+import           Data.Foldable (traverse_)
+import           Data.List.NonEmpty (NonEmpty)
+import qualified Data.List.NonEmpty as NE
+import qualified Data.Map.Strict as Map
+import           Data.Maybe (catMaybes, isJust)
+import           Data.Ratio ((%))
+import qualified Data.Set as Set
+import           Data.Text (Text)
+import qualified Data.Text as T
+import           Data.Time (Day, fromGregorianValid)
+import qualified Text.XML as XML
+import           Text.XML.Stream.Parse (psIgnoreInternalEntityDeclarations)
+
+-- | A signed monetary amount in JPY, exact as written.
+newtype Amount = Amount Rational
+    deriving (Eq, Ord, Show)
+
+-- | A tax rate in percent, exact as written (for example 10, 8, or 1).
+newtype Percent = Percent Rational
+    deriving (Eq, Ord, Show)
+
+-- | A qualified invoice issuer registration number: @T@ followed by 13 ASCII
+-- digits. Only 'parseInvoice' constructs it.
+newtype RegistrationNumber = RegistrationNumber Text
+    deriving (Eq, Ord, Show)
+
+-- | The registration number as written in the invoice.
+registrationNumberText :: RegistrationNumber -> Text
+registrationNumberText (RegistrationNumber number) = number
+
+-- | Japanese tax category codes (codelist Aligned-TaxCategoryCodes, rule
+-- aligned-ibrp-cl-01-jp). The code does not fix the rate: the rate is the
+-- separate 'categoryPercent'.
+data TaxCategoryCode
+    = StandardRate      -- ^ @S@
+    | LowerRate         -- ^ @AA@
+    | Exempt            -- ^ @E@
+    | FreeExportItem    -- ^ @G@
+    | OutsideScope      -- ^ @O@
+    deriving (Eq, Ord, Show)
+
+-- | A tax category: the code and the rate. Every code except @O@ has a rate
+-- (aligned-ibrp-048); @E@ and @G@ have rate 0 (aligned-ibrp-e-05, g-05); @O@
+-- has none (aligned-ibrp-o-05). One tax breakdown exists per distinct category
+-- (specification 4.3.1).
+data TaxCategory = TaxCategory
+    { categoryCode    :: TaxCategoryCode
+    , categoryPercent :: Maybe Percent
+    }
+    deriving (Eq, Ord, Show)
+
+-- | The seller. A qualified invoice always names the registration number.
+data Seller = Seller
+    { sellerName         :: Text
+    , sellerRegistration :: RegistrationNumber
+    }
+    deriving (Eq, Show)
+
+-- | The buyer.
+newtype Buyer = Buyer
+    { buyerName :: Text
+    }
+    deriving (Eq, Show)
+
+-- | An invoice period or a line period. For a qualified invoice the period
+-- carries the transaction date, which may differ from the issue date.
+data Period = Period
+    { periodStart :: Maybe Day
+    , periodEnd   :: Maybe Day
+    }
+    deriving (Eq, Show)
+
+-- | One invoice line.
+data InvoiceLine = InvoiceLine
+    { lineIdentifier  :: Text
+    , lineItemName    :: Text
+    , linePeriod      :: Maybe Period
+    , lineAmount      :: Amount       -- ^ @LineExtensionAmount@, net of line allowances and charges
+    , lineTaxCategory :: TaxCategory  -- ^ @Item/ClassifiedTaxCategory@
+    }
+    deriving (Eq, Show)
+
+-- | One tax breakdown of the @TaxTotal@.
+data TaxSubtotal = TaxSubtotal
+    { subtotalCategory      :: TaxCategory
+    , subtotalTaxableAmount :: Amount
+    , subtotalTaxAmount     :: Amount
+    }
+    deriving (Eq, Show)
+
+-- | Document totals (@LegalMonetaryTotal@ and the @TaxTotal@ amount).
+data MonetaryTotal = MonetaryTotal
+    { totalLineExtension :: Amount
+    , totalTaxExclusive  :: Amount
+    , totalTax           :: Amount
+    , totalTaxInclusive  :: Amount
+    , totalPayable       :: Amount
+    }
+    deriving (Eq, Show)
+
+-- | A checked invoice. The constructor is not exported: every value comes
+-- from 'parseInvoice' and satisfies the laws stated there.
+data Invoice = Invoice
+    { documentIdentifier   :: Text
+    , documentIssueDate    :: Day
+    , documentPeriod       :: Maybe Period
+    , documentSeller       :: Seller
+    , documentBuyer        :: Buyer
+    , documentLines        :: NonEmpty InvoiceLine
+    , documentTaxSubtotals :: NonEmpty TaxSubtotal
+    , documentTotals       :: MonetaryTotal
+    }
+    deriving (Eq, Show)
+
+-- | @cbc:ID@ of the invoice.
+invoiceIdentifier :: Invoice -> Text
+invoiceIdentifier = documentIdentifier
+
+-- | @cbc:IssueDate@.
+invoiceIssueDate :: Invoice -> Day
+invoiceIssueDate = documentIssueDate
+
+-- | @cac:InvoicePeriod@ of the document. Either it or a line period exists
+-- (aligned-ibrp-052).
+invoicePeriod :: Invoice -> Maybe Period
+invoicePeriod = documentPeriod
+
+-- | @cac:AccountingSupplierParty@.
+invoiceSeller :: Invoice -> Seller
+invoiceSeller = documentSeller
+
+-- | @cac:AccountingCustomerParty@.
+invoiceBuyer :: Invoice -> Buyer
+invoiceBuyer = documentBuyer
+
+-- | Invoice lines in document order.
+invoiceLines :: Invoice -> NonEmpty InvoiceLine
+invoiceLines = documentLines
+
+-- | Tax breakdowns in document order, one per distinct 'TaxCategory'.
+invoiceTaxSubtotals :: Invoice -> NonEmpty TaxSubtotal
+invoiceTaxSubtotals = documentTaxSubtotals
+
+-- | Document totals.
+invoiceTotals :: Invoice -> MonetaryTotal
+invoiceTotals = documentTotals
+
+-- | Local names from the document root to an element, for error reports.
+newtype ElementPath = ElementPath [Text]
+    deriving (Eq, Show)
+
+-- | Totals rules. The first five are those of PINT-UBL-validation without
+-- allowances, charges, prepaid amount, or rounding amount, compared as those
+-- rules compare; the last one is exact.
+data TotalRule
+    = LineExtensionRule  -- ^ ibr-co-10: line extension total = sum of line amounts
+    | TaxExclusiveRule   -- ^ ibr-co-13: tax exclusive total = line extension total
+    | TaxTotalRule       -- ^ ibr-co-14: tax total = sum of breakdown tax amounts
+    | TaxInclusiveRule   -- ^ ibr-co-15: tax inclusive = tax exclusive + tax total
+    | PayableRule        -- ^ ibr-co-16: payable = tax inclusive
+    | ExactBalanceRule
+      -- ^ sum of line amounts + sum of breakdown tax amounts = payable, unrounded
+    deriving (Eq, Show)
+
+-- | Why an invoice is rejected. Classification: external input rejected at
+-- the reading boundary. Structural errors stop the reading; the consistency
+-- errors from 'TotalMismatch' on are reported together.
+data InvoiceError
+    = MalformedXml Text                           -- ^ xml-conduit could not read the bytes
+    | UnsupportedDocument Text                    -- ^ root other than UBL @Invoice@
+    | UnsupportedSpecification ElementPath Text   -- ^ @CustomizationID@ or @ProfileID@
+    | UnsupportedTypeCode Text                    -- ^ @InvoiceTypeCode@ other than 380
+    | UnsupportedCurrency ElementPath Text        -- ^ currency code or @currencyID@ not JPY
+    | MissingElement ElementPath
+    | RepeatedElement ElementPath
+    | UnsupportedElement ElementPath              -- ^ present but outside version 0.1
+    | InvalidDecimal ElementPath Text
+    | InvalidDate ElementPath Text
+    | UnknownTaxCategory ElementPath Text
+    | InvalidRegistrationNumber Text
+    | DecimalTaxAmount ElementPath Text
+      -- ^ a JPY tax amount written with a decimal point (aligned-ibr-jp-06)
+    | TotalMismatch TotalRule Amount Amount       -- ^ stated, computed
+    | TaxAmountOutOfRange TaxSubtotal             -- ^ aligned-ibrp-051-jp, specification 4.3.1
+    | InvalidPercentForCategory TaxCategory       -- ^ aligned-ibrp-048, e-05, g-05, o-05
+    | DuplicateSubtotal TaxCategory
+    | LineCategoryWithoutSubtotal TaxCategory
+    | SubtotalWithoutLines TaxCategory
+    | TaxableAmountMismatch TaxCategory Amount Amount
+      -- ^ stated taxable amount, sum of the category's line amounts (specification 4.3.1)
+    deriving (Eq, Show)
+
+-- | Keep the path with each element so nested checks report their location.
+data Located = Located ElementPath XML.Element
+
+-- | Result of reading one part of the XML document.
+type ReadInvoice a = Either InvoiceError a
+
+-- | Read the structure and values used by the consistency checks.
+readInvoice :: XML.Element -> ReadInvoice (Invoice, Bool)
+readInvoice root = do
+    unless (name == XML.Name "Invoice" (Just invoiceNamespace) Nothing)
+        (Left (UnsupportedDocument (XML.nameLocalName name)))
+    checkSpecification "CustomizationID" customization input
+    checkSpecification "ProfileID" profile input
+    kind <- requiredText (cbc "InvoiceTypeCode") input
+    unless (kind == "380") (Left (UnsupportedTypeCode kind))
+    required (cbc "DocumentCurrencyCode") input >>= checkCurrencyCode
+    optional (cbc "TaxCurrencyCode") input >>= traverse_ checkCurrencyCode
+    rejectPresent (cac "AllowanceCharge") input
+    rejectPresent (cac "BillingReference") input
+    identifier   <- requiredText (cbc "ID") input
+    issueDate    <- required (cbc "IssueDate") input >>= readDate
+    period       <- optional (cac "InvoicePeriod") input >>= traverse readPeriod
+    supplier     <- required (cac "AccountingSupplierParty") input >>= required (cac "Party")
+    customer     <- required (cac "AccountingCustomerParty") input >>= required (cac "Party")
+    seller       <- readSeller supplier
+    buyer        <- Buyer <$> partyName customer
+    linesInOrder <- requiredMany (cac "InvoiceLine") input >>= traverse readLine
+    unless (any (isJust . linePeriod) linesInOrder || isJust period)
+        (Left (MissingElement (childPath (cac "InvoicePeriod") input)))
+    tax <- required (cac "TaxTotal") input
+    optional (cbc "TaxIncludedIndicator") tax >>= traverse_ checkTaxIncluded
+    taxAmount    <- required (cbc "TaxAmount") tax >>= readMoney
+    subtotals    <- requiredMany (cac "TaxSubtotal") tax >>= traverse readSubtotal
+    legal        <- required (cac "LegalMonetaryTotal") input
+    hasAllowance <- checkZeroAmount legal "AllowanceTotalAmount"
+    hasCharge    <- checkZeroAmount legal "ChargeTotalAmount"
+    traverse_ (checkZeroAmount legal) ["PrepaidAmount", "PayableRoundingAmount"]
+    totals <- MonetaryTotal
+        <$> (required (cbc "LineExtensionAmount") legal >>= readMoney)
+        <*> (required (cbc "TaxExclusiveAmount") legal >>= readMoney)
+        <*> pure taxAmount
+        <*> (required (cbc "TaxInclusiveAmount") legal >>= readMoney)
+        <*> (required (cbc "PayableAmount") legal >>= readMoney)
+    pure (Invoice identifier issueDate period seller buyer linesInOrder subtotals totals,
+          hasAllowance || hasCharge)
+  where
+    name = (XML.elementName root) { XML.namePrefix = Nothing }
+    input = Located (ElementPath ["Invoice"]) root
+
+    customization :: Text -> Bool
+    customization value = any (`T.isPrefixOf` value)
+        ["urn:fdc:peppol:jp:billing:3.0", "urn:peppol:pint:billing-1@jp-1"]
+
+    profile :: Text -> Bool
+    profile value = any (`T.isInfixOf` value)
+        ["urn:fdc:peppol.eu:2017:poacc:billing:01:1.0", "urn:peppol:bis:billing"]
+
+-- | Check a profile identifier using the matching rule for its field.
+checkSpecification :: Text -> (Text -> Bool) -> Located -> ReadInvoice ()
+checkSpecification field matches input = do
+    element <- required (cbc field) input
+    let value = scalar element
+    unless (matches value) (Left (UnsupportedSpecification (location element) value))
+
+-- | Require a currency code element to contain JPY.
+checkCurrencyCode :: Located -> ReadInvoice ()
+checkCurrencyCode element =
+    unless (scalar element == "JPY")
+        (Left (UnsupportedCurrency (location element) (scalar element)))
+
+-- | Accept the XML boolean spellings for a false tax-included indicator.
+checkTaxIncluded :: Located -> ReadInvoice ()
+checkTaxIncluded element =
+    unless (scalar element `elem` ["false", "0"]) (Left (UnsupportedElement (location element)))
+
+-- | Require a zero amount when this optional element is present. Report its presence.
+checkZeroAmount :: Located -> Text -> ReadInvoice Bool
+checkZeroAmount legal field = do
+    element <- optional (cbc field) legal
+    traverse_ check element
+    pure (isJust element)
+  where
+    check :: Located -> ReadInvoice ()
+    check element = do
+        Amount value <- readMoney element
+        unless (value == 0) (Left (UnsupportedElement (location element)))
+
+-- | Read the legal name and the registration number from the VAT scheme.
+readSeller :: Located -> ReadInvoice Seller
+readSeller party = do
+    name    <- partyName party
+    schemes <- traverse vatScheme (children (cac "PartyTaxScheme") party)
+
+    scheme     <- exactlyOne (childPath (cac "PartyTaxScheme") party) (catMaybes schemes)
+    identifier <- required (cbc "CompanyID") scheme
+
+    let value = scalar identifier
+    case T.uncons value of
+        Just ('T', digits) | T.length digits == 13 && T.all asciiDigit digits ->
+            pure (Seller name (RegistrationNumber value))
+        _ -> Left (InvalidRegistrationNumber value)
+
+  where
+    vatScheme :: Located -> ReadInvoice (Maybe Located)
+    vatScheme scheme = do
+        taxScheme <- required (cac "TaxScheme") scheme
+        code      <- requiredText (cbc "ID") taxScheme
+        pure (scheme <$ guard (T.toUpper code == "VAT"))
+
+-- | Read the registered name of a supplier or customer.
+partyName :: Located -> ReadInvoice Text
+partyName party =
+    required (cac "PartyLegalEntity") party >>= requiredText (cbc "RegistrationName")
+
+-- | Read the optional start and end dates of a document or line period.
+readPeriod :: Located -> ReadInvoice Period
+readPeriod element = Period
+    <$> (optional (cbc "StartDate") element >>= traverse readDate)
+    <*> (optional (cbc "EndDate") element >>= traverse readDate)
+
+-- | Read the line net amount and the item classification.
+readLine :: Located -> ReadInvoice InvoiceLine
+readLine element = do
+    identifier <- requiredText (cbc "ID") element
+    amount     <- required (cbc "LineExtensionAmount") element >>= readMoney
+    period     <- optional (cac "InvoicePeriod") element >>= traverse readPeriod
+    item       <- required (cac "Item") element
+    name       <- requiredText (cbc "Name") item
+    category   <- required (cac "ClassifiedTaxCategory") item >>= readCategory
+    pure (InvoiceLine identifier name period amount category)
+
+-- | Read a tax breakdown. Its tax amount must be written without a decimal point.
+readSubtotal :: Located -> ReadInvoice TaxSubtotal
+readSubtotal element = do
+    taxable <- required (cbc "TaxableAmount") element >>= readMoney
+    tax     <- required (cbc "TaxAmount") element
+    checkMoneyCurrency tax
+    let text = scalar tax
+        checkInteger =
+            when (T.any (== '.') text) (Left (DecimalTaxAmount (location tax) text))
+    amount   <- Amount <$> readDecimalWith checkInteger tax
+    category <- required (cac "TaxCategory") element >>= readCategory
+    pure (TaxSubtotal category taxable amount)
+
+-- | Read the category code and its optional rate in percent.
+readCategory :: Located -> ReadInvoice TaxCategory
+readCategory element = do
+    identifier <- required (cbc "ID") element
+    code <- case scalar identifier of
+        "S"   -> Right StandardRate
+        "AA"  -> Right LowerRate
+        "E"   -> Right Exempt
+        "G"   -> Right FreeExportItem
+        "O"   -> Right OutsideScope
+        other -> Left (UnknownTaxCategory (location identifier) other)
+    percent <- optional (cbc "Percent") element >>= traverse (fmap Percent . readDecimal)
+    pure (TaxCategory code percent)
+
+-- | Read a signed amount declared in JPY.
+readMoney :: Located -> ReadInvoice Amount
+readMoney element = checkMoneyCurrency element >> (Amount <$> readDecimal element)
+
+-- | Require a JPY currency attribute on the monetary element being read.
+checkMoneyCurrency :: Located -> ReadInvoice ()
+checkMoneyCurrency (Located path element) =
+    case Map.lookup (XML.Name "currencyID" Nothing Nothing) (XML.elementAttributes element) of
+        Just "JPY"  -> Right ()
+        Just other -> Left (UnsupportedCurrency path other)
+        Nothing    -> Left (MissingElement path)
+
+-- | Read a calendar date in the JP PINT year-month-day form.
+readDate :: Located -> ReadInvoice Day
+readDate element =
+    case T.splitOn "-" value of
+        [year, month, day]
+            | T.length year == 4, T.length month == 2, T.length day == 2
+            , T.all asciiDigit year, T.all asciiDigit month, T.all asciiDigit day
+            , Just date <- fromGregorianValid
+                (digitsValue year) (fromInteger (digitsValue month)) (fromInteger (digitsValue day))
+            -> Right date
+        _ -> Left (InvalidDate (location element) value)
+  where
+    value = scalar element
+
+-- | Read a signed XML Schema decimal as an exact rational.
+readDecimal :: Located -> ReadInvoice Rational
+readDecimal = readDecimalWith (pure ())
+
+-- | Run a lexical check on a valid decimal before constructing its rational value.
+readDecimalWith :: ReadInvoice () -> Located -> ReadInvoice Rational
+readDecimalWith check element
+    | [whole] <- parts, nonemptyDigits whole = check >> pure (valueOf whole "")
+    | [whole, fractional] <- parts
+    , not (T.null whole && T.null fractional)
+    , T.all asciiDigit whole
+    , T.all asciiDigit fractional = check >> pure (valueOf whole fractional)
+    | otherwise = Left (InvalidDecimal (location element) input)
+  where
+    input = scalar element
+    (sign, unsigned) = case T.uncons input of
+        Just ('-', rest) -> (-1, rest)
+        Just ('+', rest) -> (1, rest)
+        _                -> (1, input)
+    parts = T.splitOn "." unsigned
+    nonemptyDigits :: Text -> Bool
+    nonemptyDigits digits = not (T.null digits) && T.all asciiDigit digits
+
+    valueOf :: Text -> Text -> Rational
+    valueOf whole fractional =
+        (sign * digitsValue (whole <> fractional)) % (10 ^ T.length fractional)
+
+-- | Recognize the digits accepted by XML Schema decimal and JP PINT registration numbers.
+asciiDigit :: Char -> Bool
+asciiDigit character = character >= '0' && character <= '9'
+
+-- | Convert validated ASCII digits to an integer. The empty string represents zero.
+digitsValue :: Text -> Integer
+digitsValue = T.foldl' (\value digit -> 10 * value + toInteger (fromEnum digit - fromEnum '0')) 0
+
+-- | Namespace URI of the UBL invoice root.
+invoiceNamespace :: Text
+invoiceNamespace = "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2"
+
+-- | Construct a name in the UBL basic components namespace.
+cbc :: Text -> XML.Name
+cbc local = XML.Name local
+    (Just "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2") Nothing
+
+-- | Construct a name in the UBL aggregate components namespace.
+cac :: Text -> XML.Name
+cac local = XML.Name local
+    (Just "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2") Nothing
+
+-- | Return the local names from the document root to the current element.
+location :: Located -> ElementPath
+location (Located path _) = path
+
+-- | Append a child local name to the path of its parent.
+childPath :: XML.Name -> Located -> ElementPath
+childPath name (Located (ElementPath path) _) = ElementPath (path ++ [XML.nameLocalName name])
+
+-- | Select immediate children by local name and namespace URI.
+children :: XML.Name -> Located -> [Located]
+children name parent@(Located _ element) =
+    [ Located (childPath name parent) child
+    | XML.NodeElement child <- XML.elementNodes element
+    , (XML.elementName child) { XML.namePrefix = Nothing } == name
+    ]
+
+-- | Read a child that must occur exactly once.
+required :: XML.Name -> Located -> ReadInvoice Located
+required name parent = exactlyOne (childPath name parent) (children name parent)
+
+-- | Require one match and report missing or repeated matches at the supplied path.
+exactlyOne :: ElementPath -> [a] -> ReadInvoice a
+exactlyOne path matches = case matches of
+    []      -> Left (MissingElement path)
+    [value] -> Right value
+    _       -> Left (RepeatedElement path)
+
+-- | Read one or more children in document order.
+requiredMany :: XML.Name -> Located -> ReadInvoice (NonEmpty Located)
+requiredMany name parent =
+    maybe (Left (MissingElement (childPath name parent))) Right (NE.nonEmpty (children name parent))
+
+-- | Read a child that can occur once or be absent.
+optional :: XML.Name -> Located -> ReadInvoice (Maybe Located)
+optional name parent = case children name parent of
+    []      -> Right Nothing
+    [value] -> Right (Just value)
+    _       -> Left (RepeatedElement (childPath name parent))
+
+-- | Reject the presence of an element that version 0.1 excludes.
+rejectPresent :: XML.Name -> Located -> ReadInvoice ()
+rejectPresent name parent =
+    unless (null (children name parent)) (Left (UnsupportedElement (childPath name parent)))
+
+-- | Read the text of a required child element.
+requiredText :: XML.Name -> Located -> ReadInvoice Text
+requiredText name parent = scalar <$> required name parent
+
+-- | Read direct text content with leading and trailing XML whitespace removed.
+scalar :: Located -> Text
+scalar (Located _ element) =
+    T.dropAround (`elem` [' ', '\t', '\r', '\n'])
+        (T.concat [content | XML.NodeContent content <- XML.elementNodes element])
+
+-- | Collect all consistency errors after the structure and values have been read.
+consistencyErrors :: Bool -> Invoice -> [InvoiceError]
+consistencyErrors hasAdjustments invoice =
+    totalsErrors hasAdjustments invoice
+    ++ [ TaxAmountOutOfRange subtotal | subtotal <- subtotals, not (validTax subtotal) ]
+    ++ [ InvalidPercentForCategory category
+       | category <- Set.toList (Set.union lineCategories subtotalCategories)
+       , not (validPercent category)
+       ]
+    ++ [ DuplicateSubtotal category | (category, count) <- Map.toList subtotalCounts, count > 1 ]
+    ++ map LineCategoryWithoutSubtotal
+        (Set.toList (Set.difference lineCategories subtotalCategories))
+    ++ map SubtotalWithoutLines
+        (Set.toList (Set.difference subtotalCategories lineCategories))
+    ++ [ TaxableAmountMismatch category taxable (Amount expected)
+       | TaxSubtotal category taxable _ <- subtotals
+       , Just expected <- [Map.lookup category lineSums]
+       , taxable /= Amount expected
+       ]
+  where
+    subtotals = NE.toList (invoiceTaxSubtotals invoice)
+    lineSums = Map.fromListWith (+)
+        [(lineTaxCategory line, value) | line <- NE.toList (invoiceLines invoice)
+                                       , let Amount value = lineAmount line]
+    subtotalCounts = Map.fromListWith (+)
+        [(subtotalCategory subtotal, 1 :: Int) | subtotal <- subtotals]
+    lineCategories     = Map.keysSet lineSums
+    subtotalCategories = Map.keysSet subtotalCounts
+
+-- | Compare stated and computed totals using the five PINT rules and exact balance.
+totalsErrors :: Bool -> Invoice -> [InvoiceError]
+totalsErrors hasAdjustments invoice =
+    [ TotalMismatch rule stated (Amount computed)
+    | (rule, stated, computed) <-
+        [ (LineExtensionRule, totalLineExtension totals, roundMoney linesTotal)
+        , (TaxExclusiveRule, totalTaxExclusive totals, expectedExclusive)
+        , (TaxTotalRule, totalTax totals, roundMoney taxTotal)
+        , (TaxInclusiveRule, totalTaxInclusive totals, roundMoney (exclusive + statedTax))
+        , (PayableRule, totalPayable totals, value (totalTaxInclusive totals))
+        , (ExactBalanceRule, totalPayable totals, linesTotal + taxTotal)
+        ]
+    , stated /= Amount computed
+    ]
+  where
+    totals = invoiceTotals invoice
+    linesTotal = sum (fmap (value . lineAmount) (invoiceLines invoice))
+    taxTotal = sum (fmap (value . subtotalTaxAmount) (invoiceTaxSubtotals invoice))
+    extension = value (totalLineExtension totals)
+    expectedExclusive
+        | hasAdjustments = roundMoney extension
+        | otherwise      = extension
+    exclusive = value (totalTaxExclusive totals)
+    statedTax = value (totalTax totals)
+
+    value :: Amount -> Rational
+    value (Amount amount) = amount
+
+-- | XPath round chooses the integer toward positive infinity at a tie.
+xpathRound :: Rational -> Integer
+xpathRound amount = floor (amount + 1 % 2)
+
+-- | Round a monetary total to two decimal places using XPath tie handling.
+roundMoney :: Rational -> Rational
+roundMoney amount = xpathRound (100 * amount) % 100
+
+-- | Check whether the rate is present and allowed for the category.
+validPercent :: TaxCategory -> Bool
+validPercent (TaxCategory code rate) = case code of
+    OutsideScope    -> rate == Nothing
+    Exempt          -> rate == Just (Percent 0)
+    FreeExportItem  -> rate == Just (Percent 0)
+    StandardRate    -> isJust rate
+    LowerRate       -> isJust rate
+
+-- | Check the signed tax amount against the range for the category and taxable amount.
+validTax :: TaxSubtotal -> Bool
+validTax (TaxSubtotal (TaxCategory code rate) (Amount taxable) (Amount tax))
+    | code /= OutsideScope, Just (Percent percent) <- rate, xpathRound percent /= 0 =
+        let expected = taxable * percent / 100
+        in fromInteger (floor expected) <= tax && tax <= fromInteger (ceiling expected)
+    | otherwise = tax == 0
+
+-- | Read and check one invoice.
+--
+-- Input: the bytes of one XML document. Reading uses the xml-conduit defaults
+-- except that internal entity declarations are ignored: UBL invoices declare
+-- no entities, so a document that relies on one is rejected instead of
+-- expanded; the five predefined XML entities are still decoded. The setting is
+-- fixed so that every caller gets it. Elements are read along paths from the
+-- root, never by descendant search, so a second @TaxTotal@ is seen and rejected
+-- rather than mixed in.
+--
+-- Failure classification: external input rejected at the reading boundary.
+--
+-- Laws (each holds for every @Right invoice@ result; observation by the
+-- accessors of 'Invoice'; exact equality on 'Rational' unless stated):
+--
+-- * Totals. @totalLineExtension@ is the sum of 'lineAmount' (ibr-co-10),
+--   @totalTax@ the sum of 'subtotalTaxAmount' (ibr-co-14),
+--   @totalTaxExclusive == totalLineExtension@,
+--   @totalTaxInclusive == totalTaxExclusive + totalTax@ and
+--   @totalPayable == totalTaxInclusive@, compared as the PINT-UBL-validation
+--   rules compare.
+-- * Exact balance. The sum of 'lineAmount' plus the sum of 'subtotalTaxAmount'
+--   equals @totalPayable@ without rounding. The journal stage relies on this.
+-- * Categories. The categories of the lines and of the breakdowns are the
+--   same set, each breakdown category occurs once, and each breakdown's
+--   'subtotalTaxableAmount' equals the sum of its lines' amounts
+--   (specification 4.3.1 without document-level allowances or charges).
+-- * Rates. 'categoryPercent' is present except for @O@, and is 0 for @E@ and
+--   @G@.
+-- * Tax amount. Each breakdown tax amount is written without a decimal point
+--   (aligned-ibr-jp-06). For a category other than @O@ whose rate @p@ rounds,
+--   half up as XPath @round@ does, to a nonzero integer:
+--   @floor (t * p / 100) <= tax <= ceiling (t * p / 100)@ where @t@ is the
+--   taxable amount (aligned-ibrp-051-jp). Otherwise the tax amount is zero.
+-- * Registration. The seller's registration number matches @T[0-9]{13}@ in
+--   ASCII.
+parseInvoice
+    :: LBS.ByteString
+    -> Either (NonEmpty InvoiceError) Invoice
+parseInvoice bytes = do
+    document <- case XML.parseLBS settings bytes of
+        Left err    -> Left (NE.singleton (MalformedXml (T.pack (show err))))
+        Right value -> Right value
+    (invoice, hasAdjustments) <-
+        either (Left . NE.singleton) Right (readInvoice (XML.documentRoot document))
+    case NE.nonEmpty (consistencyErrors hasAdjustments invoice) of
+        Nothing     -> Right invoice
+        Just errors -> Left errors
+  where
+    settings :: XML.ParseSettings
+    settings = XML.def { psIgnoreInternalEntityDeclarations = True }
diff --git a/src/ExchangeAlgebra/IO/Input/EInvoice/Journal.hs b/src/ExchangeAlgebra/IO/Input/EInvoice/Journal.hs
new file mode 100644
--- /dev/null
+++ b/src/ExchangeAlgebra/IO/Input/EInvoice/Journal.hs
@@ -0,0 +1,332 @@
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE FlexibleContexts #-}
+{-# LANGUAGE TypeFamilies #-}
+{-# LANGUAGE TypeOperators #-}
+
+{- |
+Module      : ExchangeAlgebra.IO.Input.EInvoice.Journal
+Description : One balanced exchange algebra entry per checked invoice.
+
+Role: maps a checked 'Invoice' to terms on the caller's base and builds the
+entry. The caller's function chooses the base of every term, so the base may
+have elements beyond the account (tax rate, counterparty, date).
+
+Layer: IO (input). Depends on "ExchangeAlgebra.IO.Input.EInvoice.Document"
+and on the public exchange algebra modules only.
+
+Read order: 'InvoiceJournalSpec' and 'TermRole', then 'invoiceTerms' (the
+terms with exact amounts, before a value type is chosen), then
+'invoiceJournal'.
+
+Algebra contract: every term's value is positive. The direction of a term is
+its debit or credit side, which becomes the Hat or Not label through
+@journalForSides@; a negative document amount gives a term with the absolute
+value on the opposite side. Terms that share a base stay separate; nothing
+here calls @bar@.
+-}
+module ExchangeAlgebra.IO.Input.EInvoice.Journal
+    ( -- * Specification
+      InvoiceJournalSpec(..)
+    , BookSide(..)
+    , TaxAccounting(..)
+    , TermRole(..)
+      -- * Terms with exact amounts
+    , InvoiceTerm
+    , termRole
+    , termSide
+    , termBase
+    , termAmount
+    , invoiceTerms
+      -- * Entries
+    , InvoiceJournalError(..)
+    , invoiceJournal
+    ) where
+
+import           Data.Bifunctor (first)
+import           Data.List.NonEmpty (NonEmpty)
+import qualified Data.List.NonEmpty as NE
+import qualified Data.Map.Strict as Map
+import           Data.Text (Text)
+import qualified Data.Text as T
+
+import ExchangeAlgebra.Accounting.Account (ProcessingContext(OrdinaryJournal), Side(..))
+import ExchangeAlgebra.Accounting.Exchange
+    ( ExBaseClass(getAccountTitle), TitleOf, journalForSides )
+import ExchangeAlgebra.Algebra.Base (Hat(Not), HatBase((:<)))
+import ExchangeAlgebra.Algebra.Core (Alg)
+import ExchangeAlgebra.Algebra.Value (HatVal(..), Rounding(Nearest))
+import ExchangeAlgebra.IO.Input (ConvErrorOf(UnknownAccount), EntryErrorOf, checkedEntryTextBy)
+import ExchangeAlgebra.IO.Input.EInvoice.Document
+    ( Amount(..)
+    , Invoice
+    , InvoiceLine
+    , MonetaryTotal(totalPayable)
+    , Percent(..)
+    , TaxCategory(categoryPercent)
+    , TaxSubtotal
+    , invoiceLines
+    , invoiceTaxSubtotals
+    , invoiceTotals
+    , lineAmount
+    , lineTaxCategory
+    , subtotalCategory
+    , subtotalTaxAmount
+    )
+
+-- | Whose books the entry is for. The base function must match: for
+-- 'SellerBook' it returns sales, consumption tax received, and accounts
+-- receivable, not the buyer's accounts.
+data BookSide
+    = BuyerBook
+      -- ^ positive line and tax amounts on the debit side, positive payable on
+      -- the credit side
+    | SellerBook
+      -- ^ positive line and tax amounts on the credit side, positive payable on
+      -- the debit side
+    deriving (Eq, Show)
+
+-- | Where a breakdown's tax amount goes. Source: the National Tax Agency
+-- circular 「消費税法等の施行に伴う法人税の取扱いについて」 (直法2-1, 1989-03-01,
+-- last amended 2023-12-27), items 1(7), 1(8), 2, and 3.
+data TaxAccounting
+    = TaxExclusiveAccounting
+      -- ^ on the base the caller gives for 'TaxTerm' (consumption tax paid or
+      -- received)
+    | TaxInclusiveAccounting
+      -- ^ on the base of the breakdown category's lines, as a separate term;
+      -- rejected when a category with a nonzero rate has nonzero-amount lines
+      -- on more than one base, because the invoice gives the tax amount per
+      -- category only (specification 4.3.1)
+    deriving (Eq, Show)
+
+-- | What a term records. The caller's base function receives it.
+data TermRole
+    = LineTerm InvoiceLine      -- ^ the line amount (cost, asset, or sales)
+    | TaxTerm TaxSubtotal       -- ^ the breakdown tax amount, under both 'TaxAccounting' values
+    | SettlementTerm            -- ^ the payable amount (accounts payable or receivable)
+    deriving (Eq, Show)
+
+-- | How to turn an invoice into an entry. Under 'TaxInclusiveAccounting' the
+-- base function is not called with 'TaxTerm'.
+data InvoiceJournalSpec k = InvoiceJournalSpec
+    { specBookSide      :: BookSide
+    , specTaxAccounting :: TaxAccounting
+    , specBase          :: Invoice -> TermRole -> k
+    }
+
+-- | One term before a value type is chosen: an exact, positive amount on a
+-- side of a base. Only 'invoiceTerms' constructs it.
+data InvoiceTerm k = InvoiceTerm
+    { termRoleField   :: TermRole
+    , termSideField   :: Side
+    , termBaseField   :: k
+    , termAmountField :: Rational
+    }
+    deriving (Eq, Show)
+
+-- | Where the term's amount comes from.
+termRole :: InvoiceTerm k -> TermRole
+termRole = termRoleField
+
+-- | 'Debit' or 'Credit'.
+termSide :: InvoiceTerm k -> Side
+termSide = termSideField
+
+-- | The caller's base.
+termBase :: InvoiceTerm k -> k
+termBase = termBaseField
+
+-- | The absolute value of the document amount; greater than zero.
+termAmount :: InvoiceTerm k -> Rational
+termAmount = termAmountField
+
+-- | Put the magnitude of a nonzero amount on the side indicated by its sign.
+signedTerm
+    :: TermRole
+    -> Side
+    -> k
+    -> Rational
+    -> InvoiceTerm k
+signedTerm role positiveSide key amount
+    | amount < 0 = InvoiceTerm role (otherSide positiveSide) key (abs amount)
+    | otherwise  = InvoiceTerm role positiveSide key amount
+
+-- | Swap the debit and credit sides.
+otherSide :: Side -> Side
+otherSide Debit  = Credit
+otherSide Credit = Debit
+otherSide Side   = Side
+
+-- | The terms of an invoice.
+--
+-- Failure classification: a checked operation. @Left@ lists the categories
+-- that 'TaxInclusiveAccounting' cannot place.
+--
+-- Laws (exact equality; observation by the returned list and its accessors):
+--
+-- * Correspondence. Take the source amounts in this order: each line amount
+--   in document order, each breakdown tax amount in document order, the
+--   payable amount. The list has, in the same order, exactly one term for
+--   each nonzero source amount and none for a zero one. That term's
+--   'termRole' names its source ('LineTerm', 'TaxTerm', 'SettlementTerm'),
+--   its 'termAmount' is the absolute value of the source amount, and its
+--   'termBase' is @specBase invoice role@, except that under
+--   'TaxInclusiveAccounting' a 'TaxTerm' has the base shared by the
+--   category's nonzero-amount lines.
+-- * Sides. For 'BuyerBook', a positive line or tax amount gives 'Debit' and a
+--   positive payable gives 'Credit'; a negative source amount gives the other
+--   side. With the same base function, 'SellerBook' gives the same list with
+--   every side swapped.
+-- * Balance. The amounts on 'Debit' and on 'Credit' have equal sums.
+--   Precondition: the exact balance law of 'parseInvoice'.
+-- * Accounting methods agree. The two 'TaxAccounting' values give lists of
+--   the same length whose roles, sides, and amounts agree position by
+--   position; only the bases of 'TaxTerm' terms may differ.
+-- * Zero document. An invoice whose amounts are all zero gives @Right []@.
+invoiceTerms
+    :: Eq k
+    => InvoiceJournalSpec k
+    -> Invoice
+    -> Either (NonEmpty TaxCategory) [InvoiceTerm k]
+invoiceTerms spec invoice =
+    case NE.nonEmpty splitCategories of
+        Just categories -> Left categories
+        Nothing         -> Right (lineTerms ++ taxTerms ++ settlementTerms)
+  where
+    (lineSide, settlementSide) = case specBookSide spec of
+        BuyerBook  -> (Debit, Credit)
+        SellerBook -> (Credit, Debit)
+    lineTerms =
+        [ signedTerm role lineSide (specBase spec invoice role) amount
+        | line <- NE.toList (invoiceLines invoice)
+        , let Amount amount = lineAmount line
+        , amount /= 0
+        , let role = LineTerm line
+        ]
+    subtotals = NE.toList (invoiceTaxSubtotals invoice)
+    basesByCategory = Map.fromListWith (++)
+        [ (lineTaxCategory line, [termBase term])
+        | term <- lineTerms
+        , LineTerm line <- [termRole term]
+        ]
+    categoryBases = flip (Map.findWithDefault []) basesByCategory . subtotalCategory
+    (splitCategories, taxTerms) = case specTaxAccounting spec of
+        TaxExclusiveAccounting -> ([], exclusiveTerms)
+        TaxInclusiveAccounting -> (inclusiveSplits, inclusiveTerms)
+    exclusiveTerms =
+        [ signedTerm role lineSide (specBase spec invoice role) amount
+        | subtotal <- subtotals
+        , let Amount amount = subtotalTaxAmount subtotal
+        , amount /= 0
+        , let role = TaxTerm subtotal
+        ]
+    inclusiveSplits =
+        [ category
+        | subtotal <- subtotals
+        , let category = subtotalCategory subtotal
+        , Just (Percent rate) <- [categoryPercent category]
+        , rate /= 0
+        , key : rest <- [categoryBases subtotal]
+        , any (/= key) rest
+        ]
+    inclusiveTerms =
+        [ signedTerm (TaxTerm subtotal) lineSide key amount
+        | subtotal <- subtotals
+        , let Amount amount = subtotalTaxAmount subtotal
+        , amount /= 0
+        , key : _ <- [categoryBases subtotal]
+        ]
+    settlementTerms =
+        [ signedTerm SettlementTerm settlementSide (specBase spec invoice SettlementTerm) amount
+        | let Amount amount = totalPayable (invoiceTotals invoice)
+        , amount /= 0
+        ]
+
+-- | Why 'invoiceJournal' rejects an invoice.
+data InvoiceJournalError acct v
+    = InclusiveTaxSplit (NonEmpty TaxCategory)
+      -- ^ from 'invoiceTerms'
+    | UnrepresentableAmount Int Rational
+      -- ^ position in 'invoiceTerms' and the amount, which @v@ cannot hold exactly
+    | EntryRejected (NonEmpty (EntryErrorOf acct v))
+      -- ^ from @checkedEntryTextBy@ on the accounts of the bases; the row
+      -- index is the position in 'invoiceTerms'. An all-zero invoice gives
+      -- @EntryRejected (EmptyEntry :| [])@.
+    deriving (Eq, Show)
+
+-- | Convert an amount and reject the row if its exact value changes.
+convertTerm
+    :: HatVal v
+    => (Int, InvoiceTerm k)
+    -> Either (InvoiceJournalError acct v) (Side, k, v)
+convertTerm (index, term)
+    | Just amount <- roundRational Nearest exact
+    , exactAccum (addAccum amount emptyAccum) == Just exact =
+        Right (termSide term, termBase term, amount)
+    | otherwise = Left (UnrepresentableAmount index exact)
+  where
+    exact = termAmount term
+
+-- | Use the zero-based term position as the account resolver key.
+rowKey :: Int -> Text
+rowKey = T.pack . show
+
+-- | Resolve a row key to the account carried by that row's base.
+resolveAccount :: Map.Map Text acct -> Text -> Either (ConvErrorOf acct) acct
+resolveAccount accounts key =
+    maybe (Left (UnknownAccount key)) Right (Map.lookup key accounts)
+
+-- | Spell the side for the checked entry reader.
+sideText :: Side -> Text
+sideText Debit  = "debit"
+sideText Credit = "credit"
+sideText Side   = "side"
+
+-- | Build the entry of an invoice on the caller's base.
+--
+-- Each amount @q@ becomes @x :: v@ when @roundRational Nearest q == Just x@
+-- and @exactAccum (addAccum x emptyAccum) == Just q@; otherwise the invoice
+-- is rejected with 'UnrepresentableAmount' (for 'Double', 0.1 is rejected and
+-- 1.5 is not), so the entry never holds an amount the invoice does not state.
+-- The accounts of the bases (by @getAccountTitle@) are checked with
+-- @checkedEntryTextBy@ in the ordinary journal context.
+--
+-- Failure classification: a checked operation.
+--
+-- Laws (observation by @toList@, @norm@, and @balance@):
+--
+-- * Agreement. On success the entry equals @journalForSides@ of the
+--   'invoiceTerms' list with each amount converted as above; @toList@ of the
+--   entry has one term per element of that list, also when two of them share
+--   a base (@bar@ of the entry merges them, and also cancels opposite terms).
+-- * Balance. @balance@ of the entry is 'True'; exact for every value type,
+--   because the amounts are exact.
+-- * Check agreement. The result is @Left (EntryRejected es)@ exactly when the
+--   terms convert and @checkedEntryTextBy@ rejects them with accounts in
+--   place of bases.
+-- * Not applicable. When the caller's base has an element set that the
+--   settlement does not have (such as the tax rate), the base function should
+--   put the wildcard there, which in a ledger entry means not applicable; a
+--   projection on a concrete value of that element set then omits the
+--   settlement term.
+invoiceJournal
+    :: ( HatVal v
+       , ExBaseClass (HatBase k)
+       , TitleOf (HatBase k) ~ acct
+       , ExBaseClass (HatBase acct)
+       , TitleOf (HatBase acct) ~ acct
+       )
+    => InvoiceJournalSpec k
+    -> Invoice
+    -> Either (InvoiceJournalError acct v) (Alg v (HatBase k))
+invoiceJournal spec invoice = do
+    terms <- first InclusiveTaxSplit (invoiceTerms spec invoice)
+    rows  <- traverse convertTerm (zip [0 ..] terms)
+    let indexed = zip [0 :: Int ..] rows
+        accounts = Map.fromList
+            [(rowKey index, getAccountTitle (Not :< key)) | (index, (_, key, _)) <- indexed]
+        resolve = resolveAccount accounts
+        checkedRows =
+            [(sideText side, rowKey index, amount) | (index, (side, _, amount)) <- indexed]
+    _ <- first EntryRejected (checkedEntryTextBy resolve OrdinaryJournal checkedRows)
+    pure (journalForSides rows)
diff --git a/test/DocumentSpec.hs b/test/DocumentSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/DocumentSpec.hs
@@ -0,0 +1,206 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module DocumentSpec (runTests) where
+
+import qualified Data.List.NonEmpty as NE
+import Data.Ratio (denominator, (%))
+import qualified Data.Set as Set
+import Data.Text (Text)
+import qualified Data.Text as T
+import Test.QuickCheck (forAll)
+
+import ExchangeAlgebra.IO.Input.EInvoice.Document
+import InvoiceFixture
+import TestSupport
+
+-- | Check document laws and examples at the XML reading boundary.
+runTests :: IO ()
+runTests = do
+    checkProperty "parseInvoice / Totals" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let net = sum (map snd (items model))
+                tax = fromInteger (sum [q | (_, _, q) <- breakdown model])
+            in invoiceTotals invoice ==
+                MonetaryTotal (Amount net) (Amount net) (Amount tax)
+                              (Amount (net + tax)) (Amount (net + tax))
+    checkProperty "parseInvoice / Exact balance" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let net = sum (fmap (amountValue . lineAmount) (invoiceLines invoice))
+                tax = sum (fmap (amountValue . subtotalTaxAmount) (invoiceTaxSubtotals invoice))
+            in Amount (net + tax) == totalPayable (invoiceTotals invoice)
+    checkProperty "parseInvoice / Categories" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let rows = NE.toList (invoiceLines invoice)
+                subtotals = NE.toList (invoiceTaxSubtotals invoice)
+                observed = [(lineTaxCategory row, amountValue (lineAmount row)) | row <- rows]
+                codes = map subtotalCategory subtotals
+                sumByCategory code = sum [q | (other, q) <- observed, other == code]
+                matchesSum subtotal = subtotalTaxableAmount subtotal
+                    == Amount (sumByCategory (subtotalCategory subtotal))
+            in observed == items model
+                && Set.fromList (map fst observed) == Set.fromList codes
+                && Set.size (Set.fromList codes) == length codes
+                && all matchesSum subtotals
+    checkProperty "parseInvoice / Rates" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let codes = map lineTaxCategory (NE.toList (invoiceLines invoice))
+                     ++ map subtotalCategory (NE.toList (invoiceTaxSubtotals invoice))
+            in all validRate codes
+    checkProperty "parseInvoice / Tax amount" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let subtotals = NE.toList (invoiceTaxSubtotals invoice)
+                observed = [(subtotalCategory row, amountValue (subtotalTaxableAmount row),
+                             amountValue (subtotalTaxAmount row)) | row <- subtotals]
+                expected = [(category, taxable, fromInteger tax)
+                           | (category, taxable, tax) <- breakdown model]
+            in observed == expected && all validTaxAmount subtotals
+    checkProperty "parseInvoice / Registration" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice ->
+            let number = registrationNumberText (sellerRegistration (invoiceSeller invoice))
+            in number == registration model && T.length number == 14
+                && T.take 1 number == "T"
+                && T.all (\c -> '0' <= c && c <= '9') (T.drop 1 number)
+    rejectionExamples
+    readingExamples
+
+-- | Extract the signed amount in JPY.
+amountValue :: Amount -> Rational
+amountValue (Amount value) = value
+
+-- | Check the rate rules against a parsed category.
+validRate :: TaxCategory -> Bool
+validRate (TaxCategory code rate) = case code of
+    OutsideScope    -> rate == Nothing
+    Exempt          -> rate == Just (Percent 0)
+    FreeExportItem  -> rate == Just (Percent 0)
+    _               -> rate /= Nothing
+
+-- | Check the permitted range and integrality of a parsed tax amount.
+validTaxAmount :: TaxSubtotal -> Bool
+validTaxAmount (TaxSubtotal category (Amount taxable) (Amount tax)) =
+    denominator tax == 1 && case categoryPercent category of
+        Just (Percent rate)
+            | (floor (rate + 1 % 2) :: Integer) /= 0 ->
+                let expected = taxable * rate / 100
+                in tax `elem` map fromInteger [floor expected, ceiling expected]
+        _ -> tax == 0
+
+-- | Exercise every structural and consistency error constructor.
+rejectionExamples :: IO ()
+rejectionExamples = do
+    reject "MalformedXml" "<Invoice>" $ \err -> case err of
+        MalformedXml _ -> True
+        _ -> False
+    reject "UnsupportedDocument" "<Invoice/>" (== UnsupportedDocument "Invoice")
+    reject "UnsupportedSpecification" (change "urn:peppol:pint:billing-1@jp-1" "other") $
+        (== UnsupportedSpecification (ElementPath ["Invoice", "CustomizationID"]) "other")
+    reject "UnsupportedTypeCode" (change ">380<" ">381<") (== UnsupportedTypeCode "381")
+    reject "UnsupportedCurrency" (change "currencyID=\"JPY\">100" "currencyID=\"USD\">100") $
+        \err -> case err of
+            UnsupportedCurrency _ "USD" -> True
+            _ -> False
+    reject "MissingElement" (change "<cbc:IssueDate>2026-01-02</cbc:IssueDate>" "") $
+        (== MissingElement (ElementPath ["Invoice", "IssueDate"]))
+    reject "RepeatedElement" (insertRoot (aggregate "TaxTotal" "")) $
+        (== RepeatedElement (ElementPath ["Invoice", "TaxTotal"]))
+    reject "UnsupportedElement / BillingReference" (insertRoot (aggregate "BillingReference" "")) $
+        (== UnsupportedElement (ElementPath ["Invoice", "BillingReference"]))
+    reject "InvalidDecimal" (change ">100<" ">1e2<") $ \err -> case err of
+        InvalidDecimal _ "1e2" -> True
+        _ -> False
+    reject "InvalidDate" (change "2026-01-02" "2026-02-30") $
+        (== InvalidDate (ElementPath ["Invoice", "IssueDate"]) "2026-02-30")
+    reject "UnknownTaxCategory" (change "<cbc:ID>S</cbc:ID>" "<cbc:ID>Z</cbc:ID>") $
+        \err -> case err of
+            UnknownTaxCategory _ "Z" -> True
+            _ -> False
+    reject "InvalidRegistrationNumber" (change "T0000000000000" "T000000000000０") $
+        (== InvalidRegistrationNumber "T000000000000０")
+    reject "DecimalTaxAmount" (change "</cbc:TaxableAmount><cbc:TaxAmount currencyID=\"JPY\">10<"
+                                    "</cbc:TaxableAmount><cbc:TaxAmount currencyID=\"JPY\">10.0<") $
+        \err -> case err of
+            DecimalTaxAmount _ "10.0" -> True
+            _ -> False
+    reject "TotalMismatch" (change ">110</cbc:PayableAmount>" ">109</cbc:PayableAmount>") $
+        (== TotalMismatch PayableRule (Amount 109) (Amount 110))
+    reject "TaxAmountOutOfRange" (xml basic { breakdown = [(standard, 100, 11)] }) $
+        (== TaxAmountOutOfRange (TaxSubtotal standard (Amount 100) (Amount 11)))
+    let missingRate = TaxCategory StandardRate Nothing
+    reject "InvalidPercentForCategory" (xml (fixture [(missingRate, 100)])) $
+        (== InvalidPercentForCategory missingRate)
+    reject "DuplicateSubtotal" (xml basic { breakdown = replicate 2 (standard, 100, 10) }) $
+        (== DuplicateSubtotal standard)
+    let mismatchedCategories = xml basic { breakdown = [(exempt, 100, 0)] }
+    reject "LineCategoryWithoutSubtotal" mismatchedCategories
+        (== LineCategoryWithoutSubtotal standard)
+    reject "SubtotalWithoutLines" mismatchedCategories (== SubtotalWithoutLines exempt)
+    reject "TaxableAmountMismatch" (xml basic { breakdown = [(standard, 99, 10)] }) $
+        (== TaxableAmountMismatch standard (Amount 99) (Amount 100))
+    let inconsistent =
+            T.replace ">100</cbc:PayableAmount>" ">109</cbc:PayableAmount>" mismatchedCategories
+    assert "Consistency errors accumulate" (parseText inconsistent) $
+        \result -> case result of
+            Left errors -> TotalMismatch ExactBalanceRule (Amount 109) (Amount 100) `elem` errors
+                        && LineCategoryWithoutSubtotal standard `elem` errors
+                        && SubtotalWithoutLines exempt `elem` errors
+            Right _ -> False
+  where
+    change before after = T.replace before after (xml basic)
+
+-- | Exercise lexical, currency, and namespace boundaries.
+readingExamples :: IO ()
+readingExamples = do
+    assert "XPath negative half rounds toward positive infinity"
+        (parseFixture (fixture [(exempt, -41 % 40)])) $ \result -> case result of
+            Left errors ->
+                TotalMismatch LineExtensionRule (Amount (-41 % 40)) (Amount (-51 % 50))
+                    `elem` errors
+            Right _ -> False
+    assert "Decimal signed values and XML whitespace"
+        (parseText (T.replace ">100<" "> \n+100.\t<" (xml basic))) isAccepted
+    assert "Line-level Price and ItemPriceExtension currencies are ignored"
+        (parseText (T.replace "<cac:Item>" (price <> extension <> "<cac:Item>") (xml basic)))
+        isAccepted
+    assert "Document tax total may be written with a decimal point"
+        (parseText (T.replace "<cac:TaxTotal><cbc:TaxAmount currencyID=\"JPY\">10<"
+                              "<cac:TaxTotal><cbc:TaxAmount currencyID=\"JPY\">10.0<" (xml basic)))
+        isAccepted
+    assert "Explicit zero document adjustments preserve 0.1 payable"
+        (fmap (totalPayable . invoiceTotals) (parseText zeroAdjustments))
+        (== Right (Amount (1 % 10)))
+    reject "UnsupportedCurrency / TaxCurrencyCode"
+        (insertRoot "<cbc:TaxCurrencyCode>USD</cbc:TaxCurrencyCode>") $ \err -> case err of
+            UnsupportedCurrency (ElementPath ["Invoice", "TaxCurrencyCode"]) "USD" -> True
+            _ -> False
+    assert "Exact XML namespace matches independent of prefix"
+        (parseText (T.replace "cbc:" "field:" (T.replace "xmlns:cbc" "xmlns:field" (xml basic))))
+        isAccepted
+    let withEntity = parseText (T.replace ">Supplier<" ">A&amp;B<" (xml basic))
+    assert "Predefined XML entity is decoded" (fmap (sellerName . invoiceSeller) withEntity)
+        (== Right "A&B")
+    reject "Internal XML entity declaration cannot supply text"
+        ("<!DOCTYPE Invoice [<!ENTITY name \"Supplier\">]>"
+            <> T.replace ">Supplier<" ">&name;<" (xml basic)) $ \err -> case err of
+                MalformedXml _ -> True
+                _ -> False
+  where
+    price = aggregate "Price" "<cbc:PriceAmount currencyID=\"USD\">100</cbc:PriceAmount>"
+    extension = aggregate "ItemPriceExtension"
+        "<cbc:Amount currencyID=\"EUR\">100</cbc:Amount>"
+    zeroAdjustments = T.replace "</cac:LegalMonetaryTotal>"
+        (foldMap zeroAmount adjustmentFields <> "</cac:LegalMonetaryTotal>")
+        (xml (fixture [(exempt, 1 % 10)]))
+    adjustmentFields =
+        ["AllowanceTotalAmount", "ChargeTotalAmount", "PrepaidAmount", "PayableRoundingAmount"]
+    zeroAmount :: Text -> Text
+    zeroAmount field = "<cbc:" <> field <> " currencyID=\"JPY\">0.0</cbc:" <> field <> ">"
+    isAccepted = either (const False) (const True)
+
+-- | Insert an element as a direct child of the example invoice.
+insertRoot :: Text -> Text
+insertRoot fragment = T.replace "</Invoice>" (fragment <> "</Invoice>") (xml basic)
+
+-- | Require the given error to appear in the result.
+reject :: String -> Text -> (InvoiceError -> Bool) -> IO ()
+reject label bytes expected =
+    assert label (parseText bytes) (either (any expected) (const False))
diff --git a/test/InvoiceFixture.hs b/test/InvoiceFixture.hs
new file mode 100644
--- /dev/null
+++ b/test/InvoiceFixture.hs
@@ -0,0 +1,217 @@
+{-# LANGUAGE OverloadedStrings #-}
+
+module InvoiceFixture
+    ( Fixture(..)
+    , fixture
+    , genFixture
+    , genZeroFixture
+    , withInvoice
+    , parseFixture
+    , parseText
+    , xml
+    , aggregate
+    , basic
+    , standard
+    , reduced
+    , exempt
+    , taxValue
+    , categories
+    ) where
+
+import qualified Data.ByteString.Lazy as LBS
+import Data.List (nub)
+import Data.List.NonEmpty (NonEmpty)
+import Data.Ratio (denominator, numerator, (%))
+import Data.Text (Text)
+import qualified Data.Text as T
+import qualified Data.Text.Encoding as TE
+import Test.QuickCheck
+    ( Gen
+    , Property
+    , Testable
+    , chooseInt
+    , counterexample
+    , elements
+    , frequency
+    , property
+    , sublistOf
+    , vectorOf
+    )
+
+import ExchangeAlgebra.IO.Input.EInvoice.Document
+    ( Invoice, InvoiceError, Percent(..), TaxCategory(..), TaxCategoryCode(..), parseInvoice )
+
+-- | Signed lines, tax breakdowns, and test registration for a synthetic invoice.
+data Fixture = Fixture
+    { items        :: [(TaxCategory, Rational)]
+    , breakdown    :: [(TaxCategory, Rational, Integer)]
+    , registration :: Text
+    } deriving (Show)
+
+-- | Derive the tax breakdowns from the line amounts.
+fixture :: [(TaxCategory, Rational)] -> Fixture
+fixture linesInOrder = Fixture linesInOrder totals "T0000000000000"
+  where
+    totals =
+        [ (category, amount, taxValue category amount)
+        | category <- nub (map fst linesInOrder)
+        , let amount = sum [q | (code, q) <- linesInOrder, code == category]
+        ]
+
+-- | A single standard-rate line used for rejection examples.
+basic :: Fixture
+basic = fixture [(standard, 100)]
+
+-- | Render a UBL aggregate component.
+aggregate :: Text -> Text -> Text
+aggregate name = element ("cac:" <> name)
+
+-- | The standard category at 10 percent.
+standard :: TaxCategory
+standard = TaxCategory StandardRate (Just (Percent 10))
+
+-- | The lower-rate category at 8 percent.
+reduced :: TaxCategory
+reduced  = TaxCategory LowerRate (Just (Percent 8))
+
+-- | The exempt category with a zero rate.
+exempt :: TaxCategory
+exempt   = TaxCategory Exempt (Just (Percent 0))
+
+-- | The categories generated by the document tests.
+categories :: [TaxCategory]
+categories = [standard, reduced, exempt, TaxCategory FreeExportItem (Just (Percent 0)),
+              TaxCategory OutsideScope Nothing]
+
+-- | Choose the permitted tax amount obtained by truncation toward zero.
+taxValue :: TaxCategory -> Rational -> Integer
+taxValue category value = case categoryPercent category of
+    Nothing             -> 0
+    Just (Percent rate) -> truncate (value * rate / 100)
+
+-- | Generate a mix of categories with signed whole and fractional amounts.
+genFixture :: Gen Fixture
+genFixture = do
+    first <- elements categories
+    rest <- sublistOf (filter (/= first) categories)
+    let selected = first : rest
+    rows <- traverse genRows selected
+    digits <- vectorOf 13 (elements ['0' .. '9'])
+    pure (fixture (concat rows)) { registration = T.pack ('T' : digits) }
+  where
+    genRows category = do
+        count <- chooseInt (1, 4)
+        values <- vectorOf count (frequency [(1, pure 0), (9, signedValue)])
+        pure [(category, amount) | amount <- values]
+
+    signedValue = do
+        cents <- elements [0, 1, -1, 10, -10, 25, -25, 50, -50, 100, -100]
+        whole <- chooseInt (-1000, 1000)
+        pure (toInteger whole % 1 + cents % 100)
+
+-- | Generate the same range of categories for all-zero invoices.
+genZeroFixture :: Gen Fixture
+genZeroFixture = do
+    model <- genFixture
+    pure (fixture [(category, 0) | (category, _) <- items model])
+
+-- | Require a synthetic invoice to parse before checking its properties.
+withInvoice :: Testable prop => Fixture -> (Invoice -> prop) -> Property
+withInvoice model check = case parseFixture model of
+    Left errors   -> counterexample (show model ++ "\n" ++ show errors) False
+    Right invoice -> property (check invoice)
+
+-- | Render and read a synthetic invoice through the public parser.
+parseFixture :: Fixture -> Either (NonEmpty InvoiceError) Invoice
+parseFixture = parseText . xml
+
+-- | Encode XML text as UTF-8 and use the public parser.
+parseText :: Text -> Either (NonEmpty InvoiceError) Invoice
+parseText = parseInvoice . LBS.fromStrict . TE.encodeUtf8
+
+-- | Render a minimal UBL invoice from the test model.
+xml :: Fixture -> Text
+xml model = T.concat
+    [ "<Invoice xmlns=\"urn:oasis:names:specification:ubl:schema:xsd:Invoice-2\""
+    , " xmlns:cac=\"urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2\""
+    , " xmlns:cbc=\"urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2\">"
+    , component "CustomizationID" "urn:peppol:pint:billing-1@jp-1"
+    , component "ProfileID" "urn:peppol:bis:billing"
+    , component "ID" "invoice-1"
+    , component "IssueDate" "2026-01-02"
+    , component "InvoiceTypeCode" "380"
+    , component "DocumentCurrencyCode" "JPY"
+    , aggregate "InvoicePeriod" (component "StartDate" "2026-01-01")
+    , aggregate "AccountingSupplierParty" (party "Supplier" sellerTax)
+    , aggregate "AccountingCustomerParty" (party "Customer" "")
+    , aggregate "TaxTotal" (money "TaxAmount" tax <> foldMap subtotal (breakdown model))
+    , aggregate "LegalMonetaryTotal" (T.concat
+        [ money "LineExtensionAmount" net
+        , money "TaxExclusiveAmount" net
+        , money "TaxInclusiveAmount" gross
+        , money "PayableAmount" gross
+        ])
+    , T.concat (zipWith line [1 :: Int ..] (items model))
+    , "</Invoice>"
+    ]
+  where
+    net = sum (map snd (items model))
+    tax = fromInteger (sum [q | (_, _, q) <- breakdown model])
+    gross = net + tax
+    sellerTax = aggregate "PartyTaxScheme" (component "CompanyID" (registration model) <> vat)
+    party name extra = aggregate "Party"
+        (extra <> aggregate "PartyLegalEntity" (component "RegistrationName" name))
+
+    subtotal (category, taxable, amount) = aggregate "TaxSubtotal" (T.concat
+        [ money "TaxableAmount" taxable
+        , money "TaxAmount" (fromInteger amount)
+        , aggregate "TaxCategory" (categoryXml category)
+        ])
+    line index (category, amount) = aggregate "InvoiceLine" (T.concat
+        [ component "ID" (T.pack (show index))
+        , money "LineExtensionAmount" amount
+        , aggregate "Item"
+            (component "Name" "Item" <> aggregate "ClassifiedTaxCategory" (categoryXml category))
+        ])
+
+-- | Wrap the content in a named XML element.
+element :: Text -> Text -> Text
+element name content = "<" <> name <> ">" <> content <> "</" <> name <> ">"
+
+-- | Render a UBL basic component.
+component :: Text -> Text -> Text
+component name = element ("cbc:" <> name)
+
+-- | Render an amount with its JPY currency attribute.
+money :: Text -> Rational -> Text
+money name value =
+    "<cbc:" <> name <> " currencyID=\"JPY\">" <> decimal value <> "</cbc:" <> name <> ">"
+
+-- | Render the VAT scheme identifier.
+vat :: Text
+vat = aggregate "TaxScheme" (component "ID" "VAT")
+
+-- | Render a category with its optional percentage and its VAT scheme.
+categoryXml :: TaxCategory -> Text
+categoryXml (TaxCategory code percent) =
+    component "ID" (codeName code) <> foldMap renderPercent percent <> vat
+  where
+    renderPercent (Percent rate) = component "Percent" (decimal rate)
+    codeName StandardRate   = "S"
+    codeName LowerRate      = "AA"
+    codeName Exempt         = "E"
+    codeName FreeExportItem = "G"
+    codeName OutsideScope   = "O"
+
+-- | Render a terminating rational as an XML Schema decimal.
+decimal :: Rational -> Text
+decimal amount = sign <> T.pack (show whole) <> fraction remainder
+  where
+    sign = if amount < 0 then "-" else ""
+    divisor = denominator amount
+    (whole, remainder) = abs (numerator amount) `quotRem` divisor
+    fraction 0 = ""
+    fraction n = "." <> T.pack (digits n)
+    digits 0 = []
+    digits n = let (digit, rest) = (n * 10) `quotRem` divisor
+               in toEnum (fromEnum '0' + fromInteger digit) : digits rest
diff --git a/test/JournalSpec.hs b/test/JournalSpec.hs
new file mode 100644
--- /dev/null
+++ b/test/JournalSpec.hs
@@ -0,0 +1,315 @@
+{-# LANGUAGE FlexibleInstances #-}
+{-# LANGUAGE OverloadedStrings #-}
+{-# LANGUAGE ScopedTypeVariables #-}
+
+module JournalSpec (runTests) where
+
+import Data.Hashable (Hashable(..))
+import Data.List.NonEmpty (NonEmpty(..))
+import qualified Data.List.NonEmpty as NE
+import Data.Proxy (Proxy(..))
+import Data.Ratio ((%))
+import qualified Data.Text as T
+import Test.QuickCheck
+    ( Property
+    , conjoin
+    , counterexample
+    , forAll
+    , property
+    , (===)
+    )
+
+import ExchangeAlgebra.Accounting.Account
+    ( AccountTitles(..)
+    , PostingCapability(ClosingOnly)
+    , ProcessingContext(..)
+    , Side(..)
+    )
+import ExchangeAlgebra.Accounting.Exchange (ExBaseClass(..), Exchange(balance), journalForSides)
+import ExchangeAlgebra.Algebra.Base (Element(..), HatBase((:<)))
+import ExchangeAlgebra.Algebra.Core (Alg, norm, toList)
+import ExchangeAlgebra.Algebra.Value (HatVal, MoneyDecimal)
+import ExchangeAlgebra.IO.Input (ConvErrorOf(..), EntryErrorOf(..), checkedEntryTextBy)
+import ExchangeAlgebra.IO.Input.EInvoice.Document
+import ExchangeAlgebra.IO.Input.EInvoice.Journal
+import InvoiceFixture
+import TestSupport
+
+-- | Tax rate carried in the test base. A wildcard means no rate applies.
+newtype Rate = Rate (Maybe Percent)
+    deriving (Eq, Ord, Show)
+
+instance Hashable Rate where
+    hashWithSalt salt (Rate rate) = hashWithSalt salt (fmap (\(Percent value) -> value) rate)
+
+instance Element Rate where
+    wildcard = Rate Nothing
+
+instance ExBaseClass (HatBase (AccountTitles, Rate)) where
+    getAccountTitle (_ :< (account, _)) = account
+    setAccountTitle (marker :< (_, rate)) account = marker :< (account, rate)
+
+-- | The test base pairs an account with its tax rate.
+type Key = (AccountTitles, Rate)
+
+-- | The result of building one entry on the test base.
+type Entry v = Either (InvoiceJournalError AccountTitles v) (Alg v (HatBase Key))
+
+-- | Check the journal laws and the examples using parsed invoices.
+runTests :: IO ()
+runTests = do
+    checkProperty "invoiceTerms / Correspondence" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> withTerms buyer invoice $ \terms ->
+            let expected =
+                    [(role, specBase buyer invoice role, abs amount)
+                    | (role, amount) <- sources invoice, amount /= 0]
+            in [(termRole term, termBase term, termAmount term) | term <- terms] === expected
+    checkProperty "invoiceTerms / Sides" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> withTerms buyer invoice $ \purchase ->
+            withTerms (buyer { specBookSide = SellerBook }) invoice $ \sale ->
+                let expected = [positiveSide role amount
+                               | (role, amount) <- sources invoice, amount /= 0]
+                in conjoin
+                    [ map termSide purchase === expected
+                    , map observe sale === map (\t -> (termRole t, opposite (termSide t),
+                                                       termBase t, termAmount t)) purchase
+                    ]
+    checkProperty "invoiceTerms / Balance" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> withTerms buyer invoice $ \terms ->
+            let total side = sum [termAmount term | term <- terms, termSide term == side]
+            in total Debit === total Credit
+    checkProperty "invoiceTerms / Accounting methods agree" $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> withTerms buyer invoice $ \exclusive ->
+            withTerms inclusive invoice $ \included ->
+                let expected term = case termRole term of
+                        TaxTerm subtotal -> (Purchases, rateOf (subtotalCategory subtotal))
+                        _                -> termBase term
+                    withoutBase term = (termRole term, termSide term, termAmount term)
+                in conjoin
+                    [ map withoutBase included === map withoutBase exclusive
+                    , map termBase included === map expected exclusive
+                    ]
+    checkProperty "invoiceTerms / Zero document" $ forAll genZeroFixture $ \model ->
+        withInvoice model $ \invoice -> conjoin
+            [ invoiceTerms buyer invoice === Right []
+            , invoiceTerms inclusive invoice === Right []
+            ]
+    journalProperties "Double" (Proxy :: Proxy Double)
+    journalProperties "MoneyDecimal" (Proxy :: Proxy MoneyDecimal)
+    examples
+
+-- | Check the journal laws for one value type.
+journalProperties
+    :: forall v. (HatVal v, Fractional v, Real v)
+    => String
+    -> Proxy v
+    -> IO ()
+journalProperties label _ = do
+    checkProperty (law "Agreement") $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> conjoin
+            [ withTerms spec invoice $ \terms ->
+                case (testRows terms, invoiceJournal spec invoice :: Entry v) of
+                    (Left (row, amount), actual) ->
+                        actual === Left (UnrepresentableAmount row amount)
+                    (Right [], actual) ->
+                        actual === Left (EntryRejected (EmptyEntry :| []))
+                    (Right rows, Right actual)   ->
+                        let expected = journalForSides rows
+                        in conjoin
+                            [ toList actual === toList expected
+                            , length (toList actual) === length terms
+                            , norm actual === norm expected
+                            ]
+                    (Right _, Left errors)       -> counterexample (show errors) False
+            | spec <- [buyer, inclusive, seller]
+            ]
+    checkProperty (law "Balance") $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> conjoin
+            [ case invoiceJournal spec invoice :: Entry v of
+                Right entry -> property (balance entry)
+                Left errors -> case errors of
+                    UnrepresentableAmount _ _          -> property True
+                    EntryRejected (EmptyEntry :| [])   -> property True
+                    _                                  -> counterexample (show errors) False
+            | spec <- [buyer, inclusive, seller]
+            ]
+    checkProperty (law "Check agreement") $ forAll genFixture $ \model ->
+        withInvoice model $ \invoice -> conjoin
+            [ withTerms spec invoice $ \terms ->
+                let actual = invoiceJournal spec invoice :: Entry v
+                in case testRows terms of
+                    Left (row, amount) -> actual === Left (UnrepresentableAmount row amount)
+                    Right rows -> case directCheck rows of
+                        Left errors -> actual === Left (EntryRejected errors)
+                        Right _     -> case actual of
+                            Left errors -> counterexample (show errors) False
+                            Right _     -> property True
+            | spec <- [buyer, inclusive, seller, buyer { specBase = invalidBase }]
+            ]
+  where
+    law name = "invoiceJournal / " ++ name ++ " (" ++ label ++ ")"
+    invalidBase invoice role = case role of
+        SettlementTerm -> (IncomeSummary, wildcard)
+        _              -> specBase buyer invoice role
+
+-- | Construct expected rows using the round trip through Real and Fractional.
+testRows
+    :: (Fractional v, Real v)
+    => [InvoiceTerm Key]
+    -> Either (Int, Rational) [(Side, Key, v)]
+testRows terms = traverse convert (zip [0 ..] terms)
+  where
+    convert (index, term)
+        | toRational value == termAmount term = Right (termSide term, termBase term, value)
+        | otherwise                           = Left (index, termAmount term)
+      where
+        value = fromRational (termAmount term)
+
+-- | Submit the account part of each test row directly to the entry checker.
+directCheck
+    :: HatVal v
+    => [(Side, Key, v)]
+    -> Either (NonEmpty (EntryErrorOf AccountTitles v)) (Alg v (HatBase AccountTitles))
+directCheck rows =
+    checkedEntryTextBy resolve OrdinaryJournal
+        [(sideText side, key, amount) | (key, (side, _, amount)) <- indexed]
+  where
+    indexed = zip (map (T.pack . ("term-" ++) . show) [0 :: Int ..]) rows
+    accounts = [(key, account) | (key, (_, (account, _), _)) <- indexed]
+    resolve key = maybe (Left (UnknownAccount key)) Right (lookup key accounts)
+    sideText Debit  = "debit"
+    sideText Credit = "credit"
+    sideText Side   = "side"
+
+-- | Check positive, negative, split, fractional, and zero invoice examples.
+examples :: IO ()
+examples = do
+    let mixed = fixture [(reduced, 100), (standard, 200)]
+        mixedItems = [(Debit, (Purchases, rateOf reduced), 100),
+                      (Debit, (Purchases, rateOf standard), 200),
+                      (Debit, (ConsumptionTaxPaid, rateOf reduced), 8),
+                      (Debit, (ConsumptionTaxPaid, rateOf standard), 20),
+                      (Credit, (AccountsPayable, wildcard), 328)]
+    assert "8% and 10% invoice terms"
+        (observedTerms buyer mixed) (== Right (Right mixedItems))
+    let closingBase :: Invoice -> TermRole -> Key
+        closingBase invoice role = case role of
+            SettlementTerm -> (IncomeSummary, wildcard)
+            _              -> specBase buyer invoice role
+        closingSpec = buyer { specBase = closingBase }
+        closingEntry = invoiceJournal closingSpec :: Invoice -> Entry MoneyDecimal
+        expectedError = PostingNotAllowed 4 IncomeSummary ClosingOnly OrdinaryJournal
+    assert "Check agreement / closing-only settlement account"
+        (fmap closingEntry (parseFixture mixed)) $ \result -> case result of
+            Right (Left (EntryRejected errors)) -> expectedError `elem` errors
+            _                                  -> False
+    let negative = fixture [(reduced, -100), (standard, -200)]
+        reversed = [(opposite side, key, amount) | (side, key, amount) <- mixedItems]
+    assert "Negative invoice without a reference reverses sides"
+        (observedTerms buyer negative) (== Right (Right reversed))
+    let split = inclusive { specBase = splitBase }
+        taxed = fixture [(standard, 1000), (standard, 2000)]
+        untaxed = fixture [(exempt, 1000), (exempt, 2000)]
+    assert "InclusiveTaxSplit"
+        (fmap (invoiceJournal split :: Invoice -> Entry MoneyDecimal) (parseFixture taxed))
+        (== Right (Left (InclusiveTaxSplit (standard :| []))))
+    let untaxedRows = [(Debit, (Purchases, rateOf exempt), 1000),
+                       (Debit, (MerchandiseInventory, rateOf exempt), 2000),
+                       (Credit, (AccountsPayable, wildcard), 3000)]
+    assert "Tax-inclusive split bases with zero rate"
+        (fmap (invoiceJournal split :: Invoice -> Entry MoneyDecimal) (parseFixture untaxed))
+        (== Right (Right (journalForSides untaxedRows)))
+    assert "UnrepresentableAmount / Double 0.1"
+        (fmap (invoiceJournal buyer :: Invoice -> Entry Double)
+            (parseFixture (fixture [(exempt, 1 % 10)])))
+        (== Right (Left (UnrepresentableAmount 0 (1 % 10))))
+    assert "Exact Double amount 1.5"
+        (fmap (invoiceJournal buyer :: Invoice -> Entry Double)
+            (parseFixture (fixture [(exempt, 3 % 2)])))
+        (== Right (Right (journalForSides [(Debit, (Purchases, rateOf exempt), 1.5),
+                                           (Credit, (AccountsPayable, wildcard), 1.5)])))
+    let zero = parseFixture (fixture [(standard, 0)])
+    assert "Zero invoice has no terms"
+        (fmap (invoiceTerms buyer) zero) (== Right (Right []))
+    assert "Zero invoice journal / EmptyEntry"
+        (fmap (invoiceJournal buyer :: Invoice -> Entry Double) zero)
+        (== Right (Left (EntryRejected (EmptyEntry :| []))))
+
+-- | Assign the buyer accounts to a tax-exclusive entry.
+buyer :: InvoiceJournalSpec Key
+buyer = InvoiceJournalSpec BuyerBook TaxExclusiveAccounting (\_ role -> case role of
+    LineTerm line    -> (Purchases, rateOf (lineTaxCategory line))
+    TaxTerm subtotal -> (ConsumptionTaxPaid, rateOf (subtotalCategory subtotal))
+    SettlementTerm   -> (AccountsPayable, wildcard))
+
+-- | Use the buyer line bases for the tax breakdown terms.
+inclusive :: InvoiceJournalSpec Key
+inclusive = buyer { specTaxAccounting = TaxInclusiveAccounting }
+
+-- | Assign the seller accounts to a tax-exclusive entry.
+seller :: InvoiceJournalSpec Key
+seller = InvoiceJournalSpec SellerBook TaxExclusiveAccounting (\_ role -> case role of
+    LineTerm line    -> (Sales, rateOf (lineTaxCategory line))
+    TaxTerm subtotal -> (ConsumptionTaxReceived, rateOf (subtotalCategory subtotal))
+    SettlementTerm   -> (AccountsReceivable, wildcard))
+
+-- | Assign a different account to line 2 of the split examples.
+splitBase :: Invoice -> TermRole -> Key
+splitBase invoice role = case role of
+    LineTerm line | lineIdentifier line == "2" ->
+        (MerchandiseInventory, rateOf (lineTaxCategory line))
+    _ -> specBase buyer invoice role
+
+-- | Put the category rate in the test base.
+rateOf :: TaxCategory -> Rate
+rateOf = Rate . categoryPercent
+
+-- | Require the term stage to succeed before observing its result.
+withTerms
+    :: InvoiceJournalSpec Key
+    -> Invoice
+    -> ([InvoiceTerm Key] -> Property)
+    -> Property
+withTerms spec invoice check =
+    case invoiceTerms spec invoice of
+        Left errors -> counterexample (show errors) False
+        Right terms -> check terms
+
+-- | List the signed document amounts in their required term order.
+sources :: Invoice -> [(TermRole, Rational)]
+sources invoice =
+    [(LineTerm row, amount) | row <- NE.toList (invoiceLines invoice)
+                            , let Amount amount = lineAmount row]
+    ++ [(TaxTerm row, amount) | row <- NE.toList (invoiceTaxSubtotals invoice)
+                              , let Amount amount = subtotalTaxAmount row]
+    ++ [(SettlementTerm, payable)]
+  where
+    Amount payable = totalPayable (invoiceTotals invoice)
+
+-- | Compute the expected buyer side from the source and sign.
+positiveSide :: TermRole -> Rational -> Side
+positiveSide SettlementTerm amount
+    | amount < 0 = Debit
+    | otherwise  = Credit
+positiveSide _ amount
+    | amount < 0 = Credit
+    | otherwise  = Debit
+
+-- | Reverse the side for a seller or negative invoice.
+opposite :: Side -> Side
+opposite Debit  = Credit
+opposite Credit = Debit
+opposite Side   = Side
+
+-- | Expose the role, side, base, and amount for comparison.
+observe :: InvoiceTerm Key -> (TermRole, Side, Key, Rational)
+observe term = (termRole term, termSide term, termBase term, termAmount term)
+
+-- | Read example XML and return the terms as side, base, and amount triples.
+observedTerms
+    :: InvoiceJournalSpec Key
+    -> Fixture
+    -> Either (NonEmpty InvoiceError) (Either (NonEmpty TaxCategory) [(Side, Key, Rational)])
+observedTerms spec model =
+    fmap (fmap (map (\t -> (termSide t, termBase t, termAmount t))) . invoiceTerms spec)
+         (parseFixture model)
diff --git a/test/Spec.hs b/test/Spec.hs
new file mode 100644
--- /dev/null
+++ b/test/Spec.hs
@@ -0,0 +1,10 @@
+module Main (main) where
+
+import qualified DocumentSpec
+import qualified JournalSpec
+
+-- | Run the document and journal tests.
+main :: IO ()
+main = do
+    DocumentSpec.runTests
+    JournalSpec.runTests
diff --git a/test/TestSupport.hs b/test/TestSupport.hs
new file mode 100644
--- /dev/null
+++ b/test/TestSupport.hs
@@ -0,0 +1,23 @@
+module TestSupport (assert, checkProperty) where
+
+import Control.Monad (unless)
+import System.Exit (exitFailure)
+import Test.QuickCheck
+    ( Args(chatty, maxSuccess), Testable, isSuccess, output, quickCheckWithResult, stdArgs )
+
+-- | Check an example and print the observed value on failure.
+assert :: Show a => String -> a -> (a -> Bool) -> IO ()
+assert label actual predicate =
+    report label (predicate actual) (show actual)
+
+-- | Check a law on 250 generated examples.
+checkProperty :: Testable prop => String -> prop -> IO ()
+checkProperty label property = do
+    result <- quickCheckWithResult stdArgs { maxSuccess = 250, chatty = False } property
+    report label (isSuccess result) (output result)
+
+-- | Print one result line and abort the suite on failure.
+report :: String -> Bool -> String -> IO ()
+report label ok details = do
+    putStrLn ((if ok then "[PASS] " else "[FAIL] ") ++ label)
+    unless ok (putStrLn details >> exitFailure)
