Debian Codegraph @

addons/l10n_dk_nemhandel/models/res_partner.py

raw
1 import logging
2 import requests
3 from markupsafe import Markup
4 from hashlib import md5
5 from urllib import parse
6
7 from odoo import _, api, fields, models
8 from odoo.exceptions import ValidationError
9
10 from odoo.addons.l10n_dk_nemhandel.tools.demo_utils import handle_demo
11
12 TIMEOUT = 10
13 _logger = logging.getLogger(__name__)
14
15
16 class ResPartner(models.Model):
17 _inherit = 'res.partner'
18
19 invoice_sending_method = fields.Selection(
20 selection_add=[('nemhandel', 'By Nemhandel')],
21 )
22 invoice_edi_format = fields.Selection(selection_add=[('oioubl_21', "OIOUBL 2.1")])
23 nemhandel_verification_state = fields.Selection(
24 selection=[
25 ('not_verified', 'Not verified yet'),
26 ('not_valid', 'Not on Nemhandel'), # Is not on Nemhandel
27 ('valid', 'Valid'),
28 ],
29 string='Nemhandel endpoint verification',
30 company_dependent=True,
31 )
32
33 nemhandel_identifier_type = fields.Selection(
34 string='Nemhandel Endpoint Type',
35 help='Unique identifier used by OIOUBL and Nemhandel',
36 compute="_compute_nemhandel_identifier_type", store=True, readonly=False,
37 tracking=True,
38 selection=[
39 ('0088', "EAN/GLN"),
40 ('0184', "CVR"),
41 ('9918', "IBAN"),
42 ('0198', "SE"),
43 ],
44 )
45 nemhandel_identifier_value = fields.Char(
46 string='Nemhandel Endpoint',
47 help='Code used to identify the Endpoint on Nemhandel',
48 compute="_compute_nemhandel_identifier_value", store=True, readonly=False,
49 tracking=True,
50 )
51
52 is_using_nemhandel = fields.Boolean(compute='_compute_is_using_nemhandel')
53
54 # -------------------------------------------------------------------------
55 # COMPUTE METHODS
56 # -------------------------------------------------------------------------
57
58 @api.depends('country_code', 'vat', 'company_registry')
59 def _compute_nemhandel_identifier_type(self):
60 for partner in self:
61 partner.nemhandel_identifier_type = partner.nemhandel_identifier_type
62 country_code = partner._deduce_country_code()
63 if country_code == 'DK' and not partner.nemhandel_identifier_type:
64 partner.nemhandel_identifier_type = '0184'
65 elif country_code != 'DK':
66 partner.nemhandel_identifier_type = ''
67
68 @api.depends('country_code', 'vat', 'company_registry', 'nemhandel_identifier_type')
69 def _compute_nemhandel_identifier_value(self):
70 for partner in self:
71 if partner.nemhandel_identifier_value != partner._origin.nemhandel_identifier_value:
72 # value changed, don't override it
73 partner.nemhandel_identifier_value = partner.nemhandel_identifier_value
74 continue
75 country_code = partner._deduce_country_code()
76 if country_code == 'DK' and partner.nemhandel_identifier_type == '0184':
77 partner.nemhandel_identifier_value = partner.company_registry
78 elif country_code == 'DK':
79 partner.nemhandel_identifier_value = partner.nemhandel_identifier_value
80 else:
81 partner.nemhandel_identifier_value = ''
82
83 @api.depends_context('allowed_company_ids')
84 @api.depends('invoice_edi_format')
85 def _compute_is_using_nemhandel(self):
86 nemhandel_user = self.env.company.sudo().nemhandel_edi_user
87 for partner in self:
88 partner.is_using_nemhandel = nemhandel_user and partner.invoice_edi_format == 'oioubl_21'
89
90 # -------------------------------------------------------------------------
91 # CONSTRAINT
92 # -------------------------------------------------------------------------
93
94 @api.constrains('invoice_edi_format', 'invoice_sending_method')
95 def _check_nemhandel_send_oioubl(self):
96 if self.filtered(lambda partner: partner.invoice_edi_format != 'oioubl_21' and partner.invoice_sending_method == 'nemhandel'):
97 raise ValidationError(_('On Nemhandel, only OIOUBL 2.1 is supported.'))
98
99 # -------------------------------------------------------------------------
100 # OVERRIDE AND HELPERS
101 # -------------------------------------------------------------------------
102
103 def _get_edi_builder(self, invoice_edi_format):
104 # EXTENDS 'account_edi_ubl_cii'
105 if invoice_edi_format == 'oioubl_21':
106 return self.env['account.edi.xml.oioubl_21']
107 return super()._get_edi_builder(invoice_edi_format)
108
109 def _get_ubl_cii_formats_info(self):
110 # EXTENDS 'account_edi_ubl_cii'
111 formats_info = super()._get_ubl_cii_formats_info()
112 formats_info['oioubl_21'] = {'countries': ['DK'], 'on_peppol': False}
113 return formats_info
114
115 def _get_suggested_invoice_edi_format(self):
116 # EXTENDS 'account'
117 if self.country_code == 'DK':
118 return 'oioubl_21'
119 return super()._get_suggested_invoice_edi_format()
120
121 @api.model
122 def _get_nemhandel_participant_info(self, edi_identification):
123 hash_participant = md5(edi_identification.lower().encode()).hexdigest()
124 endpoint_participant = parse.quote_plus(f"iso6523-actorid-upis::{edi_identification}")
125 nemhandel_user = self.env.company.sudo().nemhandel_edi_user
126 edi_mode = nemhandel_user and nemhandel_user.edi_mode or self.env['ir.config_parameter'].sudo().get_param('l10n_dk_nemhandel.edi.mode')
127 sml_zone = 'edel.sml-demo' if edi_mode == 'test' else 'edel.sml'
128 smp_url = f"http://B-{hash_participant}.iso6523-actorid-upis.{sml_zone}.dataudveksling.dk/{endpoint_participant}"
129 try:
130 response = requests.get(smp_url, timeout=TIMEOUT)
131 response.raise_for_status()
132 except requests.exceptions.RequestException as e:
133 _logger.info(e)
134 return None
135 return response.content
136
137 @api.model
138 def _nemhandel_lookup_participant(self, edi_identification):
139 """NAPTR DNS nemhandel participant lookup through Odoo's Nemhandel proxy"""
140 if (edi_mode := self.env.company._get_nemhandel_edi_mode()) == 'demo':
141 return
142
143 sml_zone = f"edel.sml{'-demo' if edi_mode == 'test' else ''}.dataudveksling.dk"
144 origin = self.env['account_edi_proxy_client.user']._get_proxy_urls()['nemhandel'][edi_mode]
145 query = parse.urlencode({'peppol_identifier': edi_identification.lower(), 'zone': sml_zone})
146 endpoint = f'{origin}/api/peppol/1/lookup?{query}'
147
148 try:
149 response = requests.get(endpoint, timeout=TIMEOUT)
150 except requests.exceptions.RequestException as e:
151 _logger.error("failed to query nemhandel participant %s: %s", edi_identification, e)
152 return
153
154 if not response.ok:
155 _logger.info('unsuccessful response %s when querying nemhandel participant %s', response.status_code, edi_identification)
156 return
157
158 try:
159 decoded_response = response.json()
160 except ValueError:
161 _logger.error('invalid JSON response %s when querying nemhandel participant %s', response.status_code, edi_identification)
162 return
163
164 if error := decoded_response.get('error'):
165 if error.get('code') != 'NOT_FOUND':
166 _logger.error('error when querying nemhandel participant %s: %s', edi_identification, error.get('message', 'unknown error'))
167 return
168
169 return decoded_response.get('result')
170
171 def _l10n_dk_nemhandel_log_verification_state_update(self, company, old_value, new_value):
172 # log the update of the nemhandel verification state
173 # we do this instead of regular tracking because of the customized message
174 # and because we want to log the change for every company in the db
175 if old_value == new_value:
176 return
177
178 nemhandel_verification_state_field = self._fields['nemhandel_verification_state']
179 selection_values = dict(nemhandel_verification_state_field.selection)
180 old_label = selection_values[old_value] if old_value else False # get translated labels
181 new_label = selection_values[new_value] if new_value else False
182
183 body = Markup("""
184 <ul>
185 <li>
186 <span class='o-mail-Message-trackingOld me-1 px-1 text-muted fw-bold'>{old}</span>
187 <i class='o-mail-Message-trackingSeparator fa fa-long-arrow-right mx-1 text-600'/>
188 <span class='o-mail-Message-trackingNew me-1 fw-bold text-info'>{new}</span>
189 <span class='o-mail-Message-trackingField ms-1 fst-italic text-muted'>({field})</span>
190 <span class='o-mail-Message-trackingCompany ms-1 fst-italic text-muted'>({company})</span>
191 </li>
192 </ul>
193 """).format(
194 old=old_label,
195 new=new_label,
196 field=nemhandel_verification_state_field.string,
197 company=company.display_name,
198 )
199 self._message_log(body=body)
200
201 @api.model
202 def _check_nemhandel_participant_exists(self, participant_info, edi_identification):
203 service_href = ''
204 if isinstance(participant_info, dict):
205 participant_identifier = participant_info.get('identifier', '')
206 if services := participant_info.get('services', []):
207 service_href = services[0].get('href', '')
208 else:
209 # DEPRECATED: we now use Odoo peppol API to fetch participant info and get a json response
210 # keeping this branch for compatibility
211 participant_identifier = participant_info.findtext('{*}ParticipantIdentifier') or ''
212 service_metadata = participant_info.find('.//{*}ServiceMetadataReference')
213 if service_metadata is not None:
214 service_href = service_metadata.attrib.get('href', '')
215
216 nemhandel_user = self.env.company.sudo().nemhandel_edi_user
217 edi_mode = nemhandel_user and nemhandel_user.edi_mode or self.env['ir.config_parameter'].sudo().get_param('l10n_dk_nemhandel.edi.mode')
218 smp_nemhandel_url = 'smp-demo.nemhandel.dk' if edi_mode == 'test' else 'smp.nemhandel.dk'
219
220 return edi_identification.lower() == participant_identifier.lower() and parse.urlsplit(service_href).netloc == smp_nemhandel_url
221
222 def _update_nemhandel_state_per_company(self, vals=None):
223 partners = self.env['res.partner']
224 if vals is None:
225 partners = self.filtered(lambda p: all([p.nemhandel_identifier_type, p.nemhandel_identifier_value, p.is_using_nemhandel]))
226 elif {'nemhandel_identifier_type', 'nemhandel_identifier_value', 'is_using_nemhandel'}.intersection(vals.keys()):
227 partners = self.filtered(lambda p: p.is_using_nemhandel)
228
229 all_companies = None
230 for partner in partners.sudo():
231 if partner.company_id:
232 partner.button_nemhandel_check_partner_endpoint(company=partner.company_id)
233 continue
234
235 if all_companies is None:
236 all_companies = self.env['res.company'].sudo().search([])
237
238 for company in all_companies:
239 partner.button_nemhandel_check_partner_endpoint(company=company)
240
241 # -------------------------------------------------------------------------
242 # LOW-LEVEL METHODS
243 # -------------------------------------------------------------------------
244
245 def write(self, vals):
246 res = super().write(vals)
247 self._update_nemhandel_state_per_company(vals=vals)
248 return res
249
250 @api.model_create_multi
251 def create(self, vals_list):
252 res = super().create(vals_list)
253 if res:
254 res._update_nemhandel_state_per_company()
255 return res
256
257 # -------------------------------------------------------------------------
258 # ACTIONS
259 # -------------------------------------------------------------------------
260
261 @handle_demo
262 def button_nemhandel_check_partner_endpoint(self, company=None):
263 """ A basic check for whether a participant is reachable at the given identifier_type and identifier_value
264 """
265 self.ensure_one()
266 if not company:
267 company = self.env.company
268
269 self_partner = self.with_company(company)
270 old_value = self_partner.nemhandel_verification_state
271 self_partner.nemhandel_verification_state = self._get_nemhandel_verification_state(self_partner.invoice_edi_format)
272 if self_partner.nemhandel_verification_state == 'valid' and not self_partner.invoice_sending_method:
273 self_partner.invoice_sending_method = 'nemhandel'
274
275 self._l10n_dk_nemhandel_log_verification_state_update(company, old_value, self_partner.nemhandel_verification_state)
276 return False
277
278 @handle_demo
279 def _get_nemhandel_verification_state(self, invoice_edi_format):
280 self.ensure_one()
281 if not self.nemhandel_identifier_type or not self.nemhandel_identifier_value or invoice_edi_format != 'oioubl_21':
282 return 'not_verified'
283
284 edi_identification = f"{self.nemhandel_identifier_type}:{self.nemhandel_identifier_value}".lower()
285 participant_info = self._nemhandel_lookup_participant(edi_identification)
286 if participant_info is None:
287 return 'not_valid'
288
289 is_participant_on_network = self._check_nemhandel_participant_exists(participant_info, edi_identification)
290 return 'valid' if is_participant_on_network else 'not_valid'