Debian Codegraph @

addons/l10n_my_edi/models/account_edi_xml_ubl_my.py

raw symbols SCIP
1 # Part of Odoo. See LICENSE file for full copyright and licensing details.
2 import re
3
4 from datetime import datetime
5 from pytz import UTC
6 from lxml import etree
7
8 from odoo import api, models
9 from odoo.tools import html2plaintext
10
11 # Far from ideal, but no better solution yet.
12 COUNTRY_CODE_MAP = {
13 "BD": "BGD", "BE": "BEL", "BF": "BFA", "BG": "BGR", "BA": "BIH", "BB": "BRB", "WF": "WLF", "BL": "BLM", "BM": "BMU",
14 "BN": "BRN", "BO": "BOL", "BH": "BHR", "BI": "BDI", "BJ": "BEN", "BT": "BTN", "JM": "JAM", "BV": "BVT", "BW": "BWA",
15 "WS": "WSM", "BQ": "BES", "BR": "BRA", "BS": "BHS", "JE": "JEY", "BY": "BLR", "BZ": "BLZ", "RU": "RUS", "RW": "RWA",
16 "RS": "SRB", "TL": "TLS", "RE": "REU", "TM": "TKM", "TJ": "TJK", "RO": "ROU", "TK": "TKL", "GW": "GNB", "GU": "GUM",
17 "GT": "GTM", "GS": "SGS", "GR": "GRC", "GQ": "GNQ", "GP": "GLP", "JP": "JPN", "GY": "GUY", "GG": "GGY", "GF": "GUF",
18 "GE": "GEO", "GD": "GRD", "GB": "GBR", "GA": "GAB", "SV": "SLV", "GN": "GIN", "GM": "GMB", "GL": "GRL", "GI": "GIB",
19 "GH": "GHA", "OM": "OMN", "TN": "TUN", "JO": "JOR", "HR": "HRV", "HT": "HTI", "HU": "HUN", "HK": "HKG", "HN": "HND",
20 "HM": "HMD", "VE": "VEN", "PR": "PRI", "PS": "PSE", "PW": "PLW", "PT": "PRT", "SJ": "SJM", "PY": "PRY", "IQ": "IRQ",
21 "PA": "PAN", "PF": "PYF", "PG": "PNG", "PE": "PER", "PK": "PAK", "PH": "PHL", "PN": "PCN", "PL": "POL", "PM": "SPM",
22 "ZM": "ZMB", "EH": "ESH", "EE": "EST", "EG": "EGY", "ZA": "ZAF", "EC": "ECU", "IT": "ITA", "VN": "VNM", "SB": "SLB",
23 "ET": "ETH", "SO": "SOM", "ZW": "ZWE", "SA": "SAU", "ES": "ESP", "ER": "ERI", "ME": "MNE", "MD": "MDA", "MG": "MDG",
24 "MF": "MAF", "MA": "MAR", "MC": "MCO", "UZ": "UZB", "MM": "MMR", "ML": "MLI", "MO": "MAC", "MN": "MNG", "MH": "MHL",
25 "MK": "MKD", "MU": "MUS", "MT": "MLT", "MW": "MWI", "MV": "MDV", "MQ": "MTQ", "MP": "MNP", "MS": "MSR", "MR": "MRT",
26 "IM": "IMN", "UG": "UGA", "TZ": "TZA", "MY": "MYS", "MX": "MEX", "IL": "ISR", "FR": "FRA", "IO": "IOT", "SH": "SHN",
27 "FI": "FIN", "FJ": "FJI", "FK": "FLK", "FM": "FSM", "FO": "FRO", "NI": "NIC", "NL": "NLD", "NO": "NOR", "NA": "NAM",
28 "VU": "VUT", "NC": "NCL", "NE": "NER", "NF": "NFK", "NG": "NGA", "NZ": "NZL", "NP": "NPL", "NR": "NRU", "NU": "NIU",
29 "CK": "COK", "XK": "XKX", "CI": "CIV", "CH": "CHE", "CO": "COL", "CN": "CHN", "CM": "CMR", "CL": "CHL", "CC": "CCK",
30 "CA": "CAN", "CG": "COG", "CF": "CAF", "CD": "COD", "CZ": "CZE", "CY": "CYP", "CX": "CXR", "CR": "CRI", "CW": "CUW",
31 "CV": "CPV", "CU": "CUB", "SZ": "SWZ", "SY": "SYR", "SX": "SXM", "KG": "KGZ", "KE": "KEN", "SS": "SSD", "SR": "SUR",
32 "KI": "KIR", "KH": "KHM", "KN": "KNA", "KM": "COM", "ST": "STP", "SK": "SVK", "KR": "KOR", "SI": "SVN", "KP": "PRK",
33 "KW": "KWT", "SN": "SEN", "SM": "SMR", "SL": "SLE", "SC": "SYC", "KZ": "KAZ", "KY": "CYM", "SG": "SGP", "SE": "SWE",
34 "SD": "SDN", "DO": "DOM", "DM": "DMA", "DJ": "DJI", "DK": "DNK", "VG": "VGB", "DE": "DEU", "YE": "YEM", "DZ": "DZA",
35 "US": "USA", "UY": "URY", "YT": "MYT", "UM": "UMI", "LB": "LBN", "LC": "LCA", "LA": "LAO", "TV": "TUV", "TW": "TWN",
36 "TT": "TTO", "TR": "TUR", "LK": "LKA", "LI": "LIE", "LV": "LVA", "TO": "TON", "LT": "LTU", "LU": "LUX", "LR": "LBR",
37 "LS": "LSO", "TH": "THA", "TF": "ATF", "TG": "TGO", "TD": "TCD", "TC": "TCA", "LY": "LBY", "VA": "VAT", "VC": "VCT",
38 "AE": "ARE", "AD": "AND", "AG": "ATG", "AF": "AFG", "AI": "AIA", "VI": "VIR", "IS": "ISL", "IR": "IRN", "AM": "ARM",
39 "AL": "ALB", "AO": "AGO", "AQ": "ATA", "AS": "ASM", "AR": "ARG", "AU": "AUS", "AT": "AUT", "AW": "ABW", "IN": "IND",
40 "AX": "ALA", "AZ": "AZE", "IE": "IRL", "ID": "IDN", "UA": "UKR", "QA": "QAT", "MZ": "MOZ"
41 }
42 E_164_REGEX = re.compile(r"^\+[1-9]\d{1,14}$")
43
44
45 class AccountEdiXmlUBLMyInvoisMY(models.AbstractModel):
46 """
47 * MyInvois API formats doc: https://sdk.myinvois.hasil.gov.my/documents
48 """
49 _inherit = "account.edi.xml.ubl_21"
50 _name = 'account.edi.xml.ubl_myinvois_my'
51 _description = "Malaysian implementation of ubl for the MyInvois portal"
52
53 # -----------------------
54 # EXPORT
55 # -----------------------
56
57 def _get_myinvois_document_node(self, vals):
58 """
59 Entry point of the export of a MyInvois document.
60 The node returned by this function should be passed into dict_to_xml in order to generate the XML file to send to
61 MyInvois.
62 """
63 self._add_myinvois_document_config_vals(vals)
64 self._add_myinvois_document_base_lines_vals(vals)
65 self._setup_base_lines(vals)
66 self._add_document_currency_vals(vals)
67 self._add_myinvois_document_tax_grouping_function_vals(vals)
68 self._add_myinvois_document_monetary_total_vals(vals)
69
70 document_node = {}
71 self._add_myinvois_document_header_nodes(document_node, vals)
72 self._add_myinvois_document_accounting_supplier_party_nodes(document_node, vals)
73 self._add_myinvois_document_accounting_customer_party_nodes(document_node, vals)
74
75 myinvois_document = vals["myinvois_document"]
76 if vals['document_type'] == 'invoice' and not myinvois_document._is_consolidated_invoice():
77 self._add_myinvois_document_delivery_nodes(document_node, vals)
78 self._add_myinvois_document_payment_terms_nodes(document_node, vals)
79
80 self._add_document_allowance_charge_nodes(document_node, vals)
81 self._add_myinvois_document_exchange_rate_nodes(document_node, vals)
82 self._add_document_tax_total_nodes(document_node, vals)
83 self._add_myinvois_document_monetary_total_nodes(document_node, vals)
84 self._add_myinvois_document_line_nodes(document_node, vals)
85 return document_node
86
87 def _add_myinvois_document_config_vals(self, vals):
88 myinvois_document = vals['myinvois_document']
89 supplier = myinvois_document.company_id.partner_id.commercial_partner_id
90
91 if myinvois_document._is_consolidated_invoice() or myinvois_document._is_consolidated_invoice_refund():
92 customer = self.env["res.partner"].search(
93 domain=[
94 *self.env['res.partner']._check_company_domain(myinvois_document.company_id),
95 '|',
96 ('vat', '=', 'EI00000000010'),
97 ('l10n_my_edi_malaysian_tin', '=', 'EI00000000010'),
98 ],
99 limit=1,
100 )
101 partner_shipping = None
102 payment_term_id = None # wouldn't make sense in a consolidated invoice.
103 else:
104 invoice = myinvois_document.invoice_ids[0] # Otherwise it would be a consolidated invoice.
105 customer = invoice.partner_id
106 partner_shipping = invoice.partner_shipping_id or customer
107 payment_term_id = invoice.invoice_payment_term_id
108
109 document_type_code, original_document = self._l10n_my_edi_get_document_type_code(myinvois_document)
110 # In case of self billing, we want to invert the supplier and customer.
111 if document_type_code in ("11", "12", "13", "14"):
112 supplier, customer = customer, supplier
113 partner_shipping = customer
114 # In practice, we should never have multiple self billed invoices being part of a consolidated invoices,
115 # but it doesn't hurt to support it.
116 document_ref = ','.join([invoice.ref for invoice in myinvois_document.invoice_ids if invoice.ref]) or None
117 else:
118 document_ref = None
119
120 vals.update({
121 'document_type': 'invoice',
122 'document_type_code': document_type_code,
123 'original_document': original_document,
124
125 'document_name': myinvois_document.name,
126
127 'supplier': supplier,
128 'customer': customer,
129 'partner_shipping': partner_shipping,
130
131 'company': myinvois_document.company_id,
132 'currency_id': myinvois_document.currency_id,
133 'company_currency_id': myinvois_document.company_id.currency_id,
134
135 'use_company_currency': False,
136 'fixed_taxes_as_allowance_charges': True,
137 'custom_form_reference': myinvois_document.myinvois_custom_form_reference,
138 'document_ref': document_ref,
139 'incoterm_id': myinvois_document.invoice_ids.invoice_incoterm_id,
140 'invoice_payment_term_id': payment_term_id,
141 })
142
143 def _add_myinvois_document_base_lines_vals(self, vals):
144 myinvois_document = vals['myinvois_document']
145 vals['base_lines'] = myinvois_document._get_rounded_base_lines()
146
147 def _add_myinvois_document_tax_grouping_function_vals(self, vals):
148 def total_grouping_function(base_line, tax_data):
149 return True
150
151 def tax_grouping_function(base_line, tax_data):
152 tax = tax_data and tax_data['tax']
153 myinvois_document = base_line['myinvois_document']
154
155 if (
156 not tax
157 and not myinvois_document._is_consolidated_invoice()
158 and not myinvois_document._is_consolidated_invoice_refund()
159 ):
160 return None # Triggers UserError for missing tax on simple invoice.
161
162 is_exempt_tax = tax and tax.l10n_my_tax_type == 'E'
163 tax_exemption_reason = is_exempt_tax and (
164 myinvois_document.myinvois_exemption_reason
165 or tax.l10n_my_tax_exemption_reason
166 )
167
168 return {
169 'tax_category_code': tax.l10n_my_tax_type if tax else '06',
170 'tax_exemption_reason': tax_exemption_reason,
171 'amount': tax.amount if tax else 0.0,
172 'amount_type': tax.amount_type if tax else 'percent',
173 }
174
175 vals['total_grouping_function'] = total_grouping_function
176 vals['tax_grouping_function'] = tax_grouping_function
177
178 def _add_myinvois_document_monetary_total_vals(self, vals):
179 self._add_document_monetary_total_vals(vals)
180 myinvois_document = vals["myinvois_document"]
181 if myinvois_document.invoice_ids:
182 # Add the total amount paid.
183 vals.update({
184 'total_paid_amount': sum((invoice.amount_total - invoice.amount_residual) * invoice.invoice_currency_rate for invoice in myinvois_document.invoice_ids),
185 'total_paid_amount_currency': sum(invoice.amount_total - invoice.amount_residual for invoice in myinvois_document.invoice_ids),
186 })
187
188 # -------------------------------------------------------------------------
189 # EXPORT: Templates
190 # -------------------------------------------------------------------------
191
192 def _get_myinvois_document_address_node(self, vals):
193 partner = vals['partner']
194
195 # The API expects the iso3166-2 code for the state, in the same way as it expects the iso3166 code for the countries.
196 # In Odoo, we mostly use these (although there is no standard format) so we'll try to use what Odoo gives us.
197 # For malaysia, the codes were updated..
198
199 subentity_code = ''
200 country = partner.country_id
201
202 if partner.state_id:
203 if (
204 partner._l10n_my_edi_get_tin_for_myinvois() == 'EI00000000010'
205 and partner.l10n_my_identification_number == 'NA'
206 ):
207 # Special case for consolidated entities (e.g., general public).
208 # When TIN is 'EI00000000010' and Identification Number is 'NA', MyInvois requires
209 # the CountrySubentityCode to be fixed as '17' regardless of the actual state.
210 subentity_code = '17'
211 elif country.code != 'MY':
212 # For non-Malaysian partners return the state name instead of state code
213 subentity_code = partner.state_id.name
214 else:
215 # Get the subentity code for the partner, based on its state.
216 subentity_code = partner.state_id.code
217
218 # Strip 'MY-' prefix if present as we only need number part
219 subentity_code = subentity_code.split('-')[1] if 'MY-' in subentity_code else subentity_code
220
221 return {
222 'cbc:CityName': {'_text': partner.city},
223 'cbc:PostalZone': {'_text': partner.zip},
224 'cbc:CountrySubentity': {'_text': partner.state_id.name},
225 'cbc:CountrySubentityCode': {'_text': subentity_code},
226 'cac:AddressLine': [
227 {'cbc:Line': {'_text': partner.street}},
228 {'cbc:Line': {'_text': partner.street2}},
229 ],
230 'cac:Country': {
231 'cbc:IdentificationCode': {
232 '_text': COUNTRY_CODE_MAP.get(country.code),
233 'listAgencyID': '6',
234 'listID': 'ISO3166-1',
235 },
236 'cbc:Name': {
237 '_text': country.name,
238 'languageID': vals.get('country_vals', {}).get('name_attrs', {}).get('languageID'),
239 },
240 },
241 }
242
243 def _get_myinvois_document_party_identification_node(self, vals):
244 """ The id vals list must be filled with two values.
245 The TIN, and then one of either:
246 - Business registration number (BNR)
247 - MyKad/MyTentera identification number (NRIC)
248 - Passport number or MyPR/MyKAS identification number (PASSPORT)
249 - (ARMY)
250 Additionally, companies registered to use SST (sales & services tax) must provide their SST number.
251 Finally, if a supplier is using TTX (tourism tax), once again that number must be provided.
252 """
253 partner = vals['partner']
254
255 tin = partner._l10n_my_edi_get_tin_for_myinvois()
256
257 # If the invoice's commercial partner uses a Generic TIN, set it to the correct generic TIN
258 # depending on whether the invoice is self-billed or not.
259 if vals['document_type_code'] in ('01', '02', '03', '04') and tin == 'EI00000000030' and vals['role'] == 'customer':
260 tin = 'EI00000000020' # For normal invoices, this partner TIN should be used
261 elif vals['document_type_code'] in ('11', '12', '13', '14') and tin == 'EI00000000020' and vals['role'] == 'supplier':
262 tin = 'EI00000000030' # For self-billed invoices, this partner TIN should be used
263
264 party_identification_node = [
265 {
266 'cbc:ID': {
267 '_text': tin,
268 'schemeID': 'TIN',
269 }
270 }
271 ]
272
273 if partner.l10n_my_identification_type and partner.l10n_my_identification_number:
274 party_identification_node.append({
275 'cbc:ID': {
276 '_text': partner.l10n_my_identification_number,
277 'schemeID': partner.l10n_my_identification_type,
278 }
279 })
280 if partner.sst_registration_number:
281 party_identification_node.append({
282 'cbc:ID': {
283 '_text': partner.sst_registration_number,
284 'schemeID': 'SST',
285 }
286 })
287 if partner.ttx_registration_number and vals['role'] == 'supplier':
288 party_identification_node.append({
289 'cbc:ID': {
290 '_text': partner.ttx_registration_number,
291 'schemeID': 'TTX',
292 }
293 })
294 return party_identification_node
295
296 def _get_myinvois_document_party_node(self, vals):
297 partner = vals['partner']
298 role = vals['role']
299
300 return {
301 'cbc:IndustryClassificationCode': {
302 '_text': partner.commercial_partner_id.l10n_my_edi_industrial_classification.code,
303 'name': partner.commercial_partner_id.l10n_my_edi_industrial_classification.name
304 } if role == 'supplier' else None,
305 'cac:PartyIdentification': self._get_myinvois_document_party_identification_node({**vals, 'partner': partner.commercial_partner_id}),
306 'cac:PartyName': {
307 'cbc:Name': {'_text': partner.display_name}
308 } if role != 'delivery' else None,
309 'cac:PostalAddress': self._get_myinvois_document_address_node(vals),
310 'cac:PartyLegalEntity': {
311 'cbc:RegistrationName': {'_text': partner.commercial_partner_id.name},
312 },
313 'cac:Contact': {
314 'cbc:ID': {'_text': partner.id},
315 'cbc:Name': {'_text': partner.name},
316 'cbc:Telephone': {'_text': self._l10n_my_edi_get_formatted_phone_number(partner.phone)},
317 'cbc:ElectronicMail': {'_text': partner.email},
318 } if role != 'delivery' else None,
319 }
320
321 def _get_tax_category_node(self, vals):
322 grouping_key = vals['grouping_key']
323 return {
324 'cbc:ID': {'_text': grouping_key['tax_category_code']},
325 'cbc:Name': {'_text': grouping_key['tax_exemption_reason']},
326 'cbc:Percent': {'_text': grouping_key['amount']} if grouping_key['amount_type'] == 'percent' else None,
327 'cbc:TaxExemptionReason': {'_text': grouping_key['tax_exemption_reason']},
328 'cac:TaxScheme': {
329 'cbc:ID': {
330 '_text': 'OTH',
331 'schemeID': 'UN/ECE 5153',
332 'schemeAgencyID': '6',
333 }
334 }
335 }
336
337 def _add_myinvois_document_header_nodes(self, document_node, vals):
338 original_document_id = None
339 if vals['document_type_code'] in {'02', '03', '04', '12', '13', '14'} and vals['original_document']:
340 if vals['original_document'].myinvois_file_id:
341 decoded_vals = self._l10n_my_edi_decode_myinvois_attachment(vals['original_document'].myinvois_file_id)
342 original_document_id = decoded_vals.get('original_document_id')
343 original_invoice = vals['original_document'].invoice_ids[:1]
344 if not original_document_id and vals['document_type_code'] in {'12', '13', '14'} and original_invoice.ref:
345 original_document_id = original_invoice.ref
346 if not original_document_id:
347 original_document_id = vals['original_document'].name
348
349 document_node.update({
350 'cbc:UBLVersionID': None,
351 'cbc:ID': {'_text': vals['document_name']},
352 # The issue date and time must be the current time set in the UTC time zone
353 'cbc:IssueDate': {'_text': datetime.now(tz=UTC).strftime("%Y-%m-%d")},
354 'cbc:IssueTime': {'_text': datetime.now(tz=UTC).strftime("%H:%M:%SZ")},
355 'cbc:DueDate': None,
356
357 # The current version is 1.1 (document with signature), the type code depends on the move type.
358 'cbc:InvoiceTypeCode': {
359 '_text': vals['document_type_code'],
360 'listVersionID': '1.1',
361 },
362 'cbc:DocumentCurrencyCode': {'_text': vals['currency_id'].name},
363 'cac:OrderReference': None,
364 'cbc:BuyerReference': {'_text': vals['customer'].commercial_partner_id.ref},
365
366 # Debit/Credit note original invoice ref.
367 # Applies to credit notes, debit notes, refunds for both invoices and self-billed invoices.
368 # The original document is mandatory; but in some specific cases it will be empty (sending a credit note for an invoice
369 # managed outside Odoo/...)
370 'cac:BillingReference': {
371 'cac:InvoiceDocumentReference': {
372 'cbc:ID': {'_text': original_document_id or 'NA'},
373 'cbc:UUID': {'_text': (vals['original_document'] and vals['original_document'].myinvois_external_uuid) or 'NA'},
374 }
375 } if vals['document_type_code'] in {'02', '03', '04', '12', '13', '14'} else None,
376 'cac:AdditionalDocumentReference': [
377 {
378 'cbc:ID': {'_text': vals['custom_form_reference']},
379 'cbc:DocumentType': {'_text': 'CustomsImportForm'},
380 } if vals['document_type_code'] in {'11', '12', '13', '14'} and vals['custom_form_reference'] else None,
381 {
382 'cbc:ID': {'_text': vals["incoterm_id"].code}
383 } if vals["incoterm_id"] else None,
384 {
385 'cbc:ID': {'_text': vals['custom_form_reference']},
386 'cbc:DocumentType': {'_text': 'K2'},
387 } if vals['document_type_code'] in {'01', '02', '03', '04'} and vals['custom_form_reference'] else None,
388 ],
389 })
390
391 # Self-billed invoices must use the number given by the supplier.
392 if vals['document_type_code'] in ('11', '12', '13', '14') and vals['document_ref']:
393 document_node['cbc:ID']['_text'] = vals['document_ref']
394
395 def _add_myinvois_document_accounting_supplier_party_nodes(self, document_node, vals):
396 document_node['cac:AccountingSupplierParty'] = {
397 'cac:Party': self._get_myinvois_document_party_node({**vals, 'partner': vals['supplier'], 'role': 'supplier'}),
398 }
399
400 def _add_myinvois_document_accounting_customer_party_nodes(self, document_node, vals):
401 document_node['cac:AccountingCustomerParty'] = {
402 'cac:Party': self._get_myinvois_document_party_node({**vals, 'partner': vals['customer'], 'role': 'customer'}),
403 }
404
405 def _add_myinvois_document_delivery_nodes(self, document_node, vals):
406 document_node['cac:Delivery'] = {
407 'cac:DeliveryParty': self._get_myinvois_document_party_node({**vals, 'partner': vals['customer'], 'role': 'delivery'}),
408 }
409
410 def _add_myinvois_document_payment_terms_nodes(self, document_node, vals):
411 if vals['invoice_payment_term_id']:
412 document_node['cac:PaymentTerms'] = {
413 # The payment term's note is automatically embedded in a <p> tag in Odoo
414 'cbc:Note': {'_text': html2plaintext(vals['invoice_payment_term_id'].note)}
415 }
416
417 def _add_myinvois_document_exchange_rate_nodes(self, document_node, vals):
418 if vals['currency_id'].name != 'MYR':
419 # I couldn't find any information on maximum precision, so we will use the currency format.
420 total_amount_in_company_currency = total_amount_in_currency = 0.0
421 for base_line in vals['base_lines']:
422 total_amount_in_company_currency += base_line['tax_details']['raw_total_included']
423 total_amount_in_currency += base_line['tax_details']['raw_total_included_currency']
424 # We recalculate the rate so that it works in any cases, even when using consolidated invoices.
425 rate = self.env.ref('base.MYR').round(abs(total_amount_in_company_currency) / (total_amount_in_currency or 1))
426 # Exchange rate information must be provided if applicable
427 document_node['cac:TaxExchangeRate'] = {
428 'cbc:SourceCurrencyCode': {'_text': vals['currency_id'].name},
429 'cbc:TargetCurrencyCode': {'_text': 'MYR'},
430 'cbc:CalculationRate': {'_text': rate},
431 }
432
433 def _add_myinvois_document_monetary_total_nodes(self, document_node, vals):
434 self._add_document_monetary_total_nodes(document_node, vals)
435 currency_suffix = vals['currency_suffix']
436
437 amount_paid = vals[f'total_paid_amount{currency_suffix}']
438 if amount_paid:
439 document_node['cac:PrepaidPayment'] = {
440 'cbc:PaidAmount': {
441 '_text': self.format_float(amount_paid, vals['currency_dp']),
442 'currencyID': vals['currency_name'],
443 },
444 }
445 monetary_total_tag = self._get_tags_for_document_type(vals)['monetary_total']
446 payable_amount = self.format_float(vals[f'tax_inclusive_amount{currency_suffix}'] - amount_paid, vals['currency_dp'])
447 document_node[monetary_total_tag]['cbc:PayableAmount']['_text'] = payable_amount
448
449 def _add_myinvois_document_line_nodes(self, document_node, vals):
450 line_idx = 1
451
452 line_tag = self._get_tags_for_document_type(vals)['document_line']
453 document_node[line_tag] = line_nodes = []
454 for base_line in vals['base_lines']:
455 if not self._is_document_allowance_charge(base_line):
456 line_vals = {
457 **vals,
458 'line_idx': line_idx,
459 'base_line': base_line,
460 }
461 line_node = self._get_myinvois_document_line_node(line_vals)
462 line_nodes.append(line_node)
463 line_idx += 1
464
465 def _get_myinvois_document_line_node(self, vals):
466 self._add_myinvois_document_line_vals(vals)
467
468 line_node = {}
469 self._add_document_line_id_nodes(line_node, vals)
470 self._add_document_line_id_nodes(line_node, vals)
471 self._add_myinvois_document_line_amount_nodes(line_node, vals)
472 self._add_document_line_allowance_charge_nodes(line_node, vals)
473 self._add_document_line_tax_total_nodes(line_node, vals)
474 self._add_myinvois_document_line_item_nodes(line_node, vals)
475 self._add_document_line_tax_category_nodes(line_node, vals)
476 self._add_document_line_price_nodes(line_node, vals)
477 return line_node
478
479 def _add_myinvois_document_line_vals(self, vals):
480 """ Generic helper to calculate the amounts for a document line. """
481 self._add_document_line_total_vals(vals)
482 self._add_myinvois_document_line_gross_subtotal_and_discount_vals(vals)
483
484 def _add_myinvois_document_line_gross_subtotal_and_discount_vals(self, vals):
485 """
486 As we group lines together when consolidating, we lose the discount percentage in the process.
487 During the grouping, we stored the actual amount in the base line, se we will override here in order to use that
488 pre-computed amount.
489 """
490 self._add_document_line_gross_subtotal_and_discount_vals(vals)
491 myinvois_document = vals["myinvois_document"]
492 if myinvois_document._is_consolidated_invoice():
493 base_line = vals['base_line']
494
495 for currency_suffix in ['', '_currency']:
496 discount_amount = base_line[f'discount_amount{currency_suffix}']
497
498 vals[f'discount_amount{currency_suffix}'] = discount_amount
499 vals[f'gross_price_unit{currency_suffix}'] += discount_amount # Price unit should be excluding discounts.
500
501 def _add_myinvois_document_line_amount_nodes(self, line_node, vals):
502 super()._add_document_line_amount_nodes(line_node, vals)
503
504 base_line = vals['base_line']
505 line_node['cac:ItemPriceExtension'] = {
506 'cbc:Amount': {
507 '_text': self.format_float(base_line['tax_details']['total_excluded_currency'], vals['currency_dp']),
508 'currencyID': vals['currency_name'],
509 }
510 }
511
512 def _add_myinvois_document_line_item_nodes(self, line_node, vals):
513 self._add_document_line_item_nodes(line_node, vals)
514
515 record = vals['base_line']['record']
516 if record and record.name:
517 line_name = record.name and record.name.replace('\n', ' ')
518 else:
519 line_name = vals['base_line']['line_name']
520 if line_name:
521 line_node['cac:Item']['cbc:Description']['_text'] = line_name
522 if not line_node['cac:Item']['cbc:Name']['_text']:
523 line_node['cac:Item']['cbc:Name']['_text'] = line_name
524
525 # When the invoice is sent for the general public (refunding an order in a consolidated invoice/...) the item code
526 # must be fixed to 004 (consolidated invoice) even if the product has something else set.
527 myinvois_document = vals['myinvois_document']
528 if myinvois_document._is_consolidated_invoice() or myinvois_document._is_consolidated_invoice_refund():
529 class_code = '004'
530 else:
531 base_line = vals['base_line']
532 class_code = base_line['record'].l10n_my_edi_classification_code or \
533 base_line['record'].product_id.product_tmpl_id.l10n_my_edi_classification_code
534
535 if class_code:
536 line_node['cac:Item']['cac:CommodityClassification'] = {
537 'cbc:ItemClassificationCode': {
538 '_text': class_code,
539 'listID': 'CLASS',
540 }
541 }
542
543 # -------------------------------------------------------------------------
544 # EXPORT: Constraints
545 # -------------------------------------------------------------------------
546
547 def _export_myinvois_document_constraints(self, vals):
548 constraints = {
549 'myinvois_supplier_name_required': self._check_required_fields(vals['supplier'], 'name'),
550 'myinvois_customer_name_required': self._check_required_fields(vals['customer'].commercial_partner_id, 'name'),
551 'myinvois_document_name_required': self._check_required_fields(vals, 'document_name'),
552 }
553
554 if not vals['supplier'].commercial_partner_id.l10n_my_edi_industrial_classification:
555 self._l10n_my_edi_make_validation_error(constraints, 'industrial_classification_required', 'supplier', vals['supplier'].display_name)
556
557 for partner_type in ('supplier', 'customer'):
558 partner = vals[partner_type]
559 phone_number = partner.phone
560 # 'NA' is a valid value in some cases, e.g. consolidated invoices.
561 if phone_number != 'NA':
562 phone = self._l10n_my_edi_get_formatted_phone_number(phone_number)
563 if E_164_REGEX.match(phone) is None:
564 self._l10n_my_edi_make_validation_error(constraints, 'phone_number_format', partner_type, partner.display_name)
565 elif not phone_number:
566 self._l10n_my_edi_make_validation_error(constraints, 'phone_number_required', partner_type, partner.display_name)
567
568 # We need to provide both l10n_my_identification_type and l10n_my_identification_number
569 if not partner.commercial_partner_id.l10n_my_identification_type or not partner.commercial_partner_id.l10n_my_identification_number:
570 self._l10n_my_edi_make_validation_error(constraints, 'required_id', partner_type, partner.commercial_partner_id.display_name)
571
572 if not partner.state_id:
573 self._l10n_my_edi_make_validation_error(constraints, 'no_state', partner_type, partner.display_name)
574 if not partner.city:
575 self._l10n_my_edi_make_validation_error(constraints, 'no_city', partner_type, partner.display_name)
576 if not partner.country_id:
577 self._l10n_my_edi_make_validation_error(constraints, 'no_country', partner_type, partner.display_name)
578 if not partner.street:
579 self._l10n_my_edi_make_validation_error(constraints, 'no_street', partner_type, partner.display_name)
580
581 if partner.commercial_partner_id.sst_registration_number and len(partner.commercial_partner_id.sst_registration_number.split(';')) > 2:
582 self._l10n_my_edi_make_validation_error(constraints, 'too_many_sst', partner_type, partner.commercial_partner_id.display_name)
583
584 for line_vals in vals['document_node']['cac:InvoiceLine']:
585 line_item = line_vals['cac:Item']
586 if 'cac:CommodityClassification' not in line_item:
587 self._l10n_my_edi_make_validation_error(constraints, 'class_code_required', line_vals['cbc:ID']['_text'], line_item['cbc:Name']['_text'])
588 if not line_item.get('cac:ClassifiedTaxCategory'):
589 self._l10n_my_edi_make_validation_error(constraints, 'tax_ids_required', line_vals['cbc:ID']['_text'], line_item['cbc:Name']['_text'])
590 for tax_category in line_item['cac:ClassifiedTaxCategory']:
591 if tax_category['cbc:ID']['_text'] == 'E' and not tax_category['cbc:TaxExemptionReason']['_text']:
592 self._l10n_my_edi_make_validation_error(constraints, 'tax_exemption_required', line_vals['cbc:ID']['_text'], line_item['cbc:Name']['_text'])
593
594 myinvois_document = vals["myinvois_document"]
595 if myinvois_document._is_consolidated_invoice() or myinvois_document._is_consolidated_invoice_refund():
596 customer_vat = vals['document_node']['cac:AccountingCustomerParty']['cac:Party']['cac:PartyIdentification'][0]['cbc:ID']['_text']
597 if customer_vat != 'EI00000000010':
598 self._l10n_my_edi_make_validation_error(constraints, 'missing_general_public', vals['customer'].id, vals['customer'].name)
599
600 return constraints
601
602 @api.model
603 def _l10n_my_edi_make_validation_error(self, constraints, code, record_identifier, record_name):
604 """ Small helper that add new constrains into provided constrains dict.
605 This helper is mainly there to keep the check method tidy, and focused on its purpose (validating data)
606 """
607 message_mapping = {
608 'industrial_classification_required': self.env._(
609 "The industrial classification must be defined on company: %(company_name)s",
610 company_name=record_name
611 ),
612 'phone_number_format': self.env._(
613 "The following partner's phone number should follow the E.164 format: %(partner_name)s",
614 partner_name=record_name
615 ),
616 'phone_number_required': self.env._(
617 "The following partner's phone number is missing: %(partner_name)s",
618 partner_name=record_name
619 ),
620 'required_id': self.env._(
621 "The following partner's identification type or number is missing: %(partner_name)s",
622 partner_name=record_name
623 ),
624 'no_state': self.env._(
625 "The following partner's state is missing: %(partner_name)s",
626 partner_name=record_name
627 ),
628 'no_city': self.env._(
629 "The following partner's city is missing: %(partner_name)s",
630 partner_name=record_name
631 ),
632 'no_country': self.env._(
633 "The following partner's country is missing: %(partner_name)s",
634 partner_name=record_name
635 ),
636 'no_street': self.env._(
637 "The following partner's street is missing: %(partner_name)s",
638 partner_name=record_name
639 ),
640 'class_code_required': self.env._(
641 "You must set a classification code either on the line itself or on the product of line: %(line_name)s",
642 line_name=record_name
643 ),
644 'adjustment_origin': self.env._(
645 "You cannot send a debit / credit note for invoice %(invoice_number)s as it has not yet been sent to MyInvois.",
646 invoice_number=record_name
647 ),
648 'too_many_sst': self.env._(
649 "The following partner's should have at most two SST numbers, separated by a semicolon : %(partner_name)s",
650 partner_name=record_name
651 ),
652 'tax_ids_required': self.env._(
653 "You must set a tax on the line : %(line_name)s.\nIf taxes are not applicable, please set a 0%% tax with a tax type 'Not Applicable'.",
654 line_name=record_name
655 ),
656 'tax_exemption_required': self.env._(
657 "You must set a Tax Exemption Reason on the invoice : %(invoice_name)s as some taxes have the type 'Tax exemption' without a reason set.",
658 invoice_name=record_name
659 ),
660 'tax_exemption_required_on_tax': self.env._(
661 "You must set a Tax Exemption Reason on each tax exempt taxes in order to use them in a Myinvois Document.",
662 ),
663 'missing_general_public': self.env._(
664 "You must have a commercial partner named 'General Public' with a VAT number set to 'EI00000000010' in order to proceed.",
665 ),
666 }
667
668 constraints[f'myinvois_{record_identifier}_{code}'] = message_mapping[code]
669
670 @api.model
671 def _l10n_my_edi_decode_myinvois_attachment(self, attachment):
672 """ Extract data from MyInvois xml. """
673 def get_node(node, xpath):
674 nodes = node.xpath(xpath)
675 return nodes[0] if nodes else None
676
677 def get_value(node):
678 if node is None:
679 return None
680 return node.text
681
682 vals = {}
683 try:
684 root = etree.fromstring(attachment.raw)
685 invoice_id_node = get_node(root, "//*[local-name()='Invoice']/*[local-name()='ID']")
686 except etree.XMLSyntaxError:
687 # Not an xml
688 return {}
689 except AttributeError:
690 # Not a MyInvois xml
691 return {}
692
693 vals['original_document_id'] = get_value(invoice_id_node)
694 return vals
695
696 # ----------------
697 # EXPORT: Business methods
698 # ----------------
699
700 @api.model
701 def _l10n_my_edi_get_document_type_code(self, myinvois_document):
702 """ Returns the code matching the invoice type, as well as the original document if any. """
703 document_type_code = '01'
704 original_document = None
705
706 if not myinvois_document._is_consolidated_invoice():
707 invoice = myinvois_document.invoice_ids[0] # Otherwise it would be a consolidated invoice.
708 if 'debit_origin_id' in self.env['account.move']._fields and invoice.debit_origin_id:
709 document_type_code = '03' if invoice.move_type == 'out_invoice' else '13'
710 original_document = invoice.debit_origin_id._get_active_myinvois_document()
711 elif invoice.move_type in ('out_refund', 'in_refund'):
712 is_refund, refunded_document = self._l10n_my_edi_get_refund_details(invoice)
713 if is_refund:
714 document_type_code = '04' if invoice.move_type == 'out_refund' else '14'
715 else:
716 document_type_code = '02' if invoice.move_type == 'out_refund' else '12'
717
718 original_document = refunded_document
719 else:
720 document_type_code = '01' if invoice.move_type == 'out_invoice' else '11'
721
722 return document_type_code, original_document # Consolidated invoices are fixed to '01'
723
724 @api.model
725 def _l10n_my_edi_get_refund_details(self, invoice):
726 """
727 Helper which returns the refunded document in case of out_refund/in_refund.
728 In some cases, such as PoS, we could need a different logic than from the regular flow.
729 :param invoice: The credit note for which we want to get the refunded document.
730 :return: A tuple, where the first parameter indicates if this credit note is a refund and the second the credited/refunded document.
731 """
732 # We consider a credit note a refund if it is paid and fully reconciled with a payment or bank transaction.
733 payment_terms = invoice.line_ids.filtered(lambda aml: aml.display_type == 'payment_term')
734 counterpart_amls = payment_terms.reconciled_lines_ids
735 counterpart_move_type = 'out_invoice' if invoice.move_type == 'out_refund' else 'in_invoice'
736 has_payments = bool(counterpart_amls.move_id.filtered(lambda move: move.move_type != counterpart_move_type))
737 is_paid = invoice.payment_state in ('in_payment', 'paid', 'reversed')
738
739 refunded_document = invoice.reversed_entry_id._get_active_myinvois_document()
740 is_refund = is_paid and has_payments
741 return is_refund, refunded_document
742
743 @api.model
744 def _l10n_my_edi_get_formatted_phone_number(self, number):
745 # the phone number MUST follow the E.164 format.
746 # Don't try to reformat too much, we don't want to risk messing it up
747 if not number:
748 return '' # This wouldn't happen in the file as it's caught in the validation errors, but the vals are exported before these checks are done.
749 return number.replace(' ', '').replace('(', '').replace(')', '').replace('-', '')