Debian Codegraph @

addons/l10n_ch/models/res_bank.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 # Part of Odoo. See LICENSE file for full copyright and licensing details.
3
4 import re
5 from stdnum.util import clean
6
7 from odoo import api, fields, models, _
8 from odoo.addons.base.models.res_bank import sanitize_account_number
9 from odoo.addons.base_iban.models.res_partner_bank import normalize_iban, pretty_iban, validate_iban, get_iban_part
10 from odoo.exceptions import ValidationError
11 from odoo.tools import LazyTranslate, street_split
12 from odoo.tools.misc import mod10r
13
14 _lt = LazyTranslate(__name__)
15
16
17 def validate_qr_iban(qr_iban):
18 # Check first if it's a valid IBAN.
19 validate_iban(qr_iban)
20
21 # We sanitize first so that _check_qr_iban_range() can extract correct IID from IBAN to validate it.
22 sanitized_qr_iban = sanitize_account_number(qr_iban)
23
24 if sanitized_qr_iban[:2] not in ['CH', 'LI']:
25 raise ValidationError(_lt("QR-IBAN numbers are only available in Switzerland."))
26
27 # Now, check if it's valid QR-IBAN (based on its IID).
28 if not check_qr_iban_range(sanitized_qr_iban):
29 raise ValidationError(_lt("QR-IBAN ā€œ%sā€ is invalid.", qr_iban))
30
31 return True
32
33 def check_qr_iban_range(iban):
34 if not iban or len(iban) < 9:
35 return False
36 iid = get_iban_part(iban, 'bank')
37 return re.match(r'\d+', iid) and 30000 <= int(iid) <= 31999 # Those values for iid are reserved for QR-IBANs only
38
39
40 class ResPartnerBank(models.Model):
41 _inherit = 'res.partner.bank'
42
43 l10n_ch_qr_iban = fields.Char(string='QR-IBAN',
44 compute='_compute_l10n_ch_qr_iban',
45 store=True,
46 readonly=False,
47 help="Put the QR-IBAN here for your own bank accounts. That way, you can "
48 "still use the main IBAN in the Account Number while you will see the "
49 "QR-IBAN for the barcode. ")
50
51 # fields to configure payment slip generation
52 l10n_ch_display_qr_bank_options = fields.Boolean(compute='_compute_l10n_ch_display_qr_bank_options')
53
54 @api.depends('partner_id', 'company_id')
55 def _compute_l10n_ch_display_qr_bank_options(self):
56 for bank in self:
57 if bank.partner_id:
58 bank.l10n_ch_display_qr_bank_options = bank.partner_id.ref_company_ids.country_id.code in ('CH', 'LI')
59 elif bank.company_id:
60 bank.l10n_ch_display_qr_bank_options = bank.company_id.account_fiscal_country_id.code in ('CH', 'LI')
61 else:
62 bank.l10n_ch_display_qr_bank_options = self.env.company.account_fiscal_country_id.code in ('CH', 'LI')
63
64 @api.depends('acc_number')
65 def _compute_l10n_ch_qr_iban(self):
66 for record in self:
67 try:
68 validate_qr_iban(record.acc_number)
69 valid_qr_iban = True
70 except ValidationError:
71 valid_qr_iban = False
72 if valid_qr_iban:
73 record.l10n_ch_qr_iban = record.sanitized_acc_number
74 else:
75 record.l10n_ch_qr_iban = None
76
77 @api.model_create_multi
78 def create(self, vals_list):
79 for vals in vals_list:
80 if vals.get('l10n_ch_qr_iban'):
81 validate_qr_iban(vals['l10n_ch_qr_iban'])
82 vals['l10n_ch_qr_iban'] = pretty_iban(normalize_iban(vals['l10n_ch_qr_iban']))
83 return super().create(vals_list)
84
85 def write(self, vals):
86 if vals.get('l10n_ch_qr_iban'):
87 validate_qr_iban(vals['l10n_ch_qr_iban'])
88 vals['l10n_ch_qr_iban'] = pretty_iban(normalize_iban(vals['l10n_ch_qr_iban']))
89 return super().write(vals)
90
91 def _l10n_ch_get_qr_vals(self, amount, currency, debtor_partner, free_communication, structured_communication):
92 comment = ""
93 if free_communication:
94 comment = (free_communication[:137] + '...') if len(free_communication) > 140 else free_communication
95
96 cred_street, cred_street_number, cred_zip, cred_city = self._get_partner_address_lines(self.partner_id)
97 debt_street, debt_street_number, debt_zip, debt_city = self._get_partner_address_lines(debtor_partner)
98
99 # Compute reference type (empty by default, only mandatory for QR-IBAN,
100 # and must then be 27 characters-long, with mod10r check digit as the 27th one)
101 reference_type = 'NON'
102 reference = ''
103 acc_number = self.sanitized_acc_number
104
105 if self.l10n_ch_qr_iban:
106 # _check_for_qr_code_errors ensures we can't have a QR-IBAN without a QR-reference here
107 reference_type = 'QRR'
108 reference = structured_communication
109 acc_number = sanitize_account_number(self.l10n_ch_qr_iban)
110 elif self._is_iso11649_reference(structured_communication):
111 reference_type = 'SCOR'
112 reference = structured_communication.replace(' ', '')
113
114 currency = currency or self.currency_id or self.company_id.currency_id
115
116 result = [
117 'SPC', # QR Type
118 '0200', # Version
119 '1', # Coding Type
120 acc_number, # IBAN / QR-IBAN
121 'S', # Creditor Address Type
122 (self.acc_holder_name or self.partner_id.name)[:70], # Creditor Name
123 cred_street, # Creditor Street Name
124 cred_street_number, # Creditor Building Number
125 cred_zip, # Creditor Postal Code
126 cred_city, # Creditor Town
127 self.partner_id.country_id.code, # Creditor Country
128 '', # Ultimate Creditor Address Type
129 '', # Name
130 '', # Ultimate Creditor Address Line 1
131 '', # Ultimate Creditor Address Line 2
132 '', # Ultimate Creditor Postal Code
133 '', # Ultimate Creditor Town
134 '', # Ultimate Creditor Country
135 '{:.2f}'.format(amount), # Amount
136 currency.name, # Currency
137 'S', # Ultimate Debtor Address Type
138 debtor_partner.commercial_partner_id.name[:70], # Ultimate Debtor Name
139 debt_street, # Ultimate Debtor Street Name
140 debt_street_number, # Ultimate Debtor Building Number
141 debt_zip, # Ultimate Debtor Postal Code
142 debt_city, # Ultimate Debtor Town
143 debtor_partner.country_id.code, # Ultimate Debtor Country
144 reference_type, # Reference Type
145 reference, # Reference
146 comment, # Unstructured Message
147 'EPD', # Mandatory trailer part
148 ]
149
150 # newlines shift field content to a different line, causing the QR code to be rejected
151 return [line.replace('\n', ' ') for line in result]
152
153 def _get_qr_vals(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
154 if qr_method == 'ch_qr':
155 return self._l10n_ch_get_qr_vals(amount, currency, debtor_partner, free_communication, structured_communication)
156 return super()._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
157
158 def _get_qr_code_generation_params(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
159 if qr_method == 'ch_qr':
160 return {
161 'barcode_type': 'QR',
162 'width': 256,
163 'height': 256,
164 'quiet': 0,
165 'mask': 'ch_cross',
166 'value': '\n'.join(self._get_qr_vals(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)),
167 # Swiss QR code requires Error Correction Level = 'M' by specification
168 'barLevel': 'M',
169 }
170 return super()._get_qr_code_generation_params(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
171
172 def _get_partner_address_lines(self, partner):
173 """ Retrieves the partner's address fields, truncated to respect the line specs.
174 :returns: tuple(street, street_number, zip, city)
175 """
176 street_1_split = street_split(partner.street or '')
177 street_name = street_1_split['street_name']
178 building_number = f"{street_1_split['street_number']} {street_1_split['street_number2']}".strip()
179
180 if building_number:
181 concatenated_building_number = f"{building_number} {partner.street2 or ''}".strip()
182 if len(concatenated_building_number) <= 16:
183 building_number = concatenated_building_number
184 else:
185 # Try to complete the address with street2
186 street_2_split = street_split(partner.street2 or '')
187
188 building_number = f"{street_2_split['street_number']} {street_2_split['street_number2']}".strip()
189 if building_number:
190 street_name = f"{street_name} {street_2_split['street_name']}".strip()
191 else:
192 building_number = (partner.street2 or '').strip()
193
194 return street_name[:70], building_number[:16], partner.zip[:16], partner.city[:35]
195
196 @api.model
197 def _is_qr_reference(self, reference):
198 """ Checks whether the given reference is a QR-reference, i.e. it is
199 made of 27 digits, the 27th being a mod10r check on the 26 previous ones.
200 """
201 return reference \
202 and len(reference) == 27 \
203 and re.match(r'\d+$', reference) \
204 and reference == mod10r(reference[:-1])
205
206 @api.model
207 def _is_iso11649_reference(self, reference):
208 """ Checks whether the given reference is a ISO11649 (SCOR) reference.
209 """
210 return reference \
211 and len(reference) >= 5 \
212 and len(reference) <= 25 \
213 and reference.startswith('RF') \
214 and int(''.join(str(int(x, 36)) for x in clean(reference[4:] + reference[:4], ' -.,/:').upper().strip())) % 97 == 1
215 # see https://github.com/arthurdejong/python-stdnum/blob/master/stdnum/iso11649.py
216
217 def _l10n_ch_qr_debtor_check(self, debtor_partner):
218 """ This method should be used in _get_error_messages_for_qr and _check_for_qr_code_errors
219 It allows is to permit to set this qr method if a partner is not yet provided when executing _get_error_messages_for_qr
220 while preventing to print qr code when executing _check_for_qr_code_errors if the partner is not provided
221 """
222 if not debtor_partner or debtor_partner.country_id.code not in ('CH', 'LI'):
223 return _("The debtor partner's address isn't located in Switzerland.")
224 return False
225
226 def _get_error_messages_for_qr(self, qr_method, debtor_partner, currency):
227 def _get_error_for_ch_qr():
228 error_messages = [_("The Swiss QR code could not be generated for the following reason(s):")]
229 if self.acc_type != 'iban':
230 error_messages.append(_("The account type isn't QR-IBAN or IBAN."))
231 debtor_check = self._l10n_ch_qr_debtor_check(debtor_partner)
232 if debtor_partner and debtor_check:
233 error_messages.append(debtor_check)
234 if currency.id not in (self.env.ref('base.EUR').id, self.env.ref('base.CHF').id):
235 error_messages.append(_("The currency isn't EUR nor CHF."))
236 return '\r\n'.join(error_messages) if len(error_messages) > 1 else None
237
238 if qr_method == 'ch_qr':
239 return _get_error_for_ch_qr()
240 return super()._get_error_messages_for_qr(qr_method, debtor_partner, currency)
241
242 def _check_for_qr_code_errors(self, qr_method, amount, currency, debtor_partner, free_communication, structured_communication):
243 def _partner_fields_set(partner):
244 return partner.zip and \
245 partner.city and \
246 partner.country_id.code and \
247 (partner.street or partner.street2)
248
249 if qr_method == 'ch_qr':
250 if not _partner_fields_set(self.partner_id):
251 return _("The partner set on the bank account meant to receive the payment (%s) must have a complete postal address (street, zip, city and country).", self.acc_number)
252
253 if debtor_partner and not _partner_fields_set(debtor_partner):
254 return _("The partner must have a complete postal address (street, zip, city and country).")
255
256 if self.l10n_ch_qr_iban and not self._is_qr_reference(structured_communication):
257 return _("When using a QR-IBAN as the destination account of a QR-code, the payment reference must be a QR-reference.")
258
259 debtor_check = self._l10n_ch_qr_debtor_check(debtor_partner)
260 if debtor_check:
261 return debtor_check
262
263 return super()._check_for_qr_code_errors(qr_method, amount, currency, debtor_partner, free_communication, structured_communication)
264
265 @api.model
266 def _get_available_qr_methods(self):
267 rslt = super()._get_available_qr_methods()
268 rslt.append(('ch_qr', _("Swiss QR bill"), 10))
269 return rslt