# `SefazNfe.CTe`
[🔗](https://github.com/devaction-labs/sefaz_nfe/blob/v0.5.0/lib/sefaz_nfe/cte.ex#L1)

CT-e (modelo 57) and CT-e OS (modelo 67) transport, layout 4.00.

The facade mirrors `SefazNfe`: every operation takes one map, is wrapped in
the `[:sefaz_nfe, :operation]` telemetry span (operation atoms `:cte_*`) and
goes through `SefazNfe.Transport` and so through the circuit breaker and
`SefazNfe.SOAP.isolated_call/4`. The authorizer is per model, not per UF (BA
is SVRS for CT-e, PE is SVSP); see `SefazNfe.Endpoints`.

| Function | Service | Notes |
|----------|---------|-------|
| `authorize/1` | `CTeRecepcaoSincV4` (57), `CTeRecepcaoOSV4` (67) | sync; no receipt step |
| `consult/1` | `CTeConsultaV4` | by access key |
| `service_status/1` | `CTeStatusServicoV4` | |
| `cancel/1` | `CTeRecepcaoEventoV4` | 110111 |
| `cce/1` | `CTeRecepcaoEventoV4` | 110110, structured corrections |
| `delivery_proof/1`, `cancel_delivery_proof/1` | `CTeRecepcaoEventoV4` | 110180, 110181 (model 57) |
| `delivery_failure/1`, `cancel_delivery_failure/1` | `CTeRecepcaoEventoV4` | 110190, 110191 (model 57) |

Results are `SefazNfe.Result`, with two CT-e differences. The access key is in
`:ch_nfe`, whichever the document (`chCTe` here); and the status comes from
`SefazNfe.CStat.classify/2`, because 678 is "Consumo Indevido" for CT-e. The
processed documents are built by `SefazNfe.CTe.Proc` and carried in `:xml`.

## What goes on the wire

Only the authorization is compressed: `cteDadosMsg` holds the signed CT-e or
CT-e OS itself (no `enviCTe`, no XML declaration), gzip-compressed and
Base64-encoded, as NFePHP's `sefazEnviaCTe` does. Consultation, status and
events go as plain XML, and an event is the `eventoCTe` alone (no `envEvento`
and no `idLote`). No `cteCabecMsg` header is sent: it is obsolete from layout
4.00 and the 4.00 services do not ask for it.

## Contingency

Contingency is the caller's choice (AD-005): nothing here falls back to it,
and no XML is composed, so the ERP rebuilds the document with the new `tpEmis`
and `authorize/1` routes on it:

  * `1` goes to the UF's own authorizer;
  * `7` goes to SVC-RS and `8` to SVC-SP (the MOC's codes), but only when that
    SVC is the one that serves `:uf` (`SefazNfe.Endpoints.contingency_for/2`);
    otherwise `{:error, {:wrong_contingency, uf, svc}}`, where `svc` is the
    SVC that does serve it;
  * `3` (NFF), `4` (EPEC) and `5` (FS-DA) are
    `{:error, {:unsupported, {:tp_emis, n}}}`: 4 and 5 need a QR code
    signed with the certificate (`&sign=`), which is not generated.

Unlike NF-e, the CT-e MOC does not ask for `dhCont`/`xJust` under SVC: rule
G008 (rejeicao 586) says they must NOT be informed unless `tpEmis` is 5. They
are neither required nor refused here; SEFAZ is the one that checks.

The other operations take an optional `:contingency` (`:svc_sp` or
`:svc_rs`) with the same rules (`SefazNfe.consult_protocol/1` documents them
for NF-e). It is never inferred from the key's `tpEmis` digit.

# `authorize`

```elixir
@spec authorize(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Sign, add the QR code and send a CT-e or CT-e OS to `CTeRecepcaoSincV4` or
`CTeRecepcaoOSV4`.

The document is `:xml` (signed or not) or `:cte`, a map for
`SefazNfe.Builder.build_cte/2` (`ide.mod` 57, the default) or
`build_cte_os/2` (`ide.mod` 67); exactly one of them. A map that does not
build is `{:error, {:invalid_cte, errors}}`. The model is read from `<mod>`
and anything but 57 and 67 is `{:error, {:unsupported_model, mod}}`.

The pipeline is validate, sign `infCte`, add `infCTeSupl` with `qrCodCTe`
(`SefazNfe.CTe.Supl`), compress, POST, parse. `tpAmb` is checked against
`:environment` before anything is sent. `tpEmis` routes as the moduledoc
describes. When `SefazNfe.Schema` validation is enabled (`config :sefaz_nfe,
:schemas, ...`), the document about to be sent (signed, `infCTeSupl`
included) is checked against the bundled `cte_v4.00.xsd` (`cteOS_v4.00.xsd`
for model 67) and a violation is `{:error, {:schema, [line, ...]}}`, before
the network. Off by default; it needs `xmllint` on the `PATH`.

The result carries `:signed_xml` (what was sent, QR code included) and, once
SEFAZ answered with a protocol the document may carry (see
`SefazNfe.CTe.Proc.cte_proc/2`), `:xml` holding the `cteProc` or `cteOSProc`
to archive. Store `:signed_xml` even when the answer is a transport error:
SEFAZ may have processed the document, and `consult/1` is the way to find out
before sending it again.

# `cancel`

```elixir
@spec cancel(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110111, cancelling an authorized CT-e or CT-e OS.

Options: `:ch_cte`, `:n_prot` (the authorization's protocol), `:justification`
(15 to 255 characters), `:tax_id` (the author: the emitter's CNPJ or CPF),
`:cert`, `:uf`, `:environment`; `:sequence` (1 by default) and `:timestamp`.

Like every event here, the result carries `:signed_xml` (the `eventoCTe` sent)
and, once SEFAZ registered it (`cStat` 134, 135 or 136, and 155 for a
cancellation), `:xml` holding the `procEventoCTe`.
`SefazNfe.CTe.Proc.cte_cancel_register/2` appends the cancellation to the
`cteProc`.

# `cancel_delivery_failure`

```elixir
@spec cancel_delivery_failure(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110191, cancelling an insucesso na entrega (model 57 only).

`:n_prot` is the CT-e's protocol and `:n_prot_ie` the failure event's.

# `cancel_delivery_proof`

```elixir
@spec cancel_delivery_proof(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110181, cancelling a comprovante de entrega (model 57 only).

`:n_prot` is the CT-e's protocol and `:n_prot_ce` the delivery proof event's;
`:sequence` is the cancelled proof's sequence (1 by default).

# `cce`

```elixir
@spec cce(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110110, the structured Carta de Correcao.

`:corrections` is a non-empty list of maps with `:grupo_alterado` (the group,
such as `"ide"`), `:campo_alterado` (the field) and `:valor_alterado` (the new
value), and `:nro_item_alterado` (1-based, when the field is in a list).
Lengths follow the XSD: 20, 20 and 500 characters. `:sequence` numbers the
correction (1 by default); `xCondUso` is the fixed legal text. Anything wrong
is `{:error, {:invalid_corrections, reason}}` before the network.

# `consult`

```elixir
@spec consult(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

`CTeConsultaV4` (`consSitCTe`) by 44-character access key.

The idempotent way back after a failure between the send and the answer: ask
SEFAZ what it did with the document instead of sending it again. The model
comes from the key. Takes the optional `:contingency` described in the
moduledoc. The result carries the protocol (`:n_prot`) and, for a document
SEFAZ has, `cStat` 100 (`:authorized`), 101 (`:cancelled`) or 110
(`:denied`); 217 (not found) is a rejection.

# `delivery_failure`

```elixir
@spec delivery_failure(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110190, the insucesso na entrega (model 57 only).

Options: `:n_prot`, `:dh_tentativa_entrega`, `:tp_motivo` (1 recebedor nao
encontrado, 2 recusa do recebedor, 3 endereco inexistente, 4 outros), plus the
event keys of `cancel/1`; optionally `:n_tentativa`, `:x_just_motivo` (15 to
256 characters, required with motivo 4), `:latitude`, `:longitude`, `:image`
(hashed into `hashTentativaEntrega` like the delivery proof's) or `:hash` (the
finished hash, exclusive with `:image`, see `delivery_proof/1`); with neither,
the hash group is left out, as the XSD allows. Also `:dh_hash` and `:ch_nfes`.

# `delivery_proof`

```elixir
@spec delivery_proof(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

Event 110180, the comprovante de entrega (model 57 only).

Options: `:n_prot`, `:dh_entrega` (a `DateTime`, or ISO 8601 text with an
offset), `:n_doc` and `:x_nome` (who received it), plus the event keys of
`cancel/1`; exactly one of `:image` (the proof's bytes: a signature, a photo)
and `:hash` (the finished hash, see below); and
optionally `:latitude` and `:longitude` (a float, or text in the XSD's six
decimals), `:ch_nfes` (the NF-e keys delivered, for a normal service) and
`:dh_hash`.

`hashEntrega` is computed here from `:image`: base64 of the SHA-1 of the
access key followed by the base64 of the image
(`SefazNfe.CTe.Events.delivery_hash/2`). The image itself is not sent: it is
the author's to keep. With `:hash` the caller passes that value already
computed: 28 characters of Base64 of a 20-byte SHA-1 (anything else is
`{:error, :invalid_hash}`). `:image` and `:hash` together are
`{:error, {:conflicting_keys, [:image, :hash]}}`; neither is
`{:error, {:missing_keys, [:image]}}` for the proof.

# `service_status`

```elixir
@spec service_status(map()) :: {:ok, SefazNfe.Result.t()} | {:error, term()}
```

`CTeStatusServicoV4` for one UF.

Options: `:cert`, `:uf` and `:environment`, and `:model` (57 by default, or
67). `cStat` 107 is `:in_operation`; 108 and 109 are `:retryable`, and all
arrive as `{:ok, result}` because SEFAZ answered. See `SefazNfe.CStat`. Takes
the optional `:contingency` described in the moduledoc.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
