packages feed

exchangealgebra-einvoice-0.1.0.0: test/InvoiceFixture.hs

{-# 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