Debian Codegraph @

addons/l10n_in/models/account_invoice.py

raw symbols SCIP
1 import base64
2 import logging
3 import json
4 import re
5
6 from contextlib import contextmanager
7 from markupsafe import Markup
8
9 from odoo import Command, _, api, fields, models
10 from odoo.exceptions import ValidationError, RedirectWarning, UserError
11 from odoo.tools.float_utils import json_float_round
12 from odoo.tools.image import image_data_uri
13 from odoo.tools import float_compare, SQL
14 from odoo.tools.date_utils import get_month
15 from odoo.addons.l10n_in.models.iap_account import IAP_SERVICE_NAME
16
17 EDI_CANCEL_REASON = {
18 # Same for both e-way bill and IRN
19 '1': "Duplicate",
20 '2': "Data Entry Mistake",
21 '3': "Order Cancelled",
22 '4': "Others",
23 }
24 _logger = logging.getLogger(__name__)
25
26
27 class AccountMove(models.Model):
28 _inherit = "account.move"
29
30 l10n_in_gst_treatment = fields.Selection(
31 selection=[
32 ('regular', 'Registered Business - Regular'),
33 ('composition', 'Registered Business - Composition'),
34 ('unregistered', 'Unregistered Business'),
35 ('consumer', 'Consumer'),
36 ('overseas', 'Overseas'),
37 ('special_economic_zone', 'Special Economic Zone'),
38 ('deemed_export', 'Deemed Export'),
39 ('uin_holders', 'UIN Holders'),
40 ],
41 string="GST Treatment",
42 compute="_compute_l10n_in_gst_treatment",
43 store=True,
44 readonly=False,
45 copy=True,
46 precompute=True
47 )
48 l10n_in_state_id = fields.Many2one(
49 comodel_name='res.country.state',
50 string="Place of supply",
51 compute="_compute_l10n_in_state_id",
52 store=True,
53 copy=True,
54 readonly=False,
55 precompute=True
56 )
57 l10n_in_gstin = fields.Char(string="GSTIN")
58 # For Export invoice this data is need in GSTR report
59 l10n_in_shipping_bill_number = fields.Char('Shipping bill number')
60 l10n_in_shipping_bill_date = fields.Date('Shipping bill date')
61 l10n_in_shipping_port_code_id = fields.Many2one('l10n_in.port.code', 'Port code')
62 l10n_in_reseller_partner_id = fields.Many2one(
63 comodel_name='res.partner',
64 string="Reseller",
65 domain=[('vat', '!=', False)],
66 help="Only Registered Reseller"
67 )
68 l10n_in_journal_type = fields.Selection(string="Journal Type", related='journal_id.type')
69 l10n_in_warning = fields.Json(compute="_compute_l10n_in_warning")
70 l10n_in_is_gst_registered_enabled = fields.Boolean(related='company_id.l10n_in_is_gst_registered')
71 l10n_in_tds_deduction = fields.Selection(related='commercial_partner_id.l10n_in_pan_entity_id.tds_deduction', string="TDS Deduction")
72
73 # withholding related fields
74 l10n_in_is_withholding = fields.Boolean(
75 string="Is Indian TDS Entry",
76 copy=False,
77 help="Technical field to identify Indian withholding entry"
78 )
79 l10n_in_withholding_ref_move_id = fields.Many2one(
80 comodel_name='account.move',
81 string="Indian TDS Ref Move",
82 readonly=True,
83 index='btree_not_null',
84 copy=False,
85 help="Reference move for withholding entry",
86 )
87 l10n_in_withholding_ref_payment_id = fields.Many2one(
88 comodel_name='account.payment',
89 string="Indian TDS Ref Payment",
90 index='btree_not_null',
91 readonly=True,
92 copy=False,
93 help="Reference Payment for withholding entry",
94 )
95 l10n_in_withhold_move_ids = fields.One2many(
96 'account.move', 'l10n_in_withholding_ref_move_id',
97 string="Indian TDS Entries"
98 )
99 l10n_in_withholding_line_ids = fields.One2many(
100 'account.move.line', 'move_id',
101 string="Indian TDS Lines",
102 compute='_compute_l10n_in_withholding_line_ids',
103 )
104 l10n_in_total_withholding_amount = fields.Monetary(
105 string="Total Indian TDS Amount",
106 compute='_compute_l10n_in_total_withholding_amount',
107 help="Total withholding amount for the move",
108 )
109 l10n_in_display_higher_tcs_button = fields.Boolean(string="Display higher TCS button", compute="_compute_l10n_in_display_higher_tcs_button")
110 l10n_in_tds_feature_enabled = fields.Boolean(related='company_id.l10n_in_tds_feature')
111 l10n_in_tcs_feature_enabled = fields.Boolean(related='company_id.l10n_in_tcs_feature')
112
113 # gstin_status related field
114 l10n_in_partner_gstin_status = fields.Boolean(
115 string="GST Status",
116 compute="_compute_l10n_in_partner_gstin_status_and_date",
117 )
118 l10n_in_show_gstin_status = fields.Boolean(compute="_compute_l10n_in_show_gstin_status")
119 l10n_in_gstin_verified_date = fields.Date(compute="_compute_l10n_in_partner_gstin_status_and_date")
120
121 # -------------------------------------------------------------------------
122 # COMPUTE METHODS
123 # -------------------------------------------------------------------------
124
125 @api.depends('partner_id')
126 def _compute_l10n_in_gst_treatment(self):
127 for invoice in self.filtered(lambda m: m.country_code == 'IN' and m.state == 'draft'):
128 partner = invoice.partner_id
129 invoice.l10n_in_gst_treatment = (
130 partner.l10n_in_gst_treatment
131 or (
132 'overseas' if partner.country_id and partner.country_id.code != 'IN'
133 else partner.check_vat_in(partner.vat) and 'regular' or 'consumer'
134 )
135 )
136
137 @api.depends('partner_id', 'partner_shipping_id', 'company_id')
138 def _compute_l10n_in_state_id(self):
139 foreign_state = self.env.ref('l10n_in.state_in_oc', raise_if_not_found=False)
140 for move in self:
141 if move.country_code == 'IN' and move.is_sale_document(include_receipts=True):
142 partner = (
143 move.partner_id.commercial_partner_id == move.partner_shipping_id.commercial_partner_id
144 and move.partner_shipping_id
145 or move.partner_id
146 )
147 if partner.country_id and partner.country_id.code != 'IN':
148 move.l10n_in_state_id = foreign_state
149 continue
150 partner_state = partner.state_id or move.partner_id.commercial_partner_id.state_id or move.company_id.state_id
151 country_code = partner_state.country_id.code or move.country_code
152 move.l10n_in_state_id = partner_state if country_code == 'IN' else foreign_state
153 elif move.country_code == 'IN' and move.journal_id.type == 'purchase':
154 move.l10n_in_state_id = move.company_id.state_id
155 else:
156 move.l10n_in_state_id = False
157
158 @api.depends('l10n_in_state_id', 'l10n_in_gst_treatment')
159 def _compute_fiscal_position_id(self):
160
161 foreign_state = self.env['res.country.state'].search([('code', '!=', 'IN')], limit=1)
162
163 def _get_fiscal_state(move):
164 """
165 Maps each move to its corresponding fiscal state based on its type,
166 fiscal conditions, and the state of the associated partner or company.
167 """
168
169 if (
170 move.country_code != 'IN'
171 or not move.is_invoice(include_receipts=True)
172 # Partner's FP takes precedence through super
173 or move.partner_shipping_id.property_account_position_id
174 or move.partner_id.property_account_position_id
175 ):
176 return False
177 elif move.l10n_in_gst_treatment == 'special_economic_zone':
178 # Special Economic Zone
179 return self.env.ref('l10n_in.state_in_oc')
180 elif move.is_sale_document(include_receipts=True):
181 # In Sales Documents: Compare place of supply with company state
182 return move.l10n_in_state_id if move.l10n_in_state_id.l10n_in_tin != '96' else foreign_state
183 elif move.is_purchase_document(include_receipts=True) and move.partner_id.country_id.code == 'IN':
184 # In Purchases Documents: Compare place of supply with vendor state
185 pos_state_id = move.l10n_in_state_id
186 if pos_state_id.l10n_in_tin == '96':
187 return pos_state_id
188 elif pos_state_id == move.partner_id.state_id:
189 # Intra-State: Group by state matching the company's state.
190 return move.company_id.state_id
191 elif pos_state_id != move.partner_id.state_id:
192 # Inter-State: Group by state that doesn't match the company's state.
193 return (
194 pos_state_id == move.company_id.state_id
195 and move.partner_id.state_id
196 or pos_state_id
197 )
198 return False
199
200 FiscalPosition = self.env['account.fiscal.position']
201 for state_id, moves in self.grouped(_get_fiscal_state).items():
202 if state_id:
203 virtual_partner = self.env['res.partner'].new({
204 'state_id': state_id.id,
205 'country_id': state_id.country_id.id,
206 })
207 # Group moves by company to avoid multi-company conflicts
208 for company_id, company_moves in moves.grouped('company_id').items():
209 company_moves.fiscal_position_id = FiscalPosition.with_company(
210 company_id
211 )._get_fiscal_position(virtual_partner)
212 else:
213 super(AccountMove, moves)._compute_fiscal_position_id()
214
215 @api.onchange('name')
216 def _onchange_name_warning(self):
217 if (
218 self.country_code == 'IN'
219 and self.company_id.l10n_in_is_gst_registered
220 and self.journal_id.type == 'sale'
221 and self.name
222 and (len(self.name) > 16 or not re.match(r'^[a-zA-Z0-9-\/]+$', self.name))
223 ):
224 return {'warning': {
225 'title' : _("Invalid sequence as per GST rule 46(b)"),
226 'message': _(
227 "The invoice number should not exceed 16 characters\n"
228 "and must only contain '-' (hyphen) and '/' (slash) as special characters"
229 )
230 }}
231 return super()._onchange_name_warning()
232
233 @api.depends(
234 'invoice_line_ids.l10n_in_hsn_code',
235 'company_id.l10n_in_hsn_code_digit',
236 'invoice_line_ids.tax_ids',
237 'commercial_partner_id.l10n_in_pan_entity_id',
238 'invoice_line_ids.price_total'
239 )
240 def _compute_l10n_in_warning(self):
241 indian_invoice = self.filtered(lambda m: m.country_code == 'IN' and m.move_type != 'entry')
242 line_filter_func = lambda line: line.display_type == 'product' and line.tax_ids and line._origin
243 _xmlid_to_res_id = self.env['ir.model.data']._xmlid_to_res_id
244 for move in indian_invoice:
245 warnings = {}
246 company = move.company_id
247 action_name = _("Journal Item(s)")
248 action_text = _("View Journal Item(s)")
249 if company.l10n_in_tcs_feature or company.l10n_in_tds_feature:
250 invalid_tax_lines = move._get_l10n_in_invalid_tax_lines()
251 if company.l10n_in_tcs_feature and invalid_tax_lines:
252 warnings['lower_tcs_tax'] = {
253 'message': _("As the Partner's PAN missing/invalid apply TCS at the higher rate."),
254 'actions': invalid_tax_lines.with_context(tax_validation=True)._get_records_action(
255 name=action_name,
256 views=[(_xmlid_to_res_id("l10n_in.view_move_line_tree_hsn_l10n_in"), "list")],
257 domain=[('id', 'in', invalid_tax_lines.ids)],
258 ),
259 'action_text': action_text,
260 }
261
262 if applicable_sections := move._get_l10n_in_tds_tcs_applicable_sections():
263 tds_tcs_applicable_lines = (
264 move.move_type == 'out_invoice'
265 and move._get_tcs_applicable_lines(move.invoice_line_ids)
266 or move.invoice_line_ids
267 )
268 warnings['tds_tcs_threshold_alert'] = {
269 'message': applicable_sections._get_warning_message(),
270 'action': tds_tcs_applicable_lines.with_context(
271 default_tax_type_use=True,
272 move_type=move.move_type == 'in_invoice'
273 )._get_records_action(
274 name=action_name,
275 domain=[('id', 'in', tds_tcs_applicable_lines.ids)],
276 views=[(_xmlid_to_res_id("l10n_in.view_move_line_list_l10n_in_withholding"), "list")]
277 ),
278 'action_text': action_text,
279 }
280
281 if (
282 company.l10n_in_is_gst_registered
283 and company.l10n_in_hsn_code_digit
284 and (filtered_lines := move.invoice_line_ids.filtered(line_filter_func))
285 ):
286 lines = self.env['account.move.line']
287 for line in filtered_lines:
288 hsn_code = line.l10n_in_hsn_code
289 if (
290 not hsn_code
291 or (
292 not re.match(r'^\d{4}$|^\d{6}$|^\d{8}$', hsn_code)
293 or len(hsn_code) < int(company.l10n_in_hsn_code_digit)
294 )
295 ):
296 lines |= line._origin
297
298 if lines:
299 digit_suffixes = {
300 '4': _("4 digits, 6 digits or 8 digits"),
301 '6': _("6 digits or 8 digits"),
302 '8': _("8 digits")
303 }
304 msg = _(
305 "Ensure that the HSN/SAC Code consists either %s in invoice lines",
306 digit_suffixes.get(company.l10n_in_hsn_code_digit, _("Invalid HSN/SAC Code digit"))
307 )
308 warnings['invalid_hsn_code_length'] = {
309 'message': msg,
310 'action': lines._get_records_action(
311 name=action_name,
312 views=[(_xmlid_to_res_id("l10n_in.view_move_line_tree_hsn_l10n_in"), "list")],
313 domain=[('id', 'in', lines.ids)]
314 ),
315 'action_text': action_text,
316 }
317
318 move.l10n_in_warning = warnings
319 (self - indian_invoice).l10n_in_warning = {}
320
321 @api.depends('partner_id', 'state', 'payment_state', 'l10n_in_gst_treatment')
322 def _compute_l10n_in_show_gstin_status(self):
323 indian_moves = self.filtered(
324 lambda m: m.country_code == 'IN' and m.company_id.l10n_in_gstin_status_feature
325 )
326 (self - indian_moves).l10n_in_show_gstin_status = False
327 for move in indian_moves:
328 move.l10n_in_show_gstin_status = (
329 move.partner_id
330 and move.state == 'posted'
331 and move.move_type != 'entry'
332 and move.payment_state not in ['paid', 'reversed']
333 and move.l10n_in_gst_treatment in [
334 'regular',
335 'composition',
336 'special_economic_zone',
337 'deemed_export',
338 'uin_holders'
339 ]
340 )
341
342 @api.depends('partner_id')
343 def _compute_l10n_in_partner_gstin_status_and_date(self):
344 for move in self:
345 if (
346 move.country_code == 'IN'
347 and move.company_id.l10n_in_gstin_status_feature
348 and move.payment_state not in ['paid', 'reversed']
349 and move.state != 'cancel'
350 ):
351 move.l10n_in_partner_gstin_status = move.partner_id.l10n_in_gstin_verified_status
352 move.l10n_in_gstin_verified_date = move.partner_id.l10n_in_gstin_verified_date
353 else:
354 move.l10n_in_partner_gstin_status = False
355 move.l10n_in_gstin_verified_date = False
356
357 @api.depends('line_ids', 'l10n_in_is_withholding')
358 def _compute_l10n_in_withholding_line_ids(self):
359 # Compute the withholding lines for the move
360 for move in self:
361 if move.l10n_in_is_withholding:
362 move.l10n_in_withholding_line_ids = move.line_ids.filtered('tax_ids')
363 else:
364 move.l10n_in_withholding_line_ids = False
365
366 def _compute_l10n_in_total_withholding_amount(self):
367 for move in self:
368 if self.env.company.l10n_in_tds_feature:
369 move.l10n_in_total_withholding_amount = sum(
370 move.l10n_in_withhold_move_ids.filtered(
371 lambda m: m.state == 'posted'
372 ).l10n_in_withholding_line_ids.mapped('l10n_in_withhold_tax_amount')
373 )
374 else:
375 move.l10n_in_total_withholding_amount = 0.0
376
377 @api.depends('l10n_in_warning')
378 def _compute_l10n_in_display_higher_tcs_button(self):
379 for move in self:
380 if move.company_id.l10n_in_tcs_feature:
381 move.l10n_in_display_higher_tcs_button = (
382 move.l10n_in_warning
383 and move.l10n_in_warning.get('lower_tcs_tax')
384 )
385 else:
386 move.l10n_in_display_higher_tcs_button = False
387
388 def action_l10n_in_withholding_entries(self):
389 self.ensure_one()
390 return {
391 'name': "TDS Entries",
392 'type': 'ir.actions.act_window',
393 'res_model': 'account.move',
394 'view_mode': 'list,form',
395 'domain': [('id', 'in', self.l10n_in_withhold_move_ids.ids)],
396 }
397
398 def action_l10n_in_apply_higher_tax(self):
399 self.ensure_one()
400 invalid_lines = self._get_l10n_in_invalid_tax_lines()
401 for line in invalid_lines:
402 updated_tax_ids = []
403 for tax in line.tax_ids:
404 if tax.l10n_in_tax_type == 'tcs':
405 max_tax = max(
406 tax.l10n_in_section_id.l10n_in_section_tax_ids,
407 key=lambda t: t.amount
408 )
409 updated_tax_ids.append(max_tax.id)
410 else:
411 updated_tax_ids.append(tax.id)
412 if set(line.tax_ids.ids) != set(updated_tax_ids):
413 line.write({'tax_ids': [Command.clear()] + [Command.set(updated_tax_ids)]})
414
415 def _get_l10n_in_invalid_tax_lines(self):
416 self.ensure_one()
417 if self.country_code == 'IN' and not self.commercial_partner_id.l10n_in_pan_entity_id:
418 lines = self.env['account.move.line']
419 for line in self.invoice_line_ids:
420 for tax in line.tax_ids:
421 if (
422 tax.l10n_in_tax_type == 'tcs'
423 and tax.amount != max(tax.l10n_in_section_id.l10n_in_section_tax_ids, key=lambda t: abs(t.amount)).amount
424 ):
425 lines |= line._origin
426 return lines
427
428 def _get_sections_aggregate_sum_by_pan(self, section_alert, commercial_partner_id):
429 self.ensure_one()
430 month_start_date, month_end_date = get_month(self.date)
431 company_fiscalyear_dates = self.company_id.sudo().compute_fiscalyear_dates(self.date)
432 fiscalyear_start_date, fiscalyear_end_date = company_fiscalyear_dates['date_from'], company_fiscalyear_dates['date_to']
433 default_domain = [
434 ('account_id.l10n_in_tds_tcs_section_id', '=', section_alert.id),
435 ('move_id.move_type', '!=', 'entry'),
436 ('company_id.l10n_in_tds_feature', '!=', False),
437 ('company_id.l10n_in_tan', '=', self.company_id.l10n_in_tan),
438 ('parent_state', '=', 'posted')
439 ]
440 if commercial_partner_id.l10n_in_pan_entity_id:
441 default_domain += [('move_id.commercial_partner_id.l10n_in_pan_entity_id', '=', commercial_partner_id.l10n_in_pan_entity_id.id)]
442 else:
443 default_domain += [('move_id.commercial_partner_id', '=', commercial_partner_id.id)]
444 frequency_domains = {
445 'monthly': [('date', '>=', month_start_date), ('date', '<=', month_end_date)],
446 'fiscal_yearly': [('date', '>=', fiscalyear_start_date), ('date', '<=', fiscalyear_end_date)],
447 }
448 aggregate_result = {}
449 for frequency, frequency_domain in frequency_domains.items():
450 query = self.env['account.move.line']._search(default_domain + frequency_domain, bypass_access=True, active_test=False)
451 result = self.env.execute_query_dict(SQL(
452 """
453 SELECT COALESCE(sum(account_move_line.balance), 0) as balance,
454 COALESCE(sum(account_move_line.price_total * am.invoice_currency_rate), 0) as price_total
455 FROM %s
456 JOIN account_move AS am ON am.id = account_move_line.move_id
457 WHERE %s
458 """,
459 query.from_clause,
460 query.where_clause)
461 )
462 aggregate_result[frequency] = result[0]
463 return aggregate_result
464
465 def _l10n_in_is_warning_applicable(self, section_id):
466 self.ensure_one()
467 match section_id.tax_source_type:
468 case 'tcs':
469 return self.company_id.l10n_in_tcs_feature and self.journal_id.type == 'sale'
470 case 'tds':
471 return (
472 self.company_id.l10n_in_tds_feature
473 and self.journal_id.type == 'purchase'
474 and section_id not in self.l10n_in_withhold_move_ids.filtered(lambda m:
475 m.state == 'posted'
476 ).mapped('line_ids.tax_ids.l10n_in_section_id')
477 )
478 case _:
479 return False
480
481 def _get_l10n_in_tds_tcs_applicable_sections(self):
482 def _group_by_section_alert(invoice_lines):
483 group_by_lines = {}
484 for line in invoice_lines:
485 group_key = line.account_id.sudo().l10n_in_tds_tcs_section_id
486 if group_key and not line.company_currency_id.is_zero(line.price_total):
487 group_by_lines.setdefault(group_key, [])
488 group_by_lines[group_key].append(line)
489 return group_by_lines
490
491 def _is_section_applicable(section_alert, threshold_sums, invoice_currency_rate, lines):
492 lines_total = sum(
493 (line.price_total * invoice_currency_rate) if section_alert.consider_amount == 'total_amount' else line.balance
494 for line in lines
495 )
496 if section_alert.is_aggregate_limit:
497 aggregate_period_key = section_alert.consider_amount == 'total_amount' and 'price_total' or 'balance'
498 aggregate_total = threshold_sums.get(section_alert.aggregate_period, {}).get(aggregate_period_key)
499 if self.state == 'draft':
500 aggregate_total += lines_total
501 if aggregate_total > section_alert.aggregate_limit:
502 return True
503 return (
504 section_alert.is_per_transaction_limit
505 and lines_total > section_alert.per_transaction_limit
506 )
507
508 if self.country_code == 'IN' and self.move_type in ['in_invoice', 'out_invoice']:
509 warning = set()
510 commercial_partner_id = self.commercial_partner_id
511 if commercial_partner_id.l10n_in_pan_entity_id.tds_deduction == 'no':
512 invoice_lines = self.invoice_line_ids.filtered(lambda l: l.account_id.l10n_in_tds_tcs_section_id.tax_source_type != 'tds')
513 else:
514 invoice_lines = self.invoice_line_ids
515 existing_section = (
516 self.l10n_in_withhold_move_ids.line_ids + self.line_ids
517 ).tax_ids.l10n_in_section_id
518 for section_alert, lines in _group_by_section_alert(invoice_lines).items():
519 if (
520 (section_alert not in existing_section
521 or self._get_tcs_applicable_lines(lines))
522 and self._l10n_in_is_warning_applicable(section_alert)
523 and _is_section_applicable(
524 section_alert,
525 self._get_sections_aggregate_sum_by_pan(
526 section_alert,
527 commercial_partner_id
528 ),
529 self.invoice_currency_rate,
530 lines
531 )
532 ):
533 warning.add(section_alert.id)
534 return self.env['l10n_in.section.alert'].browse(warning)
535
536 def _get_tcs_applicable_lines(self, lines):
537 tcs_applicable_lines = set()
538 for line in lines:
539 if line.l10n_in_tds_tcs_section_id not in line.tax_ids.l10n_in_section_id:
540 tcs_applicable_lines.add(line.id)
541 return self.env['account.move.line'].browse(tcs_applicable_lines)
542
543 def l10n_in_verify_partner_gstin_status(self):
544 self.ensure_one()
545 return self.with_company(self.company_id).partner_id.action_l10n_in_verify_gstin_status()
546
547 def _get_name_invoice_report(self):
548 self.ensure_one()
549 if self.country_code == 'IN':
550 return 'l10n_in.l10n_in_report_invoice_document_inherit'
551 return super()._get_name_invoice_report()
552
553 def _post(self, soft=True):
554 """Use journal type to define document type because not miss state in any entry including POS entry"""
555 posted = super()._post(soft)
556 gst_treatment_name_mapping = {k: v for k, v in
557 self._fields['l10n_in_gst_treatment']._description_selection(self.env)}
558 for move in posted.filtered(lambda m: m.country_code == 'IN' and m.company_id.l10n_in_is_gst_registered and m.is_sale_document()):
559 if move.l10n_in_state_id and not move.l10n_in_state_id.l10n_in_tin:
560 raise UserError(_("Please set a valid TIN Number on the Place of Supply %s", move.l10n_in_state_id.name))
561 if not move.company_id.state_id:
562 msg = _("Your company %s needs to have a correct address in order to validate this invoice.\n"
563 "Set the address of your company (Don't forget the State field)", move.company_id.name)
564 action = {
565 "view_mode": "form",
566 "res_model": "res.company",
567 "type": "ir.actions.act_window",
568 "res_id" : move.company_id.id,
569 "views": [[self.env.ref("base.view_company_form").id, "form"]],
570 }
571 raise RedirectWarning(msg, action, _('Go to Company configuration'))
572 move.l10n_in_gstin = move.partner_id.vat
573 if (
574 not move.l10n_in_gstin
575 and move.l10n_in_gst_treatment in [
576 'regular',
577 'composition',
578 'special_economic_zone',
579 'deemed_export'
580 ]
581 ):
582 raise ValidationError(_(
583 "Partner %(partner_name)s (%(partner_id)s) GSTIN is required under GST Treatment %(name)s",
584 partner_name=move.partner_id.name,
585 partner_id=move.partner_id.id,
586 name=gst_treatment_name_mapping.get(move.l10n_in_gst_treatment)
587 ))
588 return posted
589
590 def _l10n_in_get_warehouse_address(self):
591 """Return address where goods are delivered/received for Invoice/Bill"""
592 # TO OVERRIDE
593 self.ensure_one()
594 return False
595
596 def _can_be_unlinked(self):
597 self.ensure_one()
598 return (self.country_code != 'IN' or not self.posted_before) and super()._can_be_unlinked()
599
600 def _generate_qr_code(self, silent_errors=False):
601 self.ensure_one()
602 if self.company_id.country_code == 'IN' and self.company_id.l10n_in_upi_id:
603 payment_url = 'upi://pay?pa=%s&pn=%s&am=%s&tr=%s&tn=%s' % (
604 self.company_id.l10n_in_upi_id,
605 self.company_id.name,
606 self.amount_residual,
607 self.payment_reference or self.name,
608 ("Payment for %s" % self.name))
609 barcode = self.env['ir.actions.report'].barcode(barcode_type="QR", value=payment_url, width=120, height=120, quiet=False)
610 return image_data_uri(base64.b64encode(barcode))
611 return super()._generate_qr_code(silent_errors)
612
613 def _l10n_in_get_hsn_summary_table(self):
614 self.ensure_one()
615 base_lines, _tax_lines = self._get_rounded_base_and_tax_lines()
616 display_uom = self.env.user.has_group('uom.group_uom')
617 return self.env['account.tax']._l10n_in_get_hsn_summary_table(base_lines, display_uom)
618
619 def _l10n_in_get_bill_from_irn(self, irn):
620 # TO OVERRIDE
621 return False
622
623 # ------Utils------
624 @api.model
625 def _l10n_in_prepare_tax_details(self):
626 def l10n_in_grouping_key_generator(base_line, tax_data):
627 invl = base_line['record']
628 tax = tax_data['tax']
629 if self.l10n_in_gst_treatment in ('overseas', 'special_economic_zone') and all(
630 self.env.ref("l10n_in.tax_tag_igst") in rl.tag_ids
631 for rl in tax.invoice_repartition_line_ids if rl.repartition_type == 'tax'
632 ):
633 tax_data['is_reverse_charge'] = False
634 tag_ids = tax.invoice_repartition_line_ids.tag_ids.ids
635 line_code = "other"
636 xmlid_to_res_id = self.env['ir.model.data']._xmlid_to_res_id
637 if not invl.currency_id.is_zero(tax_data['tax_amount_currency']):
638 if xmlid_to_res_id("l10n_in.tax_tag_cess") in tag_ids:
639 if tax.amount_type != "percent":
640 line_code = "cess_non_advol"
641 else:
642 line_code = "cess"
643 elif xmlid_to_res_id("l10n_in.tax_tag_state_cess") in tag_ids:
644 if tax.amount_type != "percent":
645 line_code = "state_cess_non_advol"
646 else:
647 line_code = "state_cess"
648 else:
649 for gst in ["cgst", "sgst", "igst"]:
650 if xmlid_to_res_id("l10n_in.tax_tag_%s" % (gst)) in tag_ids:
651 # need to separate rc tax value so it's not pass to other values
652 line_code = f'{gst}_rc' if tax_data['is_reverse_charge'] else gst
653 return {
654 "tax": tax,
655 "base_product_id": invl.product_id,
656 "tax_product_id": invl.product_id,
657 "base_product_uom_id": invl.product_uom_id,
658 "tax_product_uom_id": invl.product_uom_id,
659 "line_code": line_code,
660 }
661
662 def l10n_in_filter_to_apply(base_line, tax_values):
663 return base_line['record'].display_type != 'rounding'
664
665 return self._prepare_invoice_aggregated_taxes(
666 filter_tax_values_to_apply=l10n_in_filter_to_apply,
667 grouping_key_generator=l10n_in_grouping_key_generator,
668 )
669
670 def _get_l10n_in_seller_buyer_party(self):
671 self.ensure_one()
672 return {
673 "seller_details": self.company_id.partner_id,
674 "dispatch_details": self._l10n_in_get_warehouse_address() or self.company_id.partner_id,
675 "buyer_details": self.partner_id,
676 "ship_to_details": self.partner_shipping_id or self.partner_id
677 }
678
679 @api.model
680 def _l10n_in_extract_digits(self, string):
681 if not string:
682 return ""
683 matches = re.findall(r"\d+", string)
684 return "".join(matches)
685
686 @api.model
687 def _l10n_in_is_service_hsn(self, hsn_code):
688 return self._l10n_in_extract_digits(hsn_code).startswith('99')
689
690 @api.model
691 def _l10n_in_round_value(self, amount, precision_digits=2):
692 """
693 This method is call for rounding.
694 If anything is wrong with rounding then we quick fix in method
695 """
696 return json_float_round(amount, precision_digits)
697
698 @api.model
699 def _get_l10n_in_tax_details_by_line_code(self, tax_details):
700 l10n_in_tax_details = {}
701 for tax_detail in tax_details.values():
702 if tax_detail["tax"].l10n_in_reverse_charge:
703 l10n_in_tax_details.setdefault("is_reverse_charge", True)
704 line_code = tax_detail["line_code"]
705 l10n_in_tax_details.setdefault("%s_rate" % (line_code), tax_detail["tax"].amount)
706 l10n_in_tax_details.setdefault("%s_amount" % (line_code), 0.00)
707 l10n_in_tax_details.setdefault("%s_amount_currency" % (line_code), 0.00)
708 l10n_in_tax_details["%s_amount" % (line_code)] += tax_detail["tax_amount"]
709 l10n_in_tax_details["%s_amount_currency" % (line_code)] += tax_detail["tax_amount_currency"]
710 return l10n_in_tax_details
711
712 @api.model
713 def _l10n_in_edi_get_iap_buy_credits_message(self):
714 url = self.env['iap.account'].get_credits_url(service_name=IAP_SERVICE_NAME)
715 return Markup("""<p><b>%s</b></p><p>%s <a href="%s">%s</a></p>""") % (
716 _("You have insufficient credits to send this document!"),
717 _("Please buy more credits and retry: "),
718 url,
719 _("Buy Credits")
720 )
721
722 def _get_sync_stack(self, container):
723 stack, update_containers = super()._get_sync_stack(container)
724 _tax_container, invoice_container, misc_container = update_containers()
725 moves = invoice_container['records'] + misc_container['records']
726 stack.append((9, self._sync_l10n_in_gstr_section(moves)))
727 return stack, update_containers
728
729 @contextmanager
730 def _sync_l10n_in_gstr_section(self, moves):
731 yield
732 tax_tags_dict = self.env['account.move.line']._get_l10n_in_tax_tag_ids()
733 # we set the section on the invoice lines
734 moves.line_ids._set_l10n_in_gstr_section(tax_tags_dict)
735
736 def _get_l10n_in_invoice_label(self):
737 self.ensure_one()
738 exempt_types = {'exempt', 'nil_rated', 'non_gst'}
739 if self.country_code != 'IN' or not self.is_sale_document(include_receipts=False):
740 return
741 gst_treatment = self.l10n_in_gst_treatment
742 company = self.company_id
743 tax_types = set(self.invoice_line_ids.tax_ids.mapped('l10n_in_tax_type'))
744 if company.l10n_in_is_gst_registered and tax_types:
745 if gst_treatment in ['overseas', 'special_economic_zone']:
746 return 'Tax Invoice'
747 elif tax_types.issubset(exempt_types):
748 return 'Bill of Supply'
749 elif tax_types.isdisjoint(exempt_types):
750 return 'Tax Invoice'
751 elif gst_treatment in ['unregistered', 'consumer']:
752 return 'Invoice-cum-Bill of Supply'
753 return 'Invoice'