| 1 |
from collections import defaultdict |
| 2 |
from lxml import etree |
| 3 |
|
| 4 |
from odoo import api, models |
| 5 |
from odoo.tools import float_compare, frozendict |
| 6 |
from odoo.addons.l10n_tr_nilvera_einvoice_extended.tools.clean_node_dict import clean_node_dict |
| 7 |
from odoo.addons.l10n_tr_nilvera_einvoice_extended.tools.ubl_tr_invoice import TrInvoice |
| 8 |
|
| 9 |
|
| 10 |
class AccountEdiXmlUblTr(models.AbstractModel): |
| 11 |
_inherit = "account.edi.xml.ubl.tr" |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
def _get_invoice_node(self, vals): |
| 17 |
"""Generate and clean the invoice XML node dictionary. |
| 18 |
|
| 19 |
Extends the base invoice node by adding buyer/customer party nodes |
| 20 |
and removing child nodes not defined in the template while keeping UBL attributes. |
| 21 |
|
| 22 |
:param vals: dict with invoice data. |
| 23 |
:return: cleaned invoice node dict for XML rendering. |
| 24 |
""" |
| 25 |
document_node = super()._get_invoice_node(vals) |
| 26 |
self._add_invoice_buyer_customer_party_nodes(document_node, vals) |
| 27 |
return clean_node_dict(document_node, self._get_document_template({'document_node': document_node, 'document_type': 'invoice'})) |
| 28 |
|
| 29 |
def _add_invoice_header_nodes(self, document_node, vals): |
| 30 |
"""Extend the invoice header node generation with Turkish-specific fields. |
| 31 |
|
| 32 |
The Extended flow is only applied for outgoing invoices (out_invoice). This method customizes |
| 33 |
the standard invoice XML header for Turkish e-Invoicing (UBL) by adding localized fields and |
| 34 |
structure required by GIB. |
| 35 |
|
| 36 |
:param document_node: dict |
| 37 |
:param vals: dict |
| 38 |
:return: None |
| 39 |
""" |
| 40 |
super()._add_invoice_header_nodes(document_node, vals) |
| 41 |
|
| 42 |
if vals['document_type'] != 'invoice': |
| 43 |
return |
| 44 |
invoice = vals['invoice'] |
| 45 |
document_node.update({ |
| 46 |
'cbc:ProfileID': {'_text': self._get_tr_profile_id(invoice)}, |
| 47 |
'cbc:InvoiceTypeCode': {'_text': 'ISTISNA' if invoice.l10n_tr_is_export_invoice else invoice.l10n_tr_gib_invoice_type}, |
| 48 |
}) |
| 49 |
|
| 50 |
@api.model |
| 51 |
def _add_invoice_buyer_customer_party_nodes(self, document_node, vals): |
| 52 |
"""Adds BuyerCustomerParty node for TR E-Invoicing. |
| 53 |
|
| 54 |
For export invoices, a buyer party node is created based on the customer, |
| 55 |
and the PartyIdentification values are updated to indicate an export customer. |
| 56 |
|
| 57 |
:param document_node: dict representing the invoice XML structure to modify. |
| 58 |
:param vals: dict containing invoice-related values, including 'invoice'. |
| 59 |
""" |
| 60 |
if vals['invoice'].l10n_tr_is_export_invoice: |
| 61 |
buyer_party_node = self._get_party_node({**vals, 'partner': vals['customer'], 'role': 'buyer'}) |
| 62 |
buyer_party_node['cac:PartyIdentification'] = [{'cbc:ID': { |
| 63 |
'_text': 'EXPORT', |
| 64 |
'schemeID': 'PARTYTYPE', |
| 65 |
}, |
| 66 |
}] |
| 67 |
document_node['cac:BuyerCustomerParty'] = {'cac:Party': buyer_party_node} |
| 68 |
|
| 69 |
def _add_invoice_accounting_customer_party_nodes(self, document_node, vals): |
| 70 |
"""Extend invoice accounting customer party nodes for TR E-Invoicing. |
| 71 |
|
| 72 |
For export invoice, the AccountingCustomerParty is set to the static |
| 73 |
Turkish Ministry of Customs and Trade node. |
| 74 |
|
| 75 |
:param document_node: dict representing the invoice XML structure to modify. |
| 76 |
:param vals: dict containing invoice-related values, including 'invoice'. |
| 77 |
""" |
| 78 |
super()._add_invoice_accounting_customer_party_nodes(document_node, vals) |
| 79 |
if vals['invoice'].l10n_tr_is_export_invoice: |
| 80 |
document_node['cac:AccountingCustomerParty'] = {'cac:Party': self._get_ministry_party_node()} |
| 81 |
|
| 82 |
def _add_invoice_monetary_total_nodes(self, document_node, vals): |
| 83 |
"""Extend invoice monetary total nodes for TR E-Invoicing. |
| 84 |
|
| 85 |
For invoices registered as Export, the payable amount is set to the total amount |
| 86 |
without tax, as required by Turkish e-invoicing regulations. |
| 87 |
|
| 88 |
:param document_node: dict representing the invoice XML structure to modify. |
| 89 |
:param vals: dict containing invoice-related values, including 'invoice'. |
| 90 |
""" |
| 91 |
super()._add_invoice_monetary_total_nodes(document_node, vals) |
| 92 |
if vals['invoice'].l10n_tr_gib_invoice_type == "IHRACKAYITLI": |
| 93 |
document_node["cac:LegalMonetaryTotal"]["cbc:PayableAmount"]["_text"] = ( |
| 94 |
document_node["cac:LegalMonetaryTotal"]["cbc:TaxExclusiveAmount"]["_text"] |
| 95 |
) |
| 96 |
|
| 97 |
@api.model |
| 98 |
def _get_ministry_party_node(self): |
| 99 |
"""Return the fixed ministry (party) information required for TR E-invoicing. |
| 100 |
|
| 101 |
This method provides identification, address, tax, and naming |
| 102 |
details of the Turkish Ministry of Customs and Trade. |
| 103 |
|
| 104 |
:return: dict containing ministry party node. |
| 105 |
""" |
| 106 |
return { |
| 107 |
'cac:PartyIdentification': { |
| 108 |
'cbc:ID': { |
| 109 |
'_text': '1460415308', |
| 110 |
'schemeID': 'VKN', |
| 111 |
}, |
| 112 |
}, |
| 113 |
'cac:PartyName': { |
| 114 |
'cbc:Name': {'_text': 'Gümrük ve Ticaret Bakanlığı Gümrükler Genel Müdürlüğü- Bilgi İşlem Dairesi Başkanlığı'}, |
| 115 |
}, |
| 116 |
'cac:PostalAddress': { |
| 117 |
'cbc:CitySubdivisionName': {'_text': 'Ulus'}, |
| 118 |
'cbc:CityName': {'_text': 'Ankara'}, |
| 119 |
'cac:Country': {'cbc:Name': {'_text': 'Türkiye'}}, |
| 120 |
}, |
| 121 |
'cac:PartyTaxScheme': { |
| 122 |
'cac:TaxScheme': {'cbc:Name': {'_text': 'Ulus'}}, |
| 123 |
}, |
| 124 |
} |
| 125 |
|
| 126 |
@api.model |
| 127 |
def _get_tr_profile_id(self, invoice): |
| 128 |
"""Determine the TR profile ID for the given invoice. |
| 129 |
|
| 130 |
- If the customer is an e-invoice user and the invoice has a |
| 131 |
l10n_tr_gib_invoice_scenario, return that scenario. |
| 132 |
- If the invoice is marked as an export invoice, return "IHRACAT". |
| 133 |
- Otherwise: |
| 134 |
• Return "TEMELFATURA" if the customer is an e-invoice user. |
| 135 |
• Return "EARSIVFATURA" for e-archive invoices. |
| 136 |
|
| 137 |
:param invoice: account.move record (the invoice). |
| 138 |
:return: str, TR profile ID to be used in E-invoicing. |
| 139 |
""" |
| 140 |
if (is_einvoice := invoice.l10n_tr_nilvera_customer_status == 'einvoice') and invoice.l10n_tr_gib_invoice_scenario: |
| 141 |
return invoice.l10n_tr_gib_invoice_scenario |
| 142 |
if invoice.l10n_tr_is_export_invoice: |
| 143 |
return 'IHRACAT' |
| 144 |
return 'TEMELFATURA' if is_einvoice else 'EARSIVFATURA' |
| 145 |
|
| 146 |
def _get_document_template(self, vals): |
| 147 |
"""Determines the document template to use based on the provided values. |
| 148 |
|
| 149 |
If the document is a Turkish invoice (CustomizationID 'TR1.2' and document_type 'invoice'), |
| 150 |
it returns the `TrInvoice` template. Otherwise, it falls back to the default implementation. |
| 151 |
|
| 152 |
:param vals: Dictionary containing document data, including 'document_node' and 'document_type'. |
| 153 |
:return: Document template class to be used for generating the document. |
| 154 |
""" |
| 155 |
if vals['document_node']['cbc:CustomizationID']['_text'] == 'TR1.2' and vals['document_type'] == 'invoice': |
| 156 |
return TrInvoice |
| 157 |
return super()._get_document_template(vals) |
| 158 |
|
| 159 |
def _get_party_node(self, vals): |
| 160 |
"""Extend the party node getter with the Turkish tax office name. |
| 161 |
|
| 162 |
Adds the tax office name if the partner has a Turkish |
| 163 |
tax office set to the partner's PartyTaxScheme. |
| 164 |
|
| 165 |
:param vals: dict containing invoice-related values. |
| 166 |
:return: dict representing the updated party node. |
| 167 |
""" |
| 168 |
partner = vals['partner'] |
| 169 |
party_node = super()._get_party_node(vals) |
| 170 |
if tax_office := partner.l10n_tr_tax_office_id: |
| 171 |
party_node['cac:PartyTaxScheme']['cac:TaxScheme']['cbc:Name']['_text'] = tax_office.name |
| 172 |
return party_node |
| 173 |
|
| 174 |
def _get_invoice_line_node(self, vals): |
| 175 |
"""Generate the invoice line XML node dictionary. |
| 176 |
|
| 177 |
Extends the base line node by adding delivery-specific nodes. |
| 178 |
Uses context to skip TR reason code processing. |
| 179 |
|
| 180 |
:param vals: dict with invoice line data. |
| 181 |
:return: invoice line node dict ready for XML rendering. |
| 182 |
""" |
| 183 |
line_node = super(AccountEdiXmlUblTr, self.with_context(skip_tr_reason_code=True))._get_invoice_line_node(vals) |
| 184 |
self._add_invoice_line_delivery_nodes(line_node, vals) |
| 185 |
return line_node |
| 186 |
|
| 187 |
def _add_invoice_line_delivery_nodes(self, line_node, vals): |
| 188 |
"""Add delivery information to an invoice line node for export invoices. |
| 189 |
|
| 190 |
For export invoice, it builds the cac:Delivery section of the |
| 191 |
UBL TR XML for invoice lines. The delivery node includes |
| 192 |
address, incoterms, shipment, and customs-related details. |
| 193 |
|
| 194 |
:param line_node: dict representing the invoice line XML structure to update. |
| 195 |
:param vals: dict containing invoice line data. |
| 196 |
""" |
| 197 |
move_line = vals['base_line']['record'] |
| 198 |
if move_line.move_id.l10n_tr_is_export_invoice: |
| 199 |
line_node['cac:Delivery'] = { |
| 200 |
'cac:DeliveryAddress': { |
| 201 |
'cbc:StreetName': {'_text': move_line.move_id.partner_id.street}, |
| 202 |
'cbc:CitySubdivisionName': {'_text': move_line.move_id.partner_id.city}, |
| 203 |
'cbc:CityName': {'_text': move_line.move_id.partner_id.state_id.with_context(lang='tr_TR').name}, |
| 204 |
'cbc:PostalZone': {'_text': move_line.move_id.partner_id.zip}, |
| 205 |
'cac:Country': {'cbc:Name': {'_text': move_line.move_id.partner_id.country_id.with_context(lang='tr_TR').name}}, |
| 206 |
}, |
| 207 |
'cac:DeliveryTerms': { |
| 208 |
'cbc:ID': {'_text': move_line.move_id.invoice_incoterm_id.code, 'schemeID': 'INCOTERMS'}, |
| 209 |
}, |
| 210 |
'cac:Shipment': { |
| 211 |
'cbc:ID': {'_text': 'NO_ID'}, |
| 212 |
'cac:GoodsItem': {'cbc:RequiredCustomsID': {'_text': move_line.l10n_tr_ctsp_number or move_line.product_id.l10n_tr_ctsp_number}}, |
| 213 |
'cac:ShipmentStage': {'cbc:TransportModeCode': {'_text': move_line.move_id.l10n_tr_shipping_type}}, |
| 214 |
}, |
| 215 |
} |
| 216 |
|
| 217 |
def _add_document_line_tax_total_nodes(self, line_node, vals): |
| 218 |
"""Adds tax total nodes to a document line. |
| 219 |
|
| 220 |
For Turkish withholding invoices TEVKIFAT, this method |
| 221 |
delegates to add_withholding_document_line_tax_total_nodes. |
| 222 |
Otherwise, it falls back to the default behavior. |
| 223 |
|
| 224 |
:param line_node: XML node representing the invoice line. |
| 225 |
:param vals: Dictionary containing the invoice data. |
| 226 |
:return: Updated XML line node with tax total information. |
| 227 |
""" |
| 228 |
if vals['invoice'].l10n_tr_gib_invoice_type == 'TEVKIFAT': |
| 229 |
return self._add_withholding_document_line_tax_total_nodes(line_node, vals) |
| 230 |
return super()._add_document_line_tax_total_nodes(line_node, vals) |
| 231 |
|
| 232 |
def _add_invoice_tax_total_nodes(self, document_node, vals): |
| 233 |
"""Adds tax total nodes to the invoice document. |
| 234 |
|
| 235 |
For Turkish withholding invoices ('TEVKIFAT'), this method |
| 236 |
delegates to `_add_withholding_document_tax_total_nodes`. |
| 237 |
Otherwise, it uses the default tax total behavior. |
| 238 |
|
| 239 |
:param document_node: XML node representing the full invoice document. |
| 240 |
:param vals: Dictionary containing the invoice data. |
| 241 |
:return: lxml.etree.Element or similar XML node representing the updated invoice document. |
| 242 |
|
| 243 |
""" |
| 244 |
if vals['invoice'].l10n_tr_gib_invoice_type == 'TEVKIFAT': |
| 245 |
return self._add_withholding_document_tax_total_nodes(document_node, vals) |
| 246 |
return super()._add_document_tax_total_nodes(document_node, vals) |
| 247 |
|
| 248 |
def _add_withholding_document_tax_total_nodes(self, line_node, vals): |
| 249 |
"""Extends the aggregation of tax details to include Turkish (TR) withholding-specific amounts |
| 250 |
for an invoice line. |
| 251 |
|
| 252 |
This method performs the following: |
| 253 |
- Aggregates tax details across all base lines. |
| 254 |
- Adds two fields per grouping key: |
| 255 |
- tr_total_taxed_amount: Total tax amount used in the withholding tax line. |
| 256 |
- tr_total_taxed_residual_amount: Total tax amount after withholding, shown in the tax line. |
| 257 |
- Splits aggregated tax details into normal taxes and withholding taxes. |
| 258 |
- Updates `line_node` with: |
| 259 |
- 'cac:TaxTotal' for normal taxes |
| 260 |
- 'cac:WithholdingTaxTotal' for withholding taxes (if the document is an invoice) |
| 261 |
|
| 262 |
If there is a 20% tax and 18% is withheld on ₺10: |
| 263 |
- tr_total_taxed_amount = ₺2 |
| 264 |
- tr_total_taxed_residual_amount = ₺0.2 |
| 265 |
|
| 266 |
:param line_node: XML node representing the invoice line to be updated. |
| 267 |
:param vals: Dictionary containing invoice data and base lines. |
| 268 |
""" |
| 269 |
base_lines_aggregated_tax_details = self.env['account.tax']._aggregate_base_lines_tax_details(vals['base_lines'], self.tax_grouping_function) |
| 270 |
aggregated_tax_details = self.env['account.tax']._aggregate_base_lines_aggregated_values(base_lines_aggregated_tax_details) |
| 271 |
|
| 272 |
for base_line, aggregated_values in base_lines_aggregated_tax_details: |
| 273 |
for grouping_key in aggregated_values: |
| 274 |
taxes_data = base_line.get('tax_details', {}).get('taxes_data', []) |
| 275 |
rounding = base_line.get('record').currency_id.rounding |
| 276 |
|
| 277 |
|
| 278 |
total_taxed_amount = sum( |
| 279 |
tax_line['tax_amount'] |
| 280 |
for tax_line in taxes_data |
| 281 |
if float_compare(tax_line['tax_amount'], 0, precision_rounding=rounding) > 0 |
| 282 |
) |
| 283 |
|
| 284 |
|
| 285 |
total_residual_amount = sum(tax_line['tax_amount'] for tax_line in taxes_data) |
| 286 |
|
| 287 |
|
| 288 |
group_vals = aggregated_tax_details[grouping_key] |
| 289 |
group_vals['tr_total_taxed_amount'] = group_vals.get('tr_total_taxed_amount', 0.0) + total_taxed_amount |
| 290 |
group_vals['tr_total_taxed_residual_amount'] = group_vals.get('tr_total_taxed_residual_amount', 0.0) + total_residual_amount |
| 291 |
|
| 292 |
aggregated_tax_details_by_l10n_tr_tax_withholding_code_id = {'tax': defaultdict(dict), 'withholding_tax': defaultdict(dict)} |
| 293 |
|
| 294 |
for grouping_key, values in aggregated_tax_details.items(): |
| 295 |
if grouping_key: |
| 296 |
key = 'withholding_tax' if (l10n_tr_tax_withheld := grouping_key['l10n_tr_tax_withheld']) else 'tax' |
| 297 |
aggregated_tax_details_by_l10n_tr_tax_withholding_code_id[key][l10n_tr_tax_withheld][grouping_key] = values |
| 298 |
|
| 299 |
line_node['cac:TaxTotal'] = [ |
| 300 |
self._get_withholding_tax_total_node({**vals, 'aggregated_tax_details': tax_details, 'role': 'line'}) |
| 301 |
for tax_details in aggregated_tax_details_by_l10n_tr_tax_withholding_code_id['tax'].values() |
| 302 |
] |
| 303 |
if vals['document_type'] == 'invoice': |
| 304 |
line_node['cac:WithholdingTaxTotal'] = [ |
| 305 |
self._get_withholding_tax_total_node({**vals, 'aggregated_tax_details': tax_details, 'role': 'line', 'withholding': True, 'sign': -1}) |
| 306 |
for tax_details in aggregated_tax_details_by_l10n_tr_tax_withholding_code_id['withholding_tax'].values() |
| 307 |
] |
| 308 |
|
| 309 |
@api.model |
| 310 |
def tax_grouping_function(self, base_line, tax_data): |
| 311 |
"""Build a grouping key for tax aggregation, extended for Turkish (TR) withholding taxes. |
| 312 |
|
| 313 |
This method extends the default tax grouping logic to include TR-specific |
| 314 |
withholding details. It constructs a grouping key for each tax line and |
| 315 |
appends withholding-related fields when applicable. |
| 316 |
|
| 317 |
Specifically, for invoices of type TEVKIFAT with a withholding tax code, |
| 318 |
the following fields are added to the grouping key: |
| 319 |
- l10n_tr_tax_withheld: The ID of the withholding tax code. |
| 320 |
- percent_withheld: The percentage of tax to be withheld (as an integer). |
| 321 |
- name: The localized name of the withholding tax (in Turkish). |
| 322 |
- tax_type_code: The code of the withholding tax. |
| 323 |
|
| 324 |
:param dict base_line: The base invoice line containing the record and tax details. |
| 325 |
:param dict tax_data: The dictionary containing the tax and its computed values. |
| 326 |
:return: The grouping key dictionary for this tax line, including TR withholding details if applicable. |
| 327 |
""" |
| 328 |
invoice = base_line["record"].move_id |
| 329 |
supplier = invoice.company_id.partner_id.commercial_partner_id |
| 330 |
customer = invoice.partner_id |
| 331 |
tax = tax_data["tax"] |
| 332 |
|
| 333 |
grouping_key = { |
| 334 |
"tax_category_code": self._get_tax_category_code(customer.commercial_partner_id, supplier, tax), |
| 335 |
**self._get_tax_exemption_reason(customer.commercial_partner_id, supplier, tax), |
| 336 |
"amount": tax.amount if tax else 0.0, |
| 337 |
"amount_type": tax.amount_type if tax else "percent", |
| 338 |
"l10n_tr_tax_withheld": tax.l10n_tr_tax_withholding_code_id.id, |
| 339 |
} |
| 340 |
|
| 341 |
if invoice.l10n_tr_gib_invoice_type == "TEVKIFAT" and tax.l10n_tr_tax_withholding_code_id: |
| 342 |
withholding_code = tax.l10n_tr_tax_withholding_code_id |
| 343 |
grouping_key.update( |
| 344 |
{ |
| 345 |
"percent_withheld": int(withholding_code.percentage * 100), |
| 346 |
"name": withholding_code.with_context(lang="tr_TR").name, |
| 347 |
"tax_type_code": withholding_code.code, |
| 348 |
}, |
| 349 |
) |
| 350 |
|
| 351 |
return grouping_key |
| 352 |
|
| 353 |
def _add_withholding_document_line_tax_total_nodes(self, line_node, vals): |
| 354 |
"""Extend aggregation of line tax details to include Turkish (TR) withholding-specific amounts. |
| 355 |
|
| 356 |
For each tax grouping key, this method adds two fields: |
| 357 |
- tr_total_taxed_amount: The total tax amount applied to the line before withholding. |
| 358 |
- tr_total_taxed_residual_amount: The remaining tax amount after withholding. |
| 359 |
|
| 360 |
If there is a 20% tax and 18% is withheld on ₺10: |
| 361 |
- tr_total_taxed_amount = ₺2 |
| 362 |
- tr_total_taxed_residual_amount = ₺0.2 |
| 363 |
|
| 364 |
:param line_node: The invoice line node containing tax details. |
| 365 |
:param vals: Tax values used to compute withholding amounts. |
| 366 |
""" |
| 367 |
encountered_groups = set() |
| 368 |
base_line = vals['base_line'] |
| 369 |
tax_details = base_line['tax_details'] |
| 370 |
taxes_data = tax_details['taxes_data'] |
| 371 |
aggregated_tax_details = self.env['account.tax']._aggregate_base_line_tax_details(base_line, self.tax_grouping_function) |
| 372 |
|
| 373 |
for tax_data in taxes_data: |
| 374 |
grouping_key = self.tax_grouping_function(base_line, tax_data) |
| 375 |
if isinstance(grouping_key, dict): |
| 376 |
grouping_key = frozendict(grouping_key) |
| 377 |
already_accounted = grouping_key in encountered_groups |
| 378 |
encountered_groups.add(grouping_key) |
| 379 |
if not already_accounted: |
| 380 |
taxes_data = base_line.get('tax_details', {}).get('taxes_data', []) |
| 381 |
rounding = base_line.get('record').currency_id.rounding |
| 382 |
|
| 383 |
total_taxed_amount = sum(tax_line['tax_amount'] for tax_line in taxes_data if float_compare(tax_line['tax_amount'], 0, precision_rounding=rounding) > 0) |
| 384 |
total_residual_amount = sum(tax_line['tax_amount'] for tax_line in taxes_data) |
| 385 |
|
| 386 |
group_vals = aggregated_tax_details[grouping_key] |
| 387 |
group_vals['tr_total_taxed_amount'] = group_vals.get('tr_total_taxed_amount', 0.0) + total_taxed_amount |
| 388 |
group_vals['tr_total_taxed_residual_amount'] = group_vals.get('tr_total_taxed_residual_amount', 0.0) + total_residual_amount |
| 389 |
|
| 390 |
aggregated_tax_details_by_l10n_tr_tax_withholding_code_id = {'tax': defaultdict(dict), 'withholding_tax': defaultdict(dict)} |
| 391 |
|
| 392 |
for grouping_key, values in aggregated_tax_details.items(): |
| 393 |
if grouping_key: |
| 394 |
key = 'withholding_tax' if (l10n_tr_tax_withheld := grouping_key['l10n_tr_tax_withheld']) else 'tax' |
| 395 |
aggregated_tax_details_by_l10n_tr_tax_withholding_code_id[key][l10n_tr_tax_withheld][grouping_key] = values |
| 396 |
|
| 397 |
line_node['cac:TaxTotal'] = [ |
| 398 |
self._get_withholding_tax_total_node({**vals, 'aggregated_tax_details': tax_details, 'role': 'line'}) |
| 399 |
for tax_details in aggregated_tax_details_by_l10n_tr_tax_withholding_code_id['tax'].values() |
| 400 |
] |
| 401 |
if vals['document_type'] == 'invoice': |
| 402 |
line_node['cac:WithholdingTaxTotal'] = [ |
| 403 |
self._get_withholding_tax_total_node({**vals, 'aggregated_tax_details': tax_details, 'role': 'line', 'withholding': True, 'sign': -1}) |
| 404 |
for tax_details in aggregated_tax_details_by_l10n_tr_tax_withholding_code_id['withholding_tax'].values() |
| 405 |
] |
| 406 |
|
| 407 |
@api.model |
| 408 |
def _get_withholding_tax_total_node(self, vals): |
| 409 |
"""Build the TaxTotal node for withholding taxes in TR E-Invoicing. |
| 410 |
|
| 411 |
This method calculates total and subtotal withholding tax amounts. |
| 412 |
|
| 413 |
:param vals: dict containing tax details, currency info, and related data. |
| 414 |
:return: dict representing the withholding tax total node. |
| 415 |
""" |
| 416 |
aggregated_tax_details = vals['aggregated_tax_details'] |
| 417 |
currency_suffix = vals['currency_suffix'] |
| 418 |
currency_name = vals['currency_name'] |
| 419 |
precision = vals['currency_dp'] |
| 420 |
sign = vals.get('sign', 1) |
| 421 |
is_withholding = vals.get('withholding') |
| 422 |
|
| 423 |
def get_tax_amount_total(): |
| 424 |
"""Compute total tax amount depending on whether it is withholding.""" |
| 425 |
if is_withholding: |
| 426 |
return sum( |
| 427 |
details[f'tax_amount{currency_suffix}'] |
| 428 |
for grouping_key, details in aggregated_tax_details.items() |
| 429 |
if grouping_key |
| 430 |
) |
| 431 |
return sum( |
| 432 |
values['tr_total_taxed_residual_amount'] |
| 433 |
for grouping_key, values in aggregated_tax_details.items() |
| 434 |
if grouping_key |
| 435 |
) |
| 436 |
|
| 437 |
def get_total_tax_subtotal_amount(details): |
| 438 |
"""Compute the total taxable amount depending on whether it is withholding.""" |
| 439 |
return details['tr_total_taxed_amount'] if is_withholding else details.get(f'base_amount{currency_suffix}', 0) |
| 440 |
|
| 441 |
return { |
| 442 |
'cbc:TaxAmount': { |
| 443 |
'_text': self.format_float(sign * get_tax_amount_total(), precision), |
| 444 |
'currencyID': currency_name, |
| 445 |
}, |
| 446 |
'cac:TaxSubtotal': [ |
| 447 |
{ |
| 448 |
'cbc:TaxableAmount': { |
| 449 |
'_text': self.format_float(get_total_tax_subtotal_amount(details), precision), |
| 450 |
'currencyID': currency_name, |
| 451 |
}, |
| 452 |
'cbc:TaxAmount': { |
| 453 |
'_text': self.format_float(sign * details[f'tax_amount{currency_suffix}'], precision), |
| 454 |
'currencyID': currency_name, |
| 455 |
}, |
| 456 |
'cbc:Percent': { |
| 457 |
|
| 458 |
'_text': grouping_key['percent_withheld'] if is_withholding else grouping_key['amount'], |
| 459 |
}, |
| 460 |
'cac:TaxCategory': self._get_tax_category_node({**vals, 'grouping_key': grouping_key}), |
| 461 |
} |
| 462 |
for grouping_key, details in aggregated_tax_details.items() |
| 463 |
if grouping_key |
| 464 |
], |
| 465 |
} |
| 466 |
|
| 467 |
def _get_tax_category_node(self, vals): |
| 468 |
"""Returns the tax category node for a line or invoice, including TR-specific fields. |
| 469 |
|
| 470 |
- For lines with Turkish withholding (`l10n_tr_tax_withheld`), returns a minimal |
| 471 |
TaxScheme node with the tax name and type code. |
| 472 |
- For other lines, it extends the default tax category node to include: |
| 473 |
- `cbc:TaxExemptionReasonCode`: The TR tax exemption code. |
| 474 |
- `cbc:TaxExemptionReason`: The localized TR tax exemption name. |
| 475 |
These fields are only added if a TR exemption is set and the context does not skip it. |
| 476 |
|
| 477 |
:param vals: Dictionary containing: grouping_key & invoice record. |
| 478 |
:return: dict representing the XML structure of the tax category node. |
| 479 |
""" |
| 480 |
grouping_key = vals['grouping_key'] |
| 481 |
if grouping_key.get('l10n_tr_tax_withheld'): |
| 482 |
return { |
| 483 |
'cac:TaxScheme': { |
| 484 |
'cbc:Name': {'_text': grouping_key['name']}, |
| 485 |
'cbc:TaxTypeCode': {'_text': grouping_key['tax_type_code']}, |
| 486 |
}, |
| 487 |
} |
| 488 |
tax_totals_vals = super()._get_tax_category_node(vals) |
| 489 |
tax_invoice_exemption = vals['invoice'].l10n_tr_exemption_code_id |
| 490 |
if self.env.context.get('skip_tr_reason_code') or not tax_invoice_exemption: |
| 491 |
return tax_totals_vals |
| 492 |
|
| 493 |
tax_totals_vals.update({ |
| 494 |
'cbc:TaxExemptionReasonCode': {'_text': tax_invoice_exemption.code}, |
| 495 |
'cbc:TaxExemptionReason': {'_text': tax_invoice_exemption.with_context(lang='tr_TR').name}, |
| 496 |
}) |
| 497 |
return tax_totals_vals |
| 498 |
|
| 499 |
def _export_invoice(self, invoice): |
| 500 |
|
| 501 |
|
| 502 |
|
| 503 |
|
| 504 |
xml, errors = super()._export_invoice(invoice) |
| 505 |
xml_root = etree.fromstring(xml) |
| 506 |
shipment_id_elements = xml_root.findall('.//cac:Shipment/cbc:ID', namespaces=xml_root.nsmap) |
| 507 |
for element in shipment_id_elements: |
| 508 |
if element.text == 'NO_ID': |
| 509 |
element.text = '' |
| 510 |
return etree.tostring(xml_root, xml_declaration=True, encoding='UTF-8'), errors |