Packages

Independent Elixir SDK for the Fatture in Cloud API v2, built on Req

Current section

Files

Jump to
Raw

README.md

# ExFattureincloud

An independent Elixir SDK for the Fatture in Cloud API v2, built on Req. It
covers 124 operations across 17 resource modules, including the full pinned
OpenAPI 2.1.8 contract and the Get API Usage endpoint.

[Hex package](https://hex.pm/packages/ex_fattureincloud) ·
[API reference](https://hexdocs.pm/ex_fattureincloud) ·
[Quickstart](#quickstart)

## Installation

ExFattureincloud requires Elixir 1.16 or later. To install the Hex release, add
the package to `mix.exs` and run `mix deps.get`.

```elixir
defp deps do
  [
    {:ex_fattureincloud, "~> 0.1.0"}
  ]
end
```

Before the first Hex release, install from GitHub with
`{:ex_fattureincloud, github: "elchemista/ex_fattureincloud"}` or from a local
checkout with `{:ex_fattureincloud, path: "../ex_fattureincloud"}`.

## Quickstart

```elixir
alias ExFattureincloud.{Clients, IssuedDocuments, User}

client = ExFattureincloud.new(token: System.fetch_env!("FIC_ACCESS_TOKEN"))

{:ok, companies} = User.list_user_companies(client)
companies.data["companies"]

# Use a company ID returned for your account.
company_id = 12_345

{:ok, clients} = Clients.list_clients(client, company_id, per_page: 50)
{:ok, invoices} = IssuedDocuments.list_issued_documents(client, company_id, type: :invoice)
```

Resource functions take the client, path parameters in URL order, a body when
the operation accepts one, and optional query parameters. Use `nil` to omit an
optional JSON body. Query parameters can be passed as a keyword list or a map.
See the [endpoint catalog](guides/endpoints.md) for every function.

JSON request bodies use the API's envelope, typically `%{data: %{...}}`.

```elixir
{:ok, created} =
  Clients.create_client(client, company_id, %{
    data: %{name: "Rossi S.r.l.", type: "company", country: "Italia"}
  })
```

The SDK validates path parameters, query options, enums, and numeric bounds.
The provider validates nested body fields and business rules.

## Responses and errors

```elixir
case Clients.get_client(client, company_id, 67_890) do
  {:ok, response} ->
    response.data        # Resource data with string keys
    response.body        # Complete response, including warnings and extra fields
    response.pagination  # Page metadata returned by the API
    response.rate_limit  # Hourly and monthly quotas, plus Retry-After

  {:error, error} ->
    error.kind           # :http, :transport, :validation, :authentication, or :protocol
    error.status         # HTTP status, when available
    error.code           # API or OAuth error code, when available
    error.message
    error.body           # Original error payload, including validation details
    error.retry_after    # Seconds, including values derived from an HTTP date
end
```

JSON values retain their decoded types. Decimal numbers decode as Elixir floats.
XML responses are strings and empty responses are valid. For invoice totals,
use the provider's `get_new_issued_document_totals` or
`get_existing_issued_document_totals` operation. Use
`ExFattureincloud.unwrap!/1` when you want a successful response or an exception.

## Authentication

For a personal access token, pass the token to `ExFattureincloud.new/1`. A
zero-arity provider can supply the current token from application storage.
Each client uses its own credentials.

The SDK supports OAuth Authorization Code, refresh tokens, and Device Code
Flow. Use the OAuth helpers for application-managed tokens or supervise an
`ExFattureincloud.OAuth.TokenManager` for scheduled or on-demand renewal. The
manager shares one in-flight refresh among callers and activates rotated
credentials after the application's save callback succeeds. See the
[authentication guide](guides/authentication.md) for complete flows and recovery
behavior.

## Filters and pagination

```elixir
alias ExFattureincloud.{Filter, Pagination}

query =
  Filter.where("name", :contains, "Rossi")
  |> Filter.and_where("vat_number", :is_not, nil)
  |> Filter.build()

{:ok, clients} = Clients.list_clients(client, company_id, q: query)

Pagination.stream!(client, :list_issued_documents,
  path: [company_id: company_id],
  query: [type: :invoice, per_page: 100, sort: "id"]
)
|> Enum.take(150)
```

Pass the filter string directly as `q` and let Req URL-encode it. The builder
rejects apostrophes, backslashes, and control characters in string literals.
You can also supply a raw `q` expression.

Both pagination functions fetch pages as you consume the stream. `stream!/3`
yields items and raises on a page error. `stream/3` yields `{:ok, item}`, then
yields one `{:error, error}` and stops on failure. Use a stable sort when records
can change during pagination.

## Attachments

```elixir
fields = [
  filename: "invoice.pdf",
  attachment:
    {File.stream!("invoice.pdf"),
     filename: "invoice.pdf", content_type: "application/pdf"}
]

{:ok, upload} = IssuedDocuments.upload_issued_document_attachment(client, company_id, fields)
```

Req streams the file as multipart data. Use the returned upload token in a
separate request to associate the attachment with a document.

## Plan quotas and API usage

```elixir
alias ExFattureincloud.Usage

{:ok, quota} = Usage.documents(client, company_id)
quota.limit
quota.used
quota.remaining

{:ok, capacity} = Usage.invoice_capacity(client, company_id, 10)
capacity.can_create
capacity.e_invoice_enabled
capacity.license_expire

{:ok, api_usage} = Usage.api(client, company_id)
api_usage.data["hourly"]["remaining"]
api_usage.data["monthly"]["remaining"]
```

The annual document quota is the plan's document counter. Client, supplier,
and product quotas are global and available through `Usage.plan/3`.
`invoice_capacity/3` makes two GET requests and combines document capacity,
license status as of the UTC date, and company write permissions. It reports
electronic invoicing availability separately. Missing counters yield
`:unknown`. Capacity checks measure current availability and do not reserve it.
Sending a document through SdI is a separate operation. [Plan management](https://developers.fattureincloud.it/docs/guides/plan-management/)

Use `response.rate_limit` to read quota headers from a request you already made.
`Usage.api/2` makes a request and the returned usage includes that request.
[API limits and quotas](https://developers.fattureincloud.it/docs/basics/limits-and-quotas/)

## Webhooks

Use `ExFattureincloud.Webhooks` to manage subscriptions and
`ExFattureincloud.Webhook` to authenticate incoming notifications.

```elixir
{:ok, event} =
  ExFattureincloud.Webhook.verify_event(headers, decoded_json_body,
    audience: "https://example.com/webhooks/fic",
    application_id: 123
  )
```

The verifier checks the ES256 signature, issuer, audience, application ID,
expiration, and event ID and subject. It accepts binary and structured
CloudEvents. Use `public_key: trusted_pem` to supply a trusted replacement key.
For a verification GET, authenticate the bearer JWT with `Webhook.verify/2`
and return `Webhook.verification_response(challenge)` with HTTP 200. Read the
challenge from the header or query parameter configured on the subscription.
Handle duplicate deliveries and out-of-order events in your application.
[Provider webhook documentation](https://developers.fattureincloud.it/docs/webhooks/notifications/)

## HTTP configuration and telemetry

```elixir
client = ExFattureincloud.new(
  token: fn -> MyApp.TokenStore.current_access_token() end,
  user_agent: "MyApp/1.0",
  max_retries: 2,
  retry_delay: 500,
  max_retry_delay: 30_000,
  receive_timeout: 15_000,
  req_options: [connect_options: [timeout: 5_000]]
)
```

Automatic retries apply to GET and HEAD on network failures, HTTP
408/429/500/502/503/504, or HTTP 403 with `Retry-After`. The transport honors
`Retry-After` up to the configured delay budget and otherwise uses exponential
backoff with jitter for retryable failures. Set `max_retries: 0` to disable
retries. Write requests, uploads, and OAuth token requests are sent once.
Redirects are disabled.

The default User-Agent is `FattureInCloud/2.1.3/Go-SDK` for compatibility
with the official Go SDK. The operation selects its Accept header, including
`text/xml` for invoice XML. Use `ExFattureincloud.request/4` for a relative path
outside the pinned catalog.

Every attempt emits `[:ex_fattureincloud, :request, :start]` and
`[:ex_fattureincloud, :request, :stop]`. A scheduled retry also emits
`[:ex_fattureincloud, :request, :retry]`. Measurements include `system_time`,
`duration` in native time units, or `delay` in milliseconds, respectively.
Metadata includes the operation, method, zero-based attempt, and status or
outcome when available. HTTP response bodies may contain customer data.

## Documentation and development

- [Authentication](guides/authentication.md)
- [Endpoint catalog](guides/endpoints.md)
- [Compatibility with the official SDKs](guides/sdk-parity.md)
- [Development and release](guides/development.md)
- [Changelog](CHANGELOG.md)

Run `mix check`, `mix test --cover --warnings-as-errors`, and `mix quality`
from a checkout. GitHub Actions runs tests with a 90% coverage threshold, Credo,
Dialyzer, and the documentation and package checks on Elixir 1.19 / OTP 28 and
Elixir 1.20 / OTP 29. The contract tests exercise all 124 operations through
Req using local mocks.

## License

MIT. See [third-party notices](THIRD_PARTY_NOTICES.md) for the upstream OpenAPI
contract and SDK references.