Debian Codegraph @

addons/l10n_hr_edi/models/res_company.py

raw
1 import logging
2
3 from odoo import api, fields, models, tools
4 from odoo.exceptions import UserError, ValidationError
5
6 from ..tools import (
7 _mer_api_query_inbox,
8 _mer_api_query_document_process_status_outbox,
9 _mer_api_query_document_process_status_inbox,
10 _mer_api_check_fiscalization_status_outbox,
11 _mer_api_check_fiscalization_status_inbox,
12 _mer_api_receive_document,
13 _mer_api_notify_import,
14 MojEracunServiceError,
15 )
16
17 BATCH_SIZE = 50
18 _logger = logging.getLogger(__name__)
19
20
21 class ResCompany(models.Model):
22 _inherit = 'res.company'
23
24 l10n_hr_mer_username = fields.Char("MojEracun username", groups="account.group_account_manager")
25 l10n_hr_mer_password = fields.Char("MojEracun password", groups="account.group_account_manager")
26 l10n_hr_mer_company_ident = fields.Char("MojEracun CompanyId", groups="account.group_account_manager")
27 l10n_hr_mer_software_ident = fields.Char("MojEracun SoftwareId", default='Saodoo-001', help="Default SoftwareID for Odoo is 'Saodoo-001'")
28 l10n_hr_mer_connection_state = fields.Selection(
29 selection=[
30 ('inactive', 'Inactive'),
31 ('active', 'Active'),
32 ],
33 string='MojEracun connection status',
34 required=True,
35 default='inactive',
36 compute='_compute_l10n_hr_mojeracun_state',
37 store=True,
38 )
39 l10n_hr_mer_connection_mode = fields.Selection(
40 selection=[
41 ('prod', 'Production'),
42 ('test', 'Test'),
43 ('demo', 'Demo'),
44 ],
45 string='MojEracun Operating mode',
46 default='test',
47 )
48 l10n_hr_mer_purchase_journal_id = fields.Many2one(
49 comodel_name='account.journal',
50 string='eracun Purchase Journal',
51 domain=[('type', '=', 'purchase')],
52 compute='_compute_l10n_hr_mer_purchase_journal_id', store=True, readonly=False,
53 )
54
55 # -------------------------------------------------------------------------
56 # CONSTRAINTS
57 # -------------------------------------------------------------------------
58
59 @api.constrains('l10n_hr_mer_purchase_journal_id')
60 def _check_l10n_hr_mer_purchase_journal_id(self):
61 for company in self:
62 if company.l10n_hr_mer_purchase_journal_id and company.l10n_hr_mer_purchase_journal_id.type != 'purchase':
63 raise ValidationError(self.env._("A purchase journal must be used to receive eRacun document via MojEracun."))
64
65 # -------------------------------------------------------------------------
66 # COMPUTE METHODS
67 # -------------------------------------------------------------------------
68
69 @api.depends('l10n_hr_mer_connection_state')
70 def _compute_l10n_hr_mer_purchase_journal_id(self):
71 for company in self:
72 if not company.l10n_hr_mer_purchase_journal_id and company.l10n_hr_mer_connection_state == 'active':
73 company.l10n_hr_mer_purchase_journal_id = self.env['account.journal'].search([
74 *self.env['account.journal']._check_company_domain(company),
75 ('type', '=', 'purchase'),
76 ], limit=1)
77 else:
78 company.l10n_hr_mer_purchase_journal_id = company.l10n_hr_mer_purchase_journal_id
79
80 @api.depends('l10n_hr_mer_username', 'l10n_hr_mer_password')
81 def _compute_l10n_hr_mojeracun_state(self):
82 for company in self:
83 if any(not field for field in [
84 company.l10n_hr_mer_username,
85 company.l10n_hr_mer_password,
86 ]):
87 company.l10n_hr_mer_connection_state = 'inactive'
88
89 # -------------------------------------------------------------------------
90 # MOJERACUN PARTICIPANT MANAGEMENT
91 # -------------------------------------------------------------------------
92
93 def _l10n_hr_activate_mojeracun(self):
94 for company in self:
95 if company.l10n_hr_mer_username and company.l10n_hr_mer_password:
96 company.l10n_hr_mer_connection_state = 'active'
97
98 # -------------------------------------------------------------------------
99 # CRONS
100 # -------------------------------------------------------------------------
101
102 def _cron_mer_get_new_documents(self):
103 edi_user_companies = self.search([('l10n_hr_mer_connection_state', '=', 'active')])
104 for company in edi_user_companies:
105 company._l10n_hr_mer_get_new_documents(from_cron=True)
106
107 def _cron_mer_update_document_status(self):
108 edi_user_companies = self.search([('l10n_hr_mer_connection_state', '=', 'active')])
109 for company in edi_user_companies:
110 company._l10n_hr_mer_fetch_document_status_company(from_cron=True)
111
112 def _cron_mer_archive_signed_xmls(self):
113 edi_user_companies = self.search([('l10n_hr_mer_connection_state', '=', 'active')])
114 for company in edi_user_companies:
115 company._l10n_hr_mer_archive_signed_xmls(from_cron=True)
116
117 # -------------------------------------------------------------------------
118 # BUSINESS ACTIONS
119 # -------------------------------------------------------------------------
120
121 def _l10n_hr_mer_import_invoice(self, attachment, document):
122 """
123 Save new documents in an accounting journal, when one is specified on the company.
124 If the document is not an invoice but a rejection notice, log a note on the related move instead.
125 :param attachment: the new document
126 :param document: a dictionary of MER and fiscalization related values for the document
127 :return: `True` if the document was saved, `False` if it was not
128 """
129 self.ensure_one()
130 original_document_id = self.env['account.edi.xml.ubl_hr']._retrieve_rejection_reference(attachment)
131 if original_document_id == 'not_found':
132 _logger.error("Failed to find origin document for rejection note %s", document['mer_document_eid'])
133 return False
134 elif original_document_id:
135 original_addendum = self.env['l10n_hr_edi.addendum'].search([
136 ('mer_document_eid', '=', original_document_id[0]),
137 ('business_document_status', '!=', '1'),
138 ('move_id.company_id', '=', self.id)], limit=1)
139 if original_addendum:
140 original_addendum.move_id.message_post(body=self.env._(
141 "eRacun rejected by document with Electronic ID: %(eid)s\n\"%(reason)s\"",
142 eid=document['mer_document_eid'], reason=original_document_id[1]))
143 original_addendum.business_document_status = '1'
144 return True
145 journal = self.l10n_hr_mer_purchase_journal_id
146 if not journal:
147 return False
148
149 move = self.env['account.move'].create({
150 'state': 'draft',
151 'journal_id': journal.id,
152 'move_type': 'in_invoice',
153 })
154 if 'is_in_extractable_state' in move._fields:
155 move.is_in_extractable_state = False
156
157 move.l10n_hr_edi_addendum_id = self.env['l10n_hr_edi.addendum'].create({'move_id': move.id, **document})
158 move._extend_with_attachments(move._to_files_data(attachment), new=True)
159 move._message_log(
160 body=self.env._(
161 "eRacun document (ElectroicId: %(electronic_id)s) has been received from MojEracun successfully.",
162 electronic_id=document['mer_document_eid'],
163 ),
164 attachment_ids=attachment.ids,
165 )
166 attachment.write({'res_model': 'account.move', 'res_id': move.id})
167 _logger.info("Successfully imported MER document %s", document['mer_document_eid'])
168 return move
169
170 def _l10n_hr_mer_get_new_documents(self, undelivered_only=True, slc=False, from_cron=False):
171 """
172 Import documents from MojEracun. Additional arguments included for testing.
173 :param undelivered (bool, optional): Import only undelivered documents. Defaults to True.
174 :param notify (bool, optional): Run notify import API after importing. Defaults to True.
175 :param slc (tuple of two ints, optional): Import only a slice of the list of documents for testing. Defaults to False.
176 """
177 job_count = self.env.context.get('mer_crons_job_count') or BATCH_SIZE
178 need_retrigger = False
179 imported_documents = {}
180 for company in self.filtered(lambda c: c.l10n_hr_mer_connection_state == 'active'):
181 try:
182 response = _mer_api_query_inbox(company, 'Undelivered' if undelivered_only else None)
183 except MojEracunServiceError as e:
184 _logger.error('MojEracun service error: %s', e.message)
185 continue
186
187 if any(not (item.get('ElectronicId') and item.get('StatusId')) for item in response):
188 _logger.error("MojEracun service error: incorrect response format while querying inbox for company: %s", company.name)
189 continue
190 documents = [{'mer_document_eid': str(document['ElectronicId']), 'mer_document_status': str(document['StatusId'])} for document in response][::-1]
191 if not documents:
192 continue
193
194 need_retrigger = need_retrigger or len(documents) > job_count
195 documents = documents[:job_count]
196
197 existing_documents = self.env['l10n_hr_edi.addendum'].search([
198 ("mer_document_eid", "in", [i['mer_document_eid'] for i in documents]),
199 ('move_id.company_id', '=', company.id)])
200 documents_to_import = [i for i in documents if i['mer_document_eid'] not in existing_documents.mapped('mer_document_eid')]
201 proxy_acks = []
202 # Retrieve attachments for the document IDs received
203 if slc:
204 documents_to_import = documents_to_import[slc[0]:slc[1]]
205 for document in documents_to_import:
206 try:
207 fisc_data = _mer_api_check_fiscalization_status_inbox(company, electronic_id=document['mer_document_eid'])
208 if fisc_data == []:
209 _logger.error("Fiscalization data for document eID %s is not available on MojEracun server.", document['mer_document_eid'])
210 continue
211 else:
212 fisc_data = fisc_data[0]
213 except (MojEracunServiceError, UserError):
214 _logger.error("Failed to retreive fisc data for document eID %s", document['mer_document_eid'])
215 if from_cron:
216 continue
217 elif company.l10n_hr_mer_connection_mode == 'test':
218 # Bypassing randomness of MER test server responce
219 fisc_data = {'messages': [{
220 'status': '0',
221 'errorCode': None,
222 'errorCodeDescription': 'Nema greške',
223 'fiscalizationRequestId': '00001-test',
224 'businessStatusReason': None,
225 }],
226 'channelType': '0',
227 }
228 else:
229 raise
230 document.update({
231 'fiscalization_status': str(fisc_data['messages'][-1].get('status')),
232 'fiscalization_error': str(fisc_data['messages'][-1].get('errorCode')) + ' - ' + str(fisc_data['messages'][-1].get('errorCodeDescription')),
233 'fiscalization_request': str(fisc_data['messages'][-1].get('fiscalizationRequestId')),
234 'business_status_reason': str(fisc_data['messages'][-1].get('businessStatusReason')),
235 'fiscalization_channel_type': str(fisc_data.get('channelType')),
236 })
237 if document['fiscalization_status'] != '0':
238 _logger.warning("Document eID %s is not successfully fiscalized by MojEracun.", document['mer_document_eid'])
239 try:
240 business_data = _mer_api_query_document_process_status_inbox(company, electronic_id=document['mer_document_eid'])[0]
241 except (MojEracunServiceError, UserError):
242 _logger.error("Failed to retreive business data for document: %s", document['mer_document_eid'])
243 if from_cron:
244 continue
245 elif company.l10n_hr_mer_connection_mode == 'test':
246 # Bypassing randomness of MER test server responce
247 business_data = {
248 'DocumentProcessStatusId': '0',
249 }
250 else:
251 raise
252 document.update({
253 'business_document_status': str(business_data.get('DocumentProcessStatusId')),
254 })
255 try:
256 document_xml = _mer_api_receive_document(company, document['mer_document_eid'])
257 except MojEracunServiceError as e:
258 _logger.error("Failed to retrieve document: %s", e.message)
259 continue
260
261 attachment = self.env["ir.attachment"].create(
262 {
263 "name": f"mojeracun_{document['mer_document_eid']}_attachment.xml",
264 "raw": document_xml,
265 "type": "binary",
266 "mimetype": "application/xml",
267 }
268 )
269 if self._l10n_hr_mer_import_invoice(attachment, document):
270 # Only acknowledge on successful import
271 proxy_acks.append(document['mer_document_eid'])
272 if not tools.config['test_enable']:
273 self.env.cr.commit()
274 _mer_api_notify_import(company, document['mer_document_eid'])
275
276 imported_documents.update({company.id: proxy_acks})
277 if need_retrigger:
278 self.env.ref('l10n_hr_edi.ir_cron_mer_get_new_documents')._trigger()
279 # Return the documents that were successfully imported
280 return imported_documents
281
282 def _l10n_hr_mer_fetch_document_status_company(self, from_cron=False):
283 """
284 Fetch and update the status of up to 20000 documents belonging to a company on MojEracun.
285 """
286 for company in self.filtered(lambda c: c.l10n_hr_mer_connection_state == 'active'):
287 for query_function, check_function in [
288 (_mer_api_query_document_process_status_outbox, _mer_api_check_fiscalization_status_outbox),
289 (_mer_api_query_document_process_status_inbox, _mer_api_check_fiscalization_status_inbox)
290 ]:
291 response_mer = query_function(company, by_update_date=True)
292 documents = {
293 str(item['ElectronicId']): {
294 'mer_document_status': str(item.get('StatusId')),
295 'business_document_status': str(item.get('DocumentProcessStatusId')),
296 } for item in response_mer
297 }
298 try:
299 response_fisc = check_function(company)
300 except (MojEracunServiceError, UserError):
301 _logger.error("Failed to retreive fiscalization data for company %s", company.name)
302 if from_cron or company.l10n_hr_mer_connection_mode == 'test':
303 response_fisc = []
304 else:
305 raise
306 for item in response_fisc:
307 # As we can't fetch all the data with a single query, it's either this or making calls move-by-move
308 # Currently, because of the random nature of responses received from fisc endpoints, this breaks tests
309 if item.get('ElectronicId') in documents:
310 documents[item['ElectronicId']].update({
311 'fiscalization_status': str(item['messages'][-1].get('status')),
312 'fiscalization_error': str(item['messages'][-1].get('errorCode')) + ' - ' + str(item['messages'][-1].get('errorCodeDescription')),
313 'fiscalization_request': str(item['messages'][-1].get('fiscalizationRequestId')),
314 'business_status_reason': str(item['messages'][-1].get('fiscalizationRequestId')),
315 'fiscalization_channel_type': str(item.get('channelType')),
316 })
317 addendums = self.env['l10n_hr_edi.addendum'].search([
318 ("mer_document_eid", "in", list(documents.keys())),
319 ('move_id.company_id', '=', company.id),
320 ])
321 for addendum in addendums:
322 addendum.write(documents[addendum.mer_document_eid])
323
324 def _l10n_hr_mer_archive_signed_xmls(self, from_cron=False):
325 """
326 Download and archive signed XMLs for sent invoices that haven't been archived yet.
327 :param company: The company record
328 :param from_cron: If True, continue on errors instead of raising
329 """
330 moves = self.env['l10n_hr_edi.addendum'].search([
331 ('mer_signed_xml_archived', '=', False),
332 ('mer_document_eid', '!=', False),
333 ('move_id.move_type', 'in', ['out_invoice', 'out_refund']),
334 ('move_id.company_id', '=', self.id),
335 ]).mapped('move_id')
336 for move in moves:
337 try:
338 signed_xml = _mer_api_receive_document(self, move.l10n_hr_mer_document_eid)
339 except MojEracunServiceError as e:
340 _logger.error("Failed to archive signed XML for %s: %s", move.l10n_hr_mer_document_eid, e.message)
341 if not from_cron:
342 raise
343 continue
344 except UserError as e:
345 _logger.error("Failed to archive signed XML for %s: %s", move.l10n_hr_mer_document_eid, str(e))
346 if not from_cron:
347 raise
348 continue
349 attachment = self.env["ir.attachment"].create({
350 "name": f"{move.name.replace('/', '_')}_signed.xml",
351 "raw": signed_xml,
352 "type": "binary",
353 "mimetype": "application/xml",
354 "res_model": "account.move",
355 "res_id": move.id,
356 "description": f"Signed XML from MojEracun (ElectronicId: {move.l10n_hr_mer_document_eid})",
357 })
358 move.l10n_hr_edi_addendum_id.mer_signed_xml_archived = True
359 move._message_log(
360 body=self.env._(
361 "Successfully archived signed XML for eRacun document (ElectroicId: %(eid)s)",
362 eid=move.l10n_hr_mer_document_eid,
363 ),
364 attachment_ids=attachment.ids,
365 )