blob: 1733220c0ac2675e70d7535ed38873b6cd331430 [file] [log] [blame]
Aditya Hasef3c22f32019-01-22 18:22:20 +05301from __future__ import unicode_literals
Chillar Anand915b3432021-09-02 16:44:59 +05302
3import json
4import re
5
6import frappe
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05307from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05308from frappe.model.utils import get_fetch_values
9from frappe.utils import cint, cstr, date_diff, flt, getdate, nowdate
10from six import string_types
11
Shreya Shah4fa600a2018-06-05 11:27:53 +053012from erpnext.controllers.accounts_controller import get_taxes_and_charges
Chillar Anand915b3432021-09-02 16:44:59 +053013from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +053014from erpnext.hr.utils import get_salary_assignment
Anurag Mishra289c8222020-06-19 19:17:57 +053015from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Chillar Anand915b3432021-09-02 16:44:59 +053016from erpnext.regional.india import number_state_mapping, state_numbers, states
Ankush Menat7c4c42a2021-03-03 14:56:19 +053017
18GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") #alphanumeric and - /
19GSTIN_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}$")
20GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
21PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
22
23
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053024def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053025 if hasattr(doc, 'gst_state') and doc.gst_state:
26 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053027 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053028 return
29
Deepesh Garg459155f2019-06-14 12:01:34 +053030 gst_category = []
31
32 if len(doc.links):
33 link_doctype = doc.links[0].get("link_doctype")
34 link_name = doc.links[0].get("link_name")
35
36 if link_doctype in ["Customer", "Supplier"]:
37 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
38
Sagar Vorad75095b2019-01-23 14:40:01 +053039 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053040 if not doc.gstin or doc.gstin == 'NA':
41 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053042
Sagar Vora07cf4e82019-01-10 11:07:51 +053043 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053044 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053045
Deepesh Garg459155f2019-06-14 12:01:34 +053046 if gst_category and gst_category == 'UIN Holders':
Ankush Menat7c4c42a2021-03-03 14:56:19 +053047 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053048 frappe.throw(_("The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"),
49 title=_("Invalid GSTIN"))
Deepesh Garg459155f2019-06-14 12:01:34 +053050 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053051 if not GSTIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053052 frappe.throw(_("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN"))
Rushabh Mehta7231f292017-07-13 15:00:56 +053053
Deepesh Garg459155f2019-06-14 12:01:34 +053054 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053055 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053056
Anurag Mishra1e396dc2021-01-13 14:01:57 +053057 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053058 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053059
Deepesh Garg459155f2019-06-14 12:01:34 +053060 if doc.gst_state_number != doc.gstin[:2]:
Saqib93203162021-04-12 17:55:46 +053061 frappe.throw(_("First 2 digits of GSTIN should match with State number {0}.")
62 .format(doc.gst_state_number), title=_("Invalid GSTIN"))
Sagar Vora07cf4e82019-01-10 11:07:51 +053063
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053064def validate_pan_for_india(doc, method):
Deepesh Gargcd4b2032021-10-25 11:21:55 +053065 if doc.get('country') != 'India' or not doc.get('pan'):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053066 return
67
Ankush Menat7c4c42a2021-03-03 14:56:19 +053068 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053069 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
70
Deepesh Gargd07447a2020-11-24 08:09:17 +053071def validate_tax_category(doc, method):
Deepesh Gargb0743342020-12-17 18:46:59 +053072 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 +053073 if doc.is_inter_state:
74 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
75 else:
76 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
77
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053078def update_gst_category(doc, method):
79 for link in doc.links:
80 if link.link_doctype in ['Customer', 'Supplier']:
81 if doc.get('gstin'):
82 frappe.db.sql("""
83 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
84 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
85
Nabin Hait34c551d2019-07-03 10:34:31 +053086def set_gst_state_and_state_number(doc):
87 if not doc.gst_state:
88 if not doc.state:
89 return
90 state = doc.state.lower()
91 states_lowercase = {s.lower():s for s in states}
92 if state in states_lowercase:
93 doc.gst_state = states_lowercase[state]
94 else:
95 return
96
97 doc.gst_state_number = state_numbers[doc.gst_state]
98
99def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +0530100 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +0530101 factor = 1
102 total = 0
103 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +0530104 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530105 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530106 for char in input_chars:
107 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530108 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530109 total += digit
110 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530111 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530112 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 +0530113
Nabin Haitb962fc12017-07-17 18:02:31 +0530114def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
Subin Tom530de122021-10-11 17:33:41 +0530115 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
116 if frappe.get_meta(item_doctype).has_field('gst_hsn_code') and hsn_wise_in_gst_settings:
117 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
118 else:
119 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530120
Subin Tomd49346a2021-09-17 10:39:03 +0530121def get_itemised_tax_breakup_data(doc, account_wise=False, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530122 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530123
124 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530125
Nabin Haitb962fc12017-07-17 18:02:31 +0530126 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
127 return itemised_tax, itemised_taxable_amount
128
Subin Tom530de122021-10-11 17:33:41 +0530129 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
130
131 tax_breakup_hsn_wise = hsn_wise or hsn_wise_in_gst_settings
132 if tax_breakup_hsn_wise:
Subin Tomd49346a2021-09-17 10:39:03 +0530133 item_hsn_map = frappe._dict()
134 for d in doc.items:
135 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
Nabin Haitb962fc12017-07-17 18:02:31 +0530136
137 hsn_tax = {}
138 for item, taxes in itemised_tax.items():
Subin Tom530de122021-10-11 17:33:41 +0530139 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530140 hsn_tax.setdefault(item_or_hsn, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530141 for tax_desc, tax_detail in taxes.items():
142 key = tax_desc
143 if account_wise:
144 key = tax_detail.get('tax_account')
Subin Tomd49346a2021-09-17 10:39:03 +0530145 hsn_tax[item_or_hsn].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
146 hsn_tax[item_or_hsn][key]["tax_rate"] = tax_detail.get("tax_rate")
147 hsn_tax[item_or_hsn][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530148
149 # set taxable amount
150 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530151 for item in itemised_taxable_amount:
Subin Tom530de122021-10-11 17:33:41 +0530152 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530153 hsn_taxable_amount.setdefault(item_or_hsn, 0)
154 hsn_taxable_amount[item_or_hsn] += itemised_taxable_amount.get(item)
Nabin Haitb962fc12017-07-17 18:02:31 +0530155
156 return hsn_tax, hsn_taxable_amount
157
Shreya Shah4fa600a2018-06-05 11:27:53 +0530158def set_place_of_supply(doc, method=None):
159 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530160
Ankush Menata44df632021-03-01 17:12:53 +0530161def validate_document_name(doc, method=None):
162 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530163
Ankush Menata44df632021-03-01 17:12:53 +0530164 country = frappe.get_cached_value("Company", doc.company, "country")
165
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530166 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530167 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
168 return
169
170 if len(doc.name) > 16:
171 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
172
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530173 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530174 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
175
Rushabh Mehta7231f292017-07-13 15:00:56 +0530176# don't remove this function it is used in tests
177def test_method():
178 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530179 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530180
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530181def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530182 if not frappe.get_meta('Address').has_field('gst_state'): return
183
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530184 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530185 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530186 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
187 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188
189 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530190 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530191 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530192 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530193 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530194
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530195@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530196def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530197 if isinstance(party_details, string_types):
198 party_details = json.loads(party_details)
199 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530200
Deepesh Garga7670852020-12-04 18:07:46 +0530201 update_party_details(party_details, doctype)
202
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530203 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530204
205 if is_internal_transfer(party_details, doctype):
206 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530207 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530208 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530209
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530210 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530211 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530212 get_tax_template_based_on_category(master_doctype, company, party_details)
213
pateljannatcd05b342020-11-19 11:37:08 +0530214 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530215 return party_details
216
217 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530218 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530219
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530220 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
221 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530222 get_tax_template_based_on_category(master_doctype, company, party_details)
223
pateljannatcd05b342020-11-19 11:37:08 +0530224 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530225 return party_details
226
227 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530228 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530229
pateljannatcd05b342020-11-19 11:37:08 +0530230 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530231
pateljannatcd05b342020-11-19 11:37:08 +0530232 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530233
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530234 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
235 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
236 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
237 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530238 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530239 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530240
241 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530242 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530243 party_details["taxes_and_charges"] = default_tax
244 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
245
pateljannatcd05b342020-11-19 11:37:08 +0530246 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530247
Deepesh Garga7670852020-12-04 18:07:46 +0530248def update_party_details(party_details, doctype):
249 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
250 if party_details.get(address_field):
251 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
252
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530253def is_internal_transfer(party_details, doctype):
254 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
255 destination_gstin = party_details.company_gstin
256 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
257 destination_gstin = party_details.supplier_gstin
258
Deepesh Gargda47fe22021-09-30 13:28:53 +0530259 if not destination_gstin or party_details.gstin:
260 return False
261
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530262 if party_details.gstin == destination_gstin:
263 return True
264 else:
265 False
266
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530267def get_tax_template_based_on_category(master_doctype, company, party_details):
268 if not party_details.get('tax_category'):
269 return
270
271 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
272 'name')
273
274 if default_tax:
275 party_details["taxes_and_charges"] = default_tax
276 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
277
278def get_tax_template(master_doctype, company, is_inter_state, state_code):
279 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
280 filters = {'is_inter_state': is_inter_state})
281
282 default_tax = ''
283
284 for tax_category in tax_categories:
285 if tax_category.gst_state == number_state_mapping[state_code] or \
286 (not default_tax and not tax_category.gst_state):
287 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530288 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530289 return default_tax
290
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530291def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530292 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530293 if not (basic_component and hra_component):
294 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530295 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530296 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530297 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530298 if assignment:
299 hra_component_exists = frappe.db.exists("Salary Detail", {
300 "parent": assignment.salary_structure,
301 "salary_component": hra_component,
302 "parentfield": "earnings",
303 "parenttype": "Salary Structure"
304 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530305
Nabin Hait04e7bf42019-04-25 18:44:10 +0530306 if hra_component_exists:
307 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
308 assignment.salary_structure, basic_component, hra_component)
309 if hra_amount:
310 if doc.monthly_house_rent:
311 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530312 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530313 if annual_exemption > 0:
314 monthly_exemption = annual_exemption / 12
315 else:
316 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530317
Nabin Hait04e7bf42019-04-25 18:44:10 +0530318 elif doc.docstatus == 1:
319 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
320
321 return frappe._dict({
322 "hra_amount": hra_amount,
323 "annual_exemption": annual_exemption,
324 "monthly_exemption": monthly_exemption
325 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530326
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530327def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530328 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530329 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530330 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530331 if earning.salary_component == basic_component:
332 basic_amt = earning.amount
333 elif earning.salary_component == hra_component:
334 hra_amt = earning.amount
335 if basic_amt and hra_amt:
336 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530337 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530339def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530340 # TODO make this configurable
341 exemptions = []
342 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
343 # case 1: The actual amount allotted by the employer as the HRA.
344 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530345
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530346 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530347 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530348
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530349 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530350 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530351 # 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 +0530352 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530353 # return minimum of 3 cases
354 return min(exemptions)
355
356def get_annual_component_pay(frequency, amount):
357 if frequency == "Daily":
358 return amount * 365
359 elif frequency == "Weekly":
360 return amount * 52
361 elif frequency == "Fortnightly":
362 return amount * 26
363 elif frequency == "Monthly":
364 return amount * 12
365 elif frequency == "Bimonthly":
366 return amount * 6
367
368def validate_house_rent_dates(doc):
369 if not doc.rented_to_date or not doc.rented_from_date:
370 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530371
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530372 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
373 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530374
375 proofs = frappe.db.sql("""
376 select name
377 from `tabEmployee Tax Exemption Proof Submission`
378 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530379 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
380 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
381 """, {
382 "employee": doc.employee,
383 "payroll_period": doc.payroll_period,
384 "from_date": doc.rented_from_date,
385 "to_date": doc.rented_to_date
386 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530387
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530388 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530389 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530390
391def calculate_hra_exemption_for_period(doc):
392 monthly_rent, eligible_hra = 0, 0
393 if doc.house_rent_payment_amount:
394 validate_house_rent_dates(doc)
395 # TODO receive rented months or validate dates are start and end of months?
396 # Calc monthly rent, round to nearest .5
397 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
398 factor = round(factor * 2)/2
399 monthly_rent = doc.house_rent_payment_amount / factor
400 # update field used by calculate_annual_eligible_hra_exemption
401 doc.monthly_house_rent = monthly_rent
402 exemptions = calculate_annual_eligible_hra_exemption(doc)
403
404 if exemptions["monthly_exemption"]:
405 # calc total exemption amount
406 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530407 exemptions["monthly_house_rent"] = monthly_rent
408 exemptions["total_eligible_hra_exemption"] = eligible_hra
409 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530410
Nabin Hait34c551d2019-07-03 10:34:31 +0530411def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530412
413 ewaybills = []
414 for doc_name in dn:
415 doc = frappe.get_doc(dt, doc_name)
416
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530417 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530418
419 data = frappe._dict({
420 "transporterId": "",
421 "TotNonAdvolVal": 0,
422 })
423
424 data.userGstin = data.fromGstin = doc.company_gstin
425 data.supplyType = 'O'
426
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530427 if dt == 'Delivery Note':
428 data.subSupplyType = 1
429 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530430 data.subSupplyType = 1
431 elif doc.gst_category in ['Overseas', 'Deemed Export']:
432 data.subSupplyType = 3
433 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530434 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530435
436 data.docType = 'INV'
437 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
438
439 company_address = frappe.get_doc('Address', doc.company_address)
440 billing_address = frappe.get_doc('Address', doc.customer_address)
441
Subin Tom5265ba32021-07-13 14:58:17 +0530442 #added dispatch address
Subin Tomb24a1492021-07-19 14:37:12 +0530443 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 +0530444 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
445
Subin Tom5265ba32021-07-13 14:58:17 +0530446 data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530447
448 data.itemList = []
449 data.totalValue = doc.total
450
Subin Tomd49346a2021-09-17 10:39:03 +0530451 data = get_item_list(data, doc, hsn_wise=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530452
453 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
454 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
455
456 data = get_transport_details(data, doc)
457
458 fields = {
459 "/. -": {
460 'docNo': doc.name,
461 'fromTrdName': doc.company,
462 'toTrdName': doc.customer_name,
463 'transDocNo': doc.lr_no,
464 },
465 "@#/,&. -": {
466 'fromAddr1': company_address.address_line1,
467 'fromAddr2': company_address.address_line2,
468 'fromPlace': company_address.city,
469 'toAddr1': shipping_address.address_line1,
470 'toAddr2': shipping_address.address_line2,
471 'toPlace': shipping_address.city,
472 'transporterName': doc.transporter_name
473 }
474 }
475
476 for allowed_chars, field_map in fields.items():
477 for key, value in field_map.items():
478 if not value:
479 data[key] = ''
480 else:
481 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
482
483 ewaybills.append(data)
484
485 data = {
Subin Tom8b2fe9e2021-08-23 11:17:31 +0530486 'version': '1.0.0421',
Nabin Hait34c551d2019-07-03 10:34:31 +0530487 'billLists': ewaybills
488 }
489
490 return data
491
492@frappe.whitelist()
493def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530494 dn = json.loads(dn)
495 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530496
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530497@frappe.whitelist()
498def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530499 data = json.loads(frappe.local.form_dict.data)
500 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530501 frappe.local.response.type = 'download'
502
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530503 filename_prefix = 'Bulk'
504 docname = frappe.local.form_dict.docname
505 if docname:
506 if docname.startswith('['):
507 docname = json.loads(docname)
508 if len(docname) == 1:
509 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530510
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530511 if not isinstance(docname, list):
512 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Suraj Shetty19c5fd72021-05-10 09:18:25 +0530513 filename_prefix = re.sub(r'[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530514
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530515 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 +0530516
Prasann Shah829172c2019-06-06 12:08:09 +0530517@frappe.whitelist()
518def get_gstins_for_company(company):
519 company_gstins =[]
520 if company:
521 company_gstins = frappe.db.sql("""select
522 distinct `tabAddress`.gstin
523 from
524 `tabAddress`, `tabDynamic Link`
525 where
526 `tabDynamic Link`.parent = `tabAddress`.name and
527 `tabDynamic Link`.parenttype = 'Address' and
528 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300529 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530530 return company_gstins
531
Subin Tom5265ba32021-07-13 14:58:17 +0530532def get_address_details(data, doc, company_address, billing_address, dispatch_address):
Nabin Hait34c551d2019-07-03 10:34:31 +0530533 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
Subin Tom5265ba32021-07-13 14:58:17 +0530534 data.fromStateCode = validate_state_code(company_address.gst_state_number, 'Company Address')
Subin Tomb24a1492021-07-19 14:37:12 +0530535 data.actualFromStateCode = validate_state_code(dispatch_address.gst_state_number, 'Dispatch Address')
Nabin Hait34c551d2019-07-03 10:34:31 +0530536
537 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
538 data.toGstin = 'URP'
539 set_gst_state_and_state_number(billing_address)
540 else:
541 data.toGstin = doc.billing_address_gstin
542
543 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
544 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
545
546 if doc.customer_address != doc.shipping_address_name:
547 data.transType = 2
548 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
549 set_gst_state_and_state_number(shipping_address)
550 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
551 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
552 else:
553 data.transType = 1
554 data.actualToStateCode = data.toStateCode
555 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530556
Smit Vorabbe49332020-11-18 20:58:59 +0530557 if doc.gst_category == 'SEZ':
558 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530559
560 return data
561
Subin Tomd49346a2021-09-17 10:39:03 +0530562def get_item_list(data, doc, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530563 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
564 data[attr] = 0
565
566 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
567 tax_map = {
568 'sgst_account': ['sgstRate', 'sgstValue'],
569 'cgst_account': ['cgstRate', 'cgstValue'],
570 'igst_account': ['igstRate', 'igstValue'],
571 'cess_account': ['cessRate', 'cessValue']
572 }
573 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
Subin Tomd49346a2021-09-17 10:39:03 +0530574 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 +0530575 for hsn_code, taxable_amount in hsn_taxable_amount.items():
576 item_data = frappe._dict()
577 if not hsn_code:
578 frappe.throw(_('GST HSN Code does not exist for one or more items'))
579 item_data.hsnCode = int(hsn_code)
580 item_data.taxableAmount = taxable_amount
581 item_data.qtyUnit = ""
582 for attr in item_data_attrs:
583 item_data[attr] = 0
584
585 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
586 account_type = gst_accounts.get(account, '')
587 for tax_acc, attrs in tax_map.items():
588 if account_type == tax_acc:
589 item_data[attrs[0]] = tax_detail.get('tax_rate')
590 data[attrs[1]] += tax_detail.get('tax_amount')
591 break
592 else:
593 data.OthValue += tax_detail.get('tax_amount')
594
595 data.itemList.append(item_data)
596
597 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
598 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
599 data[attr] = flt(data[attr], 2)
600
601 return data
602
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530603def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530604 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530605 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530606
607 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530608 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530609
610 if doc.ewaybill:
611 frappe.throw(_('e-Way Bill already exists for this document'))
612
613 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
614 'shipping_address_name', 'mode_of_transport', 'distance']
615
616 for fieldname in reqd_fields:
617 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530618 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530619 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530620 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530621
622 if len(doc.company_gstin) < 15:
623 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
624
625def get_transport_details(data, doc):
626 if doc.distance > 4000:
627 frappe.throw(_('Distance cannot be greater than 4000 kms'))
628
629 data.transDistance = int(round(doc.distance))
630
631 transport_modes = {
632 'Road': 1,
633 'Rail': 2,
634 'Air': 3,
635 'Ship': 4
636 }
637
638 vehicle_types = {
639 'Regular': 'R',
640 'Over Dimensional Cargo (ODC)': 'O'
641 }
642
643 data.transMode = transport_modes.get(doc.mode_of_transport)
644
645 if doc.mode_of_transport == 'Road':
646 if not doc.gst_transporter_id and not doc.vehicle_no:
647 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
648 if doc.vehicle_no:
649 data.vehicleNo = doc.vehicle_no.replace(' ', '')
650 if not doc.gst_vehicle_type:
651 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
652 else:
653 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
654 else:
655 if not doc.lr_no or not doc.lr_date:
656 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
657
658 if doc.lr_no:
659 data.transDocNo = doc.lr_no
660
661 if doc.lr_date:
662 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
663
664 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530665 if doc.gst_transporter_id[0:2] != "88":
666 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
667 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530668
669 return data
670
671
672def validate_pincode(pincode, address):
673 pin_not_found = "Pin Code doesn't exist for {}"
674 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
675
676 if not pincode:
677 frappe.throw(_(pin_not_found.format(address)))
678
679 pincode = pincode.replace(' ', '')
680 if not pincode.isdigit() or len(pincode) != 6:
681 frappe.throw(_(incorrect_pin.format(address)))
682 else:
683 return int(pincode)
684
685def validate_state_code(state_code, address):
686 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
687 if not state_code:
688 frappe.throw(_(no_state_code.format(address)))
689 else:
690 return int(state_code)
691
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530692@frappe.whitelist()
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530693def get_gst_accounts(company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0):
694 filters={"parent": "GST Settings"}
695
696 if company:
697 filters.update({'company': company})
698 if only_reverse_charge:
699 filters.update({'is_reverse_charge_account': 1})
700 elif only_non_reverse_charge:
701 filters.update({'is_reverse_charge_account': 0})
702
Nabin Hait34c551d2019-07-03 10:34:31 +0530703 gst_accounts = frappe._dict()
704 gst_settings_accounts = frappe.get_all("GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530705 filters=filters,
Nabin Hait34c551d2019-07-03 10:34:31 +0530706 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
707
Deepesh Garg44273902021-05-20 17:19:24 +0530708 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530709 frappe.throw(_("Please set GST Accounts in GST Settings"))
710
711 for d in gst_settings_accounts:
712 for acc, val in d.items():
713 if not account_wise:
714 gst_accounts.setdefault(acc, []).append(val)
715 elif val:
716 gst_accounts[val] = acc
717
Nabin Hait34c551d2019-07-03 10:34:31 +0530718 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530719
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530720def validate_reverse_charge_transaction(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530721 country = frappe.get_cached_value('Company', doc.company, 'country')
722
723 if country != 'India':
724 return
725
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530726 base_gst_tax = 0
727 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530728
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530729 if doc.reverse_charge == 'Y':
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530730 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
731 reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
732 + gst_accounts.get('igst_account')
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530733
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530734 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
735 non_reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530736 + gst_accounts.get('igst_account')
737
738 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530739 if tax.account_head in non_reverse_charge_accounts:
740 if tax.add_deduct_tax == 'Add':
741 base_gst_tax += tax.base_tax_amount_after_discount_amount
742 else:
743 base_gst_tax += tax.base_tax_amount_after_discount_amount
744 elif tax.account_head in reverse_charge_accounts:
745 if tax.add_deduct_tax == 'Add':
746 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
747 else:
748 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530749
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530750 if base_gst_tax != base_reverse_charge_booked:
751 msg = _("Booked reverse charge is not equal to applied tax amount")
752 msg += "<br>"
753 msg += _("Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice").format(
754 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 +0530755
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530756 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530757
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530758def update_itc_availed_fields(doc, method):
759 country = frappe.get_cached_value('Company', doc.company, 'country')
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530760
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530761 if country != 'India':
762 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530763
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530764 # Initialize values
765 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
766 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530767
Deepesh Garg93f925f2021-03-15 18:04:42 +0530768 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530769 if tax.account_head in gst_accounts.get('igst_account', []):
770 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
771 if tax.account_head in gst_accounts.get('sgst_account', []):
772 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
773 if tax.account_head in gst_accounts.get('cgst_account', []):
774 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
775 if tax.account_head in gst_accounts.get('cess_account', []):
776 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530777
Deepesh Garg8b644d82021-07-15 15:36:54 +0530778def update_place_of_supply(doc, method):
779 country = frappe.get_cached_value('Company', doc.company, 'country')
780 if country != 'India':
781 return
782
Deepesh Garga06a70d2021-09-03 12:40:13 +0530783 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 +0530784 if address and address.gst_state and address.gst_state_number:
785 doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
786
Deepesh Garg004f9e62021-03-16 13:09:59 +0530787@frappe.whitelist()
788def get_regional_round_off_accounts(company, account_list):
789 country = frappe.get_cached_value('Company', company, 'country')
790
791 if country != 'India':
792 return
793
794 if isinstance(account_list, string_types):
795 account_list = json.loads(account_list)
796
797 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
798 return
799
800 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530801
802 gst_account_list = []
803 for account in ['cgst_account', 'sgst_account', 'igst_account']:
walstanbab673d92021-03-27 12:52:23 +0530804 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530805 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530806
807 account_list.extend(gst_account_list)
808
809 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530810
811def update_taxable_values(doc, method):
812 country = frappe.get_cached_value('Company', doc.company, 'country')
813
814 if country != 'India':
815 return
816
817 gst_accounts = get_gst_accounts(doc.company)
818
819 # Only considering sgst account to avoid inflating taxable value
820 gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
821 + gst_accounts.get('igst_account', [])
822
823 additional_taxes = 0
824 total_charges = 0
825 item_count = 0
826 considered_rows = []
827
828 for tax in doc.get('taxes'):
829 prev_row_id = cint(tax.row_id) - 1
830 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
831 if tax.charge_type == 'On Previous Row Amount':
832 additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
833 considered_rows.append(prev_row_id)
834 if tax.charge_type == 'On Previous Row Total':
835 additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
836 considered_rows.append(prev_row_id)
837
838 for item in doc.get('items'):
Deepesh Garg4afda3c2021-06-01 13:13:04 +0530839 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
840 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530841
842 applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
843 item.precision('taxable_value')))
844 item.taxable_value = applicable_charges + proportionate_value
845 total_charges += applicable_charges
846 item_count += 1
847
848 if total_charges != additional_taxes:
849 diff = additional_taxes - total_charges
850 doc.get('items')[item_count - 1].taxable_value += diff
Saqib9226cd32021-05-10 12:36:56 +0530851
852def get_depreciation_amount(asset, depreciable_value, row):
853 depreciation_left = flt(row.total_number_of_depreciations) - flt(asset.number_of_depreciations_booked)
854
855 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +0530856 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +0530857 if not asset.flags.increase_in_asset_life:
GangaManoj2b93e542021-06-19 13:45:37 +0530858 depreciation_amount = (flt(row.value_after_depreciation) -
859 flt(row.expected_value_after_useful_life)) / depreciation_left
860
861 # if the Depreciation Schedule is being modified after Asset Repair
862 else:
863 depreciation_amount = (flt(row.value_after_depreciation) -
864 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 +0530865
Saqib9226cd32021-05-10 12:36:56 +0530866 else:
867 rate_of_depreciation = row.rate_of_depreciation
868 # if its the first depreciation
869 if depreciable_value == asset.gross_purchase_amount:
Saqib424efd42021-09-28 18:12:02 +0530870 if row.finance_book and frappe.db.get_value('Finance Book', row.finance_book, 'for_income_tax'):
871 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
872 diff = date_diff(row.depreciation_start_date, asset.available_for_use_date)
873 if diff <= 180:
874 rate_of_depreciation = rate_of_depreciation / 2
875 frappe.msgprint(
876 _('As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%.'))
Saqib9226cd32021-05-10 12:36:56 +0530877
878 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
879
Saqib3a504902021-08-03 15:57:11 +0530880 return depreciation_amount
881
882def set_item_tax_from_hsn_code(item):
Ankush Menat4551d7d2021-08-19 13:41:10 +0530883 if not item.taxes and item.gst_hsn_code:
Saqib3a504902021-08-03 15:57:11 +0530884 hsn_doc = frappe.get_doc("GST HSN Code", item.gst_hsn_code)
885
886 for tax in hsn_doc.taxes:
887 item.append('taxes', {
888 'item_tax_template': tax.item_tax_template,
889 'tax_category': tax.tax_category,
890 'valid_from': tax.valid_from
Ankush Menat4551d7d2021-08-19 13:41:10 +0530891 })
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530892
893def delete_gst_settings_for_company(doc, method):
894 if doc.country != 'India':
895 return
896
897 gst_settings = frappe.get_doc("GST Settings")
898 records_to_delete = []
899
900 for d in reversed(gst_settings.get('gst_accounts')):
901 if d.company == doc.name:
902 records_to_delete.append(d)
903
904 for d in records_to_delete:
905 gst_settings.remove(d)
906
907 gst_settings.save()