| 1 |
import math |
| 2 |
|
| 3 |
from num2words import num2words |
| 4 |
|
| 5 |
from odoo import api, models |
| 6 |
from odoo.exceptions import UserError |
| 7 |
from odoo.tools import html2plaintext |
| 8 |
|
| 9 |
|
| 10 |
class AccountEdiXmlUblTr(models.AbstractModel): |
| 11 |
_name = "account.edi.xml.ubl.tr" |
| 12 |
_inherit = 'account.edi.xml.ubl_21' |
| 13 |
_description = "UBL-TR 1.2" |
| 14 |
|
| 15 |
# ------------------------------------------------------------------------- |
| 16 |
# EXPORT |
| 17 |
# ------------------------------------------------------------------------- |
| 18 |
|
| 19 |
def _export_invoice_filename(self, invoice): |
| 20 |
# EXTENDS account_edi_ubl_cii |
| 21 |
return '%s_einvoice.xml' % invoice.name.replace("/", "_") |
| 22 |
|
| 23 |
def _get_tax_category_code(self, customer, supplier, tax): |
| 24 |
# OVERRIDES account.edi.ubl_21 |
| 25 |
if tax and tax.amount < 0: # This is a withholding |
| 26 |
return '9015' |
| 27 |
return '0015' |
| 28 |
|
| 29 |
def _add_invoice_currency_vals(self, vals): |
| 30 |
# EXTENDS account.edi.xml.ubl_21 |
| 31 |
super()._add_invoice_currency_vals(vals) |
| 32 |
vals['currency_dp'] = 2 # Force 2 decimal places everywhere |
| 33 |
|
| 34 |
# ------------------------------------------------------------------------- |
| 35 |
# EXPORT: TEMPLATES |
| 36 |
# ------------------------------------------------------------------------- |
| 37 |
|
| 38 |
def _add_invoice_header_nodes(self, document_node, vals): |
| 39 |
super()._add_invoice_header_nodes(document_node, vals) |
| 40 |
invoice = vals['invoice'] |
| 41 |
|
| 42 |
# Check the customer status if it hasn't been done before as it's needed for profile_id |
| 43 |
if invoice.partner_id.l10n_tr_nilvera_customer_status == 'not_checked': |
| 44 |
invoice.partner_id._check_nilvera_customer() |
| 45 |
|
| 46 |
if invoice._l10n_tr_nilvera_einvoice_check_negative_lines(): |
| 47 |
raise UserError(self.env._("Nilvera portal cannot process negative quantity nor negative price on invoice lines")) |
| 48 |
|
| 49 |
# Using _get_sequence_format_param to extract the invoice sequence components for various formats. |
| 50 |
# To send an invoice to Nilvera, the format needs to follow ABC2009123456789. |
| 51 |
_, parts = invoice._get_sequence_format_param(invoice.name) |
| 52 |
prefix, year, number = parts['prefix1'][:3], parts['year'], str(parts['seq']).zfill(9) |
| 53 |
invoice_id = f"{prefix.upper()}{year}{number}" |
| 54 |
|
| 55 |
document_node.update({ |
| 56 |
'cbc:CustomizationID': {'_text': 'TR1.2'}, |
| 57 |
'cbc:ProfileID': { |
| 58 |
'_text': 'TEMELFATURA' if invoice.partner_id.l10n_tr_nilvera_customer_status == 'einvoice' else 'EARSIVFATURA' |
| 59 |
}, |
| 60 |
'cbc:ID': {'_text': invoice_id}, |
| 61 |
'cbc:CopyIndicator': {'_text': 'false'}, |
| 62 |
'cbc:UUID': {'_text': invoice.l10n_tr_nilvera_uuid}, |
| 63 |
'cbc:DueDate': None, |
| 64 |
'cbc:InvoiceTypeCode': {'_text': 'SATIS'} if vals['document_type'] == 'invoice' else None, |
| 65 |
'cbc:CreditNoteTypeCode': {'_text': 'IADE'} if vals['document_type'] == 'credit_note' else None, |
| 66 |
'cbc:PricingCurrencyCode': {'_text': invoice.currency_id.name.upper()} |
| 67 |
if vals['currency_id'] != vals['company_currency_id'] else None, |
| 68 |
'cbc:LineCountNumeric': {'_text': len(invoice.line_ids)}, |
| 69 |
'cbc:BuyerReference': None, # Nilvera will reject any <BuyerReference> tag, so remove it |
| 70 |
'cbc:Note': { |
| 71 |
'_text': html2plaintext(invoice.narration, include_references=False) if invoice.narration else None, |
| 72 |
}, |
| 73 |
}) |
| 74 |
|
| 75 |
if invoice.invoice_line_ids._fields.get('deferred_start_date'): |
| 76 |
line_ids = invoice.invoice_line_ids.filtered(lambda line: line.display_type == 'product' and line.deferred_start_date) |
| 77 |
if line_ids: |
| 78 |
document_node['cac:InvoicePeriod'] = { |
| 79 |
'cbc:StartDate': {'_text': line_ids[0].deferred_start_date}, |
| 80 |
'cbc:EndDate': {'_text': line_ids[0].deferred_end_date}, |
| 81 |
} |
| 82 |
|
| 83 |
document_node['cac:OrderReference']['cbc:IssueDate'] = {'_text': invoice.invoice_date} |
| 84 |
|
| 85 |
if invoice.partner_id.l10n_tr_nilvera_customer_status == 'earchive': |
| 86 |
document_node['cac:AdditionalDocumentReference'] = { |
| 87 |
'cbc:ID': {'_text': 'ELEKTRONIK'}, |
| 88 |
'cbc:IssueDate': {'_text': invoice.invoice_date}, |
| 89 |
'cbc:DocumentTypeCode': {'_text': 'SEND_TYPE'}, |
| 90 |
} |
| 91 |
document_node['cbc:Note'] = [ |
| 92 |
document_node['cbc:Note'], |
| 93 |
{'_text': self._l10n_tr_get_amount_integer_partn_text_note(invoice.amount_residual_signed, self.env.ref('base.TRY')), 'note_attrs': {}} |
| 94 |
] |
| 95 |
if vals['invoice'].currency_id.name != 'TRY': |
| 96 |
document_node['cbc:Note'].append({'_text': self._l10n_tr_get_amount_integer_partn_text_note(invoice.amount_residual, vals['invoice'].currency_id), 'note_attrs': {}}) |
| 97 |
document_node['cbc:Note'].append({'_text': self._l10n_tr_get_invoice_currency_exchange_rate(invoice)}) |
| 98 |
|
| 99 |
@api.model |
| 100 |
def _l10n_tr_get_amount_integer_partn_text_note(self, amount, currency): |
| 101 |
sign = math.copysign(1.0, amount) |
| 102 |
amount_integer_part, amount_decimal_part = divmod(abs(amount), 1) |
| 103 |
amount_decimal_part = int(amount_decimal_part * 100) |
| 104 |
|
| 105 |
text_i = num2words(amount_integer_part * sign, lang="tr") or 'Sifir' |
| 106 |
text_d = num2words(amount_decimal_part * sign, lang="tr") or 'Sifir' |
| 107 |
return f'YALNIZ : {text_i} {currency.name} {text_d} {currency.currency_subunit_label}'.upper() |
| 108 |
|
| 109 |
def _add_invoice_delivery_nodes(self, document_node, vals): |
| 110 |
super()._add_invoice_delivery_nodes(document_node, vals) |
| 111 |
invoice = vals['invoice'] |
| 112 |
if 'picking_ids' in invoice._fields and invoice.picking_ids: |
| 113 |
document_node['cac:Delivery']['cbc:ID'] = {'_text': invoice.picking_ids[0].name} |
| 114 |
document_node['cac:Delivery']['cbc:ActualDeliveryDate'] = {'_text': invoice.delivery_date} |
| 115 |
else: |
| 116 |
document_node['cac:Delivery'] = None |
| 117 |
|
| 118 |
def _l10n_tr_get_invoice_currency_exchange_rate(self, invoice): |
| 119 |
conversion_rate = self.env['res.currency']._get_conversion_rate( |
| 120 |
from_currency=invoice.currency_id, |
| 121 |
to_currency=invoice.company_currency_id, |
| 122 |
company=invoice.company_id, |
| 123 |
date=invoice.invoice_date, |
| 124 |
) |
| 125 |
# Nilvera Portal accepts the exchange rate for 6 decimals places only. |
| 126 |
return f'KUR : {conversion_rate:.6f} TL' |
| 127 |
|
| 128 |
def _add_invoice_payment_means_nodes(self, document_node, vals): |
| 129 |
# EXTENDS account.edi.xml.ubl_21 |
| 130 |
super()._add_invoice_payment_means_nodes(document_node, vals) |
| 131 |
payment_means_node = document_node['cac:PaymentMeans'] |
| 132 |
payment_means_node['cbc:InstructionID'] = None |
| 133 |
payment_means_node['cbc:PaymentID'] = None |
| 134 |
|
| 135 |
def _add_invoice_exchange_rate_nodes(self, document_node, vals): |
| 136 |
invoice = vals['invoice'] |
| 137 |
if vals['currency_id'] != vals['company_currency_id']: |
| 138 |
document_node['cac:PricingExchangeRate'] = { |
| 139 |
'cbc:SourceCurrencyCode': {'_text': vals['currency_name']}, |
| 140 |
'cbc:TargetCurrencyCode': {'_text': vals['company_currency_id'].name}, |
| 141 |
'cbc:CalculationRate': {'_text': round(invoice.currency_id._get_conversion_rate(invoice.currency_id, invoice.company_id.currency_id, invoice.company_id, invoice.invoice_date), 6)}, |
| 142 |
'cbc:Date': {'_text': invoice.invoice_date}, |
| 143 |
} |
| 144 |
|
| 145 |
def _l10n_tr_get_total_invoice_discount_amount(self, vals): |
| 146 |
invoice = vals['invoice'] |
| 147 |
invoice_lines = invoice.invoice_line_ids.filtered(lambda line: line.display_type not in {'line_note', 'line_section'}) |
| 148 |
return sum( |
| 149 |
line.currency_id.round(line.price_unit * line.quantity * (line.discount / 100)) |
| 150 |
for line in invoice_lines |
| 151 |
) |
| 152 |
|
| 153 |
def _add_document_allowance_charge_nodes(self, document_node, vals): |
| 154 |
super()._add_document_allowance_charge_nodes(document_node, vals) |
| 155 |
for node in document_node['cac:AllowanceCharge']: |
| 156 |
node['cbc:AllowanceChargeReasonCode'] = None |
| 157 |
|
| 158 |
total_discount_amount = self._l10n_tr_get_total_invoice_discount_amount(vals) |
| 159 |
if total_discount_amount: |
| 160 |
document_node['cac:AllowanceCharge'].append({ |
| 161 |
'cbc:ChargeIndicator': {'_text': 'false'}, |
| 162 |
'cbc:AllowanceChargeReason': {'_text': "Discount"}, |
| 163 |
'cbc:Amount': { |
| 164 |
'_text': self.format_float(total_discount_amount, vals['currency_dp']), |
| 165 |
'currencyID': vals['currency_name'], |
| 166 |
}, |
| 167 |
}) |
| 168 |
|
| 169 |
def _get_address_node(self, vals): |
| 170 |
partner = vals['partner'] |
| 171 |
model = partner._name |
| 172 |
country = partner['country' if model == 'res.bank' else 'country_id'] |
| 173 |
state = partner['state' if model == 'res.bank' else 'state_id'] |
| 174 |
|
| 175 |
return { |
| 176 |
'cbc:StreetName': {'_text': ' '.join(s for s in [partner.street, partner.street2] if s)}, |
| 177 |
'cbc:CitySubdivisionName': {'_text': partner.city}, |
| 178 |
'cbc:CityName': {'_text': state.name}, |
| 179 |
'cbc:PostalZone': {'_text': partner.zip}, |
| 180 |
'cac:Country': { |
| 181 |
'cbc:IdentificationCode': {'_text': country.code}, |
| 182 |
'cbc:Name': {'_text': country.with_context(lang='tr_TR').name}, |
| 183 |
} |
| 184 |
} |
| 185 |
|
| 186 |
def _get_party_node(self, vals): |
| 187 |
partner = vals['partner'] |
| 188 |
commercial_partner = partner.commercial_partner_id |
| 189 |
|
| 190 |
party_node = { |
| 191 |
'cac:PartyIdentification': self._get_party_identification_node_list(partner), |
| 192 |
'cac:PartyName': { |
| 193 |
'cbc:Name': {'_text': partner.display_name} |
| 194 |
}, |
| 195 |
'cac:PostalAddress': self._get_address_node(vals), |
| 196 |
'cac:PartyTaxScheme': { |
| 197 |
'cac:TaxScheme': { |
| 198 |
'cbc:Name': { |
| 199 |
'_text': ( |
| 200 |
commercial_partner.ref |
| 201 |
) |
| 202 |
} |
| 203 |
} |
| 204 |
}, |
| 205 |
'cac:PartyLegalEntity': { |
| 206 |
'cbc:RegistrationName': {'_text': commercial_partner.name}, |
| 207 |
'cbc:CompanyID': {'_text': commercial_partner.vat}, |
| 208 |
}, |
| 209 |
'cac:Contact': { |
| 210 |
'cbc:ID': {'_text': partner.id}, |
| 211 |
'cbc:Name': {'_text': partner.name}, |
| 212 |
'cbc:Telephone': {'_text': partner.phone}, |
| 213 |
'cbc:ElectronicMail': {'_text': partner.email}, |
| 214 |
} |
| 215 |
} |
| 216 |
if not partner.is_company: |
| 217 |
name_parts = partner.name.split(' ', 1) |
| 218 |
party_node['cac:Person'] = { |
| 219 |
'cbc:FirstName': {'_text': name_parts[0]}, |
| 220 |
# If no family name is present, use a zero-width space (U+200B) to ensure the XML tag is rendered. This is required by Nilvera. |
| 221 |
'cbc:FamilyName': {'_text': name_parts[1] if len(name_parts) > 1 else '\u200B'}, |
| 222 |
} |
| 223 |
return party_node |
| 224 |
|
| 225 |
def _get_party_identification_node_list(self, partner): |
| 226 |
official_categories = partner.category_id._get_l10n_tr_official_categories() |
| 227 |
return [ |
| 228 |
{ |
| 229 |
'cbc:ID': { |
| 230 |
'_text': partner.vat, |
| 231 |
'schemeID': 'VKN' if partner.is_company else 'TCKN', |
| 232 |
}, |
| 233 |
}, |
| 234 |
*( |
| 235 |
{ |
| 236 |
'cbc:ID': { |
| 237 |
'_text': category.name, |
| 238 |
'schemeID': category.parent_id.name, |
| 239 |
}, |
| 240 |
} |
| 241 |
for category in partner.category_id |
| 242 |
if category.parent_id in official_categories |
| 243 |
), |
| 244 |
] |
| 245 |
|
| 246 |
def _get_tax_category_node(self, vals): |
| 247 |
# OVERRIDES account.edi.ubl_21 |
| 248 |
grouping_key = vals['grouping_key'] |
| 249 |
is_withholding = grouping_key['tax_category_code'] == '9015' |
| 250 |
tax_category_node = { |
| 251 |
'cac:TaxScheme': { |
| 252 |
'cbc:Name': {'_text': 'KDV Tevkifatı' if is_withholding else 'Gerçek Usulde KDV'}, |
| 253 |
'cbc:TaxTypeCode': {'_text': grouping_key['tax_category_code']} |
| 254 |
} |
| 255 |
} |
| 256 |
return tax_category_node |
| 257 |
|
| 258 |
def _get_tax_subtotal_node(self, vals): |
| 259 |
# EXTENDS account.edi.xml.ubl_21 |
| 260 |
tax_subtotal_node = super()._get_tax_subtotal_node(vals) |
| 261 |
tax_subtotal_node['cac:TaxCategory']['cbc:Percent'] = None |
| 262 |
return tax_subtotal_node |
| 263 |
|
| 264 |
def _add_invoice_monetary_total_nodes(self, document_node, vals): |
| 265 |
# EXTENDS account.edi.xml.ubl_21 |
| 266 |
super()._add_invoice_monetary_total_nodes(document_node, vals) |
| 267 |
invoice = vals['invoice'] |
| 268 |
|
| 269 |
monetary_total_tag = 'cac:LegalMonetaryTotal' if vals['document_type'] in {'invoice', 'credit_note'} else 'cac:RequestedMonetaryTotal' |
| 270 |
monetary_total_node = document_node[monetary_total_tag] |
| 271 |
|
| 272 |
# allowance_total_amount needs to have a value even if 0.0 otherwise it's blank in the Nilvera PDF. |
| 273 |
total_allowance_amount = self._l10n_tr_get_total_invoice_discount_amount(vals) |
| 274 |
monetary_total_node['cbc:AllowanceTotalAmount'] = { |
| 275 |
'_text': self.format_float(total_allowance_amount, vals['currency_dp']), |
| 276 |
'currencyID': vals['currency_name'], |
| 277 |
} |
| 278 |
|
| 279 |
# <cbc:PrepaidAmount> tag is not supported by Nilvera. so it is removed and <cbc:PayableAmount> holds the |
| 280 |
# amount_total so that the total invoice amount (in invoice currency) is preserved. |
| 281 |
monetary_total_node['cbc:PrepaidAmount'] = None |
| 282 |
monetary_total_node['cbc:PayableAmount'] = { |
| 283 |
'_text': self.format_float(invoice.amount_total, vals['currency_dp']), |
| 284 |
'currencyID': vals['currency_name'], |
| 285 |
} |
| 286 |
|
| 287 |
def _add_document_line_allowance_charge_nodes(self, line_node, vals): |
| 288 |
# EXTENDS account.edi.xml.ubl_21 |
| 289 |
super()._add_document_line_allowance_charge_nodes(line_node, vals) |
| 290 |
for allowance_charge_node in line_node['cac:AllowanceCharge']: |
| 291 |
allowance_charge_node['cbc:AllowanceChargeReasonCode'] = None |
| 292 |
discount_percentage = vals.get('discount_amount') / vals.get('gross_subtotal') if vals.get('gross_subtotal') else 0 |
| 293 |
allowance_charge_node['cbc:MultiplierFactorNumeric'] = { |
| 294 |
'_text': self.format_float(discount_percentage, vals['currency_dp']), |
| 295 |
} |
| 296 |
|
| 297 |
def _add_document_line_item_nodes(self, line_node, vals): |
| 298 |
super()._add_document_line_item_nodes(line_node, vals) |
| 299 |
if line_node.get('cac:Item', {}).get('cac:StandardItemIdentification'): |
| 300 |
line_node['cac:Item']['cac:StandardItemIdentification'] = None |
| 301 |
|
| 302 |
def _add_document_line_tax_category_nodes(self, line_node, vals): |
| 303 |
# No InvoiceLine/Item/ClassifiedTaxCategory in Turkey |
| 304 |
pass |
| 305 |
|
| 306 |
def _add_invoice_line_period_nodes(self, line_node, vals): |
| 307 |
# Start and End Dates on Invoice Lines is not allowed in Turkey |
| 308 |
pass |
| 309 |
|
| 310 |
# ------------------------------------------------------------------------- |
| 311 |
# IMPORT |
| 312 |
# ------------------------------------------------------------------------- |
| 313 |
|
| 314 |
def _import_retrieve_partner_vals(self, tree, role): |
| 315 |
# EXTENDS account.edi.xml.ubl_20 |
| 316 |
partner_vals = super()._import_retrieve_partner_vals(tree, role) |
| 317 |
partner_vals.update({ |
| 318 |
'vat': self._find_value(f'.//cac:Accounting{role}Party/cac:Party//cac:PartyIdentification//cbc:ID[string-length(text()) > 5]', tree), |
| 319 |
}) |
| 320 |
return partner_vals |
| 321 |
|
| 322 |
def _import_fill_invoice_form(self, invoice, tree, qty_factor): |
| 323 |
# EXTENDS account.edi.xml.ubl_20 |
| 324 |
logs = super()._import_fill_invoice_form(invoice, tree, qty_factor) |
| 325 |
|
| 326 |
# ==== Nilvera UUID ==== |
| 327 |
if uuid_node := tree.findtext('./{*}UUID'): |
| 328 |
invoice.l10n_tr_nilvera_uuid = uuid_node |
| 329 |
|
| 330 |
return logs |