Debian Codegraph @

addons/l10n_hr_edi/models/account_move.py

raw
1 import logging
2 import pytz
3 import re
4
5 from odoo import api, models, fields
6 from odoo.exceptions import UserError, ValidationError
7 from odoo.tools import SQL
8 from odoo.tools.sql import column_exists, create_column
9
10 from ..tools import (
11 _mer_api_mark_paid,
12 _mer_api_query_document_process_status_inbox,
13 _mer_api_query_document_process_status_outbox,
14 _mer_api_update_document_process_status,
15 _mer_api_check_fiscalization_status_outbox,
16 _mer_api_check_fiscalization_status_inbox,
17 MojEracunServiceError,
18 )
19
20 _logger = logging.getLogger(__name__)
21
22
23 class AccountMove(models.Model):
24 _inherit = 'account.move'
25
26 # Fields required for correctly generating CIUS HR documents
27 l10n_hr_process_type = fields.Selection(
28 [
29 ('P1', "P1: Issuing invoices for deliveries of goods and services according to purchase orders, based on contracts"),
30 ('P2', "P2: Periodic invoicing for deliveries of goods and services based on contracts"),
31 ('P3', "P3: Issuing invoices for delivery according to an independent purchase order"),
32 ('P4', "P4: Prepayment (advance payment)"),
33 ('P5', "P5: Payment on the spot (Sport payment)"),
34 ('P6', "P6: Payment before delivery, based on purchase order"),
35 ('P7', "P7: Issuing invoices with references to the delivery note"),
36 ('P8', "P8: Issuing invoices with references to the shipping and receipt notes"),
37 ('P9', "P9: Credits or invoices with negative amounts, issued for various reasons, including empty returns packaging"),
38 ('P10', "P10: Issuing a corrective invoice (reversal/correction of invoice)"),
39 ('P11', "P11: Issuing partial and final invoices"),
40 ('P12', "P12: Self-issuance of invoice"),
41 ('P99', "P99: Customer-defined process"),
42 ],
43 string="Business Process Type",
44 compute='_compute_l10n_hr_process_type',
45 store=True,
46 readonly=False,
47 copy=False,
48 )
49 l10n_hr_customer_defined_process_name = fields.Char(
50 string="Custom Process Name",
51 help="Required when Process Type is P99. Specify the name of your custom business process. "
52 "This will appear in the UBL as P99:YourProcessName",
53 )
54 l10n_hr_fiscal_user_id = fields.Many2one(
55 comodel_name="res.partner",
56 string="Fiscal User",
57 domain=lambda self: self._get_l10n_hr_fiscal_user_id_domain(),
58 )
59 l10n_hr_operator_name = fields.Char(string="Operator Label", related='l10n_hr_fiscal_user_id.name')
60 l10n_hr_operator_oib = fields.Char(string="Operator OIB", related='l10n_hr_fiscal_user_id.l10n_hr_personal_oib')
61 # Additional fields
62 l10n_hr_edi_addendum_id = fields.One2many(comodel_name='l10n_hr_edi.addendum', inverse_name='move_id', string='HR EDI Addendum', copy=False)
63 l10n_hr_invoice_sending_time = fields.Datetime(related='l10n_hr_edi_addendum_id.invoice_sending_time')
64 # EDI and fiscalization-specific fields
65 l10n_hr_business_document_status = fields.Selection(related='l10n_hr_edi_addendum_id.business_document_status')
66 l10n_hr_business_status_reason = fields.Char(related='l10n_hr_edi_addendum_id.business_status_reason')
67 l10n_hr_fiscalization_number = fields.Char(related='l10n_hr_edi_addendum_id.fiscalization_number')
68 l10n_hr_fiscalization_status = fields.Selection(related='l10n_hr_edi_addendum_id.fiscalization_status')
69 l10n_hr_fiscalization_error = fields.Char(related='l10n_hr_edi_addendum_id.fiscalization_error')
70 l10n_hr_fiscalization_request = fields.Char(related='l10n_hr_edi_addendum_id.fiscalization_request')
71 l10n_hr_fiscalization_channel_type = fields.Selection(related='l10n_hr_edi_addendum_id.fiscalization_channel_type')
72 # Payment reporting
73 l10n_hr_payment_reported_amount = fields.Monetary(
74 related='l10n_hr_edi_addendum_id.payment_reported_amount',
75 currency_field='currency_id',
76 )
77 l10n_hr_payment_unreported = fields.Boolean(compute='_compute_l10n_hr_payment_unreported', search='_search_l10n_hr_payment_unreported')
78 l10n_hr_payment_method_type = fields.Selection(related='l10n_hr_edi_addendum_id.payment_method_type', readonly=False)
79 # MojEracun integration fields
80 l10n_hr_mer_document_eid = fields.Char(related='l10n_hr_edi_addendum_id.mer_document_eid')
81 l10n_hr_mer_document_status = fields.Selection(related='l10n_hr_edi_addendum_id.mer_document_status')
82
83 def _auto_init(self):
84 if not column_exists(self.env.cr, 'account_move', 'l10n_hr_process_type'):
85 create_column(self.env.cr, 'account_move', 'l10n_hr_process_type', 'varchar')
86 return super()._auto_init()
87
88 @api.depends('l10n_hr_edi_addendum_id.payment_reported_amount', 'amount_residual', 'amount_total')
89 def _compute_l10n_hr_payment_unreported(self):
90 for move in self:
91 move.l10n_hr_payment_unreported = move.l10n_hr_payment_reported_amount != (move.amount_total - move.amount_residual)
92
93 def _search_l10n_hr_payment_unreported(self, operator, value):
94 # A specific override to enable the "Has unreported payments" filter on the list view
95 if operator == '!=':
96 query = self._search([])
97 query.join('account_move', 'id', 'l10n_hr_edi_addendum', 'move_id', 'addendum')
98 query.add_where(SQL("""ROUND(%(payment_reported_amount)s - %(amount_total)s + %(amount_residual)s, 8) != 0""",
99 payment_reported_amount=self.env['l10n_hr_edi.addendum']._field_to_sql('account_move__addendum', 'payment_reported_amount', query),
100 amount_total=self._field_to_sql('account_move', 'amount_total', query),
101 amount_residual=self._field_to_sql('account_move', 'amount_residual', query),
102 ))
103 return [('id', 'in', query)]
104 return []
105
106 @api.constrains('move_type', 'l10n_hr_process_type')
107 def _check_l10n_hr_process_type(self):
108 for record in self:
109 if record.country_code == 'HR' and (record.l10n_hr_process_type == 'P9') == (record.move_type != 'out_refund'):
110 raise ValidationError(self.env._('Business Process Type P9 can only be used with credit notes and vice versa.'))
111
112 @api.depends('l10n_hr_fiscalization_status')
113 def _compute_show_reset_to_draft_button(self):
114 # EXTENDS 'account'
115 super()._compute_show_reset_to_draft_button()
116 for move in self:
117 if move.l10n_hr_fiscalization_status:
118 move.show_reset_to_draft_button = False
119
120 @api.depends('move_type', 'l10n_hr_process_type')
121 def _compute_l10n_hr_process_type(self):
122 for move in self:
123 if not move.l10n_hr_process_type:
124 if move.move_type == 'out_refund':
125 move.l10n_hr_process_type = 'P9'
126 elif move.move_type == 'out_invoice':
127 move.l10n_hr_process_type = 'P1'
128
129 def _get_l10n_hr_fiscalization_number(self, name):
130 """
131 Extract the fiscal numbering triple (ex. 1/1/1) from the document name.
132 Only applies for Croatian sales invoices/credit notes. Expected name
133 pattern is produced by the overridden `sequence.mixin` logic.
134 """
135 name_regex = r'.*?(?P<seq>\d+)/(?P<premises_label>\d+)/(?P<device_label>\d+)'
136 if match := re.match(name_regex, name):
137 return f"{int(match.group('seq'))}/{match.group('premises_label')}/{match.group('device_label')}"
138 else:
139 return False
140
141 def _get_l10n_hr_fiscal_user_id_domain(self):
142 internal_users = self.env.ref('base.group_user')
143 domain = [('user_ids', 'in', internal_users.user_ids.ids)]
144 return domain
145
146 @api.model
147 def UNUSED_get_ubl_cii_builder_from_xml_tree(self, tree):
148 customization_id = tree.find('{*}CustomizationID')
149 if customization_id is not None:
150 if customization_id.text == 'urn:cen.eu:en16931:2017#compliant#urn:mfin.gov.hr:cius-2025:1.0#conformant#urn:mfin.gov.hr:ext-2025:1.0':
151 return self.env['account.edi.xml.ubl_hr']
152 return super()._get_ubl_cii_builder_from_xml_tree(tree)
153
154 def _get_import_file_type(self, file_data):
155 """ Identify CIUS HR files. """
156 # EXTENDS 'account'
157 if (
158 file_data['xml_tree'] is not None
159 and (ubl_profile := file_data['xml_tree'].findtext('{*}CustomizationID'))
160 and ubl_profile == 'urn:cen.eu:en16931:2017#compliant#urn:mfin.gov.hr:cius-2025:1.0#conformant#urn:mfin.gov.hr:ext-2025:1.0'
161 ):
162 return 'account.edi.xml.ubl_hr'
163
164 return super()._get_import_file_type(file_data)
165
166 def _get_invoice_reference_odoo_invoice(self):
167 """
168 Override to propose a structured reference for HR domestic flows.
169 When the company and partner are both in Croatia and the invoice has a
170 computed fiscalization number, return a reference like:
171 "HR00 {BrOznRacOznPosPrOznNapUr}"
172 where slashes are removed per Croatian banking conventions.
173 """
174 self.ensure_one()
175 # Check if invoice has fiscalization number, company is in Croatia, and partner is in Croatia
176 if self.company_id.country_code == 'HR' and self.partner_id.country_code == 'HR':
177 fisc_num_hr_format = re.sub(r'\D', '', self._get_l10n_hr_fiscalization_number(self.name))
178 return "HR00 " + fisc_num_hr_format
179 else:
180 return super()._get_invoice_reference_odoo_invoice()
181
182 def _post(self, soft=True):
183 for move in self:
184 if move.country_code == 'HR' and move.is_sale_document():
185 if not move.l10n_hr_fiscal_user_id:
186 move.l10n_hr_fiscal_user_id = move.env.user.partner_id
187 if move.l10n_hr_mer_document_eid and move.is_purchase_document():
188 if move.l10n_hr_business_document_status == '1':
189 raise UserError(self.env._("This vendor bill is already rejected according to the Tax Authority."))
190 elif move.l10n_hr_business_document_status in ('4', '99'):
191 _mer_api_update_document_process_status(
192 move.company_id,
193 move.l10n_hr_mer_document_eid,
194 0,
195 )
196 move.l10n_hr_edi_addendum_id.business_document_status = '0'
197 _logger.info("Document eID %s reported as approved by recepient.", move.l10n_hr_mer_document_eid)
198 return super()._post(soft=soft)
199
200 def l10n_hr_edi_mer_action_reject(self):
201 self.ensure_one()
202 return {
203 'name': self.env._("Reject MojEracun invoice"),
204 'type': 'ir.actions.act_window',
205 'view_mode': 'form',
206 'res_model': 'l10n_hr_edi.mojeracun_reject_wizard',
207 'target': 'new',
208 'context': {
209 'active_model': 'account.move',
210 'active_ids': self.ids,
211 },
212 }
213
214 def l10n_hr_edi_mer_action_fetch_status(self):
215 """
216 Fetch and update the status of a single document on MojEracun.
217 """
218 self.ensure_one()
219 if self.is_sale_document():
220 response_mer = _mer_api_query_document_process_status_outbox(self.company_id, electronic_id=self.l10n_hr_mer_document_eid)[0]
221 response_fisc = _mer_api_check_fiscalization_status_outbox(self.company_id, electronic_id=self.l10n_hr_mer_document_eid)[0]
222 elif self.is_purchase_document():
223 response_mer = _mer_api_query_document_process_status_inbox(self.company_id, electronic_id=self.l10n_hr_mer_document_eid)[0]
224 response_fisc = _mer_api_check_fiscalization_status_inbox(self.company_id, electronic_id=self.l10n_hr_mer_document_eid)[0]
225 else:
226 return
227 self.l10n_hr_edi_addendum_id.write({
228 'mer_document_status': str(response_mer.get('StatusId')),
229 'business_document_status': str(response_mer.get('DocumentProcessStatusId')),
230 'fiscalization_status': str(response_fisc['messages'][-1].get('status')),
231 'fiscalization_error': str(response_fisc['messages'][-1].get('errorCode') + ' - ' + response_fisc['messages'][-1].get('errorCodeDescription')),
232 'fiscalization_request': str(response_fisc['messages'][-1].get('fiscalizationRequestId')),
233 'business_status_reason': str(response_fisc['messages'][-1].get('businessStatusReason')),
234 'fiscalization_channel_type': str(response_fisc.get('channelType')),
235 })
236
237 def l10n_hr_edi_mer_action_report_paid(self):
238 batch = len(self) != 1
239 for move in self:
240 if not move.l10n_hr_mer_document_eid:
241 continue
242 state_to_set = {'partial': '3', 'paid': '2'}.get(move.payment_state)
243 amount_to_report = (move.amount_total - move.amount_residual) - move.l10n_hr_payment_reported_amount
244 if amount_to_report and state_to_set:
245 try:
246 response = _mer_api_mark_paid(
247 move.company_id,
248 move.l10n_hr_mer_document_eid,
249 fields.Datetime.now(pytz.timezone('Europe/Zagreb')).strftime('%Y-%m-%dT%H:%M:%S'),
250 amount_to_report,
251 move.l10n_hr_payment_method_type,
252 )
253 except MojEracunServiceError:
254 if batch:
255 _logger.error("Failed to report payments document: %s", move.l10n_hr_mer_document_eid)
256 continue
257 else:
258 raise
259 move.l10n_hr_edi_addendum_id.payment_reported_amount += amount_to_report
260 move.l10n_hr_edi_addendum_id.fiscalization_request = response.get('fiscalizationRequestId')
261 if response.get('encodedXml'):
262 attachment = self.env["ir.attachment"].create(
263 {
264 "name": f"mojeracun_{response['electronicId']}_payment.xml",
265 "raw": response['encodedXml'],
266 "type": "binary",
267 "mimetype": "application/xml",
268 }
269 )
270 attachment.write({'res_model': 'account.move', 'res_id': move.id})
271 else:
272 attachment = False
273 move._message_log(
274 body=self.env._(
275 "%(ts)s: Payments for eRacun document (ElectroicId: %(eid)s) in the amount of %(mnt)s EUR has been reported successfully. (Request ID: %(req_id)s)",
276 ts=response['fiscalizationTimestamp'],
277 eid=move.l10n_hr_mer_document_eid,
278 mnt=amount_to_report,
279 req_id=response['fiscalizationRequestId'],
280 ),
281 attachment_ids=attachment.ids if attachment else False,
282 )
283 _mer_api_update_document_process_status(
284 move.company_id,
285 move.l10n_hr_mer_document_eid,
286 state_to_set,
287 )
288 move.l10n_hr_edi_addendum_id.business_document_status = state_to_set