| 1 |
import base64 |
| 2 |
import json |
| 3 |
import logging |
| 4 |
import re |
| 5 |
from collections import defaultdict |
| 6 |
|
| 7 |
|
| 8 |
from markupsafe import Markup |
| 9 |
|
| 10 |
from odoo import Command, _, api, fields, models |
| 11 |
from odoo.exceptions import AccessError, LockError, UserError |
| 12 |
from odoo.tools import float_is_zero, float_compare |
| 13 |
|
| 14 |
from odoo.addons.l10n_in.models.account_invoice import EDI_CANCEL_REASON |
| 15 |
|
| 16 |
_logger = logging.getLogger(__name__) |
| 17 |
try: |
| 18 |
import jwt |
| 19 |
except ImportError: |
| 20 |
_logger.warning("The 'jwt' library is not installed. Decoding for duplicate IRN e-invoices will be skipped.") |
| 21 |
jwt = None |
| 22 |
|
| 23 |
|
| 24 |
class AccountMove(models.Model): |
| 25 |
_inherit = "account.move" |
| 26 |
|
| 27 |
# E-Invoice Fields |
| 28 |
l10n_in_edi_status = fields.Selection( |
| 29 |
string="India E-Invoice Status", |
| 30 |
selection=[ |
| 31 |
('to_send', "To Send"), |
| 32 |
('sent', "Sent"), |
| 33 |
('cancelled', "Cancelled"), |
| 34 |
], |
| 35 |
copy=False, |
| 36 |
tracking=True, |
| 37 |
readonly=True, |
| 38 |
) |
| 39 |
l10n_in_edi_attachment_id = fields.Many2one( |
| 40 |
comodel_name='ir.attachment', |
| 41 |
string="E-Invoice(IN) Attachment", |
| 42 |
compute=lambda self: self._compute_linked_attachment_id( |
| 43 |
'l10n_in_edi_attachment_id', |
| 44 |
'l10n_in_edi_attachment_file' |
| 45 |
), |
| 46 |
depends=['l10n_in_edi_attachment_file'] |
| 47 |
) |
| 48 |
l10n_in_edi_attachment_file = fields.Binary( |
| 49 |
string="E-Invoice(IN) File", |
| 50 |
attachment=True, |
| 51 |
copy=False |
| 52 |
) |
| 53 |
l10n_in_edi_cancel_reason = fields.Selection( |
| 54 |
selection=list(EDI_CANCEL_REASON.items()), |
| 55 |
string="E-Invoice(IN) Cancel Reason", |
| 56 |
copy=False |
| 57 |
) |
| 58 |
l10n_in_edi_cancel_remarks = fields.Char( |
| 59 |
string="E-Invoice(IN) Cancel Remarks", |
| 60 |
copy=False |
| 61 |
) |
| 62 |
l10n_in_edi_content = fields.Binary( |
| 63 |
compute="_compute_l10n_in_edi_content", |
| 64 |
string="E-Invoice(IN) Content" |
| 65 |
) |
| 66 |
l10n_in_edi_error = fields.Html(readonly=True, copy=False) |
| 67 |
|
| 68 |
# E-Invoice compute |
| 69 |
def _compute_l10n_in_edi_content(self): |
| 70 |
for move in self: |
| 71 |
move.l10n_in_edi_content = ( |
| 72 |
move.country_code == 'IN' |
| 73 |
and move.company_id.l10n_in_edi_feature |
| 74 |
and move.is_sale_document(include_receipts=True) |
| 75 |
and move.journal_id.type == 'sale' |
| 76 |
and base64.b64encode( |
| 77 |
json.dumps(move._l10n_in_edi_generate_invoice_json()).encode() |
| 78 |
) |
| 79 |
) |
| 80 |
|
| 81 |
# Action Methods |
| 82 |
def action_export_l10n_in_edi_content_json(self): |
| 83 |
self.ensure_one() |
| 84 |
return { |
| 85 |
'type': 'ir.actions.act_url', |
| 86 |
'url': f'/web/content/account.move/{self.id}/l10n_in_edi_content' |
| 87 |
} |
| 88 |
|
| 89 |
def button_request_cancel(self): |
| 90 |
if self._l10n_in_edi_need_cancel_request(): |
| 91 |
if self.l10n_in_edi_cancel_remarks and self.l10n_in_edi_cancel_reason: |
| 92 |
return self._l10n_in_edi_cancel_invoice() |
| 93 |
return self.env['l10n_in_edi.cancel'].with_context( |
| 94 |
default_move_id=self.id |
| 95 |
)._get_records_action(name=_("Cancel E-Invoice"), target='new') |
| 96 |
elif self.l10n_in_edi_status == 'sent': |
| 97 |
self.message_post( |
| 98 |
body=_( |
| 99 |
"Force cancelled %(invoice)s by %(username)s", |
| 100 |
invoice=self.name, username=self.env.user.name |
| 101 |
) |
| 102 |
) |
| 103 |
self.button_cancel() |
| 104 |
self.write({ |
| 105 |
'l10n_in_edi_status': 'cancelled', |
| 106 |
'l10n_in_edi_error': False, |
| 107 |
}) |
| 108 |
return True |
| 109 |
return super().button_request_cancel() |
| 110 |
|
| 111 |
def action_l10n_in_edi_force_cancel(self): |
| 112 |
self.with_context(l10n_in_edi_force_cancel=True).button_request_cancel() |
| 113 |
|
| 114 |
def button_draft(self): |
| 115 |
for move in self: |
| 116 |
if move.l10n_in_edi_status == 'to_send': |
| 117 |
# Avoid resetting sent and cancelled invoices |
| 118 |
move.l10n_in_edi_status = False |
| 119 |
if move.l10n_in_edi_error: |
| 120 |
move.l10n_in_edi_error = False |
| 121 |
return super().button_draft() |
| 122 |
|
| 123 |
# Business Methods |
| 124 |
def _post(self, soft=True): |
| 125 |
# EXTENDS 'account' |
| 126 |
res = super()._post(soft=soft) |
| 127 |
self.filtered(lambda m: m._l10n_in_check_einvoice_eligible()).l10n_in_edi_status = 'to_send' |
| 128 |
return res |
| 129 |
|
| 130 |
def _l10n_in_edi_need_cancel_request(self): |
| 131 |
self.ensure_one() |
| 132 |
return ( |
| 133 |
self.country_code == 'IN' |
| 134 |
and not self.env.context.get('l10n_in_edi_force_cancel') |
| 135 |
and self.is_sale_document() |
| 136 |
and self.l10n_in_edi_status == 'sent' |
| 137 |
) |
| 138 |
|
| 139 |
def _need_cancel_request(self): |
| 140 |
# EXTENDS 'account' |
| 141 |
return super()._need_cancel_request() or self._l10n_in_edi_need_cancel_request() |
| 142 |
|
| 143 |
# Indian E-invoice Business Methods |
| 144 |
def _l10n_in_check_einvoice_eligible(self): |
| 145 |
self.ensure_one() |
| 146 |
return ( |
| 147 |
self.company_id.l10n_in_edi_feature |
| 148 |
and self.journal_id.type == 'sale' |
| 149 |
and any( |
| 150 |
line.display_type == 'product' |
| 151 |
and line.l10n_in_gstr_section in [ |
| 152 |
'sale_b2b_rcm', 'sale_b2b_regular', 'sale_exp_wp', 'sale_exp_wop', |
| 153 |
'sale_sez_wp', 'sale_sez_wop', 'sale_deemed_export', 'sale_cdnr_rcm', |
| 154 |
'sale_cdnr_regular', 'sale_cdnr_deemed_export', 'sale_cdnr_sez_wp', |
| 155 |
'sale_cdnr_sez_wop', 'sale_cdnur_exp_wp', 'sale_cdnur_exp_wop', |
| 156 |
] |
| 157 |
for line in self.line_ids |
| 158 |
) |
| 159 |
) |
| 160 |
|
| 161 |
def _get_l10n_in_edi_response_json(self): |
| 162 |
self.ensure_one() |
| 163 |
if self.l10n_in_edi_attachment_id: |
| 164 |
return json.loads(self.l10n_in_edi_attachment_id.sudo().raw.decode("utf-8")) |
| 165 |
return {} |
| 166 |
|
| 167 |
def _l10n_in_lock_invoice(self): |
| 168 |
try: |
| 169 |
self.lock_for_update() |
| 170 |
except LockError: |
| 171 |
raise UserError(_('This electronic document is being processed already.')) from None |
| 172 |
|
| 173 |
def _l10n_in_edi_optional_field_validation(self, partner): |
| 174 |
""" |
| 175 |
Validates optional partner fields (e.g., email, phone, street2) for e-invoicing, |
| 176 |
which are not mandatory in the government API JSON schema. Returns error messages |
| 177 |
for posting in the chatter. |
| 178 |
""" |
| 179 |
message = [] |
| 180 |
if partner.email and ( |
| 181 |
not re.match(r"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", partner.email) or |
| 182 |
not re.match(r"^.{6,100}$", partner.email) |
| 183 |
): |
| 184 |
message.append(_("- Email: invalid or longer than 100 characters.")) |
| 185 |
if partner.phone and not re.match( |
| 186 |
r"^[0-9]{10,12}$", |
| 187 |
partner.env['account.move']._l10n_in_extract_digits(partner.phone) |
| 188 |
): |
| 189 |
message.append(_("- Phone number: must be 10–12 digits.")) |
| 190 |
if partner.street2 and not re.match(r"^.{3,100}$", partner.street2): |
| 191 |
message.append(_("- Street2: must be 3–100 characters.")) |
| 192 |
return message |
| 193 |
|
| 194 |
def _l10n_in_edi_send_invoice(self): |
| 195 |
self.ensure_one() |
| 196 |
if self.l10n_in_edi_error: |
| 197 |
# make sure to clear the error before sending again |
| 198 |
self.l10n_in_edi_error = False |
| 199 |
self.message_post(body=_( |
| 200 |
"Retrying to send your E-Invoice to government portal." |
| 201 |
)) |
| 202 |
partners = set(self._get_l10n_in_seller_buyer_party().values()) |
| 203 |
for partner in partners: |
| 204 |
if partner_validation := partner._l10n_in_edi_strict_error_validation(): |
| 205 |
self.l10n_in_edi_error = Markup("<br>").join(partner_validation) |
| 206 |
return {'messages': partner_validation} |
| 207 |
self._l10n_in_lock_invoice() |
| 208 |
generate_json = self._l10n_in_edi_generate_invoice_json() |
| 209 |
response = self._l10n_in_edi_connect_to_server( |
| 210 |
url_end_point='generate', |
| 211 |
json_payload=generate_json |
| 212 |
) |
| 213 |
if error := response.get('error', {}): |
| 214 |
odoobot_id = self.env.ref('base.partner_root').id |
| 215 |
error_codes = [e.get("code") for e in error] |
| 216 |
if '2150' in error_codes: |
| 217 |
# Get IRN by details in case of IRN is already generated |
| 218 |
# this happens when timeout from the Government portal but IRN is generated |
| 219 |
response = self._l10n_in_edi_connect_to_server( |
| 220 |
url_end_point='getirnbydocdetails', |
| 221 |
params={ |
| 222 |
"doc_type": ( |
| 223 |
(self.move_type == "out_refund" and "CRN") |
| 224 |
or (self.debit_origin_id and "DBN") |
| 225 |
or "INV" |
| 226 |
), |
| 227 |
"doc_num": self.name, |
| 228 |
"doc_date": self.invoice_date and self.invoice_date.strftime("%d/%m/%Y"), |
| 229 |
} |
| 230 |
) |
| 231 |
mismatch_error = [] |
| 232 |
decoded_response = {} |
| 233 |
if jwt: |
| 234 |
try: |
| 235 |
if data := response.get('data'): |
| 236 |
signinvoice = data['SignedInvoice'] |
| 237 |
decoded_response = jwt.decode(signinvoice, options={'verify_signature': False}) |
| 238 |
decoded_response = json.loads(decoded_response['data']) |
| 239 |
except (json.JSONDecodeError, jwt.exceptions.DecodeError) as e: |
| 240 |
_logger.warning("Failed to decode SignedInvoice JWT payload: %s", str(e)) |
| 241 |
if decoded_response: |
| 242 |
received_gstin = decoded_response['BuyerDtls']['Gstin'] |
| 243 |
expected_gstin = generate_json['BuyerDtls']['GSTIN'] |
| 244 |
received_total_invoice_value = decoded_response['ValDtls']['TotInvVal'] |
| 245 |
expected_total_invoice_value = generate_json['ValDtls']['TotInvVal'] |
| 246 |
# Check for mismatch between decoded and expected e-invoice details: |
| 247 |
# - Buyer GSTIN must match |
| 248 |
# - Total Invoice Value must be within the allowed government tolerance range: |
| 249 |
# For example, if the expected invoice value is 100, |
| 250 |
# the valid range is from 99 (value - 1) to 101 (value + 1), |
| 251 |
# i.e., 99.00 < received value < 101.00 |
| 252 |
if (received_gstin != expected_gstin or |
| 253 |
not expected_total_invoice_value - 1 < received_total_invoice_value < expected_total_invoice_value + 1 |
| 254 |
): |
| 255 |
mismatch_error = [{ |
| 256 |
'code': '2150', |
| 257 |
'message': _("Duplicate IRN found for this invoice, but the buyer details or invoice values do not match.") |
| 258 |
}] |
| 259 |
# Handle the result based on mismatch or response error |
| 260 |
if mismatch_error: |
| 261 |
error = mismatch_error |
| 262 |
elif not response.get("error"): |
| 263 |
error = [] |
| 264 |
link = Markup( |
| 265 |
"<a href='https://einvoice1.gst.gov.in/Others/VSignedInvoice'>%s</a>" |
| 266 |
) % (_("here")) |
| 267 |
self.message_post( |
| 268 |
author_id=odoobot_id, |
| 269 |
body=_( |
| 270 |
"Somehow this invoice has been submited to government before." |
| 271 |
"%(br)sNormally, this should not happen too often" |
| 272 |
"%(br)sJust verify value of invoice by upload json to government website %(link)s.", |
| 273 |
br=Markup("<br/>"), |
| 274 |
link=link |
| 275 |
) |
| 276 |
) |
| 277 |
if (no_credit := 'no-credit' in error_codes) or error: |
| 278 |
msg = Markup("<br/>").join( |
| 279 |
["[%s] %s" % (e.get("code"), e.get("message")) for e in error] |
| 280 |
) |
| 281 |
is_warning = any(warning_code in error_codes for warning_code in ('404', 'timeout')) |
| 282 |
self.l10n_in_edi_error = ( |
| 283 |
self._l10n_in_edi_get_iap_buy_credits_message() |
| 284 |
if no_credit else msg |
| 285 |
) |
| 286 |
# avoid return `l10n_in_edi_error` because as a html field |
| 287 |
# values are sanitized with `<p>` tag |
| 288 |
return { |
| 289 |
'messages': [msg], |
| 290 |
'is_warning': is_warning |
| 291 |
} |
| 292 |
data = response.get("data", {}) |
| 293 |
json_dump = json.dumps(data) |
| 294 |
json_name = "%s_einvoice.json" % (self.name.replace("/", "_")) |
| 295 |
attachment = self.env["ir.attachment"].create({ |
| 296 |
'name': json_name, |
| 297 |
'raw': json_dump.encode(), |
| 298 |
'res_model': self._name, |
| 299 |
'res_field': 'l10n_in_edi_attachment_file', |
| 300 |
'res_id': self.id, |
| 301 |
'mimetype': 'application/json', |
| 302 |
'company_id': self.company_id.id, |
| 303 |
}) |
| 304 |
request_json_dump = json.dumps(generate_json, indent=4) |
| 305 |
request_json_name = "%s_request.json" % (self.name.replace("/", "_")) |
| 306 |
request_attachment = self.env["ir.attachment"].create({ |
| 307 |
'name': request_json_name, |
| 308 |
'raw': request_json_dump.encode(), |
| 309 |
'res_model': self._name, |
| 310 |
'res_id': self.id, |
| 311 |
'mimetype': 'application/json', |
| 312 |
'company_id': self.company_id.id, |
| 313 |
}) |
| 314 |
self.l10n_in_edi_status = 'sent' |
| 315 |
message = [] |
| 316 |
for partner in partners: |
| 317 |
if partner_validation := self._l10n_in_edi_optional_field_validation(partner): |
| 318 |
message.append( |
| 319 |
Markup("<strong><em>%s</em></strong><br>%s") % (partner.name, Markup("<br>").join(partner_validation)) |
| 320 |
) |
| 321 |
message.append(self.env._("E-invoice submitted successfully.")) |
| 322 |
if message: |
| 323 |
self.message_post( |
| 324 |
attachment_ids=[request_attachment.id, attachment.id], |
| 325 |
body=Markup("<strong>%s</strong><br>%s") % (_("Following:"), Markup("<br>").join(message)) |
| 326 |
) |
| 327 |
|
| 328 |
def _l10n_in_edi_cancel_invoice(self): |
| 329 |
if self.l10n_in_edi_error: |
| 330 |
# make sure to clear the error before cancelling again |
| 331 |
self.l10n_in_edi_error = False |
| 332 |
self.message_post(body=_( |
| 333 |
"Retrying to send cancellation request for E-Invoice to government portal." |
| 334 |
)) |
| 335 |
self._l10n_in_lock_invoice() |
| 336 |
l10n_in_edi_response_json = self._get_l10n_in_edi_response_json() |
| 337 |
cancel_json = { |
| 338 |
"Irn": l10n_in_edi_response_json.get("Irn"), |
| 339 |
"CnlRsn": self.l10n_in_edi_cancel_reason, |
| 340 |
"CnlRem": self.l10n_in_edi_cancel_remarks, |
| 341 |
} |
| 342 |
response = self._l10n_in_edi_connect_to_server(url_end_point='cancel', json_payload=cancel_json) |
| 343 |
# Creating a lambda function so it fetches the odoobot id only when needed |
| 344 |
_get_odoobot_id = ( |
| 345 |
lambda self: self.env.ref('base.partner_root').id |
| 346 |
) |
| 347 |
if error := response.get('error'): |
| 348 |
error_codes = [e.get('code') for e in error] |
| 349 |
if '9999' in error_codes: |
| 350 |
response = {} |
| 351 |
error = [] |
| 352 |
link = Markup( |
| 353 |
"<a href='https://einvoice1.gst.gov.in/Others/VSignedInvoice'>%s</a>" |
| 354 |
) % (_("here")) |
| 355 |
self.message_post( |
| 356 |
author_id=_get_odoobot_id(self), |
| 357 |
body=_( |
| 358 |
"Somehow this invoice had been cancelled to government before." |
| 359 |
"%(br)sNormally, this should not happen too often" |
| 360 |
"%(br)sJust verify by logging into government website %(link)s", |
| 361 |
br=Markup("<br/>"), |
| 362 |
link=link |
| 363 |
) |
| 364 |
) |
| 365 |
if "no-credit" in error_codes: |
| 366 |
self.l10n_in_edi_error = self._l10n_in_edi_get_iap_buy_credits_message() |
| 367 |
return |
| 368 |
if error: |
| 369 |
self.l10n_in_edi_error = ( |
| 370 |
Markup("<br/>").join( |
| 371 |
["[%s] %s" % (e.get("code"), e.get("message")) for e in error] |
| 372 |
) |
| 373 |
) |
| 374 |
if "error" not in response: |
| 375 |
json_dump = json.dumps(response.get('data', {})) |
| 376 |
json_name = "%s_cancel_einvoice.json" % (self.name.replace("/", "_")) |
| 377 |
if json_dump: |
| 378 |
attachment = self.env['ir.attachment'].create({ |
| 379 |
'name': json_name, |
| 380 |
'raw': json_dump.encode(), |
| 381 |
'res_model': self._name, |
| 382 |
'res_field': 'l10n_in_edi_attachment_file', |
| 383 |
'res_id': self.id, |
| 384 |
'mimetype': 'application/json', |
| 385 |
}) |
| 386 |
request_json_dump = json.dumps(cancel_json, indent=4) |
| 387 |
request_json_name = "%s_cancel_request.json" % (self.name.replace("/", "_")) |
| 388 |
request_attachment = self.env['ir.attachment'].create({ |
| 389 |
'name': request_json_name, |
| 390 |
'raw': request_json_dump.encode(), |
| 391 |
'res_model': self._name, |
| 392 |
'res_id': self.id, |
| 393 |
'mimetype': 'application/json', |
| 394 |
}) |
| 395 |
self.message_post(author_id=_get_odoobot_id(self), body=_( |
| 396 |
"E-Invoice has been cancelled successfully. " |
| 397 |
"Cancellation Reason: %(reason)s and Cancellation Remark: %(remark)s", |
| 398 |
reason=EDI_CANCEL_REASON[self.l10n_in_edi_cancel_reason], |
| 399 |
remark=self.l10n_in_edi_cancel_remarks |
| 400 |
), attachment_ids=[request_attachment.id, attachment.id] if attachment else [request_attachment.id]) |
| 401 |
self.l10n_in_edi_status = 'cancelled' |
| 402 |
self.button_cancel() |
| 403 |
if self._can_commit(): |
| 404 |
self.env.cr.commit() |
| 405 |
return True |
| 406 |
|
| 407 |
@api.model |
| 408 |
def _get_l10n_in_edi_partner_details( |
| 409 |
self, |
| 410 |
partner, |
| 411 |
set_vat=True, |
| 412 |
set_phone_and_email=True, |
| 413 |
is_overseas=False, |
| 414 |
pos_state_id=False |
| 415 |
): |
| 416 |
""" |
| 417 |
Create the dictionary based partner details |
| 418 |
if set_vat is true then, vat(GSTIN) and legal name(LglNm) is added |
| 419 |
if set_phone_and_email is true then phone and email is add |
| 420 |
if set_pos is true then state code from partner |
| 421 |
or passed state_id is added as POS(place of supply) |
| 422 |
if is_overseas is true then pin is 999999 and GSTIN(vat) is URP and Stcd is . |
| 423 |
if pos_state_id is passed then we use set POS |
| 424 |
""" |
| 425 |
zip_digits = self._l10n_in_extract_digits(partner.zip) |
| 426 |
partner_details = { |
| 427 |
'Addr1': partner.street or '', |
| 428 |
'Loc': partner.city or '', |
| 429 |
'Pin': zip_digits and int(zip_digits) or '', |
| 430 |
'Stcd': partner.state_id.l10n_in_tin or '', |
| 431 |
} |
| 432 |
if partner.street2 and re.match(r"^.{3,100}$", partner.street2): |
| 433 |
partner_details['Addr2'] = partner.street2 |
| 434 |
if set_phone_and_email: |
| 435 |
if ( |
| 436 |
partner.email |
| 437 |
and re.match(r"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", partner.email) |
| 438 |
and re.match(r"^.{6,100}$", partner.email) |
| 439 |
): |
| 440 |
partner_details['Em'] = partner.email |
| 441 |
if ( |
| 442 |
partner.phone |
| 443 |
and re.match(r"^[0-9]{10,12}$", self._l10n_in_extract_digits(partner.phone)) |
| 444 |
): |
| 445 |
partner_details['Ph'] = self._l10n_in_extract_digits(partner.phone) |
| 446 |
if pos_state_id: |
| 447 |
partner_details['POS'] = pos_state_id.l10n_in_tin or '' |
| 448 |
if set_vat: |
| 449 |
partner_details.update({ |
| 450 |
'LglNm': partner.commercial_partner_id.name, |
| 451 |
'GSTIN': partner.vat or 'URP', |
| 452 |
}) |
| 453 |
else: |
| 454 |
partner_details['Nm'] = partner.name |
| 455 |
# For no country I would suppose it is India, so not sure this is super right |
| 456 |
if is_overseas and (not partner.country_id or partner.country_id.code != 'IN'): |
| 457 |
partner_details.update({ |
| 458 |
"GSTIN": "URP", |
| 459 |
"Pin": 999999, |
| 460 |
"Stcd": "96", |
| 461 |
"POS": "96", |
| 462 |
}) |
| 463 |
return partner_details |
| 464 |
|
| 465 |
def _get_l10n_in_edi_line_details(self, index, line, line_tax_details): |
| 466 |
""" |
| 467 |
Create the dictionary with line details |
| 468 |
""" |
| 469 |
sign = self.is_inbound() and -1 or 1 |
| 470 |
tax_details_by_code = self._get_l10n_in_tax_details_by_line_code(line_tax_details['tax_details']) |
| 471 |
quantity = line.quantity |
| 472 |
if line.discount == 100.00 or float_is_zero(quantity, 3): |
| 473 |
# Full discount or zero quantity |
| 474 |
unit_price_in_inr = line.currency_id._convert( |
| 475 |
line.price_unit, |
| 476 |
line.company_currency_id, |
| 477 |
line.company_id, |
| 478 |
line.date or fields.Date.context_today(self) |
| 479 |
) |
| 480 |
else: |
| 481 |
unit_price_in_inr = ((sign * line.balance) / (1 - (line.discount / 100))) / quantity |
| 482 |
|
| 483 |
if unit_price_in_inr < 0 and quantity < 0: |
| 484 |
# If unit price and quantity both is negative then |
| 485 |
# We set unit price and quantity as positive because |
| 486 |
# government does not accept negative in qty or unit price |
| 487 |
unit_price_in_inr = -unit_price_in_inr |
| 488 |
quantity = -quantity |
| 489 |
in_round = self._l10n_in_round_value |
| 490 |
line_details = { |
| 491 |
'SlNo': str(index), |
| 492 |
'IsServc': self._l10n_in_is_service_hsn(line.l10n_in_hsn_code) and 'Y' or 'N', |
| 493 |
'HsnCd': self._l10n_in_extract_digits(line.l10n_in_hsn_code), |
| 494 |
'Qty': in_round(quantity or 0.0, 3), |
| 495 |
'Unit': ( |
| 496 |
line.product_uom_id.l10n_in_code |
| 497 |
and line.product_uom_id.l10n_in_code.split('-')[0] |
| 498 |
or 'OTH' |
| 499 |
), |
| 500 |
# Unit price in company currency and tax excluded so its different then price_unit |
| 501 |
'UnitPrice': in_round(unit_price_in_inr, 3), |
| 502 |
# total amount is before discount |
| 503 |
'TotAmt': in_round(unit_price_in_inr * quantity), |
| 504 |
'Discount': in_round((unit_price_in_inr * quantity) * (line.discount / 100)), |
| 505 |
'AssAmt': in_round(sign * line.balance), |
| 506 |
'GstRt': in_round( |
| 507 |
(tax_details_by_code.get('igst_rate', 0.00) |
| 508 |
or (tax_details_by_code.get('cgst_rate', 0.00) + tax_details_by_code.get('sgst_rate', 0.00))), |
| 509 |
3 |
| 510 |
), |
| 511 |
'IgstAmt': in_round(tax_details_by_code.get('igst_amount', 0.00)), |
| 512 |
'CgstAmt': in_round(tax_details_by_code.get('cgst_amount', 0.00)), |
| 513 |
'SgstAmt': in_round(tax_details_by_code.get('sgst_amount', 0.00)), |
| 514 |
'CesRt': in_round(tax_details_by_code.get('cess_rate', 0.00), 3), |
| 515 |
'CesAmt': in_round(tax_details_by_code.get('cess_amount', 0.00)), |
| 516 |
'CesNonAdvlAmt': in_round( |
| 517 |
tax_details_by_code.get('cess_non_advol_amount', 0.00) |
| 518 |
), |
| 519 |
'StateCesRt': in_round(tax_details_by_code.get('state_cess_rate_amount', 0.00), 3), |
| 520 |
'StateCesAmt': in_round(tax_details_by_code.get('state_cess_amount', 0.00)), |
| 521 |
'StateCesNonAdvlAmt': in_round( |
| 522 |
tax_details_by_code.get('state_cess_non_advol_amount', 0.00) |
| 523 |
), |
| 524 |
'OthChrg': in_round(tax_details_by_code.get('other_amount', 0.00)), |
| 525 |
'TotItemVal': in_round((sign * line.balance) + line_tax_details.get('tax_amount', 0.00)), |
| 526 |
} |
| 527 |
if line.name: |
| 528 |
line_details['PrdDesc'] = line.name.replace("\n", "")[:300] |
| 529 |
return line_details |
| 530 |
|
| 531 |
def _l10n_in_edi_generate_invoice_json_managing_negative_lines(self, json_payload): |
| 532 |
"""Set negative lines against positive lines as discount with same HSN code and tax rate |
| 533 |
With negative lines |
| 534 |
product name | hsn code | unit price | qty | discount | total |
| 535 |
============================================================= |
| 536 |
product A | 123456 | 1000 | 1 | 100 | 900 |
| 537 |
product B | 123456 | 1500 | 2 | 0 | 3000 |
| 538 |
Discount | 123456 | -300 | 1 | 0 | -300 |
| 539 |
Converted to without negative lines |
| 540 |
product name | hsn code | unit price | qty | discount | total |
| 541 |
============================================================= |
| 542 |
product A | 123456 | 1000 | 1 | 100 | 900 |
| 543 |
product B | 123456 | 1500 | 2 | 300 | 2700 |
| 544 |
totally discounted lines are kept as 0, though |
| 545 |
""" |
| 546 |
def discount_group_key(line_vals): |
| 547 |
return "%s-%s" % (line_vals['HsnCd'], line_vals['GstRt']) |
| 548 |
|
| 549 |
def put_discount_on(discount_line_vals, other_line_vals): |
| 550 |
discount = -discount_line_vals['AssAmt'] |
| 551 |
discount_to_allow = other_line_vals['AssAmt'] |
| 552 |
in_round = self._l10n_in_round_value |
| 553 |
amount_keys = ( |
| 554 |
'AssAmt', 'IgstAmt', 'CgstAmt', 'SgstAmt', 'CesAmt', |
| 555 |
'CesNonAdvlAmt', 'StateCesAmt', 'StateCesNonAdvlAmt', |
| 556 |
'OthChrg', 'TotItemVal' |
| 557 |
) |
| 558 |
if float_compare(discount_to_allow, discount, precision_rounding=self.currency_id.rounding) < 0: |
| 559 |
# Update discount line, needed when discount is more then max line, in short remaining_discount is not zero |
| 560 |
discount_line_vals.update({ |
| 561 |
key: in_round(discount_line_vals[key] + other_line_vals[key]) |
| 562 |
for key in amount_keys |
| 563 |
}) |
| 564 |
other_line_vals['Discount'] = in_round(other_line_vals['Discount'] + discount_to_allow) |
| 565 |
other_line_vals.update(dict.fromkeys(amount_keys, 0.00)) |
| 566 |
return False |
| 567 |
other_line_vals['Discount'] = in_round(other_line_vals['Discount'] + discount) |
| 568 |
other_line_vals.update({ |
| 569 |
key: in_round(other_line_vals[key] + discount_line_vals[key]) |
| 570 |
for key in amount_keys |
| 571 |
}) |
| 572 |
return True |
| 573 |
|
| 574 |
discount_lines = [] |
| 575 |
for discount_line in json_payload['ItemList'].copy(): #to be sure to not skip in the loop: |
| 576 |
if discount_line['AssAmt'] < 0: |
| 577 |
discount_lines.append(discount_line) |
| 578 |
json_payload['ItemList'].remove(discount_line) |
| 579 |
if not discount_lines: |
| 580 |
return json_payload |
| 581 |
self.message_post( |
| 582 |
author_id=self.env.ref('base.partner_root').id, |
| 583 |
body=_("Negative lines will be decreased from positive invoice lines having the same taxes and HSN code") |
| 584 |
) |
| 585 |
|
| 586 |
lines_grouped_and_sorted = defaultdict(list) |
| 587 |
for line in sorted(json_payload['ItemList'], key=lambda i: i['AssAmt'], reverse=True): |
| 588 |
lines_grouped_and_sorted[discount_group_key(line)].append(line) |
| 589 |
|
| 590 |
for discount_line in discount_lines: |
| 591 |
for apply_discount_on in lines_grouped_and_sorted[discount_group_key(discount_line)]: |
| 592 |
if put_discount_on(discount_line, apply_discount_on): |
| 593 |
break |
| 594 |
return json_payload |
| 595 |
|
| 596 |
def _l10n_in_edi_generate_invoice_json(self): |
| 597 |
self.ensure_one() |
| 598 |
tax_details = self._l10n_in_prepare_tax_details() |
| 599 |
seller_buyer = self._get_l10n_in_seller_buyer_party() |
| 600 |
tax_details_by_code = self._get_l10n_in_tax_details_by_line_code(tax_details['tax_details']) |
| 601 |
is_intra_state = self.l10n_in_state_id == self.company_id.state_id |
| 602 |
is_overseas = self.l10n_in_gst_treatment == "overseas" |
| 603 |
line_ids = [] |
| 604 |
global_discount_line_ids = [] |
| 605 |
grouping_lines = self.invoice_line_ids.grouped( |
| 606 |
lambda l: l.display_type == 'product' and (l._l10n_in_is_global_discount() and 'global_discount' or 'lines') |
| 607 |
) |
| 608 |
default_line = self.env['account.move.line'].browse() |
| 609 |
lines = grouping_lines.get('lines', default_line) |
| 610 |
global_discount_line = grouping_lines.get('global_discount', default_line) |
| 611 |
tax_details_per_record = tax_details['tax_details_per_record'] |
| 612 |
sign = self.is_inbound() and -1 or 1 |
| 613 |
rounding_amount = sum(line.balance for line in self.line_ids if line.display_type == 'rounding') * sign |
| 614 |
global_discount_amount = sum(line.balance for line in global_discount_line) * -sign |
| 615 |
in_round = self._l10n_in_round_value |
| 616 |
json_payload = { |
| 617 |
"Version": "1.1", |
| 618 |
"TranDtls": { |
| 619 |
"TaxSch": "GST", |
| 620 |
"SupTyp": self._l10n_in_get_supply_type(tax_details_by_code.get('igst_amount')), |
| 621 |
"RegRev": tax_details_by_code.get('is_reverse_charge') and "Y" or "N", |
| 622 |
"IgstOnIntra": ( |
| 623 |
# for Export SEZ LUT tax as per e-invoice api doc validation point 32 |
| 624 |
# Export and SEZ must be treated as Inter state supply |
| 625 |
self.l10n_in_gst_treatment not in ('special_economic_zone', 'overseas') |
| 626 |
and is_intra_state |
| 627 |
and tax_details_by_code.get("igst_amount") |
| 628 |
and "Y" or "N" |
| 629 |
), |
| 630 |
}, |
| 631 |
"DocDtls": { |
| 632 |
"Typ": (self.move_type == "out_refund" and "CRN") or (self.debit_origin_id and "DBN") or "INV", |
| 633 |
"No": self.name, |
| 634 |
"Dt": self.invoice_date and self.invoice_date.strftime("%d/%m/%Y") |
| 635 |
}, |
| 636 |
"SellerDtls": self._get_l10n_in_edi_partner_details(seller_buyer['seller_details']), |
| 637 |
"BuyerDtls": self._get_l10n_in_edi_partner_details( |
| 638 |
seller_buyer['buyer_details'], |
| 639 |
pos_state_id=self.l10n_in_state_id, |
| 640 |
is_overseas=is_overseas |
| 641 |
), |
| 642 |
"ItemList": [ |
| 643 |
self._get_l10n_in_edi_line_details( |
| 644 |
index, |
| 645 |
line, |
| 646 |
tax_details_per_record.get(line, {}) |
| 647 |
) |
| 648 |
for index, line in enumerate(lines, start=1) |
| 649 |
], |
| 650 |
"ValDtls": { |
| 651 |
"AssVal": in_round(tax_details['base_amount']), |
| 652 |
"CgstVal": in_round(tax_details_by_code.get("cgst_amount", 0.00)), |
| 653 |
"SgstVal": in_round(tax_details_by_code.get("sgst_amount", 0.00)), |
| 654 |
"IgstVal": in_round(tax_details_by_code.get("igst_amount", 0.00)), |
| 655 |
"CesVal": in_round(( |
| 656 |
tax_details_by_code.get("cess_amount", 0.00) |
| 657 |
+ tax_details_by_code.get("cess_non_advol_amount", 0.00)), |
| 658 |
), |
| 659 |
"StCesVal": in_round(( |
| 660 |
tax_details_by_code.get("state_cess_amount", 0.00) |
| 661 |
+ tax_details_by_code.get("state_cess_non_advol_amount", 0.00)), # clean this up =p |
| 662 |
), |
| 663 |
"Discount": in_round(global_discount_amount), |
| 664 |
"RndOffAmt": in_round(rounding_amount), |
| 665 |
"TotInvVal": in_round( |
| 666 |
tax_details["base_amount"] |
| 667 |
+ tax_details["tax_amount"] |
| 668 |
+ rounding_amount |
| 669 |
- global_discount_amount |
| 670 |
), |
| 671 |
}, |
| 672 |
} |
| 673 |
if self.company_currency_id != self.currency_id: |
| 674 |
json_payload["ValDtls"].update({ |
| 675 |
"TotInvValFc": in_round( |
| 676 |
(tax_details.get("base_amount_currency") + tax_details.get("tax_amount_currency"))) |
| 677 |
}) |
| 678 |
if seller_buyer['seller_details'] != seller_buyer['dispatch_details']: |
| 679 |
json_payload['DispDtls'] = self._get_l10n_in_edi_partner_details( |
| 680 |
seller_buyer['dispatch_details'], |
| 681 |
set_vat=False, |
| 682 |
set_phone_and_email=False |
| 683 |
) |
| 684 |
if seller_buyer['buyer_details'] != seller_buyer['ship_to_details']: |
| 685 |
json_payload['ShipDtls'] = self._get_l10n_in_edi_partner_details( |
| 686 |
seller_buyer['ship_to_details'], |
| 687 |
is_overseas=is_overseas |
| 688 |
) |
| 689 |
if is_overseas: |
| 690 |
json_payload['ExpDtls'] = { |
| 691 |
'RefClm': tax_details_by_code.get('igst_amount') and 'Y' or 'N', |
| 692 |
'ForCur': self.currency_id.name, |
| 693 |
'CntCode': seller_buyer['buyer_details'].country_id.code or '', |
| 694 |
} |
| 695 |
if shipping_bill_no := self.l10n_in_shipping_bill_number: |
| 696 |
json_payload['ExpDtls']['ShipBNo'] = shipping_bill_no |
| 697 |
if shipping_bill_date := self.l10n_in_shipping_bill_date: |
| 698 |
json_payload['ExpDtls']['ShipBDt'] = shipping_bill_date.strftime("%d/%m/%Y") |
| 699 |
if shipping_port_code_id := self.l10n_in_shipping_port_code_id: |
| 700 |
json_payload['ExpDtls']['Port'] = shipping_port_code_id.code |
| 701 |
json_valdtls = json_payload['ValDtls'] |
| 702 |
base_and_tax_amount = tax_details.get("base_amount") + tax_details.get("tax_amount") |
| 703 |
# For Export If with payment of Tax then we need to include Tax in Total Invoice Value |
| 704 |
if json_payload['TranDtls']['SupTyp'] == 'EXPWP' and json_valdtls['AssVal'] == base_and_tax_amount: |
| 705 |
json_payload["ValDtls"]["TotInvVal"] = self._l10n_in_round_value(sum([ |
| 706 |
json_valdtls['TotInvVal'], |
| 707 |
json_valdtls['IgstVal'], |
| 708 |
json_valdtls['CgstVal'], |
| 709 |
json_valdtls['SgstVal'], |
| 710 |
json_valdtls['CesVal'], |
| 711 |
json_valdtls['StCesVal'], |
| 712 |
])) |
| 713 |
for line in json_payload["ItemList"]: |
| 714 |
line["TotItemVal"] = self._l10n_in_round_value(sum([ |
| 715 |
line["TotItemVal"], |
| 716 |
line["IgstAmt"], |
| 717 |
line["CgstAmt"], |
| 718 |
line["SgstAmt"], |
| 719 |
line["CesAmt"], |
| 720 |
line["CesNonAdvlAmt"], |
| 721 |
line["StateCesAmt"], |
| 722 |
line["StateCesNonAdvlAmt"], |
| 723 |
])) |
| 724 |
return self._l10n_in_edi_generate_invoice_json_managing_negative_lines(json_payload) |
| 725 |
|
| 726 |
def _l10n_in_get_supply_type(self, is_igst_amount): |
| 727 |
if self.l10n_in_gst_treatment in ("overseas", "special_economic_zone") and is_igst_amount: |
| 728 |
return { |
| 729 |
'overseas': 'EXPWP', |
| 730 |
'special_economic_zone': 'SEZWP', |
| 731 |
}[self.l10n_in_gst_treatment] |
| 732 |
return { |
| 733 |
'deemed_export': 'DEXP', |
| 734 |
'overseas': 'EXPWOP', |
| 735 |
'special_economic_zone': 'SEZWOP', |
| 736 |
}.get(self.l10n_in_gst_treatment, 'B2B') |
| 737 |
|
| 738 |
# ================= Get Error ================= |
| 739 |
def _l10n_in_check_einvoice_validation(self): |
| 740 |
alerts = { |
| 741 |
**self.company_id._l10n_in_check_einvoice_validation(), |
| 742 |
**(self.partner_id | self.partner_shipping_id)._l10n_in_check_einvoice_validation(), |
| 743 |
**self.invoice_line_ids._l10n_in_check_einvoice_validation(), |
| 744 |
} |
| 745 |
if invalid_records := self.filtered(lambda m: not re.match("^.{1,16}$", m.name)): |
| 746 |
alerts['l10n_in_edi_invalid_invoice_number'] = { |
| 747 |
'message': _("Invoice number should not be more than 16 characters"), |
| 748 |
'action_text': _("View Invoices"), |
| 749 |
'action': invalid_records._get_records_action(name=_("Check Invoices")), |
| 750 |
} |
| 751 |
return alerts |
| 752 |
|
| 753 |
# ================================ API methods =========================== |
| 754 |
def _l10n_in_edi_connect_to_server(self, url_end_point, json_payload=False, params=False): |
| 755 |
""" |
| 756 |
url_end_point possible values (generate, getirnbydocdetails, generate_ewaybill_by_irn, get_ewaybill_by_irn, cancel) |
| 757 |
is used to get the EDI response from the server |
| 758 |
""" |
| 759 |
company = self.company_id |
| 760 |
token = company._l10n_in_edi_get_token() |
| 761 |
if not token: |
| 762 |
return { |
| 763 |
'error': [{ |
| 764 |
'code': '0', |
| 765 |
'message': _( |
| 766 |
"Ensure GST Number set on company setting and API are Verified." |
| 767 |
) |
| 768 |
}] |
| 769 |
} |
| 770 |
default_params = { |
| 771 |
'auth_token': token, |
| 772 |
'username': company.sudo().l10n_in_edi_username, |
| 773 |
'gstin': company.vat, |
| 774 |
} |
| 775 |
if params: |
| 776 |
# To be used when generate_ewaybill_by_irn, get_ewaybill_by_irn |
| 777 |
params.update(default_params) |
| 778 |
else: |
| 779 |
params = { |
| 780 |
**default_params, |
| 781 |
'json_payload': json_payload |
| 782 |
} |
| 783 |
try: |
| 784 |
response = self.env['iap.account']._l10n_in_connect_to_server( |
| 785 |
company.sudo().l10n_in_edi_production_env, |
| 786 |
params, |
| 787 |
f"/iap/l10n_in_edi/1/{url_end_point}", |
| 788 |
'l10n_in_edi.endpoint' |
| 789 |
) |
| 790 |
except AccessError as e: |
| 791 |
_logger.warning("Connection error: %s", e.args[0]) |
| 792 |
return { |
| 793 |
'error': [{ |
| 794 |
'code': '404', |
| 795 |
'message': _( |
| 796 |
"Unable to connect to the online E-invoice service." |
| 797 |
"The web service may be temporary down. Please try again in a moment." |
| 798 |
) |
| 799 |
}] |
| 800 |
} |
| 801 |
if (error := response.get('error')) and '1005' in [e.get("code") for e in error]: |
| 802 |
# Invalid token error then create new token and send generate request again. |
| 803 |
# This happen when authenticate called from another odoo instance with same credentials (like. Demo/Test) |
| 804 |
authenticate_response = company._l10n_in_edi_authenticate() |
| 805 |
if not authenticate_response.get("error"): |
| 806 |
response = self._l10n_in_edi_connect_to_server( |
| 807 |
url_end_point=url_end_point, |
| 808 |
json_payload=json_payload, |
| 809 |
params=params |
| 810 |
) |
| 811 |
else: |
| 812 |
return authenticate_response |
| 813 |
return response |