# Invoicing

## e-Factura XML (CIUS-RO)

`Invoicing\EFactura\CiusRoInvoice::xml($draft, $seller, $number, $sign = 1, $rate = null)` writes UBL 2.1 under
CIUS-RO 1.0.1 (`CustomizationID` `urn:cen.eu:en16931:2017#compliant#urn:efactura.mfinante.ro:CIUS-RO:1.0.1`) from an
`InvoiceDraft` and the shop's `CompanyDetails`:

- lines carry net amounts (gross ÷ (1 + rate), to the bani); VAT is worked out per category and rate on the summed nets
  (BR-CO-17); the bani left against the order total go in `PayableRoundingAmount`, so `PayableAmount` is what was paid;
- categories: S for taxed lines; for a VAT payer, E with a reason for 0% lines (the SGR deposit, gift cards — to confirm
  with the accountant); a seller not registered for VAT puts everything under O;
- prices are never negative (BR-27): discounts and storno lines are negative quantities;
- a person without a CNP is `0000000000000`; a company buyer is its CUI, with a VAT `PartyTaxScheme` only when it
  starts with RO; counties are `RO-XX` (ISO 3166-2), Bucharest's city is `SECTOR1`…`SECTOR6`;
- payment means 42 (transfer, with the shop's IBAN), 48 (card), 10 (cash);
- a foreign-currency invoice adds `TaxCurrencyCode` RON and a second `TaxTotal` in RON at the given rate (BR-53).

Tests: `tests/Feature/Invoicing/CiusRoInvoiceTest.php`.

## The native e-Factura route

`Invoices\Drivers\Anaf\AnafInvoiceDriver` (key `anaf`, fields `client_id`, `client_secret`, `series`, sandbox = ANAF's
test environment): numbers from `invoice_sequences` under a row lock, writes `CiusRoInvoice` with
`Platform\Contracts\ShopCompany` as the seller, uploads through `EFactura\AnafClient` and asks ANAF's public
`transformare/FACT1/DA` for the PDF. Neither failure stops the invoice: it is stored with `e_factura_status` `pending`
and its XML (`invoices.xml_path`). `invoicing:efactura` (every 15 minutes) uploads pending ones and follows
`processing` uploads with `stareMesaj` to `accepted` (`e_factura_download`) or `rejected` (`e_factura_message`).

`AnafClient` keeps the OAuth tokens in `anaf_tokens` (encrypted), refreshes the access token a day before it runs out,
and logs every call without tokens. `Http\Controllers\AnafConnectController` (`admin.settings.efactura.*`) sends the
owner to `logincert.anaf.ro` with a session-bound `state` and stores the tokens on the callback.

Tests: `tests/Feature/Invoicing/AnafEFacturaTest.php`.
