-
Notifications
You must be signed in to change notification settings - Fork 13
/
invoice.py
2478 lines (2255 loc) · 98.2 KB
/
invoice.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
# This file is part of the account_invoice_ar module for Tryton.
# The COPYRIGHT file at the top level of this repository contains
# the full copyright notices and license terms.
from pyafipws.wsfev1 import WSFEv1
from pyafipws.wsfexv1 import WSFEXv1
from pyafipws.pyi25 import PyI25
from pyafipws import pyqr
from io import BytesIO
import stdnum.ar.cuit as cuit
import logging
from decimal import Decimal
from datetime import date, datetime
from calendar import monthrange
from unicodedata import normalize
from trytond.model import ModelSQL, Workflow, fields, ModelView, Index
from trytond.pool import Pool, PoolMeta
from trytond.pyson import Eval, And, If, Bool
from trytond.transaction import Transaction
from trytond.model.exceptions import AccessError
from trytond.exceptions import UserError
from trytond.i18n import gettext
from trytond.tools import cursor_dict
from .pos import INVOICE_TYPE_POS
from trytond.modules.account_invoice.exceptions import InvoiceNumberError
logger = logging.getLogger(__name__)
_ZERO = Decimal('0.0')
INVOICE_TYPE_AFIP_CODE = {
('out', False, 'A', False): ('1', '01-Factura A'),
('out', False, 'A', True): ('201', '201-Factura de Crédito MiPyme A'),
('out', False, 'B', False): ('6', '06-Factura B'),
('out', False, 'B', True): ('206', '206-Factura de Crédito MiPyme B'),
('out', False, 'C', False): ('11', '11-Factura C'),
('out', False, 'C', True): ('211', '211-Factura de Crédito MiPyme C'),
('out', False, 'E', False): ('19', '19-Factura E'),
('out', True, 'A', False): ('3', '03-Nota de Crédito A'),
('out', True, 'A', True): ('203', '203-Nota de Crédito MiPyme A'),
('out', True, 'B', False): ('8', '08-Nota de Crédito B'),
('out', True, 'B', True): ('208', '208-Nota de Crédito MiPyme B'),
('out', True, 'C', False): ('13', '13-Nota de Crédito C'),
('out', True, 'C', True): ('213', '213-Nota de Crédito MiPyme C'),
('out', True, 'E', False): ('21', '21-Nota de Crédito E'),
}
INVOICE_CREDIT_AFIP_CODE = {
'1': ('3', '03-Nota de Crédito A'),
'2': ('3', '03-Nota de Crédito A'),
'3': ('2', '02-Nota de Débito A'),
'6': ('8', '08-Nota de Crédito B'),
'7': ('8', '08-Nota de Crédito B'),
'8': ('7', '07-Nota de Débito B'),
'11': ('13', '13-Nota de Crédito C'),
'12': ('13', '13-Nota de Crédito C'),
'13': ('12', '12-Nota de Débito C'),
'19': ('21', '21-Nota de Crédito E'),
'20': ('21', '21-Nota de Crédito E'),
'21': ('20', '20-Nota de Débito E'),
'27': ('48', '48-Nota de Credito Liquidacion CLASE A'),
'28': ('43', '43-Nota de Credito Liquidacion CLASE B'),
'29': ('44', '44-Nota de Credito Liquidacion CLASE C'),
'51': ('53', '53-NotaS de Credito M'),
'81': ('112', '112-Tique Nota de Credito A'),
'82': ('113', '113-Tique Nota de Credito B'),
'83': ('110', '110-Tique Nota de Credito'),
'111': ('114', '114-Tique Nota de Credito C'),
'118': ('119', '119-Tique Nota de Credito M'),
'201': ('203', '203-Nota de Credito Electronica MiPyMEs (FCE) A'),
'202': ('203', '203-Nota de Credito Electronica MiPyMEs (FCE) A'),
'203': ('202', '202-Nota de Debito Electronica MiPyMEs (FCE) A'),
'206': ('208', '208-Nota de Credito Electronica MiPyMEs (FCE) B'),
'207': ('208', '208-Nota de Credito Electronica MiPyMEs (FCE) B'),
'208': ('207', '207-Nota de Debito Electronica MiPyMEs (FCE) B'),
'211': ('213', '213- Nota de Credito Electronica MiPyMEs (FCE) C'),
'212': ('213', '213- Nota de Credito Electronica MiPyMEs (FCE) C'),
'213': ('212', '212- Nota de Debito Electronica MiPyMEs (FCE) C'),
}
INVOICE_ASOC_AFIP_CODE = {
'1': [3],
'2': [1, 3],
'3': [1, 2],
'6': [8],
'7': [6, 8],
'8': [6, 7],
'11': [13],
'12': [11, 13],
'13': [11, 12],
'19': [21],
'20': [19, 21],
'21': [19, 20],
'201': [203],
'202': [201, 203],
'203': [201, 202],
'206': [208],
'207': [206, 208],
'208': [206, 207],
'211': [213],
'212': [211, 213],
'213': [211, 212],
}
INCOTERMS = [
('', ''),
('EXW', 'EX WORKS'),
('FCA', 'FREE CARRIER'),
('FAS', 'FREE ALONGSIDE SHIP'),
('FOB', 'FREE ON BOARD'),
('CFR', 'COST AND FREIGHT'),
('CIF', 'COST, INSURANCE AND FREIGHT'),
('CPT', 'CARRIAGE PAID TO'),
('CIP', 'CARRIAGE AND INSURANCE PAID TO'),
('DAF', 'DELIVERED AT FRONTIER'),
('DES', 'DELIVERED EX SHIP'),
('DEQ', 'DELIVERED EX QUAY'),
('DDU', 'DELIVERED DUTY UNPAID'),
('DAT', 'Delivered At Terminal'),
('DAP', 'Delivered At Place'),
('DDP', 'Delivered Duty Paid'),
]
TIPO_COMPROBANTE = [
('', ''),
('001', 'FACTURAS A'),
('002', 'NOTAS DE DEBITO A'),
('003', 'NOTAS DE CREDITO A'),
('004', 'RECIBOS A'),
('005', 'NOTAS DE VENTA AL CONTADO A'),
('006', 'FACTURAS B'),
('007', 'NOTAS DE DEBITO B'),
('008', 'NOTAS DE CREDITO B'),
('009', 'RECIBOS B'),
('010', 'NOTAS DE VENTA AL CONTADO B'),
('011', 'FACTURAS C'),
('012', 'NOTAS DE DEBITO C'),
('013', 'NOTAS DE CREDITO C'),
('015', 'RECIBOS C'),
('016', 'NOTAS DE VENTA AL CONTADO C'),
('017', 'LIQUIDACION DE SERVICIOS PUBLICOS CLASE A'),
('018', 'LIQUIDACION DE SERVICIOS PUBLICOS CLASE B'),
('019', 'FACTURAS DE EXPORTACION'),
('020', 'NOTAS DE DEBITO POR OPERACIONES CON EL EXTERIOR'),
('021', 'NOTAS DE CREDITO POR OPERACIONES CON EL EXTERIOR'),
('022', 'FACTURAS - PERMISO EXPORTACION SIMPLIFICADO - DTO. 855/97'),
('023', 'COMPROBANTES A DE COMPRA PRIMARIA SECTOR PESQUERO MARITIMO'),
('024', 'COMPROBANTES A DE CONSIGNACION PRIMARIA SECTOR PESQUERO '
'MARITIMO'),
('025', 'COMPROBANTES B DE COMPRA PRIMARIA SECTOR PESQUERO MARITIMO'),
('026', 'COMPROBANTES B DE CONSIGNACION PRIMARIA SECTOR PESQUERO '
'MARITIMO'),
('027', 'LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE A'),
('028', 'LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE B'),
('029', 'LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE C'),
('030', 'COMPROBANTES DE COMPRA DE BIENES USADOS'),
('031', 'MANDATO - CONSIGNACION'),
('032', 'COMPROBANTES PARA RECICLAR MATERIALES'),
('033', 'LIQUIDACION PRIMARIA DE GRANOS'),
('034', 'COMPROBANTES A DEL APARTADO A INCISO F RG N.1415'),
('035', 'COMPROBANTES B DEL ANEXO I, APARTADO A, INC. F), RG N. 1415'),
('036', 'COMPROBANTES C DEL Anexo I, Apartado A, INC.F), R.G. N° 1415'),
('037', 'NOTAS DE DEBITO O DOCUMENTO EQUIVALENTE CON LA R.G. N° 1415'),
('038', 'NOTAS DE CREDITO O DOCUMENTO EQUIVALENTE CON LA R.G. N° 1415'),
('039', 'OTROS COMPROBANTES A QUE CUMPLEN CON LA R G 1415'),
('040', 'OTROS COMPROBANTES B QUE CUMPLAN CON LA R.G. N° 1415'),
('041', 'OTROS COMPROBANTES C QUE CUMPLAN CON LA R.G. N° 1415'),
('043', 'NOTA DE CREDITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE B'),
('044', 'NOTA DE CREDITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE C'),
('045', 'NOTA DE DEBITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE A'),
('046', 'NOTA DE DEBITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE B'),
('047', 'NOTA DE DEBITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE C'),
('048', 'NOTA DE CREDITO LIQUIDACION UNICA COMERCIAL IMPOSITIVA CLASE A'),
('049', 'COMPROBANTES DE COMPRA DE BIENES NO REGISTRABLES A CONSUMIDORES '
'FINALES'),
('050', 'RECIBO FACTURA A REGIMEN DE FACTURA DE CREDITO'),
('051', 'FACTURAS M'),
('052', 'NOTAS DE DEBITO M'),
('053', 'NOTAS DE CREDITO M'),
('054', 'RECIBOS M'),
('055', 'NOTAS DE VENTA AL CONTADO M'),
('056', 'COMPROBANTES M DEL ANEXO I APARTADO A INC F) R.G. N° 1415'),
('057', 'OTROS COMPROBANTES M QUE CUMPLAN CON LA R.G. N° 1415'),
('058', 'CUENTAS DE VENTA Y LIQUIDO PRODUCTO M'),
('059', 'LIQUIDACIONES M'),
('060', 'CUENTAS DE VENTA Y LIQUIDO PRODUCTO A'),
('061', 'CUENTAS DE VENTA Y LIQUIDO PRODUCTO B'),
('063', 'LIQUIDACIONES A'),
('064', 'LIQUIDACIONES B'),
('066', 'DESPACHO DE IMPORTACION'),
('068', 'LIQUIDACION C'),
('070', 'RECIBOS FACTURA DE CREDITO'),
('080', 'INFORME DIARIO DE CIERRE (ZETA) - CONTROLADORES FISCALES'),
('081', 'TIQUE FACTURA A'),
('082', 'TIQUE FACTURA B'),
('083', 'TIQUE'),
('088', 'REMITO ELECTRONICO'),
('089', 'RESUMEN DE DATOS'),
('090', 'OTROS COMPROBANTES - DOCUMENTOS EXCEPTUADOS - NOTAS DE CREDITO'),
('091', 'REMITOS R'),
('099', 'OTROS COMPROBANTES QUE NO CUMPLEN O ESTÁN EXCEPTUADOS DE LA '
'R.G. 1415 Y SUS MODIF'),
('110', 'TIQUE NOTA DE CREDITO'),
('111', 'TIQUE FACTURA C'),
('112', 'TIQUE NOTA DE CREDITO A'),
('113', 'TIQUE NOTA DE CREDITO B'),
('114', 'TIQUE NOTA DE CREDITO C'),
('115', 'TIQUE NOTA DE DEBITO A'),
('116', 'TIQUE NOTA DE DEBITO B'),
('117', 'TIQUE NOTA DE DEBITO C'),
('118', 'TIQUE FACTURA M'),
('119', 'TIQUE NOTA DE CREDITO M'),
('120', 'TIQUE NOTA DE DEBITO M'),
('331', 'LIQUIDACION SECUNDARIA DE GRANOS'),
('332', 'CERTIFICACION ELECTRONICA (GRANOS)'),
]
class AfipWSTransaction(ModelSQL, ModelView):
'AFIP WS Transaction'
__name__ = 'account_invoice_ar.afip_transaction'
invoice = fields.Many2One('account.invoice', 'Invoice',
ondelete='CASCADE', required=True)
pyafipws_result = fields.Selection([
('', 'n/a'),
('A', 'Aceptado'),
('R', 'Rechazado'),
('O', 'Observado'),
], 'Resultado', readonly=True,
help='Resultado procesamiento de la Solicitud, devuelto por AFIP')
pyafipws_message = fields.Text('Mensaje', readonly=True,
help='Mensaje de error u observación, devuelto por AFIP')
pyafipws_xml_request = fields.Text('Requerimiento XML', readonly=True,
help='Mensaje XML enviado a AFIP (depuración)')
pyafipws_xml_response = fields.Text('Respuesta XML', readonly=True,
help='Mensaje XML recibido de AFIP (depuración)')
class InvoiceLine(metaclass=PoolMeta):
__name__ = 'account.invoice.line'
@classmethod
def __register__(cls, module_name):
table_h = cls.__table_handler__(module_name)
pyafipws_exento_exist = table_h.column_exist('pyafipws_exento')
super().__register__(module_name)
if pyafipws_exento_exist and cls._migrate_pyafipws_exento():
table_h.drop_column('pyafipws_exento')
@classmethod
def _migrate_pyafipws_exento(cls):
cursor = Transaction().connection.cursor()
pool = Pool()
Tax = pool.get('account.tax')
Invoice = pool.get('account.invoice')
Line = pool.get('account.invoice.line')
LineTax = pool.get('account.invoice.line-account.tax')
InvoiceTax = pool.get('account.invoice.tax')
line = Line.__table__()
invoice = Invoice.__table__()
line_tax = LineTax.__table__()
invoice_tax = InvoiceTax.__table__()
try:
iva_venta_exento, = Tax.search([
('group.afip_kind', '=', 'exento'),
('group.kind', '=', 'sale'),
])
iva_venta_no_gravado, = Tax.search([
('group.afip_kind', '=', 'no_gravado'),
('group.kind', '=', 'sale'),
])
iva_compra_exento, = Tax.search([
('group.afip_kind', '=', 'exento'),
('group.kind', '=', 'purchase'),
])
iva_compra_no_gravado, = Tax.search([
('group.afip_kind', '=', 'no_gravado'),
('group.kind', '=', 'purchase'),
])
except ValueError:
return False
iva_venta_exento_id = iva_venta_exento.id
iva_venta_no_gravado_id = iva_venta_no_gravado.id
iva_compra_exento_id = iva_compra_exento.id
iva_compra_no_gravado_id = iva_compra_no_gravado.id
computed_taxes = {}
cursor.execute(*line.join(invoice,
condition=line.invoice == invoice.id
).select(line.id, line.pyafipws_exento, line.invoice,
where=invoice.type == 'out'))
for line_id, exento, invoice_id in cursor.fetchall():
cursor.execute(*line_tax.select(line_tax.id,
where=line_tax.line == line_id))
if cursor.fetchone():
continue
invoice_line = Line(line_id)
if exento:
cursor.execute(*line_tax.insert(
columns=[line_tax.line, line_tax.tax],
values=[[line_id, iva_venta_exento_id]]))
key = (invoice_id, iva_venta_exento_id)
if key not in computed_taxes:
computed_taxes[key] = {
'invoice': invoice_id,
'tax': iva_venta_exento_id,
'description': iva_venta_exento.description,
'account': iva_venta_exento.invoice_account.id,
'base': Decimal('0.0'),
'amount': Decimal('0.0'),
'manual': False,
}
computed_taxes[key]['base'] += invoice_line.amount
else:
cursor.execute(*line_tax.insert(
columns=[line_tax.line, line_tax.tax],
values=[[line_id, iva_venta_no_gravado_id]]))
key = (invoice_id, iva_venta_no_gravado_id)
if key not in computed_taxes:
computed_taxes[key] = {
'invoice': invoice_id,
'tax': iva_venta_no_gravado_id,
'description': iva_venta_no_gravado.description,
'account': iva_venta_no_gravado.invoice_account.id,
'base': Decimal('0.0'),
'amount': Decimal('0.0'),
'manual': False,
}
computed_taxes[key]['base'] += invoice_line.amount
cursor.execute(*line.join(invoice,
condition=line.invoice == invoice.id
).select(line.id, line.pyafipws_exento, line.invoice,
where=invoice.type == 'in'))
for line_id, exento, invoice_id in cursor.fetchall():
cursor.execute(*line_tax.select(line_tax.id,
where=line_tax.line == line_id))
if cursor.fetchone():
continue
invoice_line = Line(line_id)
if exento:
cursor.execute(*line_tax.insert(
columns=[line_tax.line, line_tax.tax],
values=[[line_id, iva_compra_exento_id]]))
key = (invoice_id, iva_compra_exento_id)
if key not in computed_taxes:
computed_taxes[key] = {
'invoice': invoice_id,
'tax': iva_compra_exento_id,
'description': iva_compra_exento.description,
'account': iva_compra_exento.invoice_account.id,
'base': Decimal('0.0'),
'amount': Decimal('0.0'),
'manual': False,
}
computed_taxes[key]['base'] += invoice_line.amount
else:
cursor.execute(*line_tax.insert(
columns=[line_tax.line, line_tax.tax],
values=[[line_id, iva_compra_no_gravado_id]]))
key = (invoice_id, iva_compra_no_gravado_id)
if key not in computed_taxes:
computed_taxes[key] = {
'invoice': invoice_id,
'tax': iva_compra_no_gravado_id,
'description': iva_compra_no_gravado.description,
'account': iva_compra_no_gravado.invoice_account.id,
'base': Decimal('0.0'),
'amount': Decimal('0.0'),
'manual': False,
}
computed_taxes[key]['base'] += invoice_line.amount
if computed_taxes:
cursor.execute(*invoice_tax.insert(
columns=[invoice_tax.invoice, invoice_tax.tax,
invoice_tax.description, invoice_tax.account,
invoice_tax.base, invoice_tax.amount, invoice_tax.manual],
values=[[v['invoice'], v['tax'], v['description'],
v['account'], v['base'], v['amount'], v['manual']]
for v in computed_taxes.values()]))
return True
class Invoice(metaclass=PoolMeta):
__name__ = 'account.invoice'
_states = {'readonly': Eval('state') != 'draft'}
pos = fields.Many2One('account.pos', 'Point of Sale',
domain=[('company', '=', Eval('company'))],
states={
'required': And(Eval('type') == 'out', Eval('state') != 'draft'),
'invisible': Eval('type') == 'in',
'readonly': Eval('state') != 'draft',
})
invoice_type = fields.Many2One('account.pos.sequence', 'Comprobante',
domain=[
('pos', '=', Eval('pos')),
('invoice_type', 'in',
If(Eval('total_amount', -1) >= 0,
['1', '2', '4', '5', '6', '7', '9', '11', '12', '15',
'19', '20', '201', '202', '206', '207', '211', '212'],
['3', '8', '13', '21', '203', '208', '213']),
)],
states={
'required': And(Eval('type') == 'out', Eval('state') != 'draft'),
'invisible': Eval('type') == 'in',
'readonly': Eval('state') != 'draft',
})
invoice_type_tree = fields.Function(fields.Selection(INVOICE_TYPE_POS,
'Tipo comprobante'), 'get_comprobante', searcher='search_comprobante')
pyafipws_concept = fields.Selection([
('1', '1-Productos'),
('2', '2-Servicios'),
('3', '3-Productos y Servicios'),
('4', '4-Otros (exportación)'),
('', ''),
], 'Concepto',
states={
#'required': Eval('_parent_pos', {}).get(
# 'pos_type') == 'electronic',
'readonly': Eval('state') != 'draft',
})
pyafipws_billing_start_date = fields.Date('Fecha Desde',
states={
'required': Eval('pyafipws_concept').in_(['2', '3']),
'readonly': Eval('state') != 'draft',
},
help='Seleccionar fecha de fin de servicios - Sólo servicios')
pyafipws_billing_end_date = fields.Date('Fecha Hasta',
states={
'required': Eval('pyafipws_concept').in_(['2', '3']),
'readonly': Eval('state') != 'draft',
},
help='Seleccionar fecha de inicio de servicios - Sólo servicios')
pyafipws_transfer_mode = fields.Selection([
('SCA', 'Sistema de Circulación Abierta'),
('ADC', 'Agente de Depósito Colectivo'),
('', ''),
], 'Transferencia',
states={
'readonly': Eval('state') != 'draft',
})
pyafipws_cae = fields.Char('CAE', size=14, readonly=True,
help='Código de Autorización Electrónico, devuelto por AFIP')
pyafipws_cae_due_date = fields.Date('Vencimiento CAE', readonly=True,
help='Fecha tope para verificar CAE, devuelto por AFIP')
pyafipws_barcode = fields.Char('Codigo de Barras', size=42,
help='Código de barras para usar en la impresión', readonly=True,)
pyafipws_number = fields.Char('Número', size=13, readonly=True,
help='Número de factura informado a la AFIP')
transactions = fields.One2Many('account_invoice_ar.afip_transaction',
'invoice', 'Transacciones', readonly=True)
tipo_comprobante = fields.Selection(TIPO_COMPROBANTE, 'Comprobante',
states={
'invisible': Eval('type') == 'out',
'readonly': Eval('state') != 'draft',
})
tipo_comprobante_string = tipo_comprobante.translated('tipo_comprobante')
pyafipws_incoterms = fields.Selection(INCOTERMS, 'Incoterms')
pyafipws_licenses = fields.One2Many('account.invoice.export.license',
'invoice', 'Export Licenses')
ref_pos_number = fields.Function(fields.Char('POS Number', size=5,
states={
'required': And(Eval('type') == 'in', Eval('state') != 'draft'),
'invisible': Eval('type') == 'out',
'readonly': Eval('state') != 'draft',
}), 'get_ref_subfield', setter='set_ref_subfield')
ref_voucher_number = fields.Function(fields.Char('Voucher Number', size=8,
states={
'required': And(Eval('type') == 'in', Eval('state') != 'draft'),
'invisible': Eval('type') == 'out',
'readonly': Eval('state') != 'draft',
}), 'get_ref_subfield', setter='set_ref_subfield')
pos_pos_daily_report = fields.Function(fields.Boolean("POS Daily Report"),
'on_change_with_pos_pos_daily_report')
ref_number_from = fields.Char('From number', size=13,
states={
'required': Eval('pos_pos_daily_report', False),
'invisible': ~Eval('pos_pos_daily_report', False),
'readonly': Eval('state') != 'draft',
})
ref_number_to = fields.Char('To number', size=13,
states={
'required': Eval('pos_pos_daily_report', False),
'invisible': ~Eval('pos_pos_daily_report', False),
'readonly': Eval('state') != 'draft',
})
party_iva_condition = fields.Selection('get_party_iva_condition',
'Condición ante IVA', states=_states)
party_iva_condition_string = party_iva_condition.translated(
'party_iva_condition')
pyafipws_cbu = fields.Many2One('bank.account', 'CBU del Emisor',
domain=[
('owners', '=', Eval('company_party')),
('numbers.type', '=', 'cbu'),
],
context={
'owners': Eval('company_party'),
'numbers.type': 'cbu',
},
states=_states, depends={'company_party'})
pyafipws_anulacion = fields.Boolean('FCE MiPyme anulación',
states=_states)
currency_rate = fields.Numeric('Currency rate', digits=(12, 6),
states=_states)
pyafipws_imp_neto = fields.Function(fields.Numeric('Gravado',
digits=(12, 2)), 'on_change_with_pyafipws_imp_neto')
pyafipws_imp_tot_conc = fields.Function(fields.Numeric('No Gravado',
digits=(12, 2)), 'on_change_with_pyafipws_imp_tot_conc')
pyafipws_imp_op_ex = fields.Function(fields.Numeric('Exento',
digits=(12, 2)), 'on_change_with_pyafipws_imp_op_ex')
pyafipws_imp_iva = fields.Function(fields.Numeric('Imp. IVA',
digits=(12, 2)), 'on_change_with_pyafipws_imp_iva')
pyafipws_imp_trib = fields.Function(fields.Numeric('Imp. Tributo',
digits=(12, 2)), 'on_change_with_pyafipws_imp_trib')
pyafipws_cmp_asoc = fields.Many2Many('account.invoice-cmp.asoc',
'invoice', 'cmp_asoc', 'Comprobantes asociados',
domain=[
('company', '=', Eval('company', -1)),
('type', '=', 'out'),
['OR',
('state', 'in', ['posted', 'paid']),
('id', 'in', Eval('pyafipws_cmp_asoc')),
],
],
states=_states)
pyafipws_cmp_asoc_desde = fields.Date('Período desde',
states=_states)
pyafipws_cmp_asoc_hasta = fields.Date('Período hasta',
states=_states)
del _states
@classmethod
def __setup__(cls):
super().__setup__()
cls.reference.states.update({
'readonly': Eval('type') == 'in',
})
cls.number.states.update({
'invisible': And(
Bool(Eval('pos_pos_daily_report', False)),
Eval('state', 'draft').in_([
'draft', 'validated', 'cancelled']))
})
cls.number.depends = {'pos_pos_daily_report', 'state'}
t = cls.__table__()
#cls._sql_indexes.update({
#Index(t, (t.pyafipws_concept, Index.Equality())),
#Index(t, (t.tipo_comprobante, Index.Equality())),
#})
@classmethod
def __register__(cls, module_name):
super().__register__(module_name)
cursor = Transaction().connection.cursor()
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'001\' '
'WHERE tipo_comprobante = \'fca\';')
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'006\' '
'WHERE tipo_comprobante = \'fcb\';')
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'011\' '
'WHERE tipo_comprobante = \'fcc\';')
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'081\' '
'WHERE tipo_comprobante = \'tka\';')
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'082\' '
'WHERE tipo_comprobante = \'tkb\';')
cursor.execute('UPDATE account_invoice SET tipo_comprobante = \'111\' '
'WHERE tipo_comprobante = \'tkc\';')
@staticmethod
def default_party_iva_condition():
return ''
@staticmethod
def default_pyafipws_anulacion():
return False
@staticmethod
def default_pyafipws_imp_neto():
return _ZERO
@staticmethod
def default_pyafipws_imp_tot_conc():
return _ZERO
@staticmethod
def default_pyafipws_imp_op_ex():
return _ZERO
@staticmethod
def default_pyafipws_imp_iva():
return _ZERO
@staticmethod
def default_pyafipws_imp_trib():
return _ZERO
@staticmethod
def default_pyafipws_transfer_mode():
return 'SCA'
def on_change_party(self):
super().on_change_party()
if self.party and self.party.iva_condition:
self.party_iva_condition = self.party.iva_condition
@fields.depends('currency')
def on_change_currency(self):
if self.currency:
self.currency_rate = self.currency.rate
@fields.depends('company', 'untaxed_amount', 'lines')
def on_change_with_pyafipws_imp_neto(self, name=None):
imp_neto = _ZERO
if (self.company and self.company.party.iva_condition
in ('exento', 'monotributo') and self.untaxed_amount):
return abs(self.untaxed_amount)
for line in self.lines:
for tax in line.taxes:
if tax.group.afip_kind == 'gravado':
imp_neto += line.amount
return abs(imp_neto)
@fields.depends('company', 'untaxed_amount', 'lines')
def on_change_with_pyafipws_imp_tot_conc(self, name=None):
imp_tot_conc = _ZERO
if (self.company and self.company.party.iva_condition
in ('exento', 'monotributo')):
return imp_tot_conc
for line in self.lines:
for tax in line.taxes:
if tax.group.afip_kind == 'no_gravado':
imp_tot_conc += line.amount
return abs(imp_tot_conc)
@fields.depends('company', 'untaxed_amount', 'lines')
def on_change_with_pyafipws_imp_op_ex(self, name=None):
imp_op_ex = _ZERO
if (self.company and self.company.party.iva_condition
in ('exento', 'monotributo')):
return imp_op_ex
for line in self.lines:
for tax in line.taxes:
if tax.group.afip_kind == 'exento':
imp_op_ex += line.amount
return abs(imp_op_ex)
@fields.depends('taxes', 'lines')
def on_change_with_pyafipws_imp_trib(self, name=None):
imp_trib = _ZERO
for tax_line in self.taxes:
if (tax_line.tax and tax_line.tax.group.afip_kind not
in ('gravado', 'no_gravado', 'exento')):
imp_trib += tax_line.amount
return abs(imp_trib)
@fields.depends('taxes', 'lines')
def on_change_with_pyafipws_imp_iva(self, name=None):
imp_iva = _ZERO
for tax_line in self.taxes:
if tax_line.tax and tax_line.tax.group.afip_kind == 'gravado':
imp_iva += tax_line.amount
return abs(imp_iva)
@fields.depends('pos')
def on_change_with_pos_pos_daily_report(self, name=None):
if self.pos:
return self.pos.pos_daily_report
def get_pyafipws_cbu(self):
"Return the cbu to send afip"
for bank_account in self.company.party.bank_accounts:
if bank_account.pyafipws_cbu:
return bank_account.id
@fields.depends('company', 'type')
def on_change_with_pyafipws_cbu(self, name=None):
if self.company and self.type == 'out':
return self.get_pyafipws_cbu()
@classmethod
def order_invoice_type_tree(cls, tables):
table, _ = tables[None]
return [table.invoice_type]
@classmethod
def search_comprobante(cls, name, clause):
return [
('invoice_type.invoice_type',) + tuple(clause[1:]),
]
@classmethod
def copy(cls, invoices, default=None):
if default is None:
default = {}
else:
default = default.copy()
default['transactions'] = None
default['pyafipws_cae'] = None
default['pyafipws_cae_due_date'] = None
default['pyafipws_barcode'] = None
default['pyafipws_number'] = None
default['pyafipws_number'] = None
default['pos'] = None
default['invoice_type'] = None
default['ref_pos_number'] = None
default['ref_voucher_number'] = None
default['reference'] = None
default['tipo_comprobante'] = None
return super().copy(invoices, default=default)
@classmethod
def validate(cls, invoices):
super().validate(invoices)
for invoice in invoices:
invoice.check_unique_daily_report()
@classmethod
def get_party_iva_condition(cls):
Party = Pool().get('party.party')
return Party.fields_get(['iva_condition'])[
'iva_condition']['selection']
def check_unique_daily_report(self):
if (self.type == 'out' and self.pos and
self.pos.pos_daily_report is True):
if int(self.ref_number_from) > int(self.ref_number_to):
raise UserError(gettext(
'account_invoice_ar.msg_invalid_ref_from_to'))
invoices = self.search([
('id', '!=', self.id),
('type', '=', self.type),
('pos', '=', self.pos),
('invoice_type', '=', self.invoice_type),
('state', '!=', 'cancelled'),
])
for invoice in invoices:
if (invoice.ref_number_to is None or
invoice.ref_number_from is None):
continue
ref_number_from = int(invoice.ref_number_from)
ref_number_to = int(invoice.ref_number_to)
if ((int(self.ref_number_from) >= ref_number_from and
int(self.ref_number_from) <= ref_number_to) or
(int(self.ref_number_to) >= ref_number_from and
int(self.ref_number_to) <= ref_number_to)):
raise UserError(gettext(
'account_invoice_ar.msg_reference_unique'))
@classmethod
def view_attributes(cls):
return super().view_attributes() + [
('/form/notebook/page[@id="electronic_invoice"]', 'states', {
'invisible': Eval('type') == 'in',
}),
('/form/notebook/page[@id="electronic_invoice_incoterms"]',
'states', {
'invisible': Eval('type') == 'in',
}),
('/tree/field[@name="tipo_comprobante"]', 'tree_invisible',
Eval('type') == 'out'),
('/tree/field[@name="invoice_type_tree"]', 'tree_invisible',
Eval('type') == 'in'),
]
def get_comprobante(self, name):
if self.type == 'out' and self.invoice_type:
return self.invoice_type.invoice_type
return None
def get_ref_subfield(self, name):
if self.type == 'in' and self.reference and '-' in self.reference:
if name == 'ref_pos_number':
return self.reference.split('-')[0].lstrip('0')
elif name == 'ref_voucher_number':
return self.reference.split('-')[1].lstrip('0')
return None
@classmethod
def set_ref_subfield(cls, invoices, name, value):
if value and not value.isdigit():
raise UserError(gettext(
'account_invoice_ar.msg_invalid_ref_number',
ref_value=value))
reference = None
for invoice in invoices:
if value and invoice.type == 'in':
if name == 'ref_pos_number':
reference = '%05d-%08d' % (int(value or 0),
int(invoice.ref_voucher_number or 0))
elif name == 'ref_voucher_number':
reference = '%05d-%08d' % (
int(invoice.ref_pos_number or 0), int(value or 0))
invoice.reference = reference
cls.save(invoices)
@classmethod
@ModelView.button
@Workflow.transition('validated')
def validate_invoice(cls, invoices):
for invoice in invoices:
if invoice.type == 'out':
invoice.check_invoice_type()
elif invoice.type == 'in':
invoice.pre_validate_fields()
invoice.check_vat_existance()
super().validate_invoice(invoices)
def check_invoice_type(self):
if not self.company.party.iva_condition:
raise UserError(gettext(
'account_invoice_ar.msg_missing_company_iva_condition',
company=self.company.rec_name))
if not self.party.iva_condition:
raise UserError(gettext(
'account_invoice_ar.msg_missing_party_iva_condition',
party=self.party.rec_name))
if not self.invoice_type:
raise UserError(gettext(
'account_invoice_ar.msg_not_invoice_type'))
if not self.get_tax_identifier():
raise UserError(gettext(
'account_invoice_ar.msg_miss_tax_identifier'))
if (self.get_tax_identifier() and
not self.company.party.tax_identifier.type == 'ar_cuit'):
raise UserError(gettext(
'account_invoice_ar.msg_miss_tax_identifier'))
def pre_validate_fields(self):
if not self.reference:
raise UserError(gettext(
'account_invoice_ar.msg_invoice_missing_reference'))
if not self.tipo_comprobante:
raise UserError(gettext(
'account_invoice_ar.msg_not_invoice_type'))
def check_vat_existance(self):
for t in self.taxes:
if t.tax and t.tax.group:
if t.tax.group.code == 'IVA':
return
raise UserError(gettext(
'account_invoice_ar.msg_vat_not_existance',
invoice=self.rec_name))
def _similar_domain(self, delay=None):
# Ignore cancelled invoices when checking similarity
domain = super()._similar_domain(delay=None)
domain.append(('state', '!=', 'cancelled'))
return domain
@fields.depends('party', 'tipo_comprobante', 'type', 'reference')
def on_change_reference(self):
if self.type == 'in':
invoice = self.search([
('id', '!=', self.id),
('type', '=', self.type),
('party', '=', self.party.id),
('tipo_comprobante', '=', self.tipo_comprobante),
('reference', '=', self.reference),
('state', '!=', 'cancelled'),
])
if len(invoice) > 0:
raise UserError(gettext(
'account_invoice_ar.msg_reference_unique'))
@fields.depends('pos', 'party', 'type', 'company')
def on_change_pos(self):
self.ref_number_from = None
self.ref_number_to = None
@fields.depends('pos', 'party', 'lines', 'company', 'total_amount', 'type')
def on_change_with_invoice_type(self, name=None):
return self._set_invoice_type_sequence()
@classmethod
def _tax_identifier_types(cls):
types = super()._tax_identifier_types()
types.append('ar_cuit')
return types
def _set_invoice_type_sequence(self):
'''
Set invoice type field.
require: pos field must be set first.
'''
pool = Pool()
PosSequence = pool.get('account.pos.sequence')
if not self.pos or not self.party:
return None
company_iva = (self.company_party and
self.company_party.iva_condition or None)
client_iva = self.party and self.party.iva_condition or None
credit_note = False
fce = False
total_amount = self.total_amount or Decimal('0')
if total_amount < 0:
credit_note = True
if company_iva == 'responsable_inscripto':
if not client_iva:
return None
if client_iva in ('responsable_inscripto', 'monotributo'):
kind = 'A'
elif client_iva == 'cliente_exterior':
kind = 'E'
else:
kind = 'B'
else:
if client_iva == 'cliente_exterior':
kind = 'E'
else:
kind = 'C'
if (kind != 'E' and self.party.pyafipws_fce and
abs(total_amount) >= self.party.pyafipws_fce_amount):
fce = True
invoice_type, invoice_type_desc = INVOICE_TYPE_AFIP_CODE[
(self.type, credit_note, kind, fce)
]
sequences = PosSequence.search([
('pos', '=', self.pos),
('invoice_type', '=', invoice_type)
])
if len(sequences) == 0:
raise UserError(gettext(
'account_invoice_ar.msg_missing_sequence',
invoice_type=invoice_type_desc))
elif len(sequences) > 1:
raise UserError(gettext(
'account_invoice_ar.msg_too_many_sequences',
invoice_type_desc))
else:
sequence, = sequences
return sequence.id
def set_pyafipws_concept(self):
'''
set pyafipws_concept researching the product lines.
'''
products = {'1': 0, '2': 0}
self.pyafipws_concept = ''
for line in self.lines:
if line.type != 'line':
continue
if line.product:
if line.product.type == 'goods':
products['1'] += 1
if line.product.type == 'service':
products['2'] += 1
else:
products['2'] += 1
if products['1'] != 0 and products['2'] != 0:
self.pyafipws_concept = '3'
elif products['1'] != 0:
self.pyafipws_concept = '1'
elif products['2'] != 0:
self.pyafipws_concept = '2'
def set_pyafipws_billing_dates(self):
'''
set pyafipws_billing_dates by invoice_date.
'''
if self.pyafipws_concept not in ['2', '3']:
return
if hasattr(self, 'invoice_date') and self.invoice_date:
year = int(self.invoice_date.strftime("%Y"))
month = int(self.invoice_date.strftime("%m"))
else:
today = Pool().get('ir.date').today()
year = int(today.strftime("%Y"))
month = int(today.strftime("%m"))
self.pyafipws_billing_start_date = date(year, month, 1)
self.pyafipws_billing_end_date = date(year, month,
monthrange(year, month)[1])
def _credit(self, **values):
pool = Pool()
PosSequence = pool.get('account.pos.sequence')
credit = super()._credit(**values)
credit.currency_rate = self.currency_rate
if self.type == 'in':
invoice_type, invoice_type_desc = INVOICE_CREDIT_AFIP_CODE[
str(int(self.tipo_comprobante))
]
credit.tipo_comprobante = invoice_type.rjust(3, '0')
credit.reference = None
return credit