Facturas de venta¶
Recurso client.invoices (endpoint invoices). Además de las operaciones estándar de Actions, permite enviar por correo, anular y reabrir facturas.
alegrapy.invoices.Invoices
¶
Bases: Actions
Operations related to invoices (facturas de venta) endpoint.
__init__(client=None)
¶
Initialize the resource.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
client
|
AlegraClient
|
The AlegraClient instance. |
None
|
reconcile(dedup_key, client_id, lookup_pages=2, *, date=None)
¶
Return the newest invoice carrying dedup_key, or None.
When date is given, first scans up to lookup_pages * 30 invoices of the
client with the server date filter, and falls back to the newest
lookup_pages * 30 unfiltered invoices of the client if not found (no
status filter, so drafts and open invoices are both considered). The marker
is matched against the invoice's observations as a whole stripped line.
Limitations
Coverage is the whole date day when given (up to lookup_pages * 30
invoices on that day) plus the newest lookup_pages * 30 invoices of
the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dedup_key
|
str
|
Key used when the invoice was created with |
required |
client_id
|
int or str
|
Client whose invoices are scanned. |
required |
lookup_pages
|
int
|
Number of 30-record pages to scan per pass (default 2). |
2
|
date
|
date or str
|
Invoice date ( |
None
|
Returns:
| Type | Description |
|---|---|
Optional[Dict[str, Any]]
|
dict, optional: The matching invoice, or |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the key, client id, |
create_once(params, dedup_key, *, on_unverified='retry', verify_window=30.0, lookup_pages=2, precheck=True, with_outcome=False)
¶
Create an invoice at most once per dedup_key.
A unique marker (alegrapy:dedup:<key>) is appended to observations and
the invoice is looked up by that marker so re-runs return the existing record
instead of creating a duplicate.
Flow:
- With
precheck, look for the marker first; return the invoice if found. - POST the payload. A non-ambiguous failure is raised unchanged.
- On an ambiguous failure (timeout, 5xx, dropped connection), look for the
marker during
verify_windowseconds. - If not found and
on_unverified="retry", POST once more with the same payload, verify again, and otherwise raise :class:AlegraUnverifiedCreateError. Never more than 2 POSTs. - With
on_unverified="raise", raise the error right after the window.
Limitations
"retry" reduces but does not eliminate duplicates: if Alegra shows the
invoice later than verify_window, a second invoice can be created. Use
"raise" plus a quarantine queue for zero-duplicate flows. Two processes
using the same key concurrently can both miss the precheck; serialize per
key. When params["date"] is present, lookups cover up to
lookup_pages * 30 invoices on that day plus the newest
lookup_pages * 30 invoices of the client; otherwise only the newest
window is scanned. Whether observations reaches the DIAN XML is
unverified. query() itself may repeat a POST only when it provably was
not sent (429 or request_not_sent), which cannot create an extra invoice.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
params
|
dict
|
Payload for |
required |
dedup_key
|
str
|
Stable key for this logical creation, 1..64 chars of
letters, digits, |
required |
on_unverified
|
str
|
|
'retry'
|
verify_window
|
float
|
Seconds to look for the invoice after an ambiguous failure (default 30). |
30.0
|
lookup_pages
|
int
|
Pages of 30 invoices scanned on each lookup (default 2). |
2
|
precheck
|
bool
|
Look for the marker before posting (default True). |
True
|
with_outcome
|
bool
|
When True, return a :class: |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
The created (or previously existing) invoice, or a |
Any
|
class: |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the key, client id, options or observations length are invalid; nothing is sent. |
AlegraAPIError
|
The original error for a non-ambiguous failure. |
AlegraUnverifiedCreateError
|
When an ambiguous create cannot be verified. |
annul(id, cause, *, dedup_key=None, operation_type=None, number_template_id=None, stamp=True, on_unverified='retry', verify_window=30.0, lookup_pages=2, date=None)
¶
Annul a stamped electronic invoice with a credit note.
Builds and posts a VOID_ELECTRONIC_INVOICE credit note referencing the
invoice, with double-creation protection (same invoice -> same note). Only
invoices with status open and an accepted stamp can be annulled; use
:meth:void for non-electronic documents.
The invoice is re-read before every POST. If it is now closed with zero
balance and totalPaid (an annulment already happened), no note is
created: the existing note is returned through the marker lookup, or
:class:AlegraAlreadyAnnulledError is raised.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
cause
|
str
|
Reason for the annulment; must not be blank. |
required |
dedup_key
|
str
|
Override the default |
None
|
operation_type
|
CreditNoteOperationType or str
|
Defaults to
|
None
|
number_template_id
|
int or str
|
Number template for the note. |
None
|
stamp
|
bool
|
Request electronic stamping (default True). |
True
|
on_unverified
|
str
|
|
'retry'
|
verify_window
|
float
|
Seconds to look for the note after an ambiguous failure (default 30). |
30.0
|
lookup_pages
|
int
|
Pages of 30 credit notes scanned per lookup (default 2). |
2
|
date
|
date or str
|
Credit-note date ( |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
Dict[str, Any]
|
The created (or previously existing) credit note. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the cause is blank, the invoice is not open or not stamped, the invoice has no client id, or the options are invalid. |
AlegraAlreadyAnnulledError
|
The invoice is already annulled and its note was not found in the scanned pages. |
AlegraStampError
|
The note was created but stamping failed (400 with the
created document, available as |
AlegraAPIError
|
Any other API failure. |
AlegraUnverifiedCreateError
|
When the create cannot be verified. |
get_pdf(id, max_bytes=_DEFAULT_MAX_BYTES, deadline=None)
¶
Download the PDF of an invoice and return its bytes.
The file URL comes from the authenticated GET /invoices/{id}?fields=pdf call;
the download itself is anonymous: no API credentials, client headers or cookies
are sent to the file host. Signed URLs expire, so store the file, not the URL.
Two limits apply: max_bytes caps the file size, and deadline caps the
total elapsed time of the download (including redirects), because
client.timeout only bounds connect and each individual read.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
max_bytes
|
int
|
Maximum accepted file size (default 25 MB). |
_DEFAULT_MAX_BYTES
|
deadline
|
float
|
Maximum seconds for the whole download;
defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
PDF content, starting with |
Raises:
| Type | Description |
|---|---|
AlegraFileNotAvailableError
|
If the invoice has no PDF (drafts never do). |
AlegraAPIError
|
If the URL, download or content is invalid. |
AlegraTimeoutError
|
If the total download deadline is exceeded. |
ValueError
|
If the ID, |
get_xml(id, max_bytes=_DEFAULT_MAX_BYTES, deadline=None)
¶
Download the stamped XML of an invoice and return its bytes.
Uses the same anonymous download and safety rules as :meth:get_pdf.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
max_bytes
|
int
|
Maximum accepted file size (default 25 MB). |
_DEFAULT_MAX_BYTES
|
deadline
|
float
|
Maximum seconds for the whole download;
defaults to |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
bytes |
bytes
|
XML content (a UTF-8 BOM is allowed before |
Raises:
| Type | Description |
|---|---|
AlegraFileNotAvailableError
|
If the invoice has no stamped XML. |
AlegraAPIError
|
If the URL, download or content is invalid. |
AlegraTimeoutError
|
If the total download deadline is exceeded. |
ValueError
|
If the ID, |
download_pdf(id, path, overwrite=False, max_bytes=_DEFAULT_MAX_BYTES, deadline=None)
¶
Download an invoice PDF to path atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
path
|
str or PathLike
|
Destination file; its parent must exist. |
required |
overwrite
|
bool
|
Replace an existing file (default False). |
False
|
max_bytes
|
int
|
Maximum accepted file size (default 25 MB). |
_DEFAULT_MAX_BYTES
|
deadline
|
float
|
Maximum seconds for the whole download;
defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
pathlib.Path: The final path. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the file exists and |
FileNotFoundError
|
If the parent directory does not exist. |
AlegraFileNotAvailableError
|
If the invoice has no PDF. |
AlegraAPIError
|
If the URL, download or content is invalid. |
AlegraTimeoutError
|
If the total download deadline is exceeded. |
download_xml(id, path, overwrite=False, max_bytes=_DEFAULT_MAX_BYTES, deadline=None)
¶
Download an invoice XML to path atomically.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
path
|
str or PathLike
|
Destination file; its parent must exist. |
required |
overwrite
|
bool
|
Replace an existing file (default False). |
False
|
max_bytes
|
int
|
Maximum accepted file size (default 25 MB). |
_DEFAULT_MAX_BYTES
|
deadline
|
float
|
Maximum seconds for the whole download;
defaults to |
None
|
Returns:
| Type | Description |
|---|---|
Path
|
pathlib.Path: The final path. |
Raises:
| Type | Description |
|---|---|
FileExistsError
|
If the file exists and |
FileNotFoundError
|
If the parent directory does not exist. |
AlegraFileNotAvailableError
|
If the invoice has no stamped XML. |
AlegraAPIError
|
If the URL, download or content is invalid. |
AlegraTimeoutError
|
If the total download deadline is exceeded. |
send_email(id, emails, send_copy_to_user=False, subject=None, message=None)
¶
Send invoice by email.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
emails
|
list or str
|
Email address or list of email addresses to send to. |
required |
send_copy_to_user
|
bool
|
Send a copy of the email to the user (default False). |
False
|
subject
|
str
|
Custom email subject. |
None
|
message
|
str
|
Custom email body message. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Parsed JSON response from the server. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the ID is not a valid resource identifier. |
void(id, cause=None)
¶
Void a non-electronic invoice by ID.
For Colombian electronic invoices use :meth:annul: they are cancelled with a
credit note, not voided. cause is optional and sent only when provided.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
cause
|
str
|
Reason for voiding. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Parsed JSON response from the server. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the ID is not a valid resource identifier. |
open(id)
¶
Open / Reopen a void invoice by ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
Any |
Any
|
Parsed JSON response from the server. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the ID is not a valid resource identifier. |
stamp(ids)
¶
Emit 1 to 10 electronic invoices to the tax authority via POST /invoices/stamp.
Never re-POSTs on ambiguous failures (timeouts, connection errors after send,
or 5xx): callers must check :meth:stamp_status before stamping again.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ids
|
Sequence[int or str]
|
1 to 10 unique invoice IDs. |
required |
Returns:
| Type | Description |
|---|---|
List[StampResult]
|
list[StampResult]: Per-invoice results, even when HTTP 200 mixes successes
and failures or HTTP 400 carries a per-ID |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
AlegraAPIError
|
On ambiguous failures or non-per-ID 4xx/5xx responses. |
stamp_status(id)
¶
Read an invoice and return its typed electronic-stamping status.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
StampStatus |
StampStatus
|
Normalized state, emission/final flags, observations, and CUFE. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the ID is invalid or the server response is not a dict. |
AlegraAPIError
|
On API or transport failures. |
wait_until_stamped(id, timeout=60.0, interval=2.0)
¶
Poll :meth:stamp_status until a final state is reached.
ACCEPTED, ACCEPTED_WITH_OBSERVATIONS, and REJECTED are final and
returned directly (REJECTED is not raised). DRAFT, PENDING, and
UNKNOWN continue polling until timeout expires.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
|
int or str
|
Invoice ID. |
required |
timeout
|
float
|
Maximum seconds to wait (must be positive and finite). |
60.0
|
interval
|
float
|
Seconds between polls (must be positive and finite). |
2.0
|
Returns:
| Name | Type | Description |
|---|---|---|
StampStatus |
StampStatus
|
The final stamping status. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
AlegraStampTimeoutError
|
If |
AlegraAPIError
|
On API or transport failures during polling. |