# sefaz_danfe

The printed auxiliary documents of the Brazilian electronic fiscal documents, as PDF, drawn from
the authorized XML with [Typst](https://typst.app) (a precompiled NIF: no external binary, no
browser):

| XML                                              | Document            |
| ------------------------------------------------ | ------------------- |
| `nfeProc` / `NFe`, model 55                      | DANFE (portrait or landscape) |
| `nfeProc` / `NFe`, model 65                      | DANFE NFC-e (80 mm) |
| `cteProc` / `CTe` (57), `cteOSProc` / `CTeOS` (67) | DACTE             |
| `mdfeProc` / `MDFe`                              | DAMDFE              |

![DANFE, portrait](https://raw.githubusercontent.com/devaction-labs/sefaz_danfe/main/guides/images/danfe-portrait.png)

Every layout, with its preview and the call that draws it, is in the [Layouts guide](guides/layouts.md).

The XML is read with the parser of [`sefaz_nfe`](https://github.com/devaction-labs/sefaz_nfe).
Nothing here talks to the SEFAZ, a database or a web framework.

## Installation

```elixir
def deps do
  [
    {:sefaz_danfe, "~> 0.1.0"}
  ]
end
```

## Requirements

Elixir 1.20 or later. [Typst](https://typst.app) comes as a precompiled NIF (the `typst` package),
so there is nothing to install on the machine: no Rust toolchain, no external binary. The fonts are
bundled (see [Fonts](#fonts)).

## Usage

```elixir
xml = File.read!("nfe-proc.xml")

{:ok, pdf} = SefazDanfe.render(xml)
File.write!("danfe.pdf", pdf)

# the structured, already formatted data the PDF is drawn from
{:ok, data} = SefazDanfe.data(xml)
data["number"]
#=> "000.001.001"
```

The document is recognised from the XML. Options (one that does not apply to the document is
ignored):

| Option      | Values                                  | Default | What it does                                                            |
| ----------- | --------------------------------------- | ------- | ----------------------------------------------------------------------- |
| `:canceled` | `true` / `false`                        | `false` | The NF-e or NFC-e was canceled (event 110111): the PDF says so.         |
| `:closed`   | `true` / `false`                        | `false` | The MDF-e was closed: the PDF says so.                                  |
| `:logo`     | `{:png, binary}` / `{:svg, binary}`     | `nil`   | The emitter's logo, in a fixed box of the DANFE (portrait and landscape), DANFE NFC-e, DACTE and DAMDFE. |
| `:paper`    | `:mm80` / `:mm58`                       | `:mm80` | The width of the DANFE NFC-e receipt.                                   |
| `:copy`     | `:consumer` / `:establishment`          | `:consumer` | The copy of the DANFE NFC-e: `:establishment` prints "Via do Estabelecimento" next to the emission date and time. Ignored for the other documents. |
| `:orientation` | `:auto` / `:portrait` / `:landscape` | `:auto` | The page of the DANFE of an NF-e: `:auto` follows the `tpImp` of the XML (2 is landscape, A4 on its side with the vertical canhoto). Ignored for the other documents. |

```elixir
SefazDanfe.render(xml, logo: {:png, File.read!("logo.png")})
SefazDanfe.render(nfce_xml, paper: :mm58)
```

The logo's format is named, not guessed, and its bytes are checked against it; it reaches Typst as a
virtual file, never as markup.

### Contingency notices

The notice comes from the `tpEmis` of the XML. `SefazDanfe.data/2` exposes `"emission_type"` and
`"contingency"` (`nil` for a normal emission, else `%{"mode", "entered_at", "reason"}`). Texts and
sources (manual and section) are in the docs of `SefazDanfe.Contingency`.

| Document | `tpEmis`             | Printed                                                                          |
| -------- | -------------------- | -------------------------------------------------------------------------------- |
| NF-e     | 2 (FS-IA), 5 (FS-DA) | "DANFE EM CONTINGÊNCIA - IMPRESSO EM DECORRÊNCIA DE PROBLEMAS TÉCNICOS"; the second barcode "DADOS DA NF-E" below the access key and its 36 digits (nine blocks of four) in the protocol box (`"contingency_code"` in the data); the `dhCont` / `xJust` line in the additional data |
| NF-e     | 4 (EPEC)             | "DANFE impresso em contingência - EPEC regularmente recebida pela Receita Federal do Brasil"; the box "PROTOCOLO DE AUTORIZAÇÃO DO EPEC"; the `dhCont` / `xJust` line |
| NF-e     | 6, 7 (SVC-AN/RS)     | as a normal emission, protocol included; the `dhCont` / `xJust` line             |
| NFC-e    | 9 (offline)          | "EMITIDA EM CONTINGÊNCIA" and "Pendente de autorização", below the header and below the identification of the NFC-e; no protocol line, no `dhCont` / `xJust`; the QR code still prints |
| CT-e     | 5 (FS-DA)            | "DACTE EM CONTINGÊNCIA - IMPRESSO EM DECORRÊNCIA DE PROBLEMAS TÉCNICOS"; the second barcode "DADOS DO CT-E" and its numeric form in the protocol box; the `dhCont` / `xJust` line |
| CT-e     | 4 (EPEC), 2, 7, 8   | no notice (the manuals define none); the `dhCont` / `xJust` line                 |
| MDF-e    | 2                    | "EMISSÃO EM CONTINGÊNCIA" in emphasis, in the place of the authorization protocol |

Errors are tagged tuples: `{:error, :unsupported_document}`, `{:error, {:unreadable, reason}}`,
`{:error, {:invalid_options, reason}}` (an unknown option, or a value an option does not take:
`{:logo, reason}`, `{:paper, value}`, `{:copy, value}`, `{:orientation, value}`, `{:not_a_boolean, key}`), `{:error, {:typst, reason}}`.

`SefazDanfe.render/2` is a telemetry span on `[:sefaz_danfe, :render]` with
`%{type: :nfe | :nfce | :cte | :mdfe}` in its metadata.

## Fonts

The package ships IBM Plex Sans (Regular, Bold and Condensed), licensed under the SIL Open Font
License (OFL) 1.1: see `priv/fonts/OFL.txt`. They are loaded from the package's `priv` directory; nothing
is downloaded at run time.

## License

Apache-2.0. See [LICENSE](LICENSE).
