| 1 |
from lxml import etree |
| 2 |
from urllib.parse import urlencode |
| 3 |
|
| 4 |
from odoo import api, fields, models, _ |
| 5 |
from odoo.exceptions import UserError |
| 6 |
from odoo.tools import cleanup_xml_node |
| 7 |
from odoo.tools.sql import column_exists, create_column |
| 8 |
|
| 9 |
from odoo.addons.l10n_gr_edi.models.l10n_gr_edi_document import _make_mydata_request |
| 10 |
from odoo.addons.l10n_gr_edi.models.preferred_classification import ( |
| 11 |
CLASSIFICATION_CATEGORY_EXPENSE, |
| 12 |
COMBINATIONS_WITH_POSSIBLE_EMPTY_TYPE, |
| 13 |
INVOICE_TYPES_HAVE_EXPENSE, |
| 14 |
INVOICE_TYPES_HAVE_INCOME, |
| 15 |
INVOICE_TYPES_SELECTION, |
| 16 |
PAYMENT_METHOD_SELECTION, |
| 17 |
TYPES_WITH_CORRELATE_INVOICE, |
| 18 |
TYPES_WITH_FORBIDDEN_CLASSIFICATION, |
| 19 |
TYPES_WITH_FORBIDDEN_COUNTERPART, |
| 20 |
TYPES_WITH_FORBIDDEN_QUANTITY, |
| 21 |
TYPES_WITH_MANDATORY_COUNTERPART, |
| 22 |
TYPES_WITH_MANDATORY_PAYMENT, |
| 23 |
TYPES_WITH_VAT_CATEGORY_8, |
| 24 |
TYPES_WITH_VAT_EXEMPT, |
| 25 |
VALID_TAX_AMOUNTS, |
| 26 |
VALID_TAX_CATEGORY_MAP, |
| 27 |
) |
| 28 |
|
| 29 |
|
| 30 |
class AccountMove(models.Model): |
| 31 |
_inherit = 'account.move' |
| 32 |
|
| 33 |
l10n_gr_edi_mark = fields.Char( |
| 34 |
string='Mark', |
| 35 |
compute='_compute_from_l10n_gr_edi_document_ids', |
| 36 |
store=True, |
| 37 |
) |
| 38 |
l10n_gr_edi_cls_mark = fields.Char( |
| 39 |
string='Classification Mark', |
| 40 |
compute='_compute_from_l10n_gr_edi_document_ids', |
| 41 |
store=True, |
| 42 |
) |
| 43 |
l10n_gr_edi_document_ids = fields.One2many( |
| 44 |
comodel_name='l10n_gr_edi.document', |
| 45 |
inverse_name='move_id', |
| 46 |
copy=False, |
| 47 |
readonly=True, |
| 48 |
) |
| 49 |
l10n_gr_edi_state = fields.Selection( |
| 50 |
selection=[ |
| 51 |
('invoice_sent', 'Invoice sent'), |
| 52 |
('bill_fetched', "Expense classification ready to send"), |
| 53 |
('bill_sent', "Expense classification sent"), |
| 54 |
], |
| 55 |
string='myDATA Status', |
| 56 |
compute='_compute_from_l10n_gr_edi_document_ids', |
| 57 |
store=True, |
| 58 |
tracking=True, |
| 59 |
) |
| 60 |
l10n_gr_edi_available_inv_type = fields.Char(compute='_compute_l10n_gr_edi_available_inv_type') |
| 61 |
l10n_gr_edi_correlation_id = fields.Many2one( |
| 62 |
comodel_name='account.move', |
| 63 |
string='Correlated Invoice', |
| 64 |
) |
| 65 |
l10n_gr_edi_inv_type = fields.Selection( |
| 66 |
selection=INVOICE_TYPES_SELECTION, |
| 67 |
string='myDATA Invoice Type', |
| 68 |
compute='_compute_l10n_gr_edi_inv_type', |
| 69 |
store=True, |
| 70 |
readonly=False, |
| 71 |
) |
| 72 |
l10n_gr_edi_payment_method = fields.Selection( |
| 73 |
selection=PAYMENT_METHOD_SELECTION, |
| 74 |
string='Payment Method', |
| 75 |
compute='_compute_l10n_gr_edi_payment_method', |
| 76 |
store=True, |
| 77 |
) |
| 78 |
l10n_gr_edi_alerts = fields.Json(compute='_compute_l10n_gr_edi_alerts') |
| 79 |
l10n_gr_edi_need_correlated = fields.Boolean(compute='_compute_l10n_gr_edi_need_fields') |
| 80 |
l10n_gr_edi_need_payment_method = fields.Boolean(compute='_compute_l10n_gr_edi_need_fields') |
| 81 |
l10n_gr_edi_enable_view_mydata = fields.Boolean(compute='_compute_l10n_gr_edi_enable_fields') |
| 82 |
l10n_gr_edi_enable_send_invoices = fields.Boolean(compute='_compute_l10n_gr_edi_enable_fields') |
| 83 |
l10n_gr_edi_enable_send_expense_classification = fields.Boolean(compute='_compute_l10n_gr_edi_enable_fields') |
| 84 |
l10n_gr_edi_attachment_id = fields.Many2one( |
| 85 |
comodel_name='ir.attachment', |
| 86 |
compute='_compute_from_l10n_gr_edi_document_ids', |
| 87 |
store=True, |
| 88 |
) |
| 89 |
|
| 90 |
def _auto_init(self): |
| 91 |
""" |
| 92 |
Create all compute-stored fields here to avoid MemoryError when initializing on large databases. |
| 93 |
""" |
| 94 |
for column_name, column_type in ( |
| 95 |
('l10n_gr_edi_mark', 'varchar'), |
| 96 |
('l10n_gr_edi_cls_mark', 'varchar'), |
| 97 |
('l10n_gr_edi_state', 'varchar'), |
| 98 |
('l10n_gr_edi_inv_type', 'varchar'), |
| 99 |
('l10n_gr_edi_payment_method', 'varchar'), |
| 100 |
('l10n_gr_edi_attachment_id', 'int4'), |
| 101 |
): |
| 102 |
if not column_exists(self.env.cr, 'account_move', column_name): |
| 103 |
create_column(self.env.cr, 'account_move', column_name, column_type) |
| 104 |
|
| 105 |
return super()._auto_init() |
| 106 |
|
| 107 |
|
| 108 |
|
| 109 |
|
| 110 |
|
| 111 |
@api.depends('l10n_gr_edi_document_ids') |
| 112 |
def _compute_from_l10n_gr_edi_document_ids(self): |
| 113 |
self.l10n_gr_edi_state = False |
| 114 |
self.l10n_gr_edi_mark = False |
| 115 |
self.l10n_gr_edi_cls_mark = False |
| 116 |
self.l10n_gr_edi_attachment_id = False |
| 117 |
|
| 118 |
for move in self: |
| 119 |
for document in move.l10n_gr_edi_document_ids.sorted(): |
| 120 |
if document.state in ('invoice_sent', 'bill_fetched', 'bill_sent'): |
| 121 |
move.l10n_gr_edi_state = document.state |
| 122 |
move.l10n_gr_edi_mark = document.mydata_mark |
| 123 |
move.l10n_gr_edi_cls_mark = document.mydata_cls_mark |
| 124 |
move.l10n_gr_edi_attachment_id = document.attachment_id |
| 125 |
break |
| 126 |
|
| 127 |
@api.depends('l10n_gr_edi_state') |
| 128 |
def _compute_show_reset_to_draft_button(self): |
| 129 |
|
| 130 |
""" Prevent user from resetting the move to draft if it's already sent to myDATA """ |
| 131 |
super()._compute_show_reset_to_draft_button() |
| 132 |
for move in self: |
| 133 |
if move.l10n_gr_edi_state in ('invoice_sent', 'bill_sent'): |
| 134 |
move.show_reset_to_draft_button = False |
| 135 |
|
| 136 |
@api.depends('country_code', 'state') |
| 137 |
def _compute_l10n_gr_edi_alerts(self): |
| 138 |
for move in self: |
| 139 |
|
| 140 |
|
| 141 |
if move._l10n_gr_edi_eligible_for_mydata(): |
| 142 |
move.l10n_gr_edi_alerts = move._origin._l10n_gr_edi_get_pre_error_dict() |
| 143 |
else: |
| 144 |
move.l10n_gr_edi_alerts = False |
| 145 |
|
| 146 |
@api.depends('state', 'l10n_gr_edi_state') |
| 147 |
def _compute_l10n_gr_edi_enable_fields(self): |
| 148 |
for move in self: |
| 149 |
common_send_requirements = all(( |
| 150 |
move._l10n_gr_edi_eligible_for_mydata(), |
| 151 |
move.l10n_gr_edi_state in (False, 'bill_fetched'), |
| 152 |
)) |
| 153 |
move.l10n_gr_edi_enable_view_mydata = all(( |
| 154 |
move.country_code == 'GR', |
| 155 |
move.is_invoice(include_receipts=True), |
| 156 |
)) |
| 157 |
move.l10n_gr_edi_enable_send_invoices = all(( |
| 158 |
common_send_requirements, |
| 159 |
move.is_sale_document(include_receipts=True), |
| 160 |
)) |
| 161 |
move.l10n_gr_edi_enable_send_expense_classification = all(( |
| 162 |
common_send_requirements, |
| 163 |
move.is_purchase_document(include_receipts=True), |
| 164 |
move.l10n_gr_edi_mark, |
| 165 |
)) |
| 166 |
|
| 167 |
@api.depends('country_code') |
| 168 |
def _compute_l10n_gr_edi_payment_method(self): |
| 169 |
for move in self: |
| 170 |
if move.country_code == 'GR': |
| 171 |
move.l10n_gr_edi_payment_method = move.l10n_gr_edi_payment_method or '1' |
| 172 |
else: |
| 173 |
move.l10n_gr_edi_payment_method = False |
| 174 |
|
| 175 |
|
| 176 |
|
| 177 |
|
| 178 |
|
| 179 |
@api.depends('move_type') |
| 180 |
def _compute_l10n_gr_edi_available_inv_type(self): |
| 181 |
for move in self: |
| 182 |
if move.is_sale_document(include_receipts=True): |
| 183 |
move.l10n_gr_edi_available_inv_type = ','.join(INVOICE_TYPES_HAVE_INCOME) |
| 184 |
elif move.is_purchase_document(include_receipts=True): |
| 185 |
move.l10n_gr_edi_available_inv_type = ','.join(INVOICE_TYPES_HAVE_EXPENSE) |
| 186 |
else: |
| 187 |
move.l10n_gr_edi_available_inv_type = False |
| 188 |
|
| 189 |
@api.depends('fiscal_position_id', 'l10n_gr_edi_available_inv_type') |
| 190 |
def _compute_l10n_gr_edi_inv_type(self): |
| 191 |
for move in self: |
| 192 |
if move.country_code == 'GR': |
| 193 |
if move.l10n_gr_edi_inv_type or move.move_type == 'entry': |
| 194 |
|
| 195 |
|
| 196 |
move.l10n_gr_edi_inv_type = move.l10n_gr_edi_inv_type |
| 197 |
elif move.move_type in ('out_refund', 'in_refund'): |
| 198 |
|
| 199 |
if move.l10n_gr_edi_correlation_id: |
| 200 |
|
| 201 |
move.l10n_gr_edi_inv_type = '5.1' |
| 202 |
else: |
| 203 |
move.l10n_gr_edi_inv_type = '5.2' |
| 204 |
else: |
| 205 |
inv_type = '1.1' if move.move_type == 'out_invoice' else '13.1' |
| 206 |
preferred_clss = move.fiscal_position_id.l10n_gr_edi_preferred_classification_ids.filtered( |
| 207 |
lambda p: p.l10n_gr_edi_inv_type in (move.l10n_gr_edi_available_inv_type or "").split(',')) |
| 208 |
if preferred_clss: |
| 209 |
inv_type = preferred_clss[0].l10n_gr_edi_inv_type |
| 210 |
move.l10n_gr_edi_inv_type = inv_type |
| 211 |
else: |
| 212 |
move.l10n_gr_edi_inv_type = False |
| 213 |
|
| 214 |
@api.depends('l10n_gr_edi_inv_type') |
| 215 |
def _compute_l10n_gr_edi_need_fields(self): |
| 216 |
for move in self: |
| 217 |
move.l10n_gr_edi_need_correlated = all(( |
| 218 |
move.l10n_gr_edi_inv_type in TYPES_WITH_CORRELATE_INVOICE, |
| 219 |
move.is_sale_document(include_receipts=True), |
| 220 |
)) |
| 221 |
move.l10n_gr_edi_need_payment_method = move.l10n_gr_edi_inv_type in TYPES_WITH_MANDATORY_PAYMENT |
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
def _l10n_gr_edi_create_error_document(self, values: dict): |
| 228 |
""" |
| 229 |
Creates ``l10n_gr_edi.document`` of state ``invoice_error`` or ``bill_error``. |
| 230 |
:param values: dictionary in the format of: {'error': <str>, 'xml_content': <optional/str>} |
| 231 |
""" |
| 232 |
self.ensure_one() |
| 233 |
document = self.env['l10n_gr_edi.document'].create({ |
| 234 |
'move_id': self.id, |
| 235 |
'state': 'invoice_error' if self.is_sale_document(include_receipts=True) else 'bill_error', |
| 236 |
'message': values['error'], |
| 237 |
}) |
| 238 |
if xml_content := values.get('xml_content'): |
| 239 |
document.attachment_id = self.env['ir.attachment'].sudo().create({ |
| 240 |
'name': f"mydata_{self.name.replace('/', '_')}.xml", |
| 241 |
'res_model': document._name, |
| 242 |
'res_id': document.id, |
| 243 |
'raw': xml_content, |
| 244 |
'type': 'binary', |
| 245 |
'mimetype': 'application/xml', |
| 246 |
}) |
| 247 |
return document |
| 248 |
|
| 249 |
def _l10n_gr_edi_create_sent_document(self, values: dict): |
| 250 |
""" |
| 251 |
Creates ``l10n_gr_edi.document`` of state ``invoice_sent`` or ``bill_sent``. |
| 252 |
:param values: dictionary in the format of: |
| 253 |
{ |
| 254 |
'mydata_mark': <str>, |
| 255 |
'mydata_cls_mark': <optional/str>, |
| 256 |
'mydata_url': <str>, |
| 257 |
'xml_content': <str>, |
| 258 |
} |
| 259 |
""" |
| 260 |
self.ensure_one() |
| 261 |
document = self.env['l10n_gr_edi.document'].create({ |
| 262 |
'move_id': self.id, |
| 263 |
'state': 'invoice_sent' if self.is_sale_document(include_receipts=True) else 'bill_sent', |
| 264 |
'mydata_mark': values['mydata_mark'], |
| 265 |
'mydata_cls_mark': values.get('mydata_cls_mark'), |
| 266 |
'mydata_url': values['mydata_url'], |
| 267 |
}) |
| 268 |
document.attachment_id = self.env['ir.attachment'].sudo().create({ |
| 269 |
'name': f"mydata_{self.name.replace('/', '_')}.xml", |
| 270 |
'res_model': self._name, |
| 271 |
'res_id': self.id, |
| 272 |
'raw': values['xml_content'], |
| 273 |
'type': 'binary', |
| 274 |
'mimetype': 'application/xml', |
| 275 |
}) |
| 276 |
return document |
| 277 |
|
| 278 |
|
| 279 |
|
| 280 |
|
| 281 |
|
| 282 |
@api.model |
| 283 |
def _l10n_gr_edi_generate_xml_content(self, xml_template, xml_vals): |
| 284 |
xml_content = self.env['ir.qweb']._render(xml_template, xml_vals) |
| 285 |
return etree.tostring(element_or_tree=cleanup_xml_node(xml_content), encoding='ISO-8859-7', standalone='yes') |
| 286 |
|
| 287 |
def _l10n_gr_edi_eligible_for_mydata(self): |
| 288 |
"""Shorthand for getting the eligibility of the current move to send to myDATA.""" |
| 289 |
self.ensure_one() |
| 290 |
return all(( |
| 291 |
self.country_code == 'GR', |
| 292 |
self.state == 'posted', |
| 293 |
)) |
| 294 |
|
| 295 |
def _get_name_invoice_report(self): |
| 296 |
|
| 297 |
self.ensure_one() |
| 298 |
if self.l10n_gr_edi_state == 'invoice_sent': |
| 299 |
return 'l10n_gr_edi.report_invoice_document' |
| 300 |
return super()._get_name_invoice_report() |
| 301 |
|
| 302 |
def _l10n_gr_edi_get_extra_invoice_report_values(self): |
| 303 |
"""Get the values used to render the invoice PDF.""" |
| 304 |
self.ensure_one() |
| 305 |
document = self.l10n_gr_edi_document_ids.sorted()[:1] |
| 306 |
|
| 307 |
if document.state in ('invoice_sent', 'bill_sent'): |
| 308 |
barcode_params = urlencode({ |
| 309 |
'barcode_type': 'QR', |
| 310 |
'quiet': 0, |
| 311 |
'value': document.mydata_url, |
| 312 |
'width': 180, |
| 313 |
'height': 180, |
| 314 |
}) |
| 315 |
return { |
| 316 |
'barcode_src': f'/report/barcode/?{barcode_params}', |
| 317 |
'mydata_mark': document.mydata_mark, |
| 318 |
'mydata_cls_mark': document.mydata_cls_mark, |
| 319 |
} |
| 320 |
else: |
| 321 |
return {} |
| 322 |
|
| 323 |
|
| 324 |
|
| 325 |
|
| 326 |
|
| 327 |
def _l10n_gr_edi_add_address_vals(self, values): |
| 328 |
""" |
| 329 |
Adds all the address values needed for the ``invoice_vals`` dictionary. |
| 330 |
The only guaranteed keys in to add in the dictionary is the issuer's VAT, country code, and branch number. |
| 331 |
Everything else is only displayed on some specific case/configuration. |
| 332 |
The appended dictionary will have the following additional keys: |
| 333 |
{ |
| 334 |
'issuer_vat_number': <str>, |
| 335 |
'issuer_country': <str>, |
| 336 |
'issuer_branch': <int>, |
| 337 |
'issuer_name': <str | None>, |
| 338 |
'issuer_postal_code': <str | None>, |
| 339 |
'issuer_city': <str | None>, |
| 340 |
'counterpart_vat': <str | None>, |
| 341 |
'counterpart_country': <str | None>, |
| 342 |
'counterpart_branch': <int | None>, |
| 343 |
'counterpart_name': <str | None>, |
| 344 |
'counterpart_postal_code': <str | None>, |
| 345 |
'counterpart_city': <str | None>, |
| 346 |
'counterpart_postal_code': <str | None>, |
| 347 |
'counterpart_city': <str | None>, |
| 348 |
} |
| 349 |
:param dict values: dictionary where the address values will be added |
| 350 |
:rtype: dict[str, str|int] |
| 351 |
""" |
| 352 |
self.ensure_one() |
| 353 |
issuer_not_from_greece = self.company_id.country_code != 'GR' |
| 354 |
inv_type_allows_counterpart = self.l10n_gr_edi_inv_type not in TYPES_WITH_FORBIDDEN_COUNTERPART |
| 355 |
partner_not_from_greece = self.partner_id.country_code != 'GR' |
| 356 |
inv_type_require_counterpart = self.l10n_gr_edi_inv_type in TYPES_WITH_MANDATORY_COUNTERPART |
| 357 |
|
| 358 |
conditional_address_keys = ('issuer_name', 'issuer_postal_code', 'issuer_city', 'counterpart_vat', 'counterpart_country', |
| 359 |
'counterpart_branch', 'counterpart_name', 'counterpart_postal_code', 'counterpart_city') |
| 360 |
values.update({ |
| 361 |
'issuer_vat_number': self.company_id.vat.replace('EL', '').replace('GR', ''), |
| 362 |
'issuer_country': self.company_id.country_code, |
| 363 |
'issuer_branch': self.company_id.l10n_gr_edi_branch_number or 0, |
| 364 |
**dict.fromkeys(conditional_address_keys), |
| 365 |
}) |
| 366 |
|
| 367 |
if issuer_not_from_greece: |
| 368 |
values.update({ |
| 369 |
'issuer_name': self.company_id.name.encode('ISO-8859-7'), |
| 370 |
'issuer_postal_code': self.company_id.zip, |
| 371 |
'issuer_city': (self.company_id.city or "").encode('ISO-8859-7') or None, |
| 372 |
}) |
| 373 |
|
| 374 |
if inv_type_allows_counterpart: |
| 375 |
values.update({ |
| 376 |
'counterpart_vat': self.commercial_partner_id.vat.replace('EL', '').replace('GR', ''), |
| 377 |
'counterpart_country': self.commercial_partner_id.country_code, |
| 378 |
'counterpart_branch': (self.commercial_partner_id.l10n_gr_edi_branch_number or 0), |
| 379 |
}) |
| 380 |
if partner_not_from_greece: |
| 381 |
values['counterpart_name'] = self.commercial_partner_id.name.encode('ISO-8859-7') |
| 382 |
|
| 383 |
if inv_type_require_counterpart or (inv_type_allows_counterpart and partner_not_from_greece): |
| 384 |
values.update({ |
| 385 |
'counterpart_postal_code': self.commercial_partner_id.zip, |
| 386 |
'counterpart_city': (self.commercial_partner_id.city or "").encode('ISO-8859-7') or None, |
| 387 |
}) |
| 388 |
|
| 389 |
def _l10n_gr_edi_add_payment_method_vals(self, values): |
| 390 |
""" |
| 391 |
Adds payment values needed for the ``invoice_vals`` dictionary. |
| 392 |
The appended dictionary will have the following additional key: |
| 393 |
{ 'payment_details': [ { 'type': <str>, 'amount': <float> }, ... ] } |
| 394 |
:param dict values: |
| 395 |
:rtype: dict[str, list[dict]] |
| 396 |
""" |
| 397 |
self.ensure_one() |
| 398 |
values.update({'payment_details': []}) |
| 399 |
payment_terms = self.line_ids.filtered(lambda line: line.display_type == 'payment_term') |
| 400 |
|
| 401 |
for match_field, amount_field in (('debit', 'credit'), ('credit', 'debit')): |
| 402 |
for apr in payment_terms[f'matched_{match_field}_ids']: |
| 403 |
values['payment_details'].append({ |
| 404 |
'type': self.l10n_gr_edi_payment_method or '1', |
| 405 |
'amount': apr[f'{amount_field}_amount_currency'], |
| 406 |
}) |
| 407 |
|
| 408 |
if not values['payment_details'] and self.l10n_gr_edi_inv_type in TYPES_WITH_MANDATORY_PAYMENT: |
| 409 |
|
| 410 |
values['payment_details'].append({ |
| 411 |
'type': self.l10n_gr_edi_payment_method or '1', |
| 412 |
'amount': 0, |
| 413 |
}) |
| 414 |
|
| 415 |
@api.model |
| 416 |
def _l10n_gr_edi_common_base_line_details_values(self, base_line): |
| 417 |
""" |
| 418 |
Returns additional income/expense classification items ("icls"/"ecls") if needed for the detail values. |
| 419 |
The returned format is: {'ecls': [ {'category': <str>, 'type': <str>, 'amount': <float>}, ... ], 'icls': <same_as_ecls> } |
| 420 |
:param dict base_line: dictionary obtained from the tax computation helper methods; such as `_get_rounded_base_and_tax_lines`. |
| 421 |
:rtype: dict[str, list[dict]] |
| 422 |
""" |
| 423 |
line = base_line['record'] |
| 424 |
net_amount = base_line['tax_details']['raw_total_excluded'] |
| 425 |
cls_vals = {'ecls': [], 'icls': []} |
| 426 |
|
| 427 |
if line.l10n_gr_edi_cls_category: |
| 428 |
cls_vals_list = cls_vals['ecls'] if line.l10n_gr_edi_cls_category in CLASSIFICATION_CATEGORY_EXPENSE else cls_vals['icls'] |
| 429 |
cls_type = line.l10n_gr_edi_cls_type or '' |
| 430 |
if len(cls_type) > 0 and cls_type[0] == 'X': |
| 431 |
cls_type = cls_type[1:] |
| 432 |
|
| 433 |
cls_vals_list.append({ |
| 434 |
'category': line.l10n_gr_edi_cls_category, |
| 435 |
'type': cls_type, |
| 436 |
'amount': net_amount, |
| 437 |
}) |
| 438 |
if line.l10n_gr_edi_cls_vat: |
| 439 |
cls_vals_list.append({ |
| 440 |
'category': '', |
| 441 |
'type': line.l10n_gr_edi_cls_vat, |
| 442 |
'amount': net_amount, |
| 443 |
}) |
| 444 |
|
| 445 |
return cls_vals |
| 446 |
|
| 447 |
@api.model |
| 448 |
def _l10n_gr_edi_add_sum_classification_vals(self, values): |
| 449 |
""" |
| 450 |
Aggregates all amounts from the common categories and types of the list vals from the ``details`` key, |
| 451 |
and then add them to the `values` dictionary parameter. |
| 452 |
[!WARNING!] The `values` parameter **must** have the `details` key. |
| 453 |
let ``XCLSList`` be a list with format of: |
| 454 |
[ |
| 455 |
{'category': <str>, 'type': <str>, 'amount': <float>}, |
| 456 |
..., |
| 457 |
] |
| 458 |
All in all, a subset of the `values` parameter should follow the following type formats: |
| 459 |
{ |
| 460 |
'details': { |
| 461 |
'icls': XCLSList, |
| 462 |
'ecls': XCLSList, |
| 463 |
} |
| 464 |
} |
| 465 |
The `values` dictionary will then be appended with the following keys: |
| 466 |
{ |
| 467 |
'summary_icls': XCLSList, |
| 468 |
'summary_ecls': XCLSList, |
| 469 |
} |
| 470 |
:param dict values: the dictionary where the sum classification values will be added. |
| 471 |
:rtype: dict[str, list[dict]] |
| 472 |
""" |
| 473 |
cls_vals_type = dict[tuple[str, str], float] |
| 474 |
icls_vals: cls_vals_type = {} |
| 475 |
ecls_vals: cls_vals_type = {} |
| 476 |
|
| 477 |
for detail in values['details']: |
| 478 |
icls_list, ecls_list = detail['icls'], detail['ecls'] |
| 479 |
for icls in icls_list: |
| 480 |
category_type = (icls['category'], icls['type']) |
| 481 |
icls_vals.setdefault(category_type, 0) |
| 482 |
icls_vals[category_type] += icls['amount'] |
| 483 |
for ecls in ecls_list: |
| 484 |
category_type = (ecls['category'], ecls['type']) |
| 485 |
ecls_vals.setdefault(category_type, 0) |
| 486 |
ecls_vals[category_type] += ecls['amount'] |
| 487 |
|
| 488 |
for summary_key, cls_vals in ( |
| 489 |
('summary_icls', icls_vals), |
| 490 |
('summary_ecls', ecls_vals), |
| 491 |
): |
| 492 |
values[summary_key] = [ |
| 493 |
{ |
| 494 |
'category': category, |
| 495 |
'type': cls_type, |
| 496 |
'amount': total_amount, |
| 497 |
} |
| 498 |
for (category, cls_type), total_amount in cls_vals.items() |
| 499 |
] |
| 500 |
|
| 501 |
def _l10n_gr_edi_get_invoices_xml_vals(self): |
| 502 |
""" |
| 503 |
Generates a dictionary containing the values needed for rendering ``l10n_gr_edi.mydata_invoice`` XML. |
| 504 |
:return: dict |
| 505 |
""" |
| 506 |
xml_vals = {'invoice_values_list': []} |
| 507 |
|
| 508 |
for move in self.sorted(key='id'): |
| 509 |
details = [] |
| 510 |
base_lines, _tax_lines = move._get_rounded_base_and_tax_lines() |
| 511 |
|
| 512 |
for line_no, base_line in enumerate(base_lines, start=1): |
| 513 |
line = base_line['record'] |
| 514 |
vat_category = 8 |
| 515 |
vat_exemption_category = '' |
| 516 |
if line.tax_ids and move.l10n_gr_edi_inv_type not in TYPES_WITH_VAT_EXEMPT: |
| 517 |
tax = base_line['tax_details']['taxes_data'][0]['tax'] |
| 518 |
vat_category = VALID_TAX_CATEGORY_MAP[int(tax.amount)] |
| 519 |
if vat_category == 7 and move.l10n_gr_edi_inv_type in TYPES_WITH_VAT_CATEGORY_8: |
| 520 |
vat_category = 8 |
| 521 |
if vat_category == 7: |
| 522 |
vat_exemption_category = line.l10n_gr_edi_tax_exemption_category |
| 523 |
|
| 524 |
details.append({ |
| 525 |
'line_number': line_no, |
| 526 |
'quantity': line.quantity if move.l10n_gr_edi_inv_type not in TYPES_WITH_FORBIDDEN_QUANTITY else '', |
| 527 |
'detail_type': line.l10n_gr_edi_detail_type or '', |
| 528 |
'net_value': base_line['tax_details']['raw_total_excluded'], |
| 529 |
'vat_amount': sum(tax_data['tax_amount'] for tax_data in base_line['tax_details']['taxes_data']), |
| 530 |
'vat_category': vat_category, |
| 531 |
'vat_exemption_category': vat_exemption_category, |
| 532 |
**self._l10n_gr_edi_common_base_line_details_values(base_line), |
| 533 |
}) |
| 534 |
|
| 535 |
invoice_values = { |
| 536 |
'__move__': move, |
| 537 |
'header_series': '_'.join(move.name.split('/')[:-1]), |
| 538 |
'header_aa': move.name.split('/')[-1], |
| 539 |
'header_issue_date': move.date.isoformat(), |
| 540 |
'header_invoice_type': move.l10n_gr_edi_inv_type, |
| 541 |
'header_currency': move.currency_id.name, |
| 542 |
'header_correlate': move.l10n_gr_edi_correlation_id.l10n_gr_edi_mark or '', |
| 543 |
'details': details, |
| 544 |
'summary_total_net_value': move.amount_untaxed, |
| 545 |
'summary_total_vat_amount': move.amount_tax, |
| 546 |
'summary_total_withheld_amount': 0, |
| 547 |
'summary_total_fees_amount': 0, |
| 548 |
'summary_total_stamp_duty_amount': 0, |
| 549 |
'summary_total_other_taxes_amount': 0, |
| 550 |
'summary_total_deductions_amount': 0, |
| 551 |
'summary_total_gross_value': move.amount_total, |
| 552 |
} |
| 553 |
move._l10n_gr_edi_add_address_vals(invoice_values) |
| 554 |
move._l10n_gr_edi_add_payment_method_vals(invoice_values) |
| 555 |
self._l10n_gr_edi_add_sum_classification_vals(invoice_values) |
| 556 |
xml_vals['invoice_values_list'].append(invoice_values) |
| 557 |
|
| 558 |
return xml_vals |
| 559 |
|
| 560 |
def _l10n_gr_edi_get_expense_classification_xml_vals(self): |
| 561 |
""" |
| 562 |
Generates a dictionary containing the values needed for rendering ``l10n_gr_edi.mydata_expense_classification`` XML. |
| 563 |
:return: dict |
| 564 |
""" |
| 565 |
xml_vals = {'invoice_values_list': []} |
| 566 |
|
| 567 |
for move in self: |
| 568 |
details = [] |
| 569 |
base_lines, _tax_lines = move._get_rounded_base_and_tax_lines() |
| 570 |
|
| 571 |
for line_no, base_line in enumerate(base_lines, start=1): |
| 572 |
details.append({ |
| 573 |
'line_number': line_no, |
| 574 |
**self._l10n_gr_edi_common_base_line_details_values(base_line), |
| 575 |
}) |
| 576 |
|
| 577 |
xml_vals['invoice_values_list'].append({ |
| 578 |
'__move__': move, |
| 579 |
'mark': move.l10n_gr_edi_mark, |
| 580 |
'transaction_mode': '', |
| 581 |
'details': details, |
| 582 |
}) |
| 583 |
|
| 584 |
return xml_vals |
| 585 |
|
| 586 |
|
| 587 |
|
| 588 |
|
| 589 |
|
| 590 |
def _l10n_gr_edi_get_pre_error_dict(self): |
| 591 |
""" |
| 592 |
Try to catch all possible errors before sending to myDATA. |
| 593 |
Returns an error dictionary in the format of Actionable Error JSON. |
| 594 |
""" |
| 595 |
self.ensure_one() |
| 596 |
errors = {} |
| 597 |
error_action_company = {'action_text': _("View Company"), 'action': self.company_id._get_records_action(name=_("Company"))} |
| 598 |
error_action_partner = {'action_text': _("View Partner"), 'action': self.commercial_partner_id._get_records_action(name=_("Partner"))} |
| 599 |
error_action_gr_settings = { |
| 600 |
'action_text': _("View Settings"), |
| 601 |
'action': { |
| 602 |
'name': _("Settings"), |
| 603 |
'type': 'ir.actions.act_url', |
| 604 |
'target': 'self', |
| 605 |
'url': '/odoo/settings#l10n_gr_edi_aade_settings', |
| 606 |
}, |
| 607 |
} |
| 608 |
|
| 609 |
if self.state != 'posted': |
| 610 |
errors['l10n_gr_edi_move_not_posted'] = { |
| 611 |
'message': _("You can only send to myDATA from a posted invoice."), |
| 612 |
} |
| 613 |
if not self.company_id.l10n_gr_edi_aade_id or not self.company_id.l10n_gr_edi_aade_key: |
| 614 |
errors['l10n_gr_edi_company_no_cred'] = { |
| 615 |
'message': _("You need to set AADE ID and Key in the company settings."), |
| 616 |
**error_action_gr_settings, |
| 617 |
} |
| 618 |
if self.company_id.country_code != 'GR' and (not self.company_id.city or not self.company_id.zip): |
| 619 |
errors['l10n_gr_edi_company_no_zip_street'] = { |
| 620 |
'message': _("Missing city and/or ZIP code on company %s.", self.company_id.name), |
| 621 |
**error_action_company, |
| 622 |
} |
| 623 |
if not self.company_id.vat: |
| 624 |
errors['l10n_gr_edi_company_no_vat'] = { |
| 625 |
'message': _("Missing VAT on company %s.", self.company_id.name), |
| 626 |
**error_action_company, |
| 627 |
} |
| 628 |
if not self.l10n_gr_edi_inv_type: |
| 629 |
errors['l10n_gr_edi_no_inv_type'] = { |
| 630 |
'message': _("Missing myDATA Invoice Type."), |
| 631 |
} |
| 632 |
if not self.commercial_partner_id: |
| 633 |
errors['l10n_gr_edi_no_partner'] = { |
| 634 |
'message': _("Partner must be filled to be able to send to myDATA."), |
| 635 |
} |
| 636 |
if self.commercial_partner_id: |
| 637 |
if not self.commercial_partner_id.vat: |
| 638 |
errors['l10n_gr_edi_partner_no_vat'] = { |
| 639 |
'message': _("Missing VAT on partner %s.", self.commercial_partner_id.name), |
| 640 |
**error_action_partner, |
| 641 |
} |
| 642 |
if ((self.commercial_partner_id.country_code != 'GR' or self.l10n_gr_edi_inv_type in TYPES_WITH_MANDATORY_COUNTERPART) and |
| 643 |
(not self.commercial_partner_id.zip or not self.commercial_partner_id.city)): |
| 644 |
errors['l10n_gr_edi_partner_no_zip_street'] = { |
| 645 |
'message': _("Missing city and/or ZIP code on partner %s.", self.commercial_partner_id.name), |
| 646 |
**error_action_partner, |
| 647 |
} |
| 648 |
|
| 649 |
move_disallow_classification = self.is_purchase_document(include_receipts=True) and self.l10n_gr_edi_inv_type in TYPES_WITH_FORBIDDEN_CLASSIFICATION |
| 650 |
|
| 651 |
for line_no, line in enumerate(self.invoice_line_ids, start=1): |
| 652 |
if line.display_type in ('line_section', 'line_subsection', 'line_note'): |
| 653 |
continue |
| 654 |
if move_disallow_classification and line.l10n_gr_edi_cls_category: |
| 655 |
errors[f'l10n_gr_edi_{line_no}_forbidden_classification'] = { |
| 656 |
'message': _('myDATA classification is not allowed on line %s.', line_no), |
| 657 |
} |
| 658 |
if not line.l10n_gr_edi_cls_category and line.l10n_gr_edi_available_cls_category and not move_disallow_classification: |
| 659 |
errors[f'l10n_gr_edi_line_{line_no}_missing_cls_category'] = { |
| 660 |
'message': _('Missing myDATA classification category on line %s.', line_no), |
| 661 |
} |
| 662 |
if not line.l10n_gr_edi_cls_type \ |
| 663 |
and line.l10n_gr_edi_available_cls_type \ |
| 664 |
and (line.move_id.l10n_gr_edi_inv_type, line.l10n_gr_edi_cls_category) \ |
| 665 |
not in COMBINATIONS_WITH_POSSIBLE_EMPTY_TYPE: |
| 666 |
errors[f'l10n_gr_edi_line_{line_no}_missing_cls_type'] = { |
| 667 |
'message': _('Missing myDATA classification type on line %s.', line_no), |
| 668 |
} |
| 669 |
taxes = line.tax_ids.flatten_taxes_hierarchy() |
| 670 |
if len(taxes) > 1: |
| 671 |
errors[f'l10n_gr_edi_line_{line_no}_multi_tax'] = { |
| 672 |
'message': _('myDATA does not support multiple taxes on line %s.', line_no), |
| 673 |
} |
| 674 |
if not taxes and self.l10n_gr_edi_inv_type not in TYPES_WITH_VAT_CATEGORY_8: |
| 675 |
errors[f'l10n_gr_edi_line_{line_no}_missing_tax'] = { |
| 676 |
'message': _('Missing tax on line %s.', line_no), |
| 677 |
} |
| 678 |
if len(taxes) == 1 and taxes.amount == 0 and not line.l10n_gr_edi_tax_exemption_category: |
| 679 |
errors[f'l10n_gr_edi_line_{line_no}_missing_tax_exempt'] = { |
| 680 |
'message': _('Missing myDATA Tax Exemption Category for line %s.', line_no), |
| 681 |
} |
| 682 |
if len(taxes) == 1 and taxes.amount not in VALID_TAX_AMOUNTS: |
| 683 |
errors[f'l10n_gr_edi_line_{line_no}_invalid_tax_amount'] = { |
| 684 |
'message': _('Invalid tax amount for line %(line_no)s. The valid values are %(valid_values)s.', |
| 685 |
line_no=line_no, |
| 686 |
valid_values=', '.join(str(tax) for tax in VALID_TAX_AMOUNTS)), |
| 687 |
} |
| 688 |
return errors |
| 689 |
|
| 690 |
def _l10n_gr_edi_get_pre_error_string(self): |
| 691 |
self.ensure_one() |
| 692 |
pre_error = self._l10n_gr_edi_get_pre_error_dict() |
| 693 |
error_messages = (error_val['message'] for error_val in pre_error.values()) |
| 694 |
return '\n'.join(error_messages) |
| 695 |
|
| 696 |
@api.model |
| 697 |
def _l10n_gr_edi_handle_send_result(self, result, xml_vals): |
| 698 |
""" |
| 699 |
Handle the result object received from sending xml to myDATA. |
| 700 |
Create the related error/sent document with the necessary values. |
| 701 |
""" |
| 702 |
move_xml_map = {} |
| 703 |
for invoice_vals in xml_vals['invoice_values_list']: |
| 704 |
single_xml_vals = {'invoice_values_list': [invoice_vals]} |
| 705 |
move = invoice_vals['__move__'] |
| 706 |
xml_template = 'l10n_gr_edi.mydata_invoice' if move.is_sale_document(include_receipts=True) else 'l10n_gr_edi.mydata_expense_classification' |
| 707 |
xml_content = self._l10n_gr_edi_generate_xml_content(xml_template, single_xml_vals) |
| 708 |
move_xml_map[move] = xml_content |
| 709 |
|
| 710 |
move_ids = list(move_xml_map.keys()) |
| 711 |
|
| 712 |
if 'error' in result: |
| 713 |
|
| 714 |
|
| 715 |
for move in move_ids: |
| 716 |
move._l10n_gr_edi_create_error_document(result) |
| 717 |
else: |
| 718 |
for result_id, result_dict in result.items(): |
| 719 |
move = move_ids[result_id] |
| 720 |
xml_content = move_xml_map[move] |
| 721 |
document_values = {**result_dict, 'xml_content': xml_content} |
| 722 |
|
| 723 |
move.l10n_gr_edi_document_ids.filtered(lambda d: d.state in ('invoice_error', 'bill_error')).unlink() |
| 724 |
if 'error' in result_dict: |
| 725 |
|
| 726 |
|
| 727 |
move._l10n_gr_edi_create_error_document(document_values) |
| 728 |
else: |
| 729 |
move._l10n_gr_edi_create_sent_document(document_values) |
| 730 |
|
| 731 |
if self._can_commit(): |
| 732 |
self.env.cr.commit() |
| 733 |
|
| 734 |
def _l10n_gr_edi_send_invoices(self): |
| 735 |
""" Send batches of invoice SendInvoice XML to myDATA. """ |
| 736 |
for company, invoices in self.grouped('company_id').items(): |
| 737 |
xml_vals = invoices._l10n_gr_edi_get_invoices_xml_vals() |
| 738 |
xml_content = invoices._l10n_gr_edi_generate_xml_content('l10n_gr_edi.mydata_invoice', xml_vals) |
| 739 |
result = _make_mydata_request(company=company, endpoint='SendInvoices', xml_content=xml_content) |
| 740 |
self._l10n_gr_edi_handle_send_result(result, xml_vals) |
| 741 |
|
| 742 |
def _l10n_gr_edi_send_expense_classification(self): |
| 743 |
""" Send batches of bill SendExpensesClassification XML to myDATA. """ |
| 744 |
for company, bills in self.grouped('company_id').items(): |
| 745 |
xml_vals = bills._l10n_gr_edi_get_expense_classification_xml_vals() |
| 746 |
xml_content = bills._l10n_gr_edi_generate_xml_content('l10n_gr_edi.mydata_expense_classification', xml_vals) |
| 747 |
result = _make_mydata_request(company=company, endpoint='SendExpensesClassification', xml_content=xml_content) |
| 748 |
self._l10n_gr_edi_handle_send_result(result, xml_vals) |
| 749 |
|
| 750 |
def l10n_gr_edi_try_send_invoices(self): |
| 751 |
moves_to_send = self.env['account.move'] |
| 752 |
for move in self: |
| 753 |
if error := move._l10n_gr_edi_get_pre_error_string(): |
| 754 |
move._l10n_gr_edi_create_error_document({'error': error}) |
| 755 |
else: |
| 756 |
moves_to_send |= move |
| 757 |
|
| 758 |
if moves_to_send: |
| 759 |
self.env['res.company']._with_locked_records(moves_to_send) |
| 760 |
moves_to_send._l10n_gr_edi_send_invoices() |
| 761 |
|
| 762 |
def l10n_gr_edi_try_send_expense_classification(self): |
| 763 |
moves_to_send = self.env['account.move'] |
| 764 |
for move in self: |
| 765 |
if error_message := move._l10n_gr_edi_get_pre_error_string(): |
| 766 |
move._l10n_gr_edi_create_error_document({'error': error_message}) |
| 767 |
|
| 768 |
|
| 769 |
|
| 770 |
if len(self) == 1 and self._can_commit(): |
| 771 |
self.env.cr.commit() |
| 772 |
raise UserError(error_message) |
| 773 |
else: |
| 774 |
moves_to_send |= move |
| 775 |
|
| 776 |
if moves_to_send: |
| 777 |
moves_to_send._l10n_gr_edi_send_expense_classification() |
| 778 |
if len(self) == 1 and (error_message := self.l10n_gr_edi_document_ids.sorted()[0].message): |
| 779 |
raise UserError(error_message) |
| 780 |
|
| 781 |
def _l10n_gr_edi_try_send_batch(self): |
| 782 |
""" Only available for Vendor Bills. In case of invoices, user should use Send & Print instead. """ |
| 783 |
if any(move.is_sale_document(include_receipts=True) for move in self): |
| 784 |
raise UserError(_("You should use Send & Print wizard for sending customer invoices to myDATA.")) |
| 785 |
if any(not move.l10n_gr_edi_enable_send_expense_classification for move in self): |
| 786 |
raise UserError(_("Some of the selected moves does not meet the requirements to be sent to myDATA.")) |
| 787 |
|
| 788 |
self.l10n_gr_edi_try_send_expense_classification() |