-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathaeat.py
1629 lines (1456 loc) · 63.2 KB
/
aeat.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
# -*- coding: utf-8 -*-
# The COPYRIGHT file at the top level of this repository contains the full
# copyright notices and license terms.
from logging import getLogger
from decimal import Decimal
from datetime import datetime, timedelta
from zeep import helpers
import json
from collections import namedtuple
from ast import literal_eval
from trytond.model import ModelSQL, ModelView, fields, Workflow
from trytond.wizard import Wizard, StateView, StateAction, Button
from trytond.pyson import Eval, Bool, PYSONEncoder
from trytond.pool import Pool
from trytond.transaction import Transaction
from trytond.config import config
from trytond.i18n import gettext
from trytond.exceptions import UserError
from trytond.tools import grouped_slice
from trytond.modules.account.exceptions import FiscalYearNotFoundError
from . import tools
from . import service
_logger = getLogger(__name__)
_ZERO = Decimal(0)
# AEAT SII test
SII_TEST = config.getboolean('aeat', 'sii_test', default=True)
MAX_SII_LINES = config.getint('aeat', 'sii_lines', default=300)
def _decimal(x):
return Decimal(x) if x is not None else None
def _date(x):
return datetime.strptime(x, "%d-%m-%Y").date()
def _datetime(x):
return datetime.strptime(x, "%d-%m-%Y %H:%M:%S")
COMMUNICATION_TYPE = [ # L0
(None, ''),
('A0', 'Registration of invoices/records'),
('A1', 'Amendment of invoices/records (registration errors)'),
# ('A4', 'Amendment of Invoice for Travellers'), # Not supported
# ('A5', 'Travellers registration'), # Not supported
# ('A6', 'Amendment of travellers tax devolutions'), # Not supported
('C0', 'Query Invoices'), # Not in L0
('D0', 'Delete Invoices'), # Not In L0
]
BOOK_KEY = [
(None, ''),
('E', 'Issued Invoices'),
('I', 'Investment Goods'),
('R', 'Received Invoices'),
('U', 'Particular Intracommunity Operations'),
]
# TipoFactura
OPERATION_KEY = [ # L2_EMI - L2_RECI
(None, ''),
('F1', 'Invoice (Art 6.7.3 y 7.3 of RD1619/2012)'),
('F2', 'Simplified Invoice (ticket) and Invoices without destination '
'identidication (Art 6.1.d of RD1619/2012)'),
('F3', 'Invoice issued to replace simplified invoices issued and filed'),
('F4', 'Invoice summary entry'),
('F5', 'Import (DUA)'),
('F6', 'Other accounting documents'),
# R1: errores fundados de derecho y causas del artículo 80.Uno, Dos y Seis
# LIVA
('R1', 'Corrected Invoice '
'(Art 80.1, 80.2 and 80.6 and error grounded in law)'),
# R2: concurso de acreedores
('R2', 'Corrected Invoice (Art. 80.3)'),
# R3: deudas incobrables
('R3', 'Credit Note (Art 80.4)'),
# R4: resto de causas
('R4', 'Corrected Invoice (Other)'),
('R5', 'Corrected Invoice in simplified invoices'),
('LC', 'Duty - Complementary clearing'), # Not supported
]
# IDType
PARTY_IDENTIFIER_TYPE = [
(None, 'VAT (for National operators)'),
('02', 'VAT (only for intracommunity operators)'),
('03', 'Passport'),
('04', 'Official identification document issued by the country '
'or region of residence'),
('05', 'Residence certificate'),
('06', 'Other supporting document'),
('07', 'Not registered (only for Spanish VAT not registered)'),
# Extra register add for the control of Simplified Invocies, but not in the
# SII list
('SI', 'Simplified Invoice'),
]
# ClaveRegimenEspecialOTrascendencia
SEND_SPECIAL_REGIME_KEY = [ # L3.1
(None, ''),
('01', 'General tax regime activity'),
('02', 'Export'),
('03', 'Activities to which the special scheme of used goods, '
'works of art, antiquities and collectables (135-139 of the VAT Law)'),
('04', 'Special scheme for investment gold'),
('05', 'Special scheme for travel agencies'),
('06', 'Special scheme applicable to groups of entities, VAT (Advanced)'),
('07', 'Special cash basis scheme'),
('08', 'Activities subject to Canary Islands General Indirect Tax/Tax on '
'Production, Services and Imports'),
('09', 'Invoicing of the provision of travel agency services acting as '
'intermediaries in the name of and on behalf of other persons '
'(Additional Provision 4, Royal Decree 1619/2012)'),
('10', 'Collections on behalf of third parties of professional fees or '
'industrial property, copyright or other such rights by partners, '
'associates or members undertaken by companies, associations, '
'professional organisations or other entities that, amongst their '
'functions, undertake collections'),
('11', 'Business premises lease activities subject to withholding'),
('12', 'Business premises lease activities not subject to withholding'),
('13', 'Business premises lease activities subject and not subject '
'to withholding'),
('14', 'Invoice with VAT pending accrual (work certifications with Public '
'Administration recipients)'),
('15', 'Invoice with VAT pending accrual - '
'operations of successive tract'),
('16', 'First semester 2017 and other invoices before the SII'),
]
# ClaveRegimenEspecialOTrascendencia
RECEIVE_SPECIAL_REGIME_KEY = [ # L3.2
(None, ''),
('01', 'General tax regime activity'),
('02', 'Activities through which businesses pay compensation for special '
'VAT arrangements for agriculture and fisheries (REAGYP)'),
('03', 'Activities to which the special scheme of used goods, '
'works of art, antiquities and collectables (REBU) [135-139 of the VAT'
' Law]'),
('04', 'Special scheme for investment gold'),
('05', 'Special scheme for travel agencies'),
('06', 'Special scheme applicable to groups of entities, VAT (Advanced)'),
('07', 'Special cash basis scheme'),
('08', 'Activities subject to Canary Islands General Indirect Tax/Tax '
'on Production, Services and Imports (IPSI/IGIC)'),
('09', 'Intra-Community acquisition of assets and provisions of services'),
('12', 'Business premises lease activities'),
('13', 'Invoice corresponding to an import '
'(reported without been associated with a DUA)'),
('14', 'First semester 2017 and other invoices before the SII'),
]
AEAT_COMMUNICATION_STATE = [
(None, ''),
('Correcto', 'Accepted'),
('ParcialmenteCorrecto', 'Partially Accepted'),
('Incorrecto', 'Rejected')
]
AEAT_INVOICE_STATE = [
(None, ''),
('Correcto', 'Accepted '),
('Correcta', 'Accepted'), # You guys are disgusting
('AceptadoConErrores', 'Accepted with Errors '),
('AceptadaConErrores', 'Accepted with Errors'), # Shame on AEAT
('Anulada', 'Deleted'),
('Incorrecto', 'Rejected'),
('duplicated_unsubscribed', 'Duplicated / Unsubscribed'),
]
PROPERTY_STATE = [ # L6
('0', ''),
('1', '1. Property with a land register reference located in any part '
'of Spain, with the exception of the Basque Country and Navarre'),
('2', '2. Property located in the Autonomous Community of the Basque '
'Country or the Chartered Community of Navarre.'),
('3', '3. Property in any of the foregoing locations '
'with no land register reference'),
('4', '4. Property located abroad'),
]
# L7 - Iva Subjected
IVA_SUBJECTED = [
(None, ''),
('S1', 'Subject - Not exempt. Non VAT reverse charge'),
('S2', 'Subject - Not exempt. VAT reverse charge'),
('S3', 'Subject - Not exempt. Both non VAT reverse charge '
'and VAT reverse charge')
]
# L9 - Exemption cause
EXEMPTION_CAUSE = [
(None, ''),
('E1', 'Exempt on account of Article 20'),
('E2', 'Exempt on account of Article 21'),
('E3', 'Exempt on account of Article 22'),
('E4', 'Exempt on account of Article 23 and Article 24'),
('E5', 'Exempt on account of Article 25'),
('E6', 'Exempt on other grounds'),
('NotSubject', 'Not Subject'),
]
_STATES = {
'readonly': Eval('state') != 'draft',
}
_DEPENDS = ['state']
class SIIReport(Workflow, ModelSQL, ModelView):
''' SII Report '''
__name__ = 'aeat.sii.report'
company = fields.Many2One('company.company', 'Company', required=True,
states={
'readonly': Eval('state') != 'draft',
})
company_vat = fields.Char('VAT', size=9,
states={
'required': Eval('state').in_(['confirmed', 'done']),
'readonly': ~Eval('state').in_(['draft', 'confirmed']),
})
currency = fields.Function(fields.Many2One('currency.currency',
'Currency'), 'on_change_with_currency')
fiscalyear = fields.Many2One('account.fiscalyear', 'Fiscal Year',
required=True, states={
'readonly': ((Eval('state') != 'draft')
| (Eval('lines', [0]) & Eval('fiscalyear'))),
})
period = fields.Many2One('account.period', 'Period', required=True,
domain=[('fiscalyear', '=', Eval('fiscalyear'))],
states={
'readonly': ((Eval('state') != 'draft')
| (Eval('lines', [0]) & Eval('period'))),
})
load_date = fields.Date('Load Date',
domain=['OR', [
('load_date', '=', None),
], [
('load_date', '>=', Eval('load_date_start')),
('load_date', '<=', Eval('load_date_end')),
]], help='Filter invoices to the date whitin the period.')
load_date_start = fields.Function(fields.Date('Load Date Start'),
'on_change_with_load_date_start')
load_date_end = fields.Function(fields.Date('Load Date End'),
'on_change_with_load_date_end')
operation_type = fields.Selection(COMMUNICATION_TYPE, 'Operation Type',
required=True,
states={
'readonly': ((~Eval('state').in_(['draft', 'confirmed']))
| (Eval('lines', [0]) & Eval('operation_type'))),
})
book = fields.Selection(BOOK_KEY, 'Book', required=True,
states={
'readonly': ((~Eval('state').in_(['draft', 'confirmed']))
| (Eval('lines', [0]) & Eval('book'))),
})
state = fields.Selection([
('draft', 'Draft'),
('confirmed', 'Confirmed'),
('sending', 'Sending'),
('cancelled', 'Cancelled'),
('sent', 'Sent'),
], 'State', readonly=True)
communication_state = fields.Selection(AEAT_COMMUNICATION_STATE,
'Communication State', readonly=True)
csv = fields.Char('CSV', readonly=True)
version = fields.Selection([
('0.7', '0.7'),
('1.0', '1.0'),
('1.1', '1.1'),
], 'Version', required=True, readonly=True)
lines = fields.One2Many('aeat.sii.report.lines', 'report',
'Lines', states={
'readonly': Eval('state') != 'draft',
})
# TODO crash GTK client 4.x with widget date in XML view and attribute
# readonly = True. At the moment, use PYSON to readonly field in XML views.
send_date = fields.DateTime('Send date',
states={
'invisible': Eval('state') != 'sent',
'readonly': Bool(Eval('state') == 'sent'),
})
response = fields.Text('Response', readonly=True)
aeat_register = fields.Text('Register sended to AEAT Webservice',
readonly=True)
@classmethod
def __setup__(cls):
super().__setup__()
cls._buttons.update({
'draft': {
'invisible': ~Eval('state').in_(['confirmed',
'cancelled']),
'icon': 'tryton-back',
},
'confirm': {
'invisible': ~Eval('state').in_(['draft']),
'icon': 'tryton-forward',
},
'send': {
'invisible': ~Eval('state').in_(['confirmed']),
'icon': 'tryton-ok',
},
'cancel': {
'invisible': Eval('state').in_(['cancelled', 'sent']),
'icon': 'tryton-cancel',
},
'load_invoices': {
'invisible': ~(Eval('state').in_(['draft'])
& Eval('operation_type').in_(['A0', 'A1'])),
},
'process_response': {
'invisible': ~Eval('state').in_(['sending']),
}
})
cls._transitions |= set((
('draft', 'confirmed'),
('draft', 'cancelled'),
('confirmed', 'draft'),
('confirmed', 'sent'),
('confirmed', 'cancelled'),
('sending', 'sent'),
('cancelled', 'draft'),
))
@staticmethod
def default_company():
return Transaction().context.get('company')
@staticmethod
def default_fiscalyear():
pool = Pool()
FiscalYear = pool.get('account.fiscalyear')
try:
fiscalyear = FiscalYear.find(
Transaction().context.get('company'), test_state=False)
except FiscalYearNotFoundError:
return None
return fiscalyear.id
@staticmethod
def default_state():
return 'draft'
@staticmethod
def default_version():
return '1.1'
@fields.depends('period')
def on_change_period(self):
if not self.period:
self.load_date = None
@fields.depends('company')
def on_change_with_company_vat(self):
if self.company:
return self.company.party.sii_vat_code
@fields.depends('company')
def on_change_with_currency(self, name=None):
if self.company:
return self.company.currency.id
@fields.depends('period')
def on_change_with_load_date_start(self, name=None):
return self.period.start_date if self.period else None
@fields.depends('period')
def on_change_with_load_date_end(self, name=None):
return self.period.end_date if self.period else None
@classmethod
def get_allowed_companies(cls):
company_filter = Transaction().context.get('company_filter')
companies = Transaction().context.get('companies')
company = Transaction().context.get('company')
companies = []
# context from user
if company_filter and company_filter == 'one' and company:
companies = [company]
# context from cron; context has not companies and not company_filter
elif not company_filter and company:
companies = [company]
return companies
@classmethod
def copy(cls, records, default=None):
if default is None:
default = {}
else:
default = default.copy()
default['communication_state'] = None
default['csv'] = None
default['send_date'] = None
return super().copy(records, default=default)
@classmethod
def delete(cls, reports):
# Cancel before delete
for report in reports:
if report.state != 'cancelled':
raise UserError(gettext('aeat_sii.msg_delete_cancel',
report=report.rec_name))
super().delete(reports)
@classmethod
@ModelView.button
@Workflow.transition('draft')
def draft(cls, reports):
pass
@classmethod
@ModelView.button
@Workflow.transition('confirmed')
def confirm(cls, reports):
for report in reports:
report.check_invoice_state()
report.check_duplicate_invoices()
@classmethod
@ModelView.button
@Workflow.transition('cancelled')
def cancel(cls, reports):
pass
@classmethod
@ModelView.button
@Workflow.transition('sent')
def send(cls, reports):
pool = Pool()
Invoice = pool.get('account.invoice')
for report in reports:
if report.state != 'confirmed':
continue
report.check_invoice_state()
if report.book == 'E': # issued invoices
if report.operation_type in {'A0', 'A1'}:
report.submit_issued_invoices()
elif report.operation_type == 'C0':
report.query_issued_invoices()
elif report.operation_type == 'D0':
report.delete_issued_invoices()
else:
raise NotImplementedError
elif report.book == 'R':
if report.operation_type in {'A0', 'A1'}:
report.submit_recieved_invoices()
elif report.operation_type == 'C0':
report.query_recieved_invoices()
elif report.operation_type == 'D0':
report.delete_recieved_invoices()
else:
raise NotImplementedError
else:
raise NotImplementedError
to_save = []
for report in reports:
if report.operation_type == 'C0':
continue
for line in report.lines:
invoice = line.invoice
if invoice:
invoice.sii_communication_type = report.operation_type
invoice.sii_state = line.state
to_save.append(invoice)
Invoice.save(to_save)
cls.write(reports, {
'send_date': datetime.now(),
})
_logger.debug('Done sending reports to AEAT SII')
@classmethod
@ModelView.button
@Workflow.transition('sent')
def process_response(cls, reports):
for report in reports:
if report.response:
cls._save_response(report.response)
report.save()
def check_invoice_state(self):
for line in self.lines:
if (line.invoice
and (line.invoice.state in ('draft', 'validated')
or (line.invoice.state == 'cancelled'
and line.invoice.cancel_move == None))):
raise UserError(gettext(
'aeat_sii.msg_report_wrong_invoice_state',
invoice=line.invoice.rec_name))
@classmethod
@ModelView.button
def load_invoices(cls, reports):
pool = Pool()
Invoice = pool.get('account.invoice')
ReportLine = pool.get('aeat.sii.report.lines')
Configuration = Pool().get('account.configuration')
Date = pool.get('ir.date')
config = Configuration(1)
today = Date.today()
to_create = []
for report in reports:
if not report.load_date:
load_date = (today - timedelta(
days=config.sii_default_offset_days
if config.sii_default_offset_days else 0))
if (load_date >= report.load_date_start
and load_date < report.load_date_end):
report.load_date = load_date
if (today >= report.load_date_start
and today < report.load_date_end):
report.load_date = today
else:
report.load_date = report.load_date_end
report.save()
domain = [
('sii_book_key', '=', report.book),
('move.period', '=', report.period.id),
['OR',
('state', 'in', ['posted', 'paid']),
[
('state', '=', 'cancelled'),
('cancel_move', '!=', None)
],
],
('sii_pending_sending', '=', True),
['OR', [
('invoice_date', '<=', report.load_date),
('accounting_date', '=', None),
], [
('accounting_date', '<=', report.load_date),
]],]
if report.book == 'E':
domain.append(('type', '=', 'out'))
else:
domain.append(('type', '=', 'in'))
if report.operation_type == 'A0':
domain.append(('sii_state', 'in', [None, 'Incorrecto',
'Anulada']))
elif report.operation_type in ('A1', 'A4'):
domain.append(('sii_state', 'in', [
'AceptadoConErrores', 'AceptadaConErrores']))
_logger.debug('Searching invoices for SII report: %s', domain)
for invoice in Invoice.search(domain):
if not all(x.report != report for x in invoice.sii_records):
continue
to_create.append({
'report': report,
'invoice': invoice,
})
if to_create:
ReportLine.create(to_create)
def _get_certificate(self):
Configuration = Pool().get('account.configuration')
config = Configuration(1)
certificate = config.aeat_certificate_sii
if not certificate:
_logger.info('Missing AEAT Certificate SII configuration')
raise UserError(gettext('aeat_sii.msg_missing_certificate'))
return certificate
def submit_issued_invoices(self):
# get certificate from company
certificate = self._get_certificate()
if self.state != 'confirmed':
_logger.info('This report %s has already been sended', self.id)
else:
_logger.info('Sending report %s to AEAT SII', self.id)
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
srv = service.bind_issued_invoices_service(
crt, key, test=SII_TEST)
try:
res, request = srv.submit(
headers, (x.invoice for x in self.lines))
self.aeat_register = request
except UserError as e:
raise UserError(str(e))
except Exception as e:
message = str(tools.unaccent(str(e)))
if ('Missing element ClaveRegimenEspecialOTrascendencia' in
message):
msg = ''
for line in self.lines:
if not line.invoice.sii_received_key:
msg += '\n%s (%s)' % (line.invoice.number,
line.invoice.party.rec_name)
message += '\n%s' % msg
raise UserError(gettext('aeat_sii.msg_service_message',
message=message))
else:
raise UserError(str(e))
if not self.response:
self.state == 'sending'
self.response = json.dumps(helpers.serialize_object(res))
self.save()
Transaction().commit()
self._save_response(self.response)
def delete_issued_invoices(self):
# get certificate from company
certificate = self._get_certificate()
if self.state != 'confirmed':
_logger.info('This report %s has already been sended', self.id)
else:
_logger.info('Deleting report %s from AEAT SII', self.id)
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
srv = service.bind_issued_invoices_service(
crt, key, test=SII_TEST)
try:
res = srv.cancel(
headers, [
eval(line.sii_header) for line in self.lines])
except Exception as e:
raise UserError(str(e))
if not self.response:
self.state == 'sending'
self.response = json.dumps(helpers.serialize_object(res))
self.save()
Transaction().commit()
self._save_response(self.response)
def query_issued_invoices(self, last_invoice=None):
pool = Pool()
Invoice = pool.get('account.invoice')
SIIReportLine = pool.get('aeat.sii.report.lines')
SIIReportLineTax = pool.get('aeat.sii.report.line.tax')
# get certificate from company
certificate = self._get_certificate()
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
srv = service.bind_issued_invoices_service(
crt, key, test=SII_TEST)
res = srv.query(
headers,
year=self.period.start_date.year,
period=self.period.start_date.month,
last_invoice=last_invoice)
registers = res.RegistroRespuestaConsultaLRFacturasEmitidas
# Selecte all the invoices in the same period of register asked.
invoices_list = Invoice.search([
('company', '=', self.company),
('type', '=', 'out'),
('move.period', '=', self.period),
])
invoices_ids = {}
# If the invoice is a summary of invoices, ensure to set the number as
# sended to SII. Mergin the invoice number with the first simplified
# serial number.
for invoice in invoices_list:
number = invoice.number
if invoice.sii_operation_key == 'F4':
first_invoice = invoice.simplified_serial_number('first')
number += first_invoice
invoices_ids[number] = invoice.id
pagination = res.IndicadorPaginacion
last_invoice = registers and registers[-1].IDFactura
lines_to_create = []
for reg in registers:
taxes_to_create = []
taxes = None
exemption = ''
tipo_desglose = reg.DatosFacturaEmitida.TipoDesglose
if tipo_desglose.DesgloseFactura:
sujeta = tipo_desglose.DesgloseFactura.Sujeta
no_sujeta = tipo_desglose.DesgloseFactura.NoSujeta
else:
if tipo_desglose.DesgloseTipoOperacion.PrestacionServicios:
sujeta = tipo_desglose.DesgloseTipoOperacion.\
PrestacionServicios.Sujeta
no_sujeta = tipo_desglose.DesgloseTipoOperacion.\
PrestacionServicios.NoSujeta
else:
sujeta = tipo_desglose.DesgloseTipoOperacion.Entrega.Sujeta
no_sujeta = (
tipo_desglose.DesgloseTipoOperacion.Entrega.NoSujeta)
if sujeta and sujeta.NoExenta:
for detail in sujeta.NoExenta.DesgloseIVA.DetalleIVA:
taxes_to_create.append({
'base': _decimal(detail.BaseImponible),
'rate': _decimal(detail.TipoImpositivo),
'amount': _decimal(detail.CuotaRepercutida),
'surcharge_rate': _decimal(
detail.TipoRecargoEquivalencia),
'surcharge_amount': _decimal(
detail.CuotaRecargoEquivalencia),
})
taxes = SIIReportLineTax.create(taxes_to_create)
elif sujeta and sujeta.Exenta:
exemption = sujeta.Exenta.DetalleExenta[0].CausaExencion
for exempt in EXEMPTION_CAUSE:
if exempt[0] == exemption:
exemption = exempt[1]
break
elif no_sujeta:
# TODO: Control the possible respons
# 'ImportePorArticulos7_14_Otros'
# 'ImporteTAIReglasLocalizacion'
pass
sii_report_line = {
'report': self.id,
'invoice': invoices_ids.get(
reg.IDFactura.NumSerieFacturaEmisor),
'state': reg.EstadoFactura.EstadoRegistro,
'last_modify_date': _datetime(
reg.EstadoFactura.TimestampUltimaModificacion),
'communication_code': reg.EstadoFactura.CodigoErrorRegistro,
'communication_msg': (reg.EstadoFactura.
DescripcionErrorRegistro),
'issuer_vat_number': (reg.IDFactura.IDEmisorFactura.NIF
or reg.IDFactura.IDEmisorFactura.IDOtro.ID),
'serial_number': reg.IDFactura.NumSerieFacturaEmisor,
'final_serial_number': (
reg.IDFactura.NumSerieFacturaEmisorResumenFin),
'issue_date': _date(
reg.IDFactura.FechaExpedicionFacturaEmisor),
'invoice_kind': reg.DatosFacturaEmitida.TipoFactura,
'special_key': (reg.DatosFacturaEmitida.
ClaveRegimenEspecialOTrascendencia),
'total_amount': _decimal(reg.DatosFacturaEmitida.ImporteTotal),
'taxes': [('add', [t.id for t in taxes])] if taxes else [],
'exemption_cause': exemption,
'counterpart_name': (
reg.DatosFacturaEmitida.Contraparte.NombreRazon
if reg.DatosFacturaEmitida.Contraparte else None),
'counterpart_id': (
(reg.DatosFacturaEmitida.Contraparte.NIF
or reg.DatosFacturaEmitida.Contraparte.IDOtro.ID)
if reg.DatosFacturaEmitida.Contraparte else None),
'presenter': reg.DatosPresentacion.NIFPresentador,
'presentation_date': _datetime(
reg.DatosPresentacion.TimestampPresentacion),
'csv': reg.DatosPresentacion.CSV,
'balance_state': reg.DatosPresentacion.CSV,
'aeat_register': str(reg),
}
lines_to_create.append(sii_report_line)
SIIReportLine.create(lines_to_create)
if pagination == 'S':
self.query_issued_invoices(last_invoice=last_invoice)
def submit_recieved_invoices(self):
# get certificate from company
certificate = self._get_certificate()
if self.state != 'confirmed':
_logger.info('This report %s has already been sended', self.id)
else:
_logger.info('Sending report %s to AEAT SII', self.id)
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
srv = service.bind_recieved_invoices_service(
crt, key, test=SII_TEST)
try:
res, request = srv.submit(
headers, (x.invoice for x in self.lines))
self.aeat_register = request
except Exception as e:
message = str(tools.unaccent(str(e)))
if ('Missing element ClaveRegimenEspecialOTrascendencia' in
message):
msg = ''
for line in self.lines:
if not line.invoice.sii_received_key:
msg += '\n%s (%s)' % (line.invoice.number,
line.invoice.party.rec_name)
message += '\n%s' % msg
raise UserError(gettext('aeat_sii.msg_service_message',
message=message))
else:
raise UserError(str(e))
if not self.response:
self.state == 'sending'
self.response = json.dumps(helpers.serialize_object(res))
self.save()
Transaction().commit()
self._save_response(self.response)
def delete_recieved_invoices(self):
# get certificate from company
certificate = self._get_certificate()
if self.state != 'confirmed':
_logger.info('This report %s has already been sended', self.id)
else:
_logger.info('Deleting report %s from AEAT SII', self.id)
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
try:
srv = service.bind_recieved_invoices_service(
crt, key, test=SII_TEST)
res = srv.cancel(
headers, [
eval(line.sii_header) for line in self.lines])
except Exception as e:
raise UserError(str(e))
if not self.response:
self.state == 'sending'
self.response = json.dumps(helpers.serialize_object(res))
self.save()
Transaction().commit()
self._save_response(self.response)
def _save_response(self, res):
if res:
response = json.loads(res, object_hook=lambda d: namedtuple(
'SII', d.keys())(*d.values()))
for (report_line, response_line) in zip(
self.lines, response.RespuestaLinea):
if not report_line.communication_code:
report_line.state = response_line.EstadoRegistro
report_line.communication_code = (
response_line.CodigoErrorRegistro)
report_line.communication_msg = (
response_line.DescripcionErrorRegistro)
report_line.save()
if not self.communication_state:
self.communication_state = response.EstadoEnvio
if not self.csv:
self.csv = response.CSV
self.response = ''
self.save()
def query_recieved_invoices(self, last_invoice=None):
pool = Pool()
Invoice = pool.get('account.invoice')
SIIReportLine = pool.get('aeat.sii.report.lines')
SIIReportLineTax = pool.get('aeat.sii.report.line.tax')
# get certificate from company
certificate = self._get_certificate()
headers = tools.get_headers(
name=tools.unaccent(self.company.party.name),
vat=self.company_vat,
comm_kind=self.operation_type,
version=self.version)
with certificate.tmp_ssl_credentials() as (crt, key):
srv = service.bind_recieved_invoices_service(
crt, key, test=SII_TEST)
res = srv.query(
headers,
year=self.period.start_date.year,
period=self.period.start_date.month,
last_invoice=last_invoice)
_logger.debug(res)
registers = res.RegistroRespuestaConsultaLRFacturasRecibidas
pagination = res.IndicadorPaginacion
last_invoice = registers[-1].IDFactura
# FIXME: the reference is not forced to be unique
lines_to_create = []
for reg in registers:
invoice_date = _date(reg.IDFactura.FechaExpedicionFacturaEmisor)
taxes_to_create = []
for detail in reg.DatosFacturaRecibida.DesgloseFactura.\
DesgloseIVA.DetalleIVA:
taxes_to_create.append({
'base': _decimal(detail.BaseImponible),
'rate': _decimal(detail.TipoImpositivo),
'amount': _decimal(detail.CuotaSoportada),
'surcharge_rate': _decimal(
detail.TipoRecargoEquivalencia),
'surcharge_amount': _decimal(
detail.CuotaRecargoEquivalencia),
'reagyp_rate': _decimal(
detail.PorcentCompensacionREAGYP),
'reagyp_amount': _decimal(
detail.ImporteCompensacionREAGYP),
})
taxes = SIIReportLineTax.create(taxes_to_create)
sii_report_line = {
'report': self.id,
'state': reg.EstadoFactura.EstadoRegistro,
'last_modify_date': _datetime(
reg.EstadoFactura.TimestampUltimaModificacion),
'communication_code': (
reg.EstadoFactura.CodigoErrorRegistro),
'communication_msg': (
reg.EstadoFactura.DescripcionErrorRegistro),
'issuer_vat_number': (reg.IDFactura.IDEmisorFactura.NIF
or reg.IDFactura.IDEmisorFactura.IDOtro.ID),
'serial_number': reg.IDFactura.NumSerieFacturaEmisor,
'final_serial_number': (
reg.IDFactura.NumSerieFacturaEmisorResumenFin),
'issue_date': invoice_date,
'invoice_kind': reg.DatosFacturaRecibida.TipoFactura,
'special_key': (reg.DatosFacturaRecibida.
ClaveRegimenEspecialOTrascendencia),
'total_amount': _decimal(
reg.DatosFacturaRecibida.ImporteTotal),
'taxes': [('add', [t.id for t in taxes])],
'counterpart_name': (
reg.DatosFacturaRecibida.Contraparte.NombreRazon),
'counterpart_id': (reg.DatosFacturaRecibida.Contraparte.NIF
or reg.DatosFacturaRecibida.Contraparte.IDOtro.ID),
'presenter': reg.DatosPresentacion.NIFPresentador,
'presentation_date': _datetime(
reg.DatosPresentacion.TimestampPresentacion),
'csv': reg.DatosPresentacion.CSV,
'balance_state': reg.DatosPresentacion.CSV,
'aeat_register': str(reg),
}
domain = [
('company', '=', self.company),
('reference', '=', reg.IDFactura.NumSerieFacturaEmisor),
('invoice_date', '=', invoice_date),
('move', '!=', None),
('type', '=', 'in'),
]
vat = True
if reg.IDFactura.IDEmisorFactura.NIF:
vat = reg.IDFactura.IDEmisorFactura.NIF
if not vat.startswith('ES'):
vat = 'ES' + vat
domain.append(
('party.tax_identifier', '=', vat)
)
elif reg.IDFactura.IDEmisorFactura.IDOtro.IDType == '02':
domain.append(
('party.tax_identifier', '=',
reg.IDFactura.IDEmisorFactura.IDOtro.ID)
)
else:
vat = False
invoices = Invoice.search(domain)
if not vat and len(invoices) > 1:
invoice_ok = []
for invoice in invoices:
for register in registers:
if register == reg.IDFactura.IDEmisorFactura.IDOtro.ID:
invoice_ok.append(invoice)
break
invoices = invoice_ok
if invoice_ok:
break