blob: e7539f516e44490bd2214583dea13488e4e20fdc [file] [log] [blame]
Chillar Anand915b3432021-09-02 16:44:59 +05301
2import json
3import re
4
5import frappe
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05306from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05307from frappe.model.utils import get_fetch_values
8from frappe.utils import cint, cstr, date_diff, flt, getdate, nowdate
9from six import string_types
10
Shreya Shah4fa600a2018-06-05 11:27:53 +053011from erpnext.controllers.accounts_controller import get_taxes_and_charges
Chillar Anand915b3432021-09-02 16:44:59 +053012from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +053013from erpnext.hr.utils import get_salary_assignment
Anurag Mishra289c8222020-06-19 19:17:57 +053014from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Chillar Anand915b3432021-09-02 16:44:59 +053015from erpnext.regional.india import number_state_mapping, state_numbers, states
Ankush Menat7c4c42a2021-03-03 14:56:19 +053016
17GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") #alphanumeric and - /
18GSTIN_FORMAT = re.compile("^[0-9]{2}[A-Z]{4}[0-9A-Z]{1}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}[1-9A-Z]{1}[0-9A-Z]{1}$")
19GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
20PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
21
22
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053023def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053024 if hasattr(doc, 'gst_state') and doc.gst_state:
25 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053026 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053027 return
28
Deepesh Garg459155f2019-06-14 12:01:34 +053029 gst_category = []
30
31 if len(doc.links):
32 link_doctype = doc.links[0].get("link_doctype")
33 link_name = doc.links[0].get("link_name")
34
35 if link_doctype in ["Customer", "Supplier"]:
36 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
37
Sagar Vorad75095b2019-01-23 14:40:01 +053038 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053039 if not doc.gstin or doc.gstin == 'NA':
40 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053041
Sagar Vora07cf4e82019-01-10 11:07:51 +053042 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053043 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053044
Deepesh Garg459155f2019-06-14 12:01:34 +053045 if gst_category and gst_category == 'UIN Holders':
Ankush Menat7c4c42a2021-03-03 14:56:19 +053046 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053047 frappe.throw(_("The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"),
48 title=_("Invalid GSTIN"))
Deepesh Garg459155f2019-06-14 12:01:34 +053049 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053050 if not GSTIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053051 frappe.throw(_("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN"))
Rushabh Mehta7231f292017-07-13 15:00:56 +053052
Deepesh Garg459155f2019-06-14 12:01:34 +053053 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053054 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053055
Anurag Mishra1e396dc2021-01-13 14:01:57 +053056 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053057 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053058
Deepesh Garg459155f2019-06-14 12:01:34 +053059 if doc.gst_state_number != doc.gstin[:2]:
Saqib93203162021-04-12 17:55:46 +053060 frappe.throw(_("First 2 digits of GSTIN should match with State number {0}.")
61 .format(doc.gst_state_number), title=_("Invalid GSTIN"))
Sagar Vora07cf4e82019-01-10 11:07:51 +053062
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053063def validate_pan_for_india(doc, method):
Deepesh Gargcd4b2032021-10-25 11:21:55 +053064 if doc.get('country') != 'India' or not doc.get('pan'):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053065 return
66
Ankush Menat7c4c42a2021-03-03 14:56:19 +053067 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053068 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
69
Deepesh Gargd07447a2020-11-24 08:09:17 +053070def validate_tax_category(doc, method):
Deepesh Gargb0743342020-12-17 18:46:59 +053071 if doc.get('gst_state') and frappe.db.get_value('Tax Category', {'gst_state': doc.gst_state, 'is_inter_state': doc.is_inter_state}):
Deepesh Gargd07447a2020-11-24 08:09:17 +053072 if doc.is_inter_state:
73 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
74 else:
75 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
76
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053077def update_gst_category(doc, method):
78 for link in doc.links:
79 if link.link_doctype in ['Customer', 'Supplier']:
80 if doc.get('gstin'):
81 frappe.db.sql("""
82 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
83 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
84
Nabin Hait34c551d2019-07-03 10:34:31 +053085def set_gst_state_and_state_number(doc):
86 if not doc.gst_state:
87 if not doc.state:
88 return
89 state = doc.state.lower()
90 states_lowercase = {s.lower():s for s in states}
91 if state in states_lowercase:
92 doc.gst_state = states_lowercase[state]
93 else:
94 return
95
96 doc.gst_state_number = state_numbers[doc.gst_state]
97
98def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053099 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +0530100 factor = 1
101 total = 0
102 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +0530103 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530104 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530105 for char in input_chars:
106 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530107 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530108 total += digit
109 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530110 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530111 frappe.throw(_("""Invalid {0}! The check digit validation has failed. Please ensure you've typed the {0} correctly.""").format(label))
Rushabh Mehta7231f292017-07-13 15:00:56 +0530112
Nabin Haitb962fc12017-07-17 18:02:31 +0530113def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
Subin Tom530de122021-10-11 17:33:41 +0530114 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
115 if frappe.get_meta(item_doctype).has_field('gst_hsn_code') and hsn_wise_in_gst_settings:
116 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
117 else:
118 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530119
Subin Tomd49346a2021-09-17 10:39:03 +0530120def get_itemised_tax_breakup_data(doc, account_wise=False, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530121 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530122
123 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530124
Nabin Haitb962fc12017-07-17 18:02:31 +0530125 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
126 return itemised_tax, itemised_taxable_amount
127
Subin Tom530de122021-10-11 17:33:41 +0530128 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
129
130 tax_breakup_hsn_wise = hsn_wise or hsn_wise_in_gst_settings
131 if tax_breakup_hsn_wise:
Subin Tomd49346a2021-09-17 10:39:03 +0530132 item_hsn_map = frappe._dict()
133 for d in doc.items:
134 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
Nabin Haitb962fc12017-07-17 18:02:31 +0530135
136 hsn_tax = {}
137 for item, taxes in itemised_tax.items():
Subin Tom530de122021-10-11 17:33:41 +0530138 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530139 hsn_tax.setdefault(item_or_hsn, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530140 for tax_desc, tax_detail in taxes.items():
141 key = tax_desc
142 if account_wise:
143 key = tax_detail.get('tax_account')
Subin Tomd49346a2021-09-17 10:39:03 +0530144 hsn_tax[item_or_hsn].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
145 hsn_tax[item_or_hsn][key]["tax_rate"] = tax_detail.get("tax_rate")
146 hsn_tax[item_or_hsn][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530147
148 # set taxable amount
149 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530150 for item in itemised_taxable_amount:
Subin Tom530de122021-10-11 17:33:41 +0530151 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530152 hsn_taxable_amount.setdefault(item_or_hsn, 0)
153 hsn_taxable_amount[item_or_hsn] += itemised_taxable_amount.get(item)
Nabin Haitb962fc12017-07-17 18:02:31 +0530154
155 return hsn_tax, hsn_taxable_amount
156
Shreya Shah4fa600a2018-06-05 11:27:53 +0530157def set_place_of_supply(doc, method=None):
158 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530159
Ankush Menata44df632021-03-01 17:12:53 +0530160def validate_document_name(doc, method=None):
161 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530162
Ankush Menata44df632021-03-01 17:12:53 +0530163 country = frappe.get_cached_value("Company", doc.company, "country")
164
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530165 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530166 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
167 return
168
169 if len(doc.name) > 16:
170 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
171
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530172 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530173 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
174
Rushabh Mehta7231f292017-07-13 15:00:56 +0530175# don't remove this function it is used in tests
176def test_method():
177 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530178 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530179
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530180def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530181 if not frappe.get_meta('Address').has_field('gst_state'): return
182
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530183 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530184 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530185 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
186 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530187
188 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530189 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530190 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530191 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530192 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530193
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530194@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530195def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530196 if isinstance(party_details, string_types):
197 party_details = json.loads(party_details)
198 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530199
Deepesh Garga7670852020-12-04 18:07:46 +0530200 update_party_details(party_details, doctype)
201
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530202 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530203
204 if is_internal_transfer(party_details, doctype):
205 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530206 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530207 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530208
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530209 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530210 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530211 get_tax_template_based_on_category(master_doctype, company, party_details)
212
pateljannatcd05b342020-11-19 11:37:08 +0530213 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530214 return party_details
215
216 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530217 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530218
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530219 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
220 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530221 get_tax_template_based_on_category(master_doctype, company, party_details)
222
pateljannatcd05b342020-11-19 11:37:08 +0530223 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530224 return party_details
225
226 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530227 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530228
pateljannatcd05b342020-11-19 11:37:08 +0530229 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530230
pateljannatcd05b342020-11-19 11:37:08 +0530231 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530232
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530233 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
234 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
235 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
236 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530237 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530238 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530239
240 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530241 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530242 party_details["taxes_and_charges"] = default_tax
243 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
244
pateljannatcd05b342020-11-19 11:37:08 +0530245 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530246
Deepesh Garga7670852020-12-04 18:07:46 +0530247def update_party_details(party_details, doctype):
248 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
249 if party_details.get(address_field):
250 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
251
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530252def is_internal_transfer(party_details, doctype):
253 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
254 destination_gstin = party_details.company_gstin
255 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
256 destination_gstin = party_details.supplier_gstin
257
Deepesh Gargda47fe22021-09-30 13:28:53 +0530258 if not destination_gstin or party_details.gstin:
259 return False
260
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530261 if party_details.gstin == destination_gstin:
262 return True
263 else:
264 False
265
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530266def get_tax_template_based_on_category(master_doctype, company, party_details):
267 if not party_details.get('tax_category'):
268 return
269
270 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
271 'name')
272
273 if default_tax:
274 party_details["taxes_and_charges"] = default_tax
275 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
276
277def get_tax_template(master_doctype, company, is_inter_state, state_code):
278 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
279 filters = {'is_inter_state': is_inter_state})
280
281 default_tax = ''
282
283 for tax_category in tax_categories:
284 if tax_category.gst_state == number_state_mapping[state_code] or \
285 (not default_tax and not tax_category.gst_state):
286 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530287 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530288 return default_tax
289
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530290def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530291 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530292 if not (basic_component and hra_component):
293 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530294 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530295 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530296 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530297 if assignment:
298 hra_component_exists = frappe.db.exists("Salary Detail", {
299 "parent": assignment.salary_structure,
300 "salary_component": hra_component,
301 "parentfield": "earnings",
302 "parenttype": "Salary Structure"
303 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530304
Nabin Hait04e7bf42019-04-25 18:44:10 +0530305 if hra_component_exists:
306 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
307 assignment.salary_structure, basic_component, hra_component)
308 if hra_amount:
309 if doc.monthly_house_rent:
310 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530311 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530312 if annual_exemption > 0:
313 monthly_exemption = annual_exemption / 12
314 else:
315 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530316
Nabin Hait04e7bf42019-04-25 18:44:10 +0530317 elif doc.docstatus == 1:
318 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
319
320 return frappe._dict({
321 "hra_amount": hra_amount,
322 "annual_exemption": annual_exemption,
323 "monthly_exemption": monthly_exemption
324 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530325
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530326def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530327 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530328 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530329 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530330 if earning.salary_component == basic_component:
331 basic_amt = earning.amount
332 elif earning.salary_component == hra_component:
333 hra_amt = earning.amount
334 if basic_amt and hra_amt:
335 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530336 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530337
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530338def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530339 # TODO make this configurable
340 exemptions = []
341 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
342 # case 1: The actual amount allotted by the employer as the HRA.
343 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530344
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530345 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530346 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530347
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530348 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530349 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530350 # case 3: 50% of the basic salary, if the employee is staying in a metro city (40% for a non-metro city).
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530351 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530352 # return minimum of 3 cases
353 return min(exemptions)
354
355def get_annual_component_pay(frequency, amount):
356 if frequency == "Daily":
357 return amount * 365
358 elif frequency == "Weekly":
359 return amount * 52
360 elif frequency == "Fortnightly":
361 return amount * 26
362 elif frequency == "Monthly":
363 return amount * 12
364 elif frequency == "Bimonthly":
365 return amount * 6
366
367def validate_house_rent_dates(doc):
368 if not doc.rented_to_date or not doc.rented_from_date:
369 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530370
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530371 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
372 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530373
374 proofs = frappe.db.sql("""
375 select name
376 from `tabEmployee Tax Exemption Proof Submission`
377 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530378 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
379 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
380 """, {
381 "employee": doc.employee,
382 "payroll_period": doc.payroll_period,
383 "from_date": doc.rented_from_date,
384 "to_date": doc.rented_to_date
385 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530386
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530387 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530388 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530389
390def calculate_hra_exemption_for_period(doc):
391 monthly_rent, eligible_hra = 0, 0
392 if doc.house_rent_payment_amount:
393 validate_house_rent_dates(doc)
394 # TODO receive rented months or validate dates are start and end of months?
395 # Calc monthly rent, round to nearest .5
396 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
397 factor = round(factor * 2)/2
398 monthly_rent = doc.house_rent_payment_amount / factor
399 # update field used by calculate_annual_eligible_hra_exemption
400 doc.monthly_house_rent = monthly_rent
401 exemptions = calculate_annual_eligible_hra_exemption(doc)
402
403 if exemptions["monthly_exemption"]:
404 # calc total exemption amount
405 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530406 exemptions["monthly_house_rent"] = monthly_rent
407 exemptions["total_eligible_hra_exemption"] = eligible_hra
408 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530409
Nabin Hait34c551d2019-07-03 10:34:31 +0530410def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530411
412 ewaybills = []
413 for doc_name in dn:
414 doc = frappe.get_doc(dt, doc_name)
415
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530416 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530417
418 data = frappe._dict({
419 "transporterId": "",
420 "TotNonAdvolVal": 0,
421 })
422
423 data.userGstin = data.fromGstin = doc.company_gstin
424 data.supplyType = 'O'
425
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530426 if dt == 'Delivery Note':
427 data.subSupplyType = 1
428 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530429 data.subSupplyType = 1
430 elif doc.gst_category in ['Overseas', 'Deemed Export']:
431 data.subSupplyType = 3
432 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530433 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530434
435 data.docType = 'INV'
436 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
437
438 company_address = frappe.get_doc('Address', doc.company_address)
439 billing_address = frappe.get_doc('Address', doc.customer_address)
440
Subin Tom5265ba32021-07-13 14:58:17 +0530441 #added dispatch address
Subin Tomb24a1492021-07-19 14:37:12 +0530442 dispatch_address = frappe.get_doc('Address', doc.dispatch_address_name) if doc.dispatch_address_name else company_address
Nabin Hait34c551d2019-07-03 10:34:31 +0530443 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
444
Subin Tom5265ba32021-07-13 14:58:17 +0530445 data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530446
447 data.itemList = []
448 data.totalValue = doc.total
449
Subin Tomd49346a2021-09-17 10:39:03 +0530450 data = get_item_list(data, doc, hsn_wise=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530451
452 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
453 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
454
455 data = get_transport_details(data, doc)
456
457 fields = {
458 "/. -": {
459 'docNo': doc.name,
460 'fromTrdName': doc.company,
461 'toTrdName': doc.customer_name,
462 'transDocNo': doc.lr_no,
463 },
464 "@#/,&. -": {
465 'fromAddr1': company_address.address_line1,
466 'fromAddr2': company_address.address_line2,
467 'fromPlace': company_address.city,
468 'toAddr1': shipping_address.address_line1,
469 'toAddr2': shipping_address.address_line2,
470 'toPlace': shipping_address.city,
471 'transporterName': doc.transporter_name
472 }
473 }
474
475 for allowed_chars, field_map in fields.items():
476 for key, value in field_map.items():
477 if not value:
478 data[key] = ''
479 else:
480 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
481
482 ewaybills.append(data)
483
484 data = {
Subin Tom8b2fe9e2021-08-23 11:17:31 +0530485 'version': '1.0.0421',
Nabin Hait34c551d2019-07-03 10:34:31 +0530486 'billLists': ewaybills
487 }
488
489 return data
490
491@frappe.whitelist()
492def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530493 dn = json.loads(dn)
494 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530495
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530496@frappe.whitelist()
497def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530498 data = json.loads(frappe.local.form_dict.data)
499 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530500 frappe.local.response.type = 'download'
501
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530502 filename_prefix = 'Bulk'
503 docname = frappe.local.form_dict.docname
504 if docname:
505 if docname.startswith('['):
506 docname = json.loads(docname)
507 if len(docname) == 1:
508 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530509
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530510 if not isinstance(docname, list):
511 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Suraj Shetty19c5fd72021-05-10 09:18:25 +0530512 filename_prefix = re.sub(r'[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530513
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530514 frappe.local.response.filename = '{0}_e-WayBill_Data_{1}.json'.format(filename_prefix, frappe.utils.random_string(5))
Nabin Hait34c551d2019-07-03 10:34:31 +0530515
Prasann Shah829172c2019-06-06 12:08:09 +0530516@frappe.whitelist()
517def get_gstins_for_company(company):
518 company_gstins =[]
519 if company:
520 company_gstins = frappe.db.sql("""select
521 distinct `tabAddress`.gstin
522 from
523 `tabAddress`, `tabDynamic Link`
524 where
525 `tabDynamic Link`.parent = `tabAddress`.name and
526 `tabDynamic Link`.parenttype = 'Address' and
527 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300528 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530529 return company_gstins
530
Subin Tom5265ba32021-07-13 14:58:17 +0530531def get_address_details(data, doc, company_address, billing_address, dispatch_address):
Nabin Hait34c551d2019-07-03 10:34:31 +0530532 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
Subin Tom5265ba32021-07-13 14:58:17 +0530533 data.fromStateCode = validate_state_code(company_address.gst_state_number, 'Company Address')
Subin Tomb24a1492021-07-19 14:37:12 +0530534 data.actualFromStateCode = validate_state_code(dispatch_address.gst_state_number, 'Dispatch Address')
Nabin Hait34c551d2019-07-03 10:34:31 +0530535
536 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
537 data.toGstin = 'URP'
538 set_gst_state_and_state_number(billing_address)
539 else:
540 data.toGstin = doc.billing_address_gstin
541
542 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
543 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
544
545 if doc.customer_address != doc.shipping_address_name:
546 data.transType = 2
547 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
548 set_gst_state_and_state_number(shipping_address)
549 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
550 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
551 else:
552 data.transType = 1
553 data.actualToStateCode = data.toStateCode
554 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530555
Smit Vorabbe49332020-11-18 20:58:59 +0530556 if doc.gst_category == 'SEZ':
557 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530558
559 return data
560
Subin Tomd49346a2021-09-17 10:39:03 +0530561def get_item_list(data, doc, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530562 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
563 data[attr] = 0
564
565 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
566 tax_map = {
567 'sgst_account': ['sgstRate', 'sgstValue'],
568 'cgst_account': ['cgstRate', 'cgstValue'],
569 'igst_account': ['igstRate', 'igstValue'],
570 'cess_account': ['cessRate', 'cessValue']
571 }
572 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
Subin Tomd49346a2021-09-17 10:39:03 +0530573 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True, hsn_wise=hsn_wise)
Nabin Hait34c551d2019-07-03 10:34:31 +0530574 for hsn_code, taxable_amount in hsn_taxable_amount.items():
575 item_data = frappe._dict()
576 if not hsn_code:
577 frappe.throw(_('GST HSN Code does not exist for one or more items'))
578 item_data.hsnCode = int(hsn_code)
579 item_data.taxableAmount = taxable_amount
580 item_data.qtyUnit = ""
581 for attr in item_data_attrs:
582 item_data[attr] = 0
583
584 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
585 account_type = gst_accounts.get(account, '')
586 for tax_acc, attrs in tax_map.items():
587 if account_type == tax_acc:
588 item_data[attrs[0]] = tax_detail.get('tax_rate')
589 data[attrs[1]] += tax_detail.get('tax_amount')
590 break
591 else:
592 data.OthValue += tax_detail.get('tax_amount')
593
594 data.itemList.append(item_data)
595
596 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
597 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
598 data[attr] = flt(data[attr], 2)
599
600 return data
601
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530602def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530603 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530604 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530605
606 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530607 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530608
609 if doc.ewaybill:
610 frappe.throw(_('e-Way Bill already exists for this document'))
611
612 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
613 'shipping_address_name', 'mode_of_transport', 'distance']
614
615 for fieldname in reqd_fields:
616 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530617 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530618 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530619 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530620
621 if len(doc.company_gstin) < 15:
622 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
623
624def get_transport_details(data, doc):
625 if doc.distance > 4000:
626 frappe.throw(_('Distance cannot be greater than 4000 kms'))
627
628 data.transDistance = int(round(doc.distance))
629
630 transport_modes = {
631 'Road': 1,
632 'Rail': 2,
633 'Air': 3,
634 'Ship': 4
635 }
636
637 vehicle_types = {
638 'Regular': 'R',
639 'Over Dimensional Cargo (ODC)': 'O'
640 }
641
642 data.transMode = transport_modes.get(doc.mode_of_transport)
643
644 if doc.mode_of_transport == 'Road':
645 if not doc.gst_transporter_id and not doc.vehicle_no:
646 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
647 if doc.vehicle_no:
648 data.vehicleNo = doc.vehicle_no.replace(' ', '')
649 if not doc.gst_vehicle_type:
650 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
651 else:
652 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
653 else:
654 if not doc.lr_no or not doc.lr_date:
655 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
656
657 if doc.lr_no:
658 data.transDocNo = doc.lr_no
659
660 if doc.lr_date:
661 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
662
663 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530664 if doc.gst_transporter_id[0:2] != "88":
665 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
666 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530667
668 return data
669
670
671def validate_pincode(pincode, address):
672 pin_not_found = "Pin Code doesn't exist for {}"
673 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
674
675 if not pincode:
676 frappe.throw(_(pin_not_found.format(address)))
677
678 pincode = pincode.replace(' ', '')
679 if not pincode.isdigit() or len(pincode) != 6:
680 frappe.throw(_(incorrect_pin.format(address)))
681 else:
682 return int(pincode)
683
684def validate_state_code(state_code, address):
685 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
686 if not state_code:
687 frappe.throw(_(no_state_code.format(address)))
688 else:
689 return int(state_code)
690
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530691@frappe.whitelist()
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530692def get_gst_accounts(company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0):
693 filters={"parent": "GST Settings"}
694
695 if company:
696 filters.update({'company': company})
697 if only_reverse_charge:
698 filters.update({'is_reverse_charge_account': 1})
699 elif only_non_reverse_charge:
700 filters.update({'is_reverse_charge_account': 0})
701
Nabin Hait34c551d2019-07-03 10:34:31 +0530702 gst_accounts = frappe._dict()
703 gst_settings_accounts = frappe.get_all("GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530704 filters=filters,
Nabin Hait34c551d2019-07-03 10:34:31 +0530705 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
706
Deepesh Garg44273902021-05-20 17:19:24 +0530707 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530708 frappe.throw(_("Please set GST Accounts in GST Settings"))
709
710 for d in gst_settings_accounts:
711 for acc, val in d.items():
712 if not account_wise:
713 gst_accounts.setdefault(acc, []).append(val)
714 elif val:
715 gst_accounts[val] = acc
716
Nabin Hait34c551d2019-07-03 10:34:31 +0530717 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530718
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530719def validate_reverse_charge_transaction(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530720 country = frappe.get_cached_value('Company', doc.company, 'country')
721
722 if country != 'India':
723 return
724
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530725 base_gst_tax = 0
726 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530727
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530728 if doc.reverse_charge == 'Y':
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530729 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
730 reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
731 + gst_accounts.get('igst_account')
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530732
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530733 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
734 non_reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530735 + gst_accounts.get('igst_account')
736
737 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530738 if tax.account_head in non_reverse_charge_accounts:
739 if tax.add_deduct_tax == 'Add':
740 base_gst_tax += tax.base_tax_amount_after_discount_amount
741 else:
742 base_gst_tax += tax.base_tax_amount_after_discount_amount
743 elif tax.account_head in reverse_charge_accounts:
744 if tax.add_deduct_tax == 'Add':
745 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
746 else:
747 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530748
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530749 if base_gst_tax != base_reverse_charge_booked:
750 msg = _("Booked reverse charge is not equal to applied tax amount")
751 msg += "<br>"
752 msg += _("Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice").format(
753 gst_document_link='<a href="https://docs.erpnext.com/docs/user/manual/en/regional/india/gst-setup">GST Documentation</a>')
Deepesh Garg24f9a802020-06-03 10:59:37 +0530754
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530755 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530756
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530757def update_itc_availed_fields(doc, method):
758 country = frappe.get_cached_value('Company', doc.company, 'country')
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530759
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530760 if country != 'India':
761 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530762
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530763 # Initialize values
764 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
765 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530766
Deepesh Garg93f925f2021-03-15 18:04:42 +0530767 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530768 if tax.account_head in gst_accounts.get('igst_account', []):
769 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
770 if tax.account_head in gst_accounts.get('sgst_account', []):
771 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
772 if tax.account_head in gst_accounts.get('cgst_account', []):
773 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
774 if tax.account_head in gst_accounts.get('cess_account', []):
775 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530776
Deepesh Garg8b644d82021-07-15 15:36:54 +0530777def update_place_of_supply(doc, method):
778 country = frappe.get_cached_value('Company', doc.company, 'country')
779 if country != 'India':
780 return
781
Deepesh Garga06a70d2021-09-03 12:40:13 +0530782 address = frappe.db.get_value("Address", doc.get('customer_address'), ["gst_state", "gst_state_number"], as_dict=1)
Deepesh Garg8b644d82021-07-15 15:36:54 +0530783 if address and address.gst_state and address.gst_state_number:
784 doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
785
Deepesh Garg004f9e62021-03-16 13:09:59 +0530786@frappe.whitelist()
787def get_regional_round_off_accounts(company, account_list):
788 country = frappe.get_cached_value('Company', company, 'country')
789
790 if country != 'India':
791 return
792
793 if isinstance(account_list, string_types):
794 account_list = json.loads(account_list)
795
796 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
797 return
798
799 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530800
801 gst_account_list = []
802 for account in ['cgst_account', 'sgst_account', 'igst_account']:
walstanbab673d92021-03-27 12:52:23 +0530803 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530804 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530805
806 account_list.extend(gst_account_list)
807
808 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530809
810def update_taxable_values(doc, method):
811 country = frappe.get_cached_value('Company', doc.company, 'country')
812
813 if country != 'India':
814 return
815
816 gst_accounts = get_gst_accounts(doc.company)
817
818 # Only considering sgst account to avoid inflating taxable value
819 gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
820 + gst_accounts.get('igst_account', [])
821
822 additional_taxes = 0
823 total_charges = 0
824 item_count = 0
825 considered_rows = []
826
827 for tax in doc.get('taxes'):
828 prev_row_id = cint(tax.row_id) - 1
829 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
830 if tax.charge_type == 'On Previous Row Amount':
831 additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
832 considered_rows.append(prev_row_id)
833 if tax.charge_type == 'On Previous Row Total':
834 additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
835 considered_rows.append(prev_row_id)
836
837 for item in doc.get('items'):
Deepesh Garg4afda3c2021-06-01 13:13:04 +0530838 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
839 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530840
841 applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
842 item.precision('taxable_value')))
843 item.taxable_value = applicable_charges + proportionate_value
844 total_charges += applicable_charges
845 item_count += 1
846
847 if total_charges != additional_taxes:
848 diff = additional_taxes - total_charges
849 doc.get('items')[item_count - 1].taxable_value += diff
Saqib9226cd32021-05-10 12:36:56 +0530850
GangaManoj3c8879e2021-09-21 06:07:06 +0530851def get_depreciation_amount(asset, depreciable_value, row):
852 depreciation_left = flt(row.total_number_of_depreciations) - flt(asset.number_of_depreciations_booked)
Saqib9226cd32021-05-10 12:36:56 +0530853
854 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +0530855 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +0530856 if not asset.flags.increase_in_asset_life:
GangaManoj700e78d2021-09-21 07:03:12 +0530857 depreciation_amount = (flt(asset.gross_purchase_amount) - flt(asset.opening_accumulated_depreciation) -
GangaManoj2b93e542021-06-19 13:45:37 +0530858 flt(row.expected_value_after_useful_life)) / depreciation_left
859
860 # if the Depreciation Schedule is being modified after Asset Repair
861 else:
862 depreciation_amount = (flt(row.value_after_depreciation) -
863 flt(row.expected_value_after_useful_life)) / (date_diff(asset.to_date, asset.available_for_use_date) / 365)
Ankush Menat4551d7d2021-08-19 13:41:10 +0530864
Saqib9226cd32021-05-10 12:36:56 +0530865 else:
866 rate_of_depreciation = row.rate_of_depreciation
867 # if its the first depreciation
868 if depreciable_value == asset.gross_purchase_amount:
Saqib424efd42021-09-28 18:12:02 +0530869 if row.finance_book and frappe.db.get_value('Finance Book', row.finance_book, 'for_income_tax'):
870 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
871 diff = date_diff(row.depreciation_start_date, asset.available_for_use_date)
872 if diff <= 180:
873 rate_of_depreciation = rate_of_depreciation / 2
874 frappe.msgprint(
875 _('As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%.'))
Saqib9226cd32021-05-10 12:36:56 +0530876
877 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
878
Saqib3a504902021-08-03 15:57:11 +0530879 return depreciation_amount
880
881def set_item_tax_from_hsn_code(item):
Ankush Menat4551d7d2021-08-19 13:41:10 +0530882 if not item.taxes and item.gst_hsn_code:
Saqib3a504902021-08-03 15:57:11 +0530883 hsn_doc = frappe.get_doc("GST HSN Code", item.gst_hsn_code)
884
885 for tax in hsn_doc.taxes:
886 item.append('taxes', {
887 'item_tax_template': tax.item_tax_template,
888 'tax_category': tax.tax_category,
889 'valid_from': tax.valid_from
Ankush Menat4551d7d2021-08-19 13:41:10 +0530890 })
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530891
892def delete_gst_settings_for_company(doc, method):
893 if doc.country != 'India':
894 return
895
896 gst_settings = frappe.get_doc("GST Settings")
897 records_to_delete = []
898
899 for d in reversed(gst_settings.get('gst_accounts')):
900 if d.company == doc.name:
901 records_to_delete.append(d)
902
903 for d in records_to_delete:
904 gst_settings.remove(d)
905
906 gst_settings.save()