-
-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmodels.py
1844 lines (1523 loc) · 58.2 KB
/
models.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import annotations
import base64
import logging
import os
import random
import re
import warnings
from datetime import datetime
from datetime import timedelta
from datetime import timezone
from decimal import Decimal
from io import BytesIO
from tempfile import NamedTemporaryFile
from typing import TYPE_CHECKING
from typing import BinaryIO
from typing import ClassVar
from typing import Generic
from typing import TypeVar
from uuid import uuid4
from django.conf import settings
from django.core import management
from django.core.files import File
from django.core.validators import MinValueValidator
from django.db import connection
from django.db import models
from django.db.models import CheckConstraint
from django.db.models import Count
from django.db.models import F
from django.db.models import Q
from django.db.models import Sum
from django.utils.module_loading import import_string
from django.utils.translation import gettext_lazy as _
from lxml import etree
from lxml.builder import E
from OpenSSL.crypto import FILETYPE_PEM
from OpenSSL.crypto import X509
from OpenSSL.crypto import load_certificate
from zeep.exceptions import Fault
from django_afip.clients import TZ_AR
from django_afip.pdf import PdfBuilder
from . import clients
from . import crypto
from . import exceptions
from . import parsers
from . import serializers
if TYPE_CHECKING:
from django.core.files.storage import Storage
logger = logging.getLogger(__name__)
# http://www.afip.gov.ar/afip/resol1415_anexo2.html
VAT_CONDITIONS = (
"IVA Responsable Inscripto",
"IVA Responsable No Inscripto",
"IVA Exento",
"No Responsable IVA",
"Responsable Monotributo",
)
# NOTE: If you find a VAT condition not listed here, please open an issue, and
# a reference to where it's defined.
CLIENT_VAT_CONDITIONS = (
"IVA Responsable Inscripto",
"IVA Responsable No Inscripto",
"IVA Sujeto Exento",
"Consumidor Final",
"Responsable Monotributo",
"Proveedor del Exterior",
"Cliente del Exterior",
"IVA Liberado - Ley Nº 19.640",
"IVA Responsable Inscripto - Agente de Percepción",
"Monotributista Social",
"IVA no alcanzado",
)
def load_metadata() -> None:
"""Loads metadata from fixtures into the database."""
for model in GenericAfipType.SUBCLASSES:
label = model._meta.label.split(".")[1].lower()
management.call_command("loaddata", label, app="afip")
def check_response(response) -> None: # noqa: ANN001
"""Check that a response is not an error.
AFIP allows us to create valid tickets with invalid key/CUIT pairs, so we
can end up with tickets that fail on any service.
Due to how zeep works, we can't quite catch these sort of errors on some
middleware level (well, honestly, we need to do a large refactor).
This method checks if responses have an error, and raise a readable
message.
"""
if "Errors" in response:
if response.Errors:
raise exceptions.AfipException(response)
elif "errorConstancia" in response and response.errorConstancia:
raise exceptions.AfipException(response)
def first_currency() -> int | None:
"""Returns the id for the first currency
The `default` parameter of a foreign key *MUST* be a primary key (and not
an instance), else migrations break. This helper method exists solely for
that purpose.
"""
ct = CurrencyType.objects.filter(code="PES").first()
if ct:
return ct.pk
return None
def _get_storage_from_settings(setting_name: str) -> Storage:
path = getattr(settings, setting_name, None)
if not path:
return import_string(settings.DEFAULT_FILE_STORAGE)()
return import_string(path)
_T = TypeVar("_T", bound="GenericAfipType", covariant=True)
class GenericAfipTypeManager(models.Manager, Generic[_T]):
"""Default Manager for GenericAfipType."""
def __init__(self, service_name: str, type_name: str) -> None:
"""Create a new Manager instance for a GenericAfipType.
This should generally only be required to manually populate a single
type with upstream data.
"""
super().__init__()
self.__service_name = service_name
self.__type_name = type_name
def populate(self, ticket: AuthTicket | None = None) -> None:
"""Fetch and save data for this model from AFIP's WS.
Direct usage of this method is discouraged, use
:func:`~.models.load_metadata` instead.
"""
ticket = ticket or AuthTicket.objects.get_any_active("wsfe")
client = clients.get_client("wsfe", ticket.owner.is_sandboxed)
service = getattr(client.service, self.__service_name)
response_xml = service(serializers.serialize_ticket(ticket))
check_response(response_xml)
for result in getattr(response_xml.ResultGet, self.__type_name):
self.get_or_create(
code=result.Id,
description=result.Desc,
valid_from=parsers.parse_date(result.FchDesde),
valid_to=parsers.parse_date_maybe(result.FchHasta),
)
def get_by_natural_key(self, code: str) -> _T:
return self.get(code=code)
def exists_by_natural_key(self, code: str) -> bool:
return self.filter(code=code).exists()
class GenericAfipType(models.Model):
"""An abstract class for several of AFIP's metadata types.
You should not use this class directly, only subclasses of it. You should
not create subclasses of this model unless you really know what you're doing.
"""
SUBCLASSES: ClassVar[list[type[GenericAfipType]]] = []
def __init_subclass__(cls, **kwargs) -> None:
"""Keeps a registry of known subclasses."""
super().__init_subclass__(**kwargs)
GenericAfipType.SUBCLASSES.append(cls)
code = models.CharField(
_("code"),
max_length=3,
)
description = models.CharField(
_("description"),
max_length=250,
)
valid_from = models.DateField(
_("valid from"),
null=True,
blank=True,
)
valid_to = models.DateField(
_("valid until"),
null=True,
blank=True,
)
def natural_key(self) -> tuple[str]:
return (self.code,)
def __str__(self) -> str:
return self.description
class Meta:
abstract = True
class ReceiptType(GenericAfipType):
"""An AFIP receipt type.
See the AFIP's documentation for details on each receipt type.
"""
objects = GenericAfipTypeManager("FEParamGetTiposCbte", "CbteTipo")
class Meta:
verbose_name = _("receipt type")
verbose_name_plural = _("receipt types")
class ConceptType(GenericAfipType):
"""An AFIP concept type.
See the AFIP's documentation for details on each concept type.
"""
objects = GenericAfipTypeManager("FEParamGetTiposConcepto", "ConceptoTipo")
class Meta:
verbose_name = _("concept type")
verbose_name_plural = _("concept types")
class DocumentType(GenericAfipType):
"""An AFIP document type.
See the AFIP's documentation for details on each document type.
"""
objects = GenericAfipTypeManager("FEParamGetTiposDoc", "DocTipo")
class Meta:
verbose_name = _("document type")
verbose_name_plural = _("document types")
class VatType(GenericAfipType):
"""An AFIP VAT type.
See the AFIP's documentation for details on each VAT type.
"""
@property
def as_decimal(self) -> 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``).
"""
match = re.match(r"^([0-9]{1,2}\.?[0-9]{0,2})%$", self.description)
if not match:
raise ValueError("The description for this VatType is not a percentage.")
return Decimal(match.groups()[0]) / 100
objects = GenericAfipTypeManager("FEParamGetTiposIva", "IvaTipo")
class Meta:
verbose_name = _("vat type")
verbose_name_plural = _("vat types")
class TaxType(GenericAfipType):
"""An AFIP tax type.
See the AFIP's documentation for details on each tax type.
"""
objects = GenericAfipTypeManager("FEParamGetTiposTributos", "TributoTipo")
class Meta:
verbose_name = _("tax type")
verbose_name_plural = _("tax types")
class CurrencyType(GenericAfipType):
"""An AFIP curreny type.
See the AFIP's documentation for details on each currency type.
"""
objects = GenericAfipTypeManager("FEParamGetTiposMonedas", "Moneda")
def __str__(self) -> str:
return f"{self.description} ({self.code})"
class Meta:
verbose_name = _("currency type")
verbose_name_plural = _("currency types")
class OptionalType(GenericAfipType):
"""An AFIP optional type.
See the AFIP's documentation for details on each optional type.
"""
# This specific type has length = 4.
code = models.CharField(
_("code"),
max_length=4,
)
objects = GenericAfipTypeManager("FEParamGetTiposOpcional", "OpcionalTipo")
def __str__(self) -> str:
return f"{self.description} ({self.code})"
class Meta:
verbose_name = _("optional type")
verbose_name_plural = _("optional types")
class TaxPayer(models.Model):
"""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
"""
# XXX: Split this into TaxPayer and Credentials
# The former has a unique CUIT, which will be its natural key.
# The latter has the key and cert and alike.
#
# For the migration path:
# - Make sure that if there's 1:1 TaxPayer:Credentials,
# everything continues to work as it does now.
# - Provide data migrations
name = models.CharField(
_("name"),
max_length=32,
help_text=_("A friendly name to recognize this taxpayer."),
)
key = models.FileField(
verbose_name=_("key"),
upload_to="afip/taxpayers/keys/",
storage=_get_storage_from_settings("AFIP_KEY_STORAGE"),
blank=True,
null=True,
)
certificate = models.FileField(
verbose_name=_("certificate"),
upload_to="afip/taxpayers/certs/",
storage=_get_storage_from_settings("AFIP_CERT_STORAGE"),
blank=True,
null=True,
)
cuit = models.BigIntegerField(
_("cuit"),
)
is_sandboxed = models.BooleanField(
_("is sandboxed"),
help_text=_(
"Indicates if this taxpayer should use with the sandbox servers "
"rather than the production servers."
),
)
certificate_expiration = models.DateTimeField(
_("certificate expiration"),
editable=False,
null=True, # Either no cert, or an old TaxPayer.
help_text=_(
"Stores expiration for the current certificate.<br>Note that this "
"field is updated pre-save, so the value may be invalid for unsaved models."
),
)
active_since = models.DateField(
_("active since"),
help_text=_("Date since which this taxpayer has been legally active."),
)
logo = models.ImageField(
verbose_name=_("logo"),
upload_to="afip/taxpayers/logos/",
storage=_get_storage_from_settings("AFIP_LOGO_STORAGE"),
blank=True,
null=True,
help_text=_("A logo to use when generating printable receipts."),
)
@property
def logo_as_data_uri(self) -> str:
"""This TaxPayer's logo as a data uri.
This can be used to embed the image into an HTML or PDF file.
"""
_, ext = os.path.splitext(self.logo.file.name)
with self.logo.open() as f:
data = base64.b64encode(f.read())
image_fmt = ext[1:] # Remove the leading dot.
return f"data:image/{image_fmt};base64,{data.decode()}"
@property
def certificate_object(self) -> X509 | None:
"""Returns the certificate as an OpenSSL object
Returns the certificate as an OpenSSL object (rather than as a file
object).
"""
if not self.certificate:
return None
self.certificate.seek(0)
return load_certificate(FILETYPE_PEM, self.certificate.read())
def get_certificate_expiration(self) -> datetime | None:
"""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).
"""
cert = self.certificate_object
if not cert:
return None
not_after = cert.get_notAfter()
if not not_after:
return None
datestring = not_after.decode()
dt = datetime.strptime(datestring, "%Y%m%d%H%M%SZ")
return dt.replace(tzinfo=timezone.utc)
def generate_key(self, force: bool = False) -> bool:
"""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.
"""
if self.key and not force:
logger.warning("Tried to generate key for a taxpayer that already had one")
return False
with NamedTemporaryFile(suffix=".key") as file_:
crypto.create_key(file_)
self.key = File(file_, name=f"{uuid4().hex}.key")
self.save()
return True
def generate_csr(self, basename: str = "djangoafip") -> BinaryIO:
"""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.
"""
csr = BytesIO()
crypto.create_csr(
self.key.file,
self.name,
f"{basename}{int(datetime.now().timestamp())}",
f"CUIT {self.cuit}",
csr,
)
csr.seek(0)
return csr
def create_ticket(self, service: str) -> AuthTicket:
"""Create an AuthTicket for a given service.
Tickets are saved to the database. It is recommended to use the
:meth:`~.TaxPayer.get_or_create_ticket` method instead.
"""
ticket = AuthTicket(owner=self, service=service)
ticket.authorize()
return ticket
def get_ticket(self, service: str) -> AuthTicket | None:
"""Return an existing AuthTicket for a given service, if any.
It is recommended to use the :meth:`~.TaxPayer.get_or_create_ticket` method
instead.
"""
return self.auth_tickets.filter(
expires__gt=datetime.now(timezone.utc),
service=service,
).last()
def get_or_create_ticket(self, service: str) -> AuthTicket:
"""
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.
"""
return self.get_ticket(service) or self.create_ticket(service)
def fetch_points_of_sales(
self,
ticket: AuthTicket | None = None,
) -> list[tuple[PointOfSales, bool]]:
"""
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,)``.
"""
ticket = ticket or self.get_or_create_ticket("wsfe")
client = clients.get_client("wsfe", self.is_sandboxed)
response = client.service.FEParamGetPtosVenta(
serializers.serialize_ticket(ticket),
)
check_response(response)
results = []
for pos_data in response.ResultGet.PtoVenta:
results.append(
PointOfSales.objects.update_or_create(
number=pos_data.Nro,
owner=self,
defaults={
"issuance_type": pos_data.EmisionTipo,
"blocked": pos_data.Bloqueado == "S",
"drop_date": parsers.parse_date_maybe(pos_data.FchBaja),
},
)
)
return results
def __repr__(self) -> str:
return f"<TaxPayer {self.pk}: {self.name}, CUIT {self.cuit}>"
def __str__(self) -> str:
return str(self.name)
class Meta:
verbose_name = _("taxpayer")
verbose_name_plural = _("taxpayers")
class PointOfSales(models.Model):
"""
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 :meth:`~.TaxPayer.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.
"""
number = models.PositiveSmallIntegerField(
_("number"),
)
# AFIP has replied that this field may be up to 200bytes,
# so 200 characters should always be more than enough.
issuance_type = models.CharField(
_("issuance type"),
max_length=200,
help_text="Indicates if this POS emits using CAE and CAEA.",
)
blocked = models.BooleanField(
_("blocked"),
)
drop_date = models.DateField(
_("drop date"),
null=True,
blank=True,
)
owner = models.ForeignKey(
TaxPayer,
related_name="points_of_sales",
verbose_name=_("owner"),
on_delete=models.CASCADE,
)
# The following fields are only used for PDF generation.
issuing_name = models.CharField(
max_length=128,
null=True,
verbose_name=_("issuing name"),
help_text=_("The name of the issuing entity as shown on receipts."),
)
issuing_address = models.TextField(
_("issuing address"),
null=True,
help_text=_("The address of the issuing entity as shown on receipts."),
)
issuing_email = models.CharField(
max_length=128,
verbose_name=_("issuing email"),
blank=True,
null=True,
help_text=_("The email of the issuing entity as shown on receipts."),
)
vat_condition = models.CharField(
max_length=48,
choices=(
(
condition,
condition,
)
for condition in VAT_CONDITIONS
),
null=True,
verbose_name=_("vat condition"),
)
gross_income_condition = models.CharField(
max_length=48,
null=True,
verbose_name=_("gross income condition"),
)
sales_terms = models.CharField(
max_length=48,
null=True,
verbose_name=_("sales terms"),
help_text=_(
"The terms of the sale printed onto receipts by default "
"(eg: single payment, checking account, etc)."
),
)
def __str__(self) -> str:
return str(self.number)
class Meta:
unique_together = (("number", "owner"),)
verbose_name = _("point of sales")
verbose_name_plural = _("points of sales")
class AuthTicketManager(models.Manager["AuthTicket"]):
def get_any_active(self, service: str) -> AuthTicket:
"""Return a valid, active ticket for a given service."""
ticket = AuthTicket.objects.filter(
token__isnull=False,
expires__gt=datetime.now(timezone.utc),
service=service,
).first()
if ticket:
return ticket
taxpayer = TaxPayer.objects.order_by("?").first()
if not taxpayer:
raise exceptions.AuthenticationError(
_("There are no taxpayers to generate a ticket."),
)
return taxpayer.create_ticket(service)
def get_by_natural_key(self, unique_id: int) -> AuthTicket:
return self.get(unique_id=unique_id)
def default_generated() -> datetime:
"""The default generated date for new tickets."""
return datetime.now(TZ_AR)
def default_expires() -> datetime:
"""The default expiration date for new tickets."""
return datetime.now(TZ_AR) + timedelta(hours=12)
def default_unique_id() -> int:
"""A random unique id for new tickets."""
return random.randint(0, 2147483647)
class AuthTicket(models.Model):
"""An AFIP Authorization ticket.
This is a signed ticket used to communicate with AFIP's webservices.
Applications should not generally have to deal with these tickets
themselves; most services will find or create one as necessary.
"""
owner = models.ForeignKey(
TaxPayer,
verbose_name=_("owner"),
related_name="auth_tickets",
on_delete=models.CASCADE,
)
unique_id = models.IntegerField(
_("unique id"),
default=default_unique_id,
)
generated = models.DateTimeField(
_("generated"),
default=default_generated,
)
expires = models.DateTimeField(
_("expires"),
default=default_expires,
)
service = models.CharField(
_("service"),
max_length=34,
help_text=_("Service for which this ticket has been authorized."),
)
token = models.TextField(
_("token"),
)
signature = models.TextField(
_("signature"),
)
objects = AuthTicketManager()
TOKEN_XPATH = "/loginTicketResponse/credentials/token"
SIGN_XPATH = "/loginTicketResponse/credentials/sign"
def __create_request_xml(self) -> bytes:
"""Create a new ticket request XML
This is the payload we sent to AFIP to request a new ticket."""
request_xml = E.loginTicketRequest(
{"version": "1.0"},
E.header(
E.uniqueId(str(self.unique_id)),
E.generationTime(serializers.serialize_datetime(self.generated)),
E.expirationTime(serializers.serialize_datetime(self.expires)),
),
E.service(self.service),
)
# Hint: tostring returns bytes.
return etree.tostring(request_xml, pretty_print=True)
def __sign_request(self, request: bytes) -> bytes:
with self.owner.certificate.file.open("rb") as f:
cert = f.read()
with self.owner.key.file.open("rb") as f:
key = f.read()
return crypto.create_embeded_pkcs7_signature(request, cert, key)
def authorize(self) -> None:
"""Send this ticket to AFIP for authorization."""
request_xml = self.__create_request_xml()
signed_request = self.__sign_request(request_xml)
request = base64.b64encode(signed_request).decode()
client = clients.get_client("wsaa", self.owner.is_sandboxed)
try:
raw_response = client.service.loginCms(request)
except Fault as e:
if str(e) == "Certificado expirado":
raise exceptions.CertificateExpired(str(e)) from e
if str(e) == "Certificado no emitido por AC de confianza":
raise exceptions.UntrustedCertificate(str(e)) from e
raise exceptions.AuthenticationError(str(e)) from e
response = etree.fromstring(raw_response.encode("utf-8"))
self.token = response.xpath(self.TOKEN_XPATH)[0].text
self.signature = response.xpath(self.SIGN_XPATH)[0].text
self.save()
def natural_key(self) -> tuple[int]:
return (self.unique_id,)
def __str__(self) -> str:
return str(self.unique_id)
class Meta:
verbose_name = _("authorization ticket")
verbose_name_plural = _("authorization tickets")
class ReceiptQuerySet(models.QuerySet):
"""The default queryset obtains when querying via :class:`~.ReceiptManager`."""
# This private flag is provided only to disable the durability checks in tests.
# Inspired by Django's flag of the same name for `Atomic`.
_ensure_durability = True
def _assign_numbers(self) -> None:
"""Assign numbers in preparation for validating these receipts.
WARNING: Don't call the method manually unless you know what you're
doing!
"""
first = self.select_related("point_of_sales", "receipt_type").first()
assert first is not None # should never happen; mostly a hint for mypy
next_num = (
Receipt.objects.fetch_last_receipt_number(
first.point_of_sales,
first.receipt_type,
)
+ 1
)
for receipt in self.filter(receipt_number__isnull=True):
# Atomically update receipt number
Receipt.objects.filter(
pk=receipt.id,
receipt_number__isnull=True,
).update(
receipt_number=next_num,
)
next_num += 1
def check_groupable(self) -> ReceiptQuerySet:
"""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 :class:`~.CannotValidateTogether`.
"""
types = self.aggregate(
poses=Count(
"point_of_sales_id",
),
types=Count("receipt_type"),
)
if set(types.values()) > {1}:
raise exceptions.CannotValidateTogether
return self
def validate(self, ticket: AuthTicket | None = None) -> list[str]:
"""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 :class:`~.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 :class:`~.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.
"""
if self._ensure_durability and connection.in_atomic_block:
raise RuntimeError("This function cannot be called within a transaction")
# Skip any already-validated ones:
qs = self.filter(validation__isnull=True).check_groupable()
if qs.count() == 0:
return []
qs.order_by("issued_date", "id")._assign_numbers()
return qs._validate(ticket)
def _validate(self, ticket: AuthTicket | None = None) -> list[str]:
first = self.first()
assert first is not None # should never happen; mostly a hint for mypy
ticket = ticket or first.point_of_sales.owner.get_or_create_ticket("wsfe")
client = clients.get_client("wsfe", first.point_of_sales.owner.is_sandboxed)
response = client.service.FECAESolicitar(
serializers.serialize_ticket(ticket),
serializers.serialize_multiple_receipts(self),
)
check_response(response)
errs = []
for cae_data in response.FeDetResp.FECAEDetResponse:
if cae_data.Resultado == ReceiptValidation.RESULT_APPROVED:
validation = ReceiptValidation.objects.create(
result=cae_data.Resultado,
cae=cae_data.CAE,
cae_expiration=parsers.parse_date(cae_data.CAEFchVto),
receipt=self.get(
receipt_number=cae_data.CbteDesde,
),
processed_date=parsers.parse_datetime(
response.FeCabResp.FchProceso,
),
)
if cae_data.Observaciones:
for obs in cae_data.Observaciones.Obs:
observation = Observation.objects.create(
code=obs.Code,
message=obs.Msg,
)
validation.observations.add(observation)
elif cae_data.Observaciones:
for obs in cae_data.Observaciones.Obs:
errs.append(f"Error {obs.Code}: {parsers.parse_string(obs.Msg)}")
# Remove the number from ones that failed to validate:
self.filter(validation__isnull=True).update(receipt_number=None)
return errs
class ReceiptManager(models.Manager):
"""Default manager for the :class:`~.Receipt` class.
This should be accessed using ``Receipt.objects``.
"""
def fetch_last_receipt_number(
self,
point_of_sales: PointOfSales,
receipt_type: ReceiptType,
) -> int:
"""Returns the number for the last validated receipt."""
client = clients.get_client("wsfe", point_of_sales.owner.is_sandboxed)
response_xml = client.service.FECompUltimoAutorizado(
serializers.serialize_ticket(