-
-
Notifications
You must be signed in to change notification settings - Fork 306
/
wizard_import_fatturapa.py
1763 lines (1627 loc) · 72.5 KB
/
wizard_import_fatturapa.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
import logging
import re
from datetime import datetime
from odoo import api, fields, models, registry
from odoo.exceptions import UserError
from odoo.tools import float_is_zero
from odoo.tools.translate import _
from odoo.addons.base_iban.models.res_partner_bank import pretty_iban
from . import efattura
_logger = logging.getLogger(__name__)
WT_CODES_MAPPING = {
"RT01": "ritenuta",
"RT02": "ritenuta",
"RT03": "inps",
"RT04": "enasarco",
"RT05": "enpam",
"RT06": "other",
}
class WizardImportFatturapa(models.TransientModel):
_name = "wizard.import.fatturapa"
_description = "Import E-bill"
e_invoice_detail_level = fields.Selection(
[
("0", "Minimum"),
("1", "Tax rate"),
("2", "Maximum"),
],
string="E-bills Detail Level",
help="Minimum level: Bill is created with no lines; "
"User will have to create them, according to what specified in "
"the electronic bill.\n"
"Tax rate level: Rate level: an invoice line is created for each "
"rate present in the electronic invoice\n"
"Maximum level: every line contained in the electronic bill "
"will create a line in the bill.",
required=True,
)
price_decimal_digits = fields.Integer(
"Prices decimal digits",
required=True,
help="Decimal digits used in prices computation. This is needed to correctly "
"import e-invoices with many decimal digits, not being forced to "
"increase decimal digits of all your prices. "
'Otherwise, increase "Product Price" precision.',
)
quantity_decimal_digits = fields.Integer(
"Quantities decimal digits",
required=True,
help='Decimal digits used for quantity field. See "Prices decimal digits".',
)
discount_decimal_digits = fields.Integer(
"Discounts decimal digits",
required=True,
help='Decimal digits used for discount field. See "Prices decimal digits".',
)
@api.model
def default_get(self, fields):
res = super(WizardImportFatturapa, self).default_get(fields)
res["price_decimal_digits"] = self.env["decimal.precision"].precision_get(
"Product Price"
)
res["quantity_decimal_digits"] = self.env["decimal.precision"].precision_get(
"Product Unit of Measure"
)
res["discount_decimal_digits"] = self.env["decimal.precision"].precision_get(
"Discount"
)
res["e_invoice_detail_level"] = "2"
fatturapa_attachment_ids = self.env.context.get("active_ids", False)
fatturapa_attachment_obj = self.env["fatturapa.attachment.in"]
partners = self.env["res.partner"]
for fatturapa_attachment_id in fatturapa_attachment_ids:
fatturapa_attachment = fatturapa_attachment_obj.browse(
fatturapa_attachment_id
)
if fatturapa_attachment.in_invoice_ids:
raise UserError(
_("File %s is linked to bills yet.") % fatturapa_attachment.name
)
partners |= fatturapa_attachment.xml_supplier_id
if len(partners) == 1:
res["e_invoice_detail_level"] = partners[0].e_invoice_detail_level
if partners[0].e_invoice_price_decimal_digits >= 0:
res["price_decimal_digits"] = partners[
0
].e_invoice_price_decimal_digits
if partners[0].e_invoice_quantity_decimal_digits >= 0:
res["quantity_decimal_digits"] = partners[
0
].e_invoice_quantity_decimal_digits
if partners[0].e_invoice_discount_decimal_digits >= 0:
res["discount_decimal_digits"] = partners[
0
].e_invoice_discount_decimal_digits
return res
def CountryByCode(self, CountryCode):
country_model = self.env["res.country"]
return country_model.search([("code", "=", CountryCode)])
def ProvinceByCode(self, provinceCode):
province_model = self.env["res.country.state"]
return province_model.search(
[("code", "=", provinceCode), ("country_id.code", "=", "IT")]
)
def log_inconsistency(self, message):
inconsistencies = self.env.context.get("inconsistencies", "")
if inconsistencies:
inconsistencies += "\n"
inconsistencies += message
# convert to dict in order to be able to modify context
self.env.context = dict(self.env.context)
self.env.context.update(inconsistencies=inconsistencies)
def check_partner_base_data(self, partner_id, DatiAnagrafici):
partner = self.env["res.partner"].browse(partner_id)
if (
DatiAnagrafici.Anagrafica.Denominazione
and partner.name != DatiAnagrafici.Anagrafica.Denominazione
):
self.log_inconsistency(
_("Company Name field contains '%s'." " Your System contains '%s'")
% (DatiAnagrafici.Anagrafica.Denominazione, partner.name)
)
if (
DatiAnagrafici.Anagrafica.Nome
and partner.firstname != DatiAnagrafici.Anagrafica.Nome
):
self.log_inconsistency(
_("Name field contains '%s'." " Your System contains '%s'")
% (DatiAnagrafici.Anagrafica.Nome, partner.firstname)
)
if (
DatiAnagrafici.Anagrafica.Cognome
and partner.lastname != DatiAnagrafici.Anagrafica.Cognome
):
self.log_inconsistency(
_("Surname field contains '%s'." " Your System contains '%s'")
% (DatiAnagrafici.Anagrafica.Cognome, partner.lastname)
)
def getPartnerBase(self, DatiAnagrafici): # noqa: C901
if not DatiAnagrafici:
return False
partner_model = self.env["res.partner"]
cf = DatiAnagrafici.CodiceFiscale or False
vat = False
if DatiAnagrafici.IdFiscaleIVA:
# Format Italian VAT ID to always have 11 char
# to avoid validation error when creating the given partner
if DatiAnagrafici.IdFiscaleIVA.IdPaese.upper() == "IT":
vat = "{}{}".format(
DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
DatiAnagrafici.IdFiscaleIVA.IdCodice.rjust(11, "0")[:11],
)
else:
vat = "{}{}".format(
DatiAnagrafici.IdFiscaleIVA.IdPaese.upper(),
re.sub(r"\W+", "", DatiAnagrafici.IdFiscaleIVA.IdCodice).upper(),
)
partners = partner_model
res_partner_rule = (
self.env["ir.model.data"]
.sudo()
.xmlid_to_object("base.res_partner_rule", raise_if_not_found=False)
)
if vat:
domain = [("vat", "=", vat)]
if (
self.env.context.get("from_attachment")
and res_partner_rule
and res_partner_rule.active
):
att = self.env.context.get("from_attachment")
domain.extend(
[
"|",
("company_id", "child_of", att.company_id.id),
("company_id", "=", False),
]
)
partners = partner_model.search(domain)
if not partners and cf:
domain = [("fiscalcode", "=", cf)]
if (
self.env.context.get("from_attachment")
and res_partner_rule
and res_partner_rule.active
):
att = self.env.context.get("from_attachment")
domain.extend(
[
"|",
("company_id", "child_of", att.company_id.id),
("company_id", "=", False),
]
)
partners = partner_model.search(domain)
commercial_partner_id = False
if len(partners) > 1:
for partner in partners:
if (
commercial_partner_id
and partner.commercial_partner_id.id != commercial_partner_id
):
raise UserError(
_(
"Two distinct partners with "
"VAT number %s or Fiscal Code %s already "
"present in db." % (vat, cf)
)
)
commercial_partner_id = partner.commercial_partner_id.id
if partners:
if not commercial_partner_id:
commercial_partner_id = partners[0].commercial_partner_id.id
self.check_partner_base_data(commercial_partner_id, DatiAnagrafici)
return commercial_partner_id
else:
# partner to be created
country_id = False
if DatiAnagrafici.IdFiscaleIVA:
CountryCode = DatiAnagrafici.IdFiscaleIVA.IdPaese
countries = self.CountryByCode(CountryCode)
if countries:
country_id = countries[0].id
else:
raise UserError(
_("Country Code %s not found in system.") % CountryCode
)
vals = {
"vat": vat,
"fiscalcode": cf,
"is_company": (
DatiAnagrafici.Anagrafica.Denominazione and True or False
),
"eori_code": DatiAnagrafici.Anagrafica.CodEORI or "",
"country_id": country_id,
}
if DatiAnagrafici.Anagrafica.Nome:
vals["firstname"] = DatiAnagrafici.Anagrafica.Nome
if DatiAnagrafici.Anagrafica.Cognome:
vals["lastname"] = DatiAnagrafici.Anagrafica.Cognome
if DatiAnagrafici.Anagrafica.Denominazione:
vals["name"] = DatiAnagrafici.Anagrafica.Denominazione
return partner_model.create(vals).id
def getCedPrest(self, cedPrest):
partner_model = self.env["res.partner"]
partner_id = self.getPartnerBase(cedPrest.DatiAnagrafici)
no_contact_update = False
if partner_id:
no_contact_update = partner_model.browse(
partner_id
).electronic_invoice_no_contact_update
fiscalPosModel = self.env["fatturapa.fiscal_position"]
if partner_id and not no_contact_update:
partner_company_id = partner_model.browse(partner_id).company_id.id
vals = {
"street": cedPrest.Sede.Indirizzo,
"zip": cedPrest.Sede.CAP,
"city": cedPrest.Sede.Comune,
"register": cedPrest.DatiAnagrafici.AlboProfessionale or "",
}
if cedPrest.DatiAnagrafici.ProvinciaAlbo:
ProvinciaAlbo = cedPrest.DatiAnagrafici.ProvinciaAlbo
prov = self.ProvinceByCode(ProvinciaAlbo)
if not prov:
self.log_inconsistency(
_("Register Province ( %s ) not present " "in your system")
% ProvinciaAlbo
)
else:
vals["register_province"] = prov[0].id
if cedPrest.Sede.Provincia:
Provincia = cedPrest.Sede.Provincia
prov_sede = self.ProvinceByCode(Provincia)
if not prov_sede:
self.log_inconsistency(
_("Province ( %s ) not present in your system") % Provincia
)
else:
vals["state_id"] = prov_sede[0].id
vals["register_code"] = cedPrest.DatiAnagrafici.NumeroIscrizioneAlbo
vals["register_regdate"] = cedPrest.DatiAnagrafici.DataIscrizioneAlbo
if cedPrest.DatiAnagrafici.RegimeFiscale:
rfPos = cedPrest.DatiAnagrafici.RegimeFiscale
FiscalPos = fiscalPosModel.search([("code", "=", rfPos)])
if not FiscalPos:
raise UserError(
_("Tax Regime %s not present in your system.") % rfPos
)
else:
vals["register_fiscalpos"] = FiscalPos[0].id
if cedPrest.IscrizioneREA:
REA = cedPrest.IscrizioneREA
offices = self.ProvinceByCode(REA.Ufficio)
rea_nr = REA.NumeroREA
if not offices:
office_id = False
self.log_inconsistency(
_(
"REA Office Province Code ( %s ) not present in "
"your system"
)
% REA.Ufficio
)
else:
office_id = offices[0].id
vals["rea_office"] = office_id
rea_domain = [
("rea_code", "=", rea_nr),
("company_id", "=", partner_company_id),
("id", "!=", partner_id),
]
if office_id:
rea_domain.append(("rea_office", "=", office_id))
rea_partners = partner_model.search(rea_domain)
if rea_partners:
rea_names = ", ".join(rea_partners.mapped("name"))
p_name = partner_model.browse(partner_id).name
self.log_inconsistency(
_(
"Current invoice is from {} with REA Code"
" {}. Yet it seems that partners {} have the same"
" REA Code. This code should be unique; please fix"
" it.".format(p_name, rea_nr, rea_names)
)
)
else:
vals["rea_code"] = REA.NumeroREA
vals["rea_capital"] = REA.CapitaleSociale or 0.0
vals["rea_member_type"] = REA.SocioUnico or False
vals["rea_liquidation_state"] = REA.StatoLiquidazione or False
if cedPrest.Contatti:
vals["phone"] = cedPrest.Contatti.Telefono
vals["email"] = cedPrest.Contatti.Email
partner_model.browse(partner_id).write(vals)
return partner_id
def getCarrirerPartner(self, Carrier):
partner_model = self.env["res.partner"]
partner_id = self.getPartnerBase(Carrier.DatiAnagraficiVettore)
no_contact_update = False
if partner_id:
no_contact_update = partner_model.browse(
partner_id
).electronic_invoice_no_contact_update
if partner_id and not no_contact_update:
vals = {
"license_number": Carrier.DatiAnagraficiVettore.NumeroLicenzaGuida
or "",
}
partner_model.browse(partner_id).write(vals)
return partner_id
# move_line.tax_ids
def _prepare_generic_line_data(self, line):
retLine = {}
account_taxes = self.get_account_taxes(line.AliquotaIVA, line.Natura)
if account_taxes:
retLine["tax_ids"] = [(6, 0, [account_taxes[0].id])]
return retLine
def get_account_taxes(self, AliquotaIVA, Natura):
account_tax_model = self.env["account.tax"]
# check if a default tax exists and generate def_purchase_tax object
ir_values = self.env["ir.default"]
company_id = self.env.company.id
supplier_taxes_ids = ir_values.get(
"product.product", "supplier_taxes_id", company_id=company_id
)
def_purchase_tax = False
if supplier_taxes_ids:
def_purchase_tax = account_tax_model.browse(supplier_taxes_ids, limit=1)
if float(AliquotaIVA) == 0.0 and Natura:
account_taxes = account_tax_model.search(
[
("type_tax_use", "=", "purchase"),
("kind_id.code", "=", Natura),
("amount", "=", 0.0),
],
order="sequence",
)
if not account_taxes:
self.log_inconsistency(
_(
"No tax with percentage "
"%s and nature %s found. Please configure this tax."
)
% (AliquotaIVA, Natura)
)
if len(account_taxes) > 1:
self.log_inconsistency(
_(
"Too many taxes with percentage "
"%s and nature %s found. Tax %s with lower priority has "
"been set on invoice lines."
)
% (AliquotaIVA, Natura, account_taxes[0].description)
)
else:
account_taxes = account_tax_model.search(
[
("type_tax_use", "=", "purchase"),
("amount", "=", float(AliquotaIVA)),
("price_include", "=", False),
# partially deductible VAT must be set by user
("children_tax_ids", "=", False),
],
order="sequence",
)
if not account_taxes:
self.log_inconsistency(
_(
"XML contains tax with percentage '%s' "
"but it does not exist in your system"
)
% AliquotaIVA
)
# check if there are multiple taxes with
# same percentage
if len(account_taxes) > 1:
# just logging because this is an usual case: see split payment
_logger.warning(
_(
"Too many taxes with percentage equals "
"to '%s'.\nFix it if required"
)
% AliquotaIVA
)
# if there are multiple taxes with same percentage
# and there is a default tax with this percentage,
# set taxes list equal to supplier_taxes_id, loaded before
if def_purchase_tax and def_purchase_tax.amount == (float(AliquotaIVA)):
account_taxes = def_purchase_tax
return account_taxes
def get_line_product(self, line, partner):
product = False
supplier_info = self.env["product.supplierinfo"]
if len(line.CodiceArticolo or []) == 1:
supplier_code = line.CodiceArticolo[0].CodiceValore
supplier_infos = supplier_info.search(
[("product_code", "=", supplier_code), ("name", "=", partner.id)]
)
if supplier_infos:
products = supplier_infos.mapped("product_id")
if len(products) == 1:
product = products[0]
else:
templates = supplier_infos.mapped("product_tmpl_id")
if len(templates) == 1:
product = templates.product_variant_ids[0]
if not product and partner.e_invoice_default_product_id:
product = partner.e_invoice_default_product_id
return product
def adjust_accounting_data(self, product, line_vals):
account = self.get_credit_account(product)
line_vals["account_id"] = account.id
new_tax = None
if len(product.product_tmpl_id.supplier_taxes_id) == 1:
new_tax = product.product_tmpl_id.supplier_taxes_id[0]
elif len(account.tax_ids) == 1:
new_tax = account.tax_ids[0]
line_tax_id = line_vals.get("tax_ids") and line_vals["tax_ids"][0][2][0]
line_tax = self.env["account.tax"].browse(line_tax_id)
if new_tax and line_tax and new_tax != line_tax:
if new_tax._get_tax_amount() != line_tax._get_tax_amount():
self.log_inconsistency(
_(
"XML contains tax %s. Product %s has tax %s. Using "
"the XML one"
)
% (line_tax.name, product.name, new_tax.name)
)
else:
# If product has the same amount of the one in XML,
# I use it. Typical case: 22% det 50%
line_vals["tax_ids"] = [(6, 0, [new_tax.id])]
# move_line.tax_ids
# move_line.name
# move_line.sequence
# move_line.account_id
# move_line.price_unit
# move_line.quantity
def _prepareInvoiceLineAliquota(self, credit_account_id, line, nline):
retLine = {}
account_taxes = self.get_account_taxes(line.AliquotaIVA, line.Natura)
if account_taxes:
retLine["tax_ids"] = [(6, 0, [account_taxes[0].id])]
retLine.update(
{
"name": "Riepilogo Aliquota {}".format(line.AliquotaIVA),
"sequence": nline,
"account_id": credit_account_id,
"price_unit": float(abs(line.ImponibileImporto)),
}
)
return retLine
# move_line.name
# move_line.sequence
# move_line.account_id
# move_line.price_unit
# move_line.quantity
# move_line.discount
# move_line.admin_ref
# move_line.invoice_line_tax_wt_ids
def _prepareInvoiceLine(self, credit_account_id, line, wt_founds=False):
retLine = self._prepare_generic_line_data(line)
retLine.update(
{
"name": line.Descrizione,
"sequence": int(line.NumeroLinea),
"account_id": credit_account_id,
"price_unit": float(line.PrezzoUnitario),
"exclude_from_invoice_tab": False,
}
)
if line.Quantita is None:
retLine["quantity"] = 1.0
else:
retLine["quantity"] = float(line.Quantita)
if (
float(line.PrezzoUnitario)
and line.Quantita
and float(line.Quantita)
and line.ScontoMaggiorazione # Quantita not required
):
retLine["discount"] = self._computeDiscount(line)
if line.RiferimentoAmministrazione:
retLine["admin_ref"] = line.RiferimentoAmministrazione
if wt_founds and line.Ritenuta:
retLine["invoice_line_tax_wt_ids"] = [(6, 0, [x.id for x in wt_founds])]
return retLine
def _prepareRelDocsLine(self, invoice_id, line, doc_type):
res = []
lineref = line.RiferimentoNumeroLinea or False
IdDoc = line.IdDocumento or "Error"
Data = line.Data or False
NumItem = line.NumItem or ""
Code = line.CodiceCommessaConvenzione or ""
Cig = line.CodiceCIG or ""
Cup = line.CodiceCUP or ""
invoice_lineid = False
if lineref:
for numline in lineref:
invoice_lineid = False
invoice_line_model = self.env["account.move.line"]
invoice_lines = invoice_line_model.search(
[
("move_id", "=", invoice_id),
("sequence", "=", int(numline)),
]
)
if invoice_lines:
invoice_lineid = invoice_lines[0].id
val = {
"type": doc_type,
"name": IdDoc,
"lineRef": numline,
"invoice_line_id": invoice_lineid,
"invoice_id": invoice_id,
"date": Data,
"numitem": NumItem,
"code": Code,
"cig": Cig,
"cup": Cup,
}
res.append(val)
else:
val = {
"type": doc_type,
"name": IdDoc,
"invoice_line_id": invoice_lineid,
"invoice_id": invoice_id,
"date": Data,
"numitem": NumItem,
"code": Code,
"cig": Cig,
"cup": Cup,
}
res.append(val)
return res
def _prepareWelfareLine(self, invoice_id, line):
TipoCassa = line.TipoCassa or False
AlCassa = line.AlCassa and (float(line.AlCassa) / 100) or None
ImportoContributoCassa = (
line.ImportoContributoCassa and float(line.ImportoContributoCassa) or None
)
ImponibileCassa = line.ImponibileCassa and float(line.ImponibileCassa) or None
AliquotaIVA = line.AliquotaIVA and (float(line.AliquotaIVA) / 100) or None
Ritenuta = line.Ritenuta or ""
Natura = line.Natura or False
kind_id = False
if Natura:
kind = self.env["account.tax.kind"].search([("code", "=", Natura)])
if not kind:
self.log_inconsistency(_("Tax kind %s not found") % Natura)
else:
kind_id = kind[0].id
RiferimentoAmministrazione = line.RiferimentoAmministrazione or ""
WelfareTypeModel = self.env["welfare.fund.type"]
if not TipoCassa:
raise UserError(_("Welfare Fund is not defined."))
WelfareType = WelfareTypeModel.search([("name", "=", TipoCassa)])
res = {
"welfare_rate_tax": AlCassa,
"welfare_amount_tax": ImportoContributoCassa,
"welfare_taxable": ImponibileCassa,
"welfare_Iva_tax": AliquotaIVA,
"subjected_withholding": Ritenuta,
"kind_id": kind_id,
"pa_line_code": RiferimentoAmministrazione,
"invoice_id": invoice_id,
}
if not WelfareType:
raise UserError(
_("Welfare Fund %s not present in your system.") % TipoCassa
)
else:
res["name"] = WelfareType[0].id
return res
def _prepareDiscRisePriceLine(self, line_id, line):
Tipo = line.Tipo or False
Percentuale = line.Percentuale and float(line.Percentuale) or 0.0
Importo = line.Importo and float(line.Importo) or 0.0
res = {
"percentage": Percentuale,
"amount": Importo,
self.env.context.get("drtype"): line_id,
}
res["name"] = Tipo
return res
def _computeDiscount(self, DettaglioLinea):
line_total = float(DettaglioLinea.PrezzoTotale)
line_unit = line_total / float(DettaglioLinea.Quantita)
discount = (1 - (line_unit / float(DettaglioLinea.PrezzoUnitario))) * 100.0
return discount
def _addGlobalDiscount(self, invoice_id, DatiGeneraliDocumento):
discount = 0.0
if (
DatiGeneraliDocumento.ScontoMaggiorazione
and self.e_invoice_detail_level == "2"
):
invoice = self.env["account.move"].browse(invoice_id)
for DiscRise in DatiGeneraliDocumento.ScontoMaggiorazione:
if DiscRise.Percentuale:
amount = invoice.amount_total * (float(DiscRise.Percentuale) / 100)
if DiscRise.Tipo == "SC":
discount -= amount
elif DiscRise.Tipo == "MG":
discount += amount
elif DiscRise.Importo:
if DiscRise.Tipo == "SC":
discount -= float(DiscRise.Importo)
elif DiscRise.Tipo == "MG":
discount += float(DiscRise.Importo)
company = invoice.company_id
global_discount_product = company.sconto_maggiorazione_product_id
credit_account = self.get_credit_account(
product=global_discount_product,
)
line_vals = {
"move_id": invoice_id,
"name": _("Global bill discount from document general data"),
"account_id": credit_account.id,
"price_unit": discount,
"quantity": 1,
}
if global_discount_product:
line_vals["product_id"] = global_discount_product.id
line_vals["name"] = global_discount_product.name
self.adjust_accounting_data(global_discount_product, line_vals)
self.env["account.move.line"].with_context(
check_move_validity=False
).create(line_vals)
return True
def _createPaymentsLine(self, payment_id, line, partner_id, invoice):
details = line.DettaglioPagamento or False
if details:
PaymentModel = self.env["fatturapa.payment.detail"]
PaymentMethodModel = self.env["fatturapa.payment_method"]
BankModel = self.env["res.bank"]
PartnerBankModel = self.env["res.partner.bank"]
for dline in details:
method = PaymentMethodModel.search(
[("code", "=", dline.ModalitaPagamento)]
)
if not method:
raise UserError(
_(
"Payment method %s is not defined in your system."
% dline.ModalitaPagamento
)
)
val = {
"recipient": dline.Beneficiario,
"fatturapa_pm_id": method[0].id,
"payment_term_start": dline.DataRiferimentoTerminiPagamento
or False,
"payment_days": dline.GiorniTerminiPagamento or 0,
"payment_due_date": dline.DataScadenzaPagamento or False,
"payment_amount": dline.ImportoPagamento or 0.0,
"post_office_code": dline.CodUfficioPostale or "",
"recepit_surname": dline.CognomeQuietanzante or "",
"recepit_name": dline.NomeQuietanzante or "",
"recepit_cf": dline.CFQuietanzante or "",
"recepit_title": dline.TitoloQuietanzante or "1",
"payment_bank_name": dline.IstitutoFinanziario or "",
"payment_bank_iban": dline.IBAN or "",
"payment_bank_abi": dline.ABI or "",
"payment_bank_cab": dline.CAB or "",
"payment_bank_bic": dline.BIC or "",
"payment_bank": False,
"prepayment_discount": dline.ScontoPagamentoAnticipato or 0.0,
"max_payment_date": dline.DataLimitePagamentoAnticipato or False,
"penalty_amount": dline.PenalitaPagamentiRitardati or 0.0,
"penalty_date": dline.DataDecorrenzaPenale or False,
"payment_code": dline.CodicePagamento or "",
"payment_data_id": payment_id,
}
bank = False
payment_bank_id = False
if dline.BIC:
banks = BankModel.search([("bic", "=", dline.BIC.strip())])
if not banks:
if not dline.IstitutoFinanziario:
self.log_inconsistency(
_(
"Name of Bank with BIC '%s' is not set."
" Can't create bank"
)
% dline.BIC
)
else:
bank = BankModel.create(
{
"name": dline.IstitutoFinanziario,
"bic": dline.BIC,
}
)
else:
bank = banks[0]
if dline.IBAN:
iban = dline.IBAN.strip()
SearchDom = [
("acc_number", "=", pretty_iban(iban)),
("partner_id", "=", partner_id),
]
payment_bank_id = False
payment_banks = PartnerBankModel.search(SearchDom)
if not payment_banks and not bank:
self.log_inconsistency(
_(
"BIC is required and not exist in Xml\n"
"Curr bank data is: \n"
"IBAN: %s\n"
"Bank Name: %s\n"
)
% (
iban or "",
dline.IstitutoFinanziario or "",
)
)
elif not payment_banks and bank:
existing_account = PartnerBankModel.search(
[
("acc_number", "=", iban),
("company_id", "=", invoice.company_id.id),
]
)
if existing_account:
self.log_inconsistency(
_("Bank account %s already exists") % iban
)
else:
payment_bank_id = PartnerBankModel.create(
{
"acc_number": iban,
"partner_id": partner_id,
"bank_id": bank.id,
"bank_name": dline.IstitutoFinanziario or bank.name,
"bank_bic": dline.BIC or bank.bic,
}
).id
if payment_banks:
payment_bank_id = payment_banks[0].id
if payment_bank_id:
val["payment_bank"] = payment_bank_id
PaymentModel.create(val)
return True
# TODO sul partner?
def set_StabileOrganizzazione(self, CedentePrestatore, invoice):
if CedentePrestatore.StabileOrganizzazione:
invoice.efatt_stabile_organizzazione_indirizzo = (
CedentePrestatore.StabileOrganizzazione.Indirizzo
)
invoice.efatt_stabile_organizzazione_civico = (
CedentePrestatore.StabileOrganizzazione.NumeroCivico
)
invoice.efatt_stabile_organizzazione_cap = (
CedentePrestatore.StabileOrganizzazione.CAP
)
invoice.efatt_stabile_organizzazione_comune = (
CedentePrestatore.StabileOrganizzazione.Comune
)
invoice.efatt_stabile_organizzazione_provincia = (
CedentePrestatore.StabileOrganizzazione.Provincia
)
invoice.efatt_stabile_organizzazione_nazione = (
CedentePrestatore.StabileOrganizzazione.Nazione
)
def get_purchase_journal(self, company):
journal_model = self.env["account.journal"]
journals = journal_model.search(
[("type", "=", "purchase"), ("company_id", "=", company.id)], limit=1
)
if not journals:
raise UserError(
_("Define a purchase journal " "for this company: '%s' (id: %d).")
% (company.name, company.id)
)
return journals[0]
def create_e_invoice_line(self, line):
vals = {
"line_number": int(line.NumeroLinea or 0),
"service_type": line.TipoCessionePrestazione,
"name": line.Descrizione,
"qty": float(line.Quantita or 0),
"uom": line.UnitaMisura,
"period_start_date": line.DataInizioPeriodo,
"period_end_date": line.DataFinePeriodo,
"unit_price": float(line.PrezzoUnitario or 0),
"total_price": float(line.PrezzoTotale or 0),
"tax_amount": float(line.AliquotaIVA or 0),
"wt_amount": line.Ritenuta,
"tax_kind": line.Natura,
"admin_ref": line.RiferimentoAmministrazione,
}
einvoiceline = self.env["einvoice.line"].create(vals)
if line.CodiceArticolo:
for caline in line.CodiceArticolo:
self.env["fatturapa.article.code"].create(
{
"name": caline.CodiceTipo or "",
"code_val": caline.CodiceValore or "",
"e_invoice_line_id": einvoiceline.id,
}
)
if line.ScontoMaggiorazione:
for DiscRisePriceLine in line.ScontoMaggiorazione:
DiscRisePriceVals = self.with_context(
drtype="e_invoice_line_id"
)._prepareDiscRisePriceLine(einvoiceline.id, DiscRisePriceLine)
self.env["discount.rise.price"].create(DiscRisePriceVals)
if line.AltriDatiGestionali:
for dato in line.AltriDatiGestionali:
self.env["einvoice.line.other.data"].create(
{
"name": dato.TipoDato,
"text_ref": dato.RiferimentoTesto,
"num_ref": float(dato.RiferimentoNumero or 0),
"date_ref": dato.RiferimentoData,
"e_invoice_line_id": einvoiceline.id,
}
)
return einvoiceline
def get_credit_account(self, product=None):
"""
Try to get default credit account for invoice line looking in
1) product (if provided)
2) purchase journal
3) company default.
:param product: Product whose expense account will be used
:return: The account found
"""
credit_account = self.env["account.account"].browse()
# If there is a product, get its default expense account
if product:
template = product.product_tmpl_id
accounts_dict = template.get_product_accounts()
credit_account = accounts_dict["expense"]
company = self.env.user.company_id
# Search in purchase journal
journal = self.get_purchase_journal(company)
if not credit_account:
credit_account = journal.default_account_id
# Search in company defaults
if not credit_account:
credit_account = (
self.env["ir.property"]
.with_company(company)
._get("property_account_expense_categ_id", "product.category")
)
if not credit_account:
raise UserError(
_(
"Please configure Default Credit Account "
"in Journal '{journal}' "
"or check default expense account "
"for company '{company}'."
).format(
journal=journal.display_name,
company=company.display_name,
)
)
return credit_account
def invoiceCreate(self, fatt, fatturapa_attachment, FatturaBody, partner_id):
partner_model = self.env["res.partner"]
invoice_model = self.env["account.move"]
currency_model = self.env["res.currency"]
ftpa_doctype_model = self.env["fiscal.document.type"]
rel_docs_model = self.env["fatturapa.related_document_type"]
company = self.env.company
partner = partner_model.browse(partner_id)
# currency 2.1.1.2
currency = currency_model.search(
[("name", "=", FatturaBody.DatiGenerali.DatiGeneraliDocumento.Divisa)]
)
if not currency:
raise UserError(
_(
"No currency found with code %s."
% FatturaBody.DatiGenerali.DatiGeneraliDocumento.Divisa
)
)
purchase_journal = self.get_purchase_journal(company)
credit_account = self.get_credit_account()
comment = ""
# 2.1.1
docType_id = False
invtype = "in_invoice"
docType = FatturaBody.DatiGenerali.DatiGeneraliDocumento.TipoDocumento
if docType:
docType_record = ftpa_doctype_model.search([("code", "=", docType)])
if docType_record:
docType_id = docType_record[0].id
else:
raise UserError(_("Document type %s not handled.") % docType)
if docType == "TD04":
invtype = "in_refund"
# 2.1.1.11
causLst = FatturaBody.DatiGenerali.DatiGeneraliDocumento.Causale
if causLst:
for rel_doc in causLst:
comment += rel_doc + "\n"
if fatturapa_attachment.e_invoice_received_date:
e_invoice_received_date = (
fatturapa_attachment.e_invoice_received_date.date()