API

Core models

These are the code models which will normally be used for Receipt validation.

class django_afip.models.PointOfSales(*args, **kwargs)[source]

Represents an existing AFIP point of sale.

Points of sales need to be created via AFIP’s web interface and it is recommended that you use fetch_points_of_sales() to fetch these programatically.

Note that deleting or altering these models will not affect upstream point of sales.

This model also contains a few fields that are not required or sent to the AFIP when validating receipt. They are used only for PDF generation. Those fields are:

  • issuing_name
  • issuing_address
  • issuing_email
  • vat_condition
  • gross_income_condition
  • sales_terms

These fields may be ignored when using an external mechanism to generate PDF or printable receipts.

Parameters:
  • number (PositiveSmallIntegerField) – Number
  • issuance_type (CharField) – Indicates if this POS emits using CAE and CAEA.
  • blocked (BooleanField) – Blocked
  • drop_date (DateField) – Drop date
  • owner_id (ForeignKey to TaxPayer) – Owner
  • issuing_name (CharField) – The name of the issuing entity as shown on receipts.
  • issuing_address (TextField) – The address of the issuing entity as shown on receipts.
  • issuing_email (CharField) – The email of the issuing entity as shown on receipts.
  • vat_condition (CharField) – Vat condition
  • gross_income_condition (CharField) – Gross income condition
  • sales_terms (CharField) – The terms of the sale printed onto receipts by default (eg: single payment, checking account, etc).
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.Receipt(*args, **kwargs)[source]

A receipt, as sent to AFIP.

Note that AFIP allows sending ranges of receipts, but this isn’t generally what you want, so we model invoices individually.

You’ll probably want to relate some Sale or Order object from your model with each Receipt.

All document_ fields contain the recipient’s data.

If the taxpayer has taxes or pays VAT, you need to attach Tax and/or Vat instances to the Receipt.

Application code SHOULD NOT set the receipt_number code. It will be set by validate() internally. When writing code outside django-afip, this should be considered read-only. The sole exception is importing previously-validated receipts from another database. `

Parameters:
  • point_of_sales_id (ForeignKey to PointOfSales) – Point of sales
  • receipt_type_id (ForeignKey to ReceiptType) – Receipt type
  • concept_id (ForeignKey to ConceptType) – Concept
  • document_type_id (ForeignKey to DocumentType) – The document type of the recipient of this receipt.
  • document_number (BigIntegerField) – The document number of the recipient of this receipt.
  • receipt_number (PositiveIntegerField) – If left blank, the next valid number will assigned when validating the receipt.
  • issued_date (DateField) – Can diverge up to 5 days for good, or 10 days otherwise.
  • total_amount (DecimalField) – Must be equal to the sum of net_taxed, exempt_amount, net_taxes, and all taxes and vats.
  • net_untaxed (DecimalField) – The total amount to which taxes do not apply.For C-type receipts, this must be zero.
  • net_taxed (DecimalField) – The total amount to which taxes apply.For C-type receipts, this is equal to the subtotal.
  • exempt_amount (DecimalField) – Only for categories which are tax-exempt.For C-type receipts, this must be zero.
  • service_start (DateField) – Date on which a service started. No applicable for goods.
  • service_end (DateField) – Date on which a service ended. No applicable for goods.
  • expiration_date (DateField) – Date on which this receipt expires. No applicable for goods.
  • currency_id (ForeignKey to CurrencyType) – Currency in which this receipt is issued.
  • currency_quote (DecimalField) – The currency’s quote on the day this receipt was issued.
  • related_receipts (ManyToManyField) – Related receipts
exception DoesNotExist
exception MultipleObjectsReturned
formatted_number

This receipt’s number in the usual format: 0001-00003087.

is_validated

True if this instance is validated.

Note that resolving this property requires a DB query, so if you’ve a very large amount of receipts you should prefetch (see django’s select_related) the validation field. Even so, a DB query may be triggered.

If you need a large list of validated receipts, you should actually filter them via a QuerySet:

Receipt.objects.filter(validation__result==RESULT_APPROVED)
revalidate() → ReceiptValidation | None[source]

Revalidate this receipt.

Fetches data of a validated receipt from AFIP’s servers. If the receipt exists a ReceiptValidation instance is created and returned, otherwise, returns None. If there is already a ReceiptValidation for this instance, returns self.validation. This should be used for verification purpose, here’s a list of some use cases:

  • Incomplete validation process
  • Fetch CAE data from AFIP’s servers
total_tax

Returns the sum of all Tax objects.

total_vat

Returns the sum of all Vat objects.

validate(ticket: AuthTicket = None, raise_=False) → list[str][source]

Validates this receipt.

This is a shortcut to validate(). See the documentation for that method for details. Calling this validates only this instance.

Changed in version 11: The raise_ flag has been deprecated.

Parameters:
  • ticket – Use this ticket. If None, one will be loaded or created automatically.
  • raise – If True, an exception will be raised when validation fails.
class django_afip.models.ReceiptValidation(*args, **kwargs)[source]

The validation for a single Receipt.

This contains all validation-related data for a receipt, including its CAE and the CAE expiration, unless validation has failed.

The observation field may contain any data returned by AFIP regarding validation failure.

Parameters:
  • result (CharField) – Indicates whether the validation was succesful or not.
  • processed_date (DateTimeField) – Processed date
  • cae (CharField) – The CAE as returned by the AFIP.
  • cae_expiration (DateField) – The CAE expiration as returned by the AFIP.
  • receipt_id (OneToOneField to Receipt) – The Receipt for which this validation applies.
  • observations (ManyToManyField) – The observations as returned by the AFIP. These are generally present for failed validations.
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.Tax(*args, **kwargs)[source]

A tax (type+amount) for a specific Receipt.

Parameters:
  • tax_type_id (ForeignKey to TaxType) – Tax type
  • description (CharField) – Description
  • base_amount (DecimalField) – Base amount
  • aliquot (DecimalField) – Aliquot
  • amount (DecimalField) – Amount
  • receipt_id (ForeignKey to Receipt) – Receipt
exception DoesNotExist
exception MultipleObjectsReturned
compute_amount() → decimal.Decimal[source]

Auto-assign and return the total amount for this tax.

class django_afip.models.TaxPayer(*args, **kwargs)[source]

Represents an AFIP TaxPayer.

Note that multiple instances of this object can actually represent the same taxpayer, each using a different key.

The following fields are only used for generating printables, and are never sent to AFIP, hence, are entirely optional:

  • logo
Parameters:
  • name (CharField) – A friendly name to recognize this taxpayer.
  • key (FileField) – Key
  • certificate (FileField) – Certificate
  • cuit (BigIntegerField) – Cuit
  • is_sandboxed (BooleanField) – Indicates if this taxpayer should use with the sandbox servers rather than the production servers.
  • certificate_expiration (DateTimeField) – Stores expiration for the current certificate.Note that this field is updated pre-save, so the value may be invalid for unsaved models.
  • active_since (DateField) – Date since which this taxpayer has been legally active.
  • logo (ImageField) – A logo to use when generating printable receipts.
exception DoesNotExist
exception MultipleObjectsReturned
certificate_object

Returns the certificate as an OpenSSL object

Returns the certificate as an OpenSSL object (rather than as a file object).

create_ticket(service: str) → django_afip.models.AuthTicket[source]

Create an AuthTicket for a given service.

Tickets are saved to the database. It is recommended to use the get_or_create_ticket() method instead.

fetch_points_of_sales(ticket: AuthTicket = None) → list[tuple[PointOfSales, bool]][source]

Fetch all point of sales objects.

Fetch all point of sales from the WS and store (or update) them locally.

Returns a list of tuples with the format (pos, created,).

generate_csr(basename='djangoafip') → BinaryIO[source]

Creates a CSR with this TaxPayer’s key

The CSR (certificate signing request) can be used to request a new certificate via AFIP’s website. After generating a new CSR, it should be manually uploaded to AFIP’s website, and a new certificate will be returned. That certificate should be uploaded to the certificate field.

It is safe to use with when renovating expired certificates on production systems.

generate_key(force=False) → bool[source]

Creates a key file for this TaxPayer

Creates a key file for this TaxPayer if it does not have one, and immediately saves it.

A new key will not be generated if one is already set, unless the force parameter is true. This is to prevent overwriting a potentially in-use key.

Returns True if and only if a key was created.

get_certificate_expiration() → datetime | None[source]

Return the certificate expiration from the current certificate

Gets the certificate expiration from the certificate file. Note that this value is stored into certificate_expiration when an instance is saved, so you should generally prefer that method (since this one requires reading and parsing the entire certificate).

get_or_create_ticket(service: str) → django_afip.models.AuthTicket[source]

Return or create a new AuthTicket for a given serivce.

Return an existing ticket for a service if one is available, otherwise, create a new one and return that.

This is generally the preferred method of obtaining tickets for any service.

get_ticket(service: str) → AuthTicket | None[source]

Return an existing AuthTicket for a given service, if any.

It is recommended to use the get_or_create_ticket() method instead.

logo_as_data_uri

This TaxPayer’s logo as a data uri.

This can be used to embed the image into an HTML or PDF file.

class django_afip.models.Vat(*args, **kwargs)[source]

A VAT (type+amount) for a specific Receipt.

Parameters:
  • vat_type_id (ForeignKey to VatType) – Vat type
  • base_amount (DecimalField) – Base amount
  • amount (DecimalField) – Amount
  • receipt_id (ForeignKey to Receipt) – Receipt
exception DoesNotExist
exception MultipleObjectsReturned

Metadata models

These models represent metadata like currency types or document types.

You should make sure you populate these tables either via the afipmetadata command, or the load_metadata function:

django_afip.models.load_metadata() → None[source]

Loads metadata from fixtures into the database.

class django_afip.models.ConceptType(*args, **kwargs)[source]

An AFIP concept type.

See the AFIP’s documentation for details on each concept type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.CurrencyType(*args, **kwargs)[source]

An AFIP curreny type.

See the AFIP’s documentation for details on each currency type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.DocumentType(*args, **kwargs)[source]

An AFIP document type.

See the AFIP’s documentation for details on each document type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.Observation(*args, **kwargs)[source]

An observation returned by AFIP.

AFIP seems to assign re-used codes to Observation, so we actually store them as separate objects, and link to them from failed validations.

Parameters:
  • code (PositiveSmallIntegerField) – Code
  • message (CharField) – Message
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.ReceiptType(*args, **kwargs)[source]

An AFIP receipt type.

See the AFIP’s documentation for details on each receipt type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.TaxType(*args, **kwargs)[source]

An AFIP tax type.

See the AFIP’s documentation for details on each tax type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
class django_afip.models.VatType(*args, **kwargs)[source]

An AFIP VAT type.

See the AFIP’s documentation for details on each VAT type.

Parameters:
  • code (CharField) – Code
  • description (CharField) – Description
  • valid_from (DateField) – Valid from
  • valid_to (DateField) – Valid until
exception DoesNotExist
exception MultipleObjectsReturned
as_decimal

Return this VatType as a Decimal.

Parses the percent amount from the description field. This number is usable when calculating the Vat for entries which have this type. If Vat is 21%, then the returned value is Decimal("0.21").

Assuming that an item pays 21% vat, when using a net price for the calculation, the following are all correct:

total_price = net_price * Decimal(1.21)
vat = net_price * Decimal(0.21)
vat = total_price - net_price

If using the total price, this approach should be used (this can be derived from the above):

net_price = total_price / Decimal(1.21)
vat = total_price - net_price

Keep in mind that AFIP requires the usage of “round half even”, which is what Python’s Decimal class uses by default (See decimal.ROUND_HALF_EVEN).

Managers

Managers should be accessed via models. For example, ReceiptManager should be accessed using Receipt.objects.

class django_afip.models.ReceiptManager[source]

Default manager for the Receipt class.

This should be accessed using Receipt.objects.

fetch_last_receipt_number(point_of_sales: django_afip.models.PointOfSales, receipt_type: django_afip.models.ReceiptType) → int[source]

Returns the number for the last validated receipt.

fetch_receipt_data(receipt_type: django_afip.models.ReceiptType, receipt_number: int, point_of_sales: django_afip.models.PointOfSales)[source]

Returns receipt related data

get_queryset() → django_afip.models.ReceiptQuerySet[source]

Return a new QuerySet object.

This always joins with ReceiptType.

class django_afip.models.ReceiptPDFManager[source]
create_for_receipt(receipt: django_afip.models.Receipt, **kwargs) → django_afip.models.ReceiptPDF[source]

Creates a ReceiptPDF object for a given receipt.

Does not actually generate the related PDF file.

All attributes will be completed with the information for the relevant PointOfSales instance.

Parameters:
  • receipt – The receipt for the PDF which will be generated.
  • **kwargs

    Passed directly to the ReceiptPDF constructor.

QuerySets

QuerySets are generally accessed via their models. For example, Receipt.objects.filter() will return a ReceiptQuerySet.

class django_afip.models.ReceiptQuerySet(model=None, query=None, using=None, hints=None)[source]

The default queryset obtains when querying via ReceiptManager.

check_groupable() → django_afip.models.ReceiptQuerySet[source]

Check that all receipts returned by this queryset are groupable.

“Groupable” means that they can be validated together: they have the same POS and receipt type.

Returns the same queryset is all receipts are groupable, otherwise, raises CannotValidateTogether.

validate(ticket: AuthTicket = None) → list[str][source]

Validate all receipts matching this queryset.

Note that, due to how AFIP implements its numbering, this method is not thread-safe, or even multiprocess-safe. You MAY however, call this method concurrently for receipts from different PointOfSales.

It is possible that not all instances matching this queryset are validated properly. This method is written in a way that the database will always remain in a consistent state.

Only successfully validated receipts will marked as such. This method takes care of saving all changes to database.

Returns a list of errors as returned from AFIP’s webservices. When AFIP returns a failure response, an exception is not raised because partial failures are possible. Network issues (e.g.: DNS failure) _will_ raise an exception.

Receipts that successfully validate will have a ReceiptValidation object attached to them with a validation date and CAE information.

Already-validated receipts are ignored.

Attempting to validate an empty queryset will simply return an empty list.

This method takes the following steps:

  • Assigns numbers to all receipts.
  • Saves the assigned numbers to the database.
  • Sends the receipts to AFIP.
  • Saves the results into the local DB.

Should execution be interrupted (e.g.: a power failure), receipts will have been saved with their number. In this case, the revalidate method should be used, to determine if they have been registered by AFIP, or if the interruption happened before sending them.

Calling this method inside a transaction will raise RuntimeError, since doing so risks leaving the database in an inconsistent state should there be any fatal interruptions. In particular, the receipt numbers will not have been saved, so it would be impossible to recover from the incomplete operation.

Helpers

django_afip.helpers.get_server_status(production: bool) → django_afip.helpers.ServerStatus[source]

Return the status of AFIP’s WS servers

Parameters:production – Whether to check the production servers. If false, the testing servers will be checked instead.
class django_afip.helpers.ServerStatus(app: bool, db: bool, auth: bool)[source]

A dataclass holding the server’s reported status.

An instance is truthy if all services are okay, or evaluates to False if at least one isn’t:

if not server_status:
    print("At least one service is down")
else
    print("All serivces are up")
app = None

Whether the application server is working.

auth = None

Whether the authentication server is working.

db = None

Whether the database server is working.

WebService clients

These clients provide direct access to AFIP’s WS. These are reserved for advanced usage.

django_afip.clients.get_client()[source]

Return a client for a given service.

The sandbox argument should only be necessary if the client will be used to make a request. If it will only be used to serialize objects, it is irrelevant. A caller can avoid the overhead of determining the sandbox mode in the calling context if only serialization operations will take place.

This function is cached with lru_cache, and will re-use existing clients if possible.

Parameters:
  • service_name – The name of the web services.
  • sandbox – Whether the sandbox (or production) environment should be used by the returned client.
Returns:

A zeep client to communicate with an AFIP web service.