| 1 |
import base64 |
| 2 |
import requests |
| 3 |
import uuid |
| 4 |
from werkzeug.urls import url_encode |
| 5 |
|
| 6 |
from odoo import _, api, fields, models |
| 7 |
from odoo.exceptions import ValidationError |
| 8 |
|
| 9 |
JOFOTARA_URL = "https://backend.jofotara.gov.jo/core/invoices/" |
| 10 |
|
| 11 |
|
| 12 |
class AccountMove(models.Model): |
| 13 |
_inherit = 'account.move' |
| 14 |
|
| 15 |
l10n_jo_edi_uuid = fields.Char(string="Invoice UUID", copy=False, compute="_compute_l10n_jo_edi_uuid", store=True) |
| 16 |
l10n_jo_edi_qr = fields.Char(string="QR", copy=False) |
| 17 |
|
| 18 |
l10n_jo_edi_is_needed = fields.Boolean( |
| 19 |
compute="_compute_l10n_jo_edi_is_needed", |
| 20 |
help="Jordan: technical field to determine if this invoice is eligible to be e-invoiced.", |
| 21 |
) |
| 22 |
l10n_jo_edi_state = fields.Selection( |
| 23 |
selection=[('to_send', 'To Send'), ('sent', 'Sent'), ('demo', 'Sent (Demo)')], |
| 24 |
string="JoFotara State", |
| 25 |
tracking=True, |
| 26 |
copy=False) |
| 27 |
l10n_jo_edi_error = fields.Text( |
| 28 |
string="JoFotara Error", |
| 29 |
copy=False, |
| 30 |
readonly=True, |
| 31 |
help="Jordan: Error details.", |
| 32 |
) |
| 33 |
l10n_jo_edi_computed_xml = fields.Binary( |
| 34 |
string="Jordan E-Invoice computed XML File", |
| 35 |
compute="_compute_l10n_jo_edi_computed_xml", |
| 36 |
help="Jordan: technical field computing e-invoice XML data, useful at submission failure scenarios.", |
| 37 |
) |
| 38 |
l10n_jo_edi_xml_attachment_file = fields.Binary( |
| 39 |
string="Jordan E-Invoice XML File", |
| 40 |
copy=False, |
| 41 |
attachment=True, |
| 42 |
help="Jordan: technical field holding the e-invoice XML data.", |
| 43 |
) |
| 44 |
l10n_jo_edi_xml_attachment_id = fields.Many2one( |
| 45 |
comodel_name="ir.attachment", |
| 46 |
string="Jordan E-Invoice XML", |
| 47 |
compute=lambda self: self._compute_linked_attachment_id( |
| 48 |
"l10n_jo_edi_xml_attachment_id", "l10n_jo_edi_xml_attachment_file" |
| 49 |
), |
| 50 |
depends=["l10n_jo_edi_xml_attachment_file"], |
| 51 |
help="Jordan: e-invoice XML.", |
| 52 |
) |
| 53 |
reversed_entry_id = fields.Many2one(tracking=True) |
| 54 |
l10n_jo_edi_invoice_type = fields.Selection( |
| 55 |
selection=[ |
| 56 |
('local', 'Local'), |
| 57 |
('export', 'Export'), |
| 58 |
('development', 'Development Area'), |
| 59 |
], |
| 60 |
string="Invoice Type", |
| 61 |
precompute=True, |
| 62 |
compute='_compute_l10n_jo_edi_invoice_type', |
| 63 |
readonly=False, store=True, |
| 64 |
tracking=True, |
| 65 |
help="Invoice Types as per the Income and Sales Tax Department for JoFotara", |
| 66 |
) |
| 67 |
|
| 68 |
@api.depends("country_code", "move_type") |
| 69 |
def _compute_l10n_jo_edi_is_needed(self): |
| 70 |
for move in self: |
| 71 |
move.l10n_jo_edi_is_needed = ( |
| 72 |
move.country_code == "JO" |
| 73 |
and move.move_type in ("out_invoice", "out_refund") |
| 74 |
) |
| 75 |
|
| 76 |
@api.depends("l10n_jo_edi_state") |
| 77 |
def _compute_show_reset_to_draft_button(self): |
| 78 |
|
| 79 |
super()._compute_show_reset_to_draft_button() |
| 80 |
self.filtered(lambda move: move.l10n_jo_edi_state == 'sent').show_reset_to_draft_button = False |
| 81 |
|
| 82 |
@api.depends("l10n_jo_edi_is_needed") |
| 83 |
def _compute_l10n_jo_edi_uuid(self): |
| 84 |
for invoice in self: |
| 85 |
if invoice.l10n_jo_edi_is_needed and not invoice.l10n_jo_edi_uuid: |
| 86 |
invoice.l10n_jo_edi_uuid = uuid.uuid4() |
| 87 |
|
| 88 |
@api.depends("state", "l10n_jo_edi_is_needed") |
| 89 |
def _compute_l10n_jo_edi_computed_xml(self): |
| 90 |
for invoice in self: |
| 91 |
if invoice.state == 'posted' and invoice.l10n_jo_edi_is_needed: |
| 92 |
xml_content = self.env['account.edi.xml.ubl_21.jo']._export_invoice(invoice)[0] |
| 93 |
invoice.l10n_jo_edi_computed_xml = base64.b64encode(xml_content) |
| 94 |
else: |
| 95 |
invoice.l10n_jo_edi_computed_xml = False |
| 96 |
|
| 97 |
@api.depends('partner_id.country_code') |
| 98 |
def _compute_l10n_jo_edi_invoice_type(self): |
| 99 |
for move in self.filtered(lambda m: m.l10n_jo_edi_is_needed and m.l10n_jo_edi_invoice_type != 'development'): |
| 100 |
country_code = move.commercial_partner_id.country_code |
| 101 |
if country_code == 'JO': |
| 102 |
move.l10n_jo_edi_invoice_type = 'local' |
| 103 |
elif country_code: |
| 104 |
move.l10n_jo_edi_invoice_type = 'export' |
| 105 |
else: |
| 106 |
move.l10n_jo_edi_invoice_type = False |
| 107 |
|
| 108 |
@api.depends('partner_id', 'company_id') |
| 109 |
def _compute_preferred_payment_method_line_id(self): |
| 110 |
super()._compute_preferred_payment_method_line_id() |
| 111 |
|
| 112 |
for move in self.filtered(lambda m: m.partner_id and m.l10n_jo_edi_is_needed): |
| 113 |
expected_type = 'bank' if move.partner_id.is_company or move.partner_id.parent_id else 'cash' |
| 114 |
journal = self.env['account.journal'].search([ |
| 115 |
('type', '=', expected_type), |
| 116 |
('company_id', '=', move.company_id.id), |
| 117 |
('inbound_payment_method_line_ids', '!=', False), |
| 118 |
], limit=1) |
| 119 |
if journal and (payment_method_line := journal.inbound_payment_method_line_ids[0]): |
| 120 |
move.preferred_payment_method_line_id = payment_method_line |
| 121 |
|
| 122 |
def download_l10n_jo_edi_computed_xml(self): |
| 123 |
if error_message := self._l10n_jo_validate_config() or self._l10n_jo_validate_fields(): |
| 124 |
raise ValidationError(_("The following errors have to be fixed in order to create an XML:\n") + error_message) |
| 125 |
params = url_encode({ |
| 126 |
'model': self._name, |
| 127 |
'id': self.id, |
| 128 |
'field': 'l10n_jo_edi_computed_xml', |
| 129 |
'filename': self._l10n_jo_edi_get_xml_attachment_name(), |
| 130 |
'mimetype': 'application/xml', |
| 131 |
'download': 'true', |
| 132 |
}) |
| 133 |
return {'type': 'ir.actions.act_url', 'url': '/web/content/?' + params, 'target': 'new'} |
| 134 |
|
| 135 |
def _l10n_jo_qr_code_src(self): |
| 136 |
self.ensure_one() |
| 137 |
encoded_params = url_encode({ |
| 138 |
'barcode_type': 'QR', |
| 139 |
'quiet': 0, |
| 140 |
'value': self.l10n_jo_edi_qr, |
| 141 |
'width': 200, |
| 142 |
'height': 200, |
| 143 |
}) |
| 144 |
return f'/report/barcode/?{encoded_params}' |
| 145 |
|
| 146 |
def _is_sales_refund(self): |
| 147 |
self.ensure_one() |
| 148 |
return self.company_id.l10n_jo_edi_taxpayer_type == 'sales' and self.move_type == 'out_refund' |
| 149 |
|
| 150 |
def _get_invoice_scope_code(self): |
| 151 |
return { |
| 152 |
'local': '0', |
| 153 |
'export': '1', |
| 154 |
'development': '2', |
| 155 |
}.get(self.l10n_jo_edi_invoice_type, '0') |
| 156 |
|
| 157 |
def _get_invoice_payment_method_code(self): |
| 158 |
return '1' if self.preferred_payment_method_line_id.journal_id.type == 'cash' else '2' |
| 159 |
|
| 160 |
def _get_invoice_tax_payer_type_code(self): |
| 161 |
return { |
| 162 |
'income': '1', |
| 163 |
'sales': '2', |
| 164 |
'special': '3', |
| 165 |
}.get(self.company_id.l10n_jo_edi_taxpayer_type, '1') |
| 166 |
|
| 167 |
def button_draft(self): |
| 168 |
|
| 169 |
self.write( |
| 170 |
{ |
| 171 |
"l10n_jo_edi_error": False, |
| 172 |
"l10n_jo_edi_state": False, |
| 173 |
"l10n_jo_edi_qr": False, |
| 174 |
} |
| 175 |
) |
| 176 |
return super().button_draft() |
| 177 |
|
| 178 |
def _get_fields_to_detach(self): |
| 179 |
|
| 180 |
fields_list = super()._get_fields_to_detach() |
| 181 |
fields_list.append('l10n_jo_edi_xml_attachment_file') |
| 182 |
return fields_list |
| 183 |
|
| 184 |
def _post(self, soft=True): |
| 185 |
|
| 186 |
for invoice in self.filtered('l10n_jo_edi_is_needed'): |
| 187 |
invoice.l10n_jo_edi_state = 'to_send' |
| 188 |
return super()._post(soft) |
| 189 |
|
| 190 |
def _get_name_invoice_report(self): |
| 191 |
|
| 192 |
self.ensure_one() |
| 193 |
if self.l10n_jo_edi_state in ['sent', 'demo'] and self.l10n_jo_edi_xml_attachment_id: |
| 194 |
return 'l10n_jo_edi.report_invoice_document' |
| 195 |
return super()._get_name_invoice_report() |
| 196 |
|
| 197 |
def _l10n_jo_build_jofotara_headers(self): |
| 198 |
self.ensure_one() |
| 199 |
return { |
| 200 |
'Client-Id': self.sudo().company_id.l10n_jo_edi_client_identifier, |
| 201 |
'Secret-Key': self.sudo().company_id.l10n_jo_edi_secret_key, |
| 202 |
} |
| 203 |
|
| 204 |
def _send_l10n_jo_edi_request(self, params, headers): |
| 205 |
if self.env.company.l10n_jo_edi_demo_mode: |
| 206 |
return {'EINV_QR': "Demo JoFotara QR"} |
| 207 |
|
| 208 |
try: |
| 209 |
response = requests.post(JOFOTARA_URL, json=params, headers=headers, timeout=50) |
| 210 |
except requests.exceptions.Timeout: |
| 211 |
return {'error': _("Request timeout! Please try again.")} |
| 212 |
except requests.exceptions.RequestException as e: |
| 213 |
return {'error': _("Invalid request: %s", e)} |
| 214 |
|
| 215 |
if not response.ok: |
| 216 |
content = response.content.decode() |
| 217 |
if response.status_code == 403: |
| 218 |
content = _("Access forbidden. Please verify your JoFotara credentials.") |
| 219 |
return {'error': _("Request failed: %s", content)} |
| 220 |
dict_response = response.json() |
| 221 |
return dict_response |
| 222 |
|
| 223 |
def _submit_to_jofotara(self): |
| 224 |
self.ensure_one() |
| 225 |
headers = self._l10n_jo_build_jofotara_headers() |
| 226 |
xml_invoice = self.env['account.edi.xml.ubl_21.jo']._export_invoice(self)[0] |
| 227 |
params = {'invoice': base64.b64encode(xml_invoice).decode()} |
| 228 |
dict_response = self._send_l10n_jo_edi_request(params, headers) |
| 229 |
if 'error' in dict_response and len(dict_response) == 1: |
| 230 |
return dict_response['error'] |
| 231 |
self.l10n_jo_edi_qr = str(dict_response.get('EINV_QR', '')) |
| 232 |
self.invoice_pdf_report_id.res_field = False |
| 233 |
self.env["ir.attachment"].create( |
| 234 |
{ |
| 235 |
"res_model": "account.move", |
| 236 |
"res_id": self.id, |
| 237 |
"res_field": "l10n_jo_edi_xml_attachment_file", |
| 238 |
"name": self._l10n_jo_edi_get_xml_attachment_name(), |
| 239 |
"raw": xml_invoice, |
| 240 |
} |
| 241 |
) |
| 242 |
|
| 243 |
def _l10n_jo_edi_get_xml_attachment_name(self): |
| 244 |
return f"{self.name.replace('/', '_')}_edi.xml" |
| 245 |
|
| 246 |
def _l10n_jo_validate_config(self): |
| 247 |
error_msgs = [] |
| 248 |
if not self.sudo().company_id.l10n_jo_edi_client_identifier: |
| 249 |
error_msgs.append(_("Client ID is missing.")) |
| 250 |
if not self.sudo().company_id.l10n_jo_edi_secret_key: |
| 251 |
error_msgs.append(_("Secret key is missing.")) |
| 252 |
if not self.company_id.l10n_jo_edi_taxpayer_type: |
| 253 |
error_msgs.append(_("Taxpayer type is missing.")) |
| 254 |
if not self.company_id.l10n_jo_edi_sequence_income_source: |
| 255 |
error_msgs.append(_("Activity number (Sequence of income source) is missing.")) |
| 256 |
|
| 257 |
if error_msgs: |
| 258 |
return _("%s \nTo set: Configuration > Settings > Electronic Invoicing (Jordan)", "\n".join(error_msgs)) |
| 259 |
|
| 260 |
def _l10n_jo_validate_fields(self): |
| 261 |
def has_non_digit_vat(partner, partner_type, error_msgs): |
| 262 |
if partner.vat and not partner.vat.isdigit(): |
| 263 |
error_msgs.append(_("JoFotara portal cannot process %s VAT with non-digit characters in it", partner_type)) |
| 264 |
|
| 265 |
error_msgs = [] |
| 266 |
|
| 267 |
if not self.preferred_payment_method_line_id: |
| 268 |
error_msgs.append(_("Please select a payment method before submission.")) |
| 269 |
if not self.l10n_jo_edi_invoice_type: |
| 270 |
error_msgs.append(_("Please select an invoice type before submitting this invoice to JoFotara.")) |
| 271 |
|
| 272 |
customer = self.partner_id |
| 273 |
has_non_digit_vat(customer, 'customer', error_msgs) |
| 274 |
|
| 275 |
supplier = self.company_id.partner_id.commercial_partner_id |
| 276 |
has_non_digit_vat(supplier, 'supplier', error_msgs) |
| 277 |
|
| 278 |
if self.move_type == 'out_refund': |
| 279 |
if not self.reversed_entry_id: |
| 280 |
error_msgs.append(_('Please use "Reversal of" to link this credit note with an Invoice')) |
| 281 |
elif self.currency_id != self.reversed_entry_id.currency_id: |
| 282 |
error_msgs.append(_("Please make sure the currency of the credit note is the same as the related invoice")) |
| 283 |
|
| 284 |
if not self.ref: |
| 285 |
error_msgs.append(_('Please make sure the "Customer Reference" contains the reason for the return')) |
| 286 |
|
| 287 |
if any( |
| 288 |
line.display_type not in ('line_section', 'line_subsection', 'line_note') |
| 289 |
and (line.quantity < 0 or line.price_unit < 0) |
| 290 |
for line in self.invoice_line_ids |
| 291 |
): |
| 292 |
error_msgs.append(_("JoFotara portal cannot process negative quantity nor negative price on invoice lines")) |
| 293 |
|
| 294 |
for line in self.invoice_line_ids.filtered(lambda line: line.display_type not in ('line_section', 'line_subsection', 'line_note')): |
| 295 |
if self.company_id.l10n_jo_edi_taxpayer_type == 'income' and len(line.tax_ids) != 0: |
| 296 |
error_msgs.append(_("No taxes are allowed on invoice lines for taxpayers unregistered in the sales tax")) |
| 297 |
elif self.company_id.l10n_jo_edi_taxpayer_type == 'sales' and len(line.tax_ids) != 1: |
| 298 |
error_msgs.append(_("One general tax per invoice line is expected for taxpayers registered in the sales tax")) |
| 299 |
elif self.company_id.l10n_jo_edi_taxpayer_type == 'special' and len(line.tax_ids) != 2: |
| 300 |
error_msgs.append(_("One special and one general tax per invoice line is expected for taxpayers registered in the special tax")) |
| 301 |
|
| 302 |
return "\n".join(error_msgs) |
| 303 |
|
| 304 |
def _mark_sent_jo_edi(self): |
| 305 |
self.l10n_jo_edi_error = False |
| 306 |
self.l10n_jo_edi_state = 'demo' if self.env.company.l10n_jo_edi_demo_mode else 'sent' |
| 307 |
|
| 308 |
def _l10n_jo_edi_send(self): |
| 309 |
self.ensure_one() |
| 310 |
if not self.env['res.company']._with_locked_records(records=self, allow_raising=False): |
| 311 |
return |
| 312 |
if error_message := self._l10n_jo_validate_config() or self._l10n_jo_validate_fields() or self._submit_to_jofotara(): |
| 313 |
self.l10n_jo_edi_error = error_message |
| 314 |
return error_message |
| 315 |
else: |
| 316 |
self._mark_sent_jo_edi() |
| 317 |
self.message_post( |
| 318 |
body=_("E-invoice (JoFotara) submitted successfully."), |
| 319 |
attachment_ids=self.l10n_jo_edi_xml_attachment_id.ids, |
| 320 |
) |