Debian Codegraph @

addons/l10n_hr_edi/models/account_move_send.py

raw
1 import logging
2 import pytz
3
4 from odoo import api, fields, models
5 from odoo.exceptions import UserError, ValidationError
6
7 from ..tools import _mer_api_send, MojEracunServiceError
8
9 _logger = logging.getLogger(__name__)
10
11
12 class AccountMoveSend(models.AbstractModel):
13 _inherit = 'account.move.send'
14
15 @api.model
16 def _check_move_constrains(self, moves):
17 # HR-BR-37: Invoice must contain HR-BT-4: Operator code in accordance with the Fiscalization Act.
18 if any((move.country_code == 'HR' and not move.l10n_hr_operator_name) for move in moves):
19 raise UserError(self.env._("Operator label is required for sending invoices in Croatia."))
20 # HR-BR-9: Invoice must contain HR-BT-5: Operator OIB in accordance with the Fiscalization Act.
21 if any((move.country_code == 'HR' and not move.l10n_hr_operator_oib) for move in moves):
22 raise UserError(self.env._("Operator OIB is required for sending invoices in Croatia."))
23 # HR-BR-25: ensure KPD is provided for every business line except for advance (P4)
24 if any((move.country_code == 'HR' and move.l10n_hr_process_type != 'P4' and
25 any(line.display_type == 'product' and not line.l10n_hr_kpd_category_id for line in move.line_ids)) for move in moves):
26 raise UserError(self.env._('KPD categories must be defined on every invoice line for any Business Process Type other than P4.'))
27 if any((move.country_code == 'HR' and move.l10n_hr_process_type == 'P99' and not move.l10n_hr_customer_defined_process_name) for move in moves):
28 raise UserError(self.env._('Name of custom business process is required for Business Process Type P99.'))
29 if any((move.country_code == 'HR' and
30 len({line.tax_ids.tax_exigibility for line in move.line_ids if line.display_type == 'product'}) != 1) for move in moves):
31 raise ValidationError(self.env._('For Croatia, all VAT taxes on an invoice should either be cash basis or not.'))
32 if any(move.country_code == 'HR' and
33 any(any((tax.tax_exigibility == 'on_payment' and not tax.invoice_legal_notes) for tax in line.tax_ids
34 ) for line in move.line_ids if line.display_type == 'product') for move in moves):
35 raise ValidationError(self.env._('For Croatia, Legal Notes should be provided for all cash basis taxes.'))
36 super()._check_move_constrains(moves)
37
38 # -------------------------------------------------------------------------
39 # SENDING METHODS
40 # -------------------------------------------------------------------------
41
42 def _get_default_invoice_edi_format(self, move, **kwargs) -> str:
43 # EXTENDS 'account'
44 if 'mojeracun' in kwargs.get('sending_methods', []):
45 return 'ubl_hr'
46 return super()._get_default_invoice_edi_format(move, **kwargs)
47
48 def _is_applicable_to_company(self, method, company):
49 # EXTENDS 'account'
50 if method == 'mojeracun':
51 return company.l10n_hr_mer_connection_state == 'active' and company.country_code == 'HR'
52 return super()._is_applicable_to_company(method, company)
53
54 def _is_applicable_to_move(self, method, move, **move_data):
55 # EXTENDS 'account'
56 if method == 'mojeracun':
57 partner = move.partner_id.commercial_partner_id.with_company(move.company_id)
58 invoice_edi_format = move_data.get('invoice_edi_format') or 'ubl_hr'
59 return all([
60 self._is_applicable_to_company(method, move.company_id),
61 partner.vat, # Alternatively, partner GLN when proper support for that is added
62 move._need_ubl_cii_xml(invoice_edi_format)
63 or (move.ubl_cii_xml_id and move.l10n_hr_mer_document_status not in {'20', '30', '40'}),
64 ])
65 return super()._is_applicable_to_move(method, move, **move_data)
66
67 def _hook_if_errors(self, moves_data, allow_raising=True):
68 # EXTENDS 'account'
69 moves_failed_file_generation = self.env['account.move']
70 for move, move_data in moves_data.items():
71 if 'mojeracun' in move_data['sending_methods'] and move_data.get('blocking_error'):
72 moves_failed_file_generation |= move
73 moves_failed_file_generation.l10n_hr_mer_document_status = '50'
74 return super()._hook_if_errors(moves_data, allow_raising=allow_raising)
75
76 @api.model
77 def _generate_and_send_invoices(self, moves, from_cron=False, allow_raising=True, allow_fallback_pdf=False, **custom_settings):
78 for move in moves:
79 if move.country_code == 'HR' and move.is_sale_document():
80 move.l10n_hr_edi_addendum_id = self.env['l10n_hr_edi.addendum'].create({
81 'move_id': move.id,
82 'fiscalization_number': move._get_l10n_hr_fiscalization_number(move.name),
83 'invoice_sending_time': fields.Datetime.now(pytz.timezone('Europe/Zagreb')),
84 })
85 return super()._generate_and_send_invoices(moves, from_cron=from_cron, allow_raising=allow_raising, allow_fallback_pdf=allow_fallback_pdf, **custom_settings)
86
87 def _call_web_service_after_invoice_pdf_render(self, invoices_data):
88 # EXTENDS 'account'
89 super()._call_web_service_after_invoice_pdf_render(invoices_data)
90
91 for invoice, invoice_data in invoices_data.items():
92 # MojEracun determines the receiver endpoint entirely from the XML,
93 # so there is no need to check for partner endpoint
94 if 'mojeracun' not in invoice_data['sending_methods']:
95 continue
96 if not self._is_applicable_to_move('mojeracun', invoice, **invoice_data):
97 raise UserError(self.env._("Failed to send invoice via MojEracun: check configuration."))
98
99 if invoice_data.get('ubl_cii_xml_attachment_values'):
100 xml_file = invoice_data['ubl_cii_xml_attachment_values']['raw']
101 elif invoice.ubl_cii_xml_id and invoice.l10n_hr_mer_document_status not in {'20', '30', '40'}:
102 xml_file = invoice.ubl_cii_xml_id.raw
103 else:
104 invoice.l10n_hr_edi_addendum_id.mer_document_status = '50'
105 builder = invoice.partner_id.commercial_partner_id._get_edi_builder(invoice_data['invoice_edi_format'])
106 invoice_data['error'] = self.env._(
107 "Errors occurred while creating the EDI document (format: %s):",
108 builder._description,
109 )
110 return
111 addendum = invoice.l10n_hr_edi_addendum_id
112 try:
113 response = _mer_api_send(invoice.company_id, xml_file.decode())
114 except MojEracunServiceError as e:
115 addendum.mer_document_status = '50'
116 invoice_data['error'] = e.message
117 else:
118 if not response.get('ElectronicId'):
119 addendum.mer_document_status = '50'
120 errors = []
121 for key in response:
122 errors.append(' '.join(response[key].get('Messages', [])))
123 invoice_data['error'] = {'error_title': "Error", 'errors': errors}
124 else:
125 addendum.mer_document_eid = response['ElectronicId']
126 addendum.mer_document_status = '20'
127 log_message = self.env._('The document has been sent to MojEracun service provider for processing')
128 invoice._message_log(body=log_message)
129 if self._can_commit():
130 self.env.cr.commit()