blob: cb30605291cf8ae5e667ddeb61ae1af52397cc22 [file] [log] [blame]
Aditya Hasef3c22f32019-01-22 18:22:20 +05301from __future__ import unicode_literals
Nabin Hait34c551d2019-07-03 10:34:31 +05302import frappe, re, json
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05303from frappe import _
Deepesh Garg1c146062020-08-18 19:32:52 +05304import erpnext
Deepesh Garg3c004ad2020-07-02 21:18:29 +05305from frappe.utils import cstr, flt, date_diff, nowdate, round_based_on_smallest_currency_fraction, money_in_words
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05306from erpnext.regional.india import states, state_numbers
Nabin Haitb962fc12017-07-17 18:02:31 +05307from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Shreya Shah4fa600a2018-06-05 11:27:53 +05308from erpnext.controllers.accounts_controller import get_taxes_and_charges
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +05309from erpnext.hr.utils import get_salary_assignment
Anurag Mishra289c8222020-06-19 19:17:57 +053010from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053011from erpnext.regional.india import number_state_mapping
12from six import string_types
Deepesh Garg24f9a802020-06-03 10:59:37 +053013from erpnext.accounts.general_ledger import make_gl_entries
14from erpnext.accounts.utils import get_account_currency
Deepesh Garga7670852020-12-04 18:07:46 +053015from frappe.model.utils import get_fetch_values
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053016
17def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053018 if hasattr(doc, 'gst_state') and doc.gst_state:
19 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053020 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053021 return
22
Deepesh Garg459155f2019-06-14 12:01:34 +053023 gst_category = []
24
25 if len(doc.links):
26 link_doctype = doc.links[0].get("link_doctype")
27 link_name = doc.links[0].get("link_name")
28
29 if link_doctype in ["Customer", "Supplier"]:
30 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
31
Sagar Vorad75095b2019-01-23 14:40:01 +053032 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053033 if not doc.gstin or doc.gstin == 'NA':
34 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053035
Sagar Vora07cf4e82019-01-10 11:07:51 +053036 if len(doc.gstin) != 15:
37 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053038
Deepesh Garg459155f2019-06-14 12:01:34 +053039 if gst_category and gst_category == 'UIN Holders':
40 p = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
41 if not p.match(doc.gstin):
42 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
43 else:
44 p = 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}$")
45 if not p.match(doc.gstin):
46 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053047
Deepesh Garg459155f2019-06-14 12:01:34 +053048 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053049 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053050
Anurag Mishra1e396dc2021-01-13 14:01:57 +053051 if not doc.gst_state:
52 frappe.throw(_("Please Enter GST state"))
53
Deepesh Garg459155f2019-06-14 12:01:34 +053054 if doc.gst_state_number != doc.gstin[:2]:
55 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
56 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053057
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053058def validate_pan_for_india(doc, method):
Nabin Hait866cf702021-02-22 21:35:00 +053059 if doc.get('country') != 'India' or not doc.pan:
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053060 return
61
62 p = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
63 if not p.match(doc.pan):
64 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
65
Deepesh Gargd07447a2020-11-24 08:09:17 +053066def validate_tax_category(doc, method):
Deepesh Gargb0743342020-12-17 18:46:59 +053067 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 +053068 if doc.is_inter_state:
69 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
70 else:
71 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
72
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053073def update_gst_category(doc, method):
74 for link in doc.links:
75 if link.link_doctype in ['Customer', 'Supplier']:
76 if doc.get('gstin'):
77 frappe.db.sql("""
78 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
79 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
80
Nabin Hait34c551d2019-07-03 10:34:31 +053081def set_gst_state_and_state_number(doc):
82 if not doc.gst_state:
83 if not doc.state:
84 return
85 state = doc.state.lower()
86 states_lowercase = {s.lower():s for s in states}
87 if state in states_lowercase:
88 doc.gst_state = states_lowercase[state]
89 else:
90 return
91
92 doc.gst_state_number = state_numbers[doc.gst_state]
93
94def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053095 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053096 factor = 1
97 total = 0
98 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053099 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530100 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530101 for char in input_chars:
102 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530103 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530104 total += digit
105 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530106 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530107 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 +0530108
Nabin Haitb962fc12017-07-17 18:02:31 +0530109def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
110 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
111 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
112 else:
113 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530114
Nabin Hait34c551d2019-07-03 10:34:31 +0530115def get_itemised_tax_breakup_data(doc, account_wise=False):
116 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530117
118 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530119
Nabin Haitb962fc12017-07-17 18:02:31 +0530120 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
121 return itemised_tax, itemised_taxable_amount
122
123 item_hsn_map = frappe._dict()
124 for d in doc.items:
125 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
126
127 hsn_tax = {}
128 for item, taxes in itemised_tax.items():
129 hsn_code = item_hsn_map.get(item)
130 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530131 for tax_desc, tax_detail in taxes.items():
132 key = tax_desc
133 if account_wise:
134 key = tax_detail.get('tax_account')
135 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
136 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
137 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530138
139 # set taxable amount
140 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530141 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530142 hsn_code = item_hsn_map.get(item)
143 hsn_taxable_amount.setdefault(hsn_code, 0)
144 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
145
146 return hsn_tax, hsn_taxable_amount
147
Shreya Shah4fa600a2018-06-05 11:27:53 +0530148def set_place_of_supply(doc, method=None):
149 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530150
Rushabh Mehta7231f292017-07-13 15:00:56 +0530151# don't remove this function it is used in tests
152def test_method():
153 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530154 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530155
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530156def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530157 if not frappe.get_meta('Address').has_field('gst_state'): return
158
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530159 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530160 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530161 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
162 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530163
164 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530165 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530166 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530167 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530168 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530169
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530170@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530171def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530172 if isinstance(party_details, string_types):
173 party_details = json.loads(party_details)
174 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530175
Deepesh Garga7670852020-12-04 18:07:46 +0530176 update_party_details(party_details, doctype)
177
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530178 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530179
180 if is_internal_transfer(party_details, doctype):
181 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530182 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530183 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530184
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530185 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530186 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530187
188 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
189 get_tax_template_based_on_category(master_doctype, company, party_details)
190
pateljannatcd05b342020-11-19 11:37:08 +0530191 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530192 return party_details
193
194 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530195 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530196
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530197 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
198 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530199 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
200 get_tax_template_based_on_category(master_doctype, company, party_details)
201
pateljannatcd05b342020-11-19 11:37:08 +0530202 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530203 return party_details
204
205 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530206 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530207
pateljannatcd05b342020-11-19 11:37:08 +0530208 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530209
pateljannatcd05b342020-11-19 11:37:08 +0530210 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530211
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530212 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
213 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
214 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
215 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530216 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530218
219 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530220 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530221 party_details["taxes_and_charges"] = default_tax
222 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
223
pateljannatcd05b342020-11-19 11:37:08 +0530224 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530225
Deepesh Garga7670852020-12-04 18:07:46 +0530226def update_party_details(party_details, doctype):
227 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
228 if party_details.get(address_field):
229 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
230
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530231def is_internal_transfer(party_details, doctype):
232 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
233 destination_gstin = party_details.company_gstin
234 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
235 destination_gstin = party_details.supplier_gstin
236
237 if party_details.gstin == destination_gstin:
238 return True
239 else:
240 False
241
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530242def get_tax_template_based_on_category(master_doctype, company, party_details):
243 if not party_details.get('tax_category'):
244 return
245
246 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
247 'name')
248
249 if default_tax:
250 party_details["taxes_and_charges"] = default_tax
251 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
252
253def get_tax_template(master_doctype, company, is_inter_state, state_code):
254 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
255 filters = {'is_inter_state': is_inter_state})
256
257 default_tax = ''
258
259 for tax_category in tax_categories:
260 if tax_category.gst_state == number_state_mapping[state_code] or \
261 (not default_tax and not tax_category.gst_state):
262 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530263 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530264 return default_tax
265
266def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
267
268 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
269 ['gst_category', 'export_type'], as_dict=1)
270
271 if gst_details:
272 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
273 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
274 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
275
276 party_details["taxes_and_charges"] = default_tax
277 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
278
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530279
280def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530281 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530282 if not (basic_component and hra_component):
283 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530284 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530285 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530286 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530287 if assignment:
288 hra_component_exists = frappe.db.exists("Salary Detail", {
289 "parent": assignment.salary_structure,
290 "salary_component": hra_component,
291 "parentfield": "earnings",
292 "parenttype": "Salary Structure"
293 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530294
Nabin Hait04e7bf42019-04-25 18:44:10 +0530295 if hra_component_exists:
296 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
297 assignment.salary_structure, basic_component, hra_component)
298 if hra_amount:
299 if doc.monthly_house_rent:
300 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530301 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530302 if annual_exemption > 0:
303 monthly_exemption = annual_exemption / 12
304 else:
305 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530306
Nabin Hait04e7bf42019-04-25 18:44:10 +0530307 elif doc.docstatus == 1:
308 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
309
310 return frappe._dict({
311 "hra_amount": hra_amount,
312 "annual_exemption": annual_exemption,
313 "monthly_exemption": monthly_exemption
314 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530315
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530316def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530317 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530318 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530319 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530320 if earning.salary_component == basic_component:
321 basic_amt = earning.amount
322 elif earning.salary_component == hra_component:
323 hra_amt = earning.amount
324 if basic_amt and hra_amt:
325 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530326 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530327
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530328def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530329 # TODO make this configurable
330 exemptions = []
331 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
332 # case 1: The actual amount allotted by the employer as the HRA.
333 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530334
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530335 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530336 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530337
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530339 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530340 # 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 +0530341 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530342 # return minimum of 3 cases
343 return min(exemptions)
344
345def get_annual_component_pay(frequency, amount):
346 if frequency == "Daily":
347 return amount * 365
348 elif frequency == "Weekly":
349 return amount * 52
350 elif frequency == "Fortnightly":
351 return amount * 26
352 elif frequency == "Monthly":
353 return amount * 12
354 elif frequency == "Bimonthly":
355 return amount * 6
356
357def validate_house_rent_dates(doc):
358 if not doc.rented_to_date or not doc.rented_from_date:
359 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530360
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530361 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
362 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530363
364 proofs = frappe.db.sql("""
365 select name
366 from `tabEmployee Tax Exemption Proof Submission`
367 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530368 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
369 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
370 """, {
371 "employee": doc.employee,
372 "payroll_period": doc.payroll_period,
373 "from_date": doc.rented_from_date,
374 "to_date": doc.rented_to_date
375 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530376
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530377 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530378 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530379
380def calculate_hra_exemption_for_period(doc):
381 monthly_rent, eligible_hra = 0, 0
382 if doc.house_rent_payment_amount:
383 validate_house_rent_dates(doc)
384 # TODO receive rented months or validate dates are start and end of months?
385 # Calc monthly rent, round to nearest .5
386 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
387 factor = round(factor * 2)/2
388 monthly_rent = doc.house_rent_payment_amount / factor
389 # update field used by calculate_annual_eligible_hra_exemption
390 doc.monthly_house_rent = monthly_rent
391 exemptions = calculate_annual_eligible_hra_exemption(doc)
392
393 if exemptions["monthly_exemption"]:
394 # calc total exemption amount
395 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530396 exemptions["monthly_house_rent"] = monthly_rent
397 exemptions["total_eligible_hra_exemption"] = eligible_hra
398 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530399
Nabin Hait34c551d2019-07-03 10:34:31 +0530400def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530401
402 ewaybills = []
403 for doc_name in dn:
404 doc = frappe.get_doc(dt, doc_name)
405
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530406 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530407
408 data = frappe._dict({
409 "transporterId": "",
410 "TotNonAdvolVal": 0,
411 })
412
413 data.userGstin = data.fromGstin = doc.company_gstin
414 data.supplyType = 'O'
415
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530416 if dt == 'Delivery Note':
417 data.subSupplyType = 1
418 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530419 data.subSupplyType = 1
420 elif doc.gst_category in ['Overseas', 'Deemed Export']:
421 data.subSupplyType = 3
422 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530423 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530424
425 data.docType = 'INV'
426 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
427
428 company_address = frappe.get_doc('Address', doc.company_address)
429 billing_address = frappe.get_doc('Address', doc.customer_address)
430
431 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
432
433 data = get_address_details(data, doc, company_address, billing_address)
434
435 data.itemList = []
436 data.totalValue = doc.total
437
438 data = get_item_list(data, doc)
439
440 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
441 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
442
443 data = get_transport_details(data, doc)
444
445 fields = {
446 "/. -": {
447 'docNo': doc.name,
448 'fromTrdName': doc.company,
449 'toTrdName': doc.customer_name,
450 'transDocNo': doc.lr_no,
451 },
452 "@#/,&. -": {
453 'fromAddr1': company_address.address_line1,
454 'fromAddr2': company_address.address_line2,
455 'fromPlace': company_address.city,
456 'toAddr1': shipping_address.address_line1,
457 'toAddr2': shipping_address.address_line2,
458 'toPlace': shipping_address.city,
459 'transporterName': doc.transporter_name
460 }
461 }
462
463 for allowed_chars, field_map in fields.items():
464 for key, value in field_map.items():
465 if not value:
466 data[key] = ''
467 else:
468 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
469
470 ewaybills.append(data)
471
472 data = {
473 'version': '1.0.1118',
474 'billLists': ewaybills
475 }
476
477 return data
478
479@frappe.whitelist()
480def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530481 dn = json.loads(dn)
482 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530483
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530484@frappe.whitelist()
485def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530486 data = json.loads(frappe.local.form_dict.data)
487 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530488 frappe.local.response.type = 'download'
489
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530490 filename_prefix = 'Bulk'
491 docname = frappe.local.form_dict.docname
492 if docname:
493 if docname.startswith('['):
494 docname = json.loads(docname)
495 if len(docname) == 1:
496 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530497
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530498 if not isinstance(docname, list):
499 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
500 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530501
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530502 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 +0530503
Prasann Shah829172c2019-06-06 12:08:09 +0530504@frappe.whitelist()
505def get_gstins_for_company(company):
506 company_gstins =[]
507 if company:
508 company_gstins = frappe.db.sql("""select
509 distinct `tabAddress`.gstin
510 from
511 `tabAddress`, `tabDynamic Link`
512 where
513 `tabDynamic Link`.parent = `tabAddress`.name and
514 `tabDynamic Link`.parenttype = 'Address' and
515 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300516 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530517 return company_gstins
518
Nabin Hait34c551d2019-07-03 10:34:31 +0530519def get_address_details(data, doc, company_address, billing_address):
520 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
521 data.fromStateCode = data.actualFromStateCode = validate_state_code(
522 company_address.gst_state_number, 'Company Address')
523
524 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
525 data.toGstin = 'URP'
526 set_gst_state_and_state_number(billing_address)
527 else:
528 data.toGstin = doc.billing_address_gstin
529
530 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
531 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
532
533 if doc.customer_address != doc.shipping_address_name:
534 data.transType = 2
535 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
536 set_gst_state_and_state_number(shipping_address)
537 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
538 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
539 else:
540 data.transType = 1
541 data.actualToStateCode = data.toStateCode
542 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530543
Smit Vorabbe49332020-11-18 20:58:59 +0530544 if doc.gst_category == 'SEZ':
545 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530546
547 return data
548
549def get_item_list(data, doc):
550 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
551 data[attr] = 0
552
553 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
554 tax_map = {
555 'sgst_account': ['sgstRate', 'sgstValue'],
556 'cgst_account': ['cgstRate', 'cgstValue'],
557 'igst_account': ['igstRate', 'igstValue'],
558 'cess_account': ['cessRate', 'cessValue']
559 }
560 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
561 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
562 for hsn_code, taxable_amount in hsn_taxable_amount.items():
563 item_data = frappe._dict()
564 if not hsn_code:
565 frappe.throw(_('GST HSN Code does not exist for one or more items'))
566 item_data.hsnCode = int(hsn_code)
567 item_data.taxableAmount = taxable_amount
568 item_data.qtyUnit = ""
569 for attr in item_data_attrs:
570 item_data[attr] = 0
571
572 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
573 account_type = gst_accounts.get(account, '')
574 for tax_acc, attrs in tax_map.items():
575 if account_type == tax_acc:
576 item_data[attrs[0]] = tax_detail.get('tax_rate')
577 data[attrs[1]] += tax_detail.get('tax_amount')
578 break
579 else:
580 data.OthValue += tax_detail.get('tax_amount')
581
582 data.itemList.append(item_data)
583
584 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
585 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
586 data[attr] = flt(data[attr], 2)
587
588 return data
589
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530590def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530591 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530592 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530593
594 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530595 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530596
597 if doc.ewaybill:
598 frappe.throw(_('e-Way Bill already exists for this document'))
599
600 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
601 'shipping_address_name', 'mode_of_transport', 'distance']
602
603 for fieldname in reqd_fields:
604 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530605 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530606 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530607 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530608
609 if len(doc.company_gstin) < 15:
610 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
611
612def get_transport_details(data, doc):
613 if doc.distance > 4000:
614 frappe.throw(_('Distance cannot be greater than 4000 kms'))
615
616 data.transDistance = int(round(doc.distance))
617
618 transport_modes = {
619 'Road': 1,
620 'Rail': 2,
621 'Air': 3,
622 'Ship': 4
623 }
624
625 vehicle_types = {
626 'Regular': 'R',
627 'Over Dimensional Cargo (ODC)': 'O'
628 }
629
630 data.transMode = transport_modes.get(doc.mode_of_transport)
631
632 if doc.mode_of_transport == 'Road':
633 if not doc.gst_transporter_id and not doc.vehicle_no:
634 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
635 if doc.vehicle_no:
636 data.vehicleNo = doc.vehicle_no.replace(' ', '')
637 if not doc.gst_vehicle_type:
638 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
639 else:
640 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
641 else:
642 if not doc.lr_no or not doc.lr_date:
643 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
644
645 if doc.lr_no:
646 data.transDocNo = doc.lr_no
647
648 if doc.lr_date:
649 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
650
651 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530652 if doc.gst_transporter_id[0:2] != "88":
653 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
654 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530655
656 return data
657
658
659def validate_pincode(pincode, address):
660 pin_not_found = "Pin Code doesn't exist for {}"
661 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
662
663 if not pincode:
664 frappe.throw(_(pin_not_found.format(address)))
665
666 pincode = pincode.replace(' ', '')
667 if not pincode.isdigit() or len(pincode) != 6:
668 frappe.throw(_(incorrect_pin.format(address)))
669 else:
670 return int(pincode)
671
672def validate_state_code(state_code, address):
673 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
674 if not state_code:
675 frappe.throw(_(no_state_code.format(address)))
676 else:
677 return int(state_code)
678
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530679@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530680def get_gst_accounts(company, account_wise=False):
681 gst_accounts = frappe._dict()
682 gst_settings_accounts = frappe.get_all("GST Account",
683 filters={"parent": "GST Settings", "company": company},
684 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
685
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530686 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530687 frappe.throw(_("Please set GST Accounts in GST Settings"))
688
689 for d in gst_settings_accounts:
690 for acc, val in d.items():
691 if not account_wise:
692 gst_accounts.setdefault(acc, []).append(val)
693 elif val:
694 gst_accounts[val] = acc
695
Nabin Hait34c551d2019-07-03 10:34:31 +0530696 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530697
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530698def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530699 country = frappe.get_cached_value('Company', doc.company, 'country')
700
701 if country != 'India':
702 return
703
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530704 if not doc.total_taxes_and_charges:
705 return
706
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530707 if doc.reverse_charge == 'Y':
708 gst_accounts = get_gst_accounts(doc.company)
709 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
710 + gst_accounts.get('igst_account')
711
Deepesh Garg1c146062020-08-18 19:32:52 +0530712 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530713 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530714
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530715 for tax in doc.get('taxes'):
716 if tax.category not in ("Total", "Valuation and Total"):
717 continue
718
719 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530720 base_gst_tax += tax.base_tax_amount_after_discount_amount
721 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530722
723 doc.taxes_and_charges_added -= gst_tax
724 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530725 doc.base_taxes_and_charges_added -= base_gst_tax
726 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530727
Deepesh Garg1c146062020-08-18 19:32:52 +0530728 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530729
Deepesh Garg1c146062020-08-18 19:32:52 +0530730def update_totals(gst_tax, base_gst_tax, doc):
731 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530732 doc.grand_total -= gst_tax
733
734 if doc.meta.get_field("rounded_total"):
735 if doc.is_rounded_total_disabled():
736 doc.outstanding_amount = doc.grand_total
737 else:
738 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
739 doc.currency, doc.precision("rounded_total"))
740
741 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
742 doc.precision("rounding_adjustment"))
743
Deepesh Garg18827352020-07-17 11:31:15 +0530744 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530745
746 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530747 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530748 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530749
750def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530751 country = frappe.get_cached_value('Company', doc.company, 'country')
752
753 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530754 return gl_entries
755
Deepesh Garg24f9a802020-06-03 10:59:37 +0530756 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530757 gst_accounts = get_gst_accounts(doc.company)
758 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
759 + gst_accounts.get('igst_account')
760
761 for tax in doc.get('taxes'):
762 if tax.category not in ("Total", "Valuation and Total"):
763 continue
764
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530765 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530766 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
767 account_currency = get_account_currency(tax.account_head)
768
769 gl_entries.append(doc.get_gl_dict(
770 {
771 "account": tax.account_head,
772 "cost_center": tax.cost_center,
773 "posting_date": doc.posting_date,
774 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530775 dr_or_cr: tax.base_tax_amount_after_discount_amount,
776 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530777 if account_currency==doc.company_currency \
778 else tax.tax_amount_after_discount_amount
779 }, account_currency, item=tax)
780 )
781
Deepesh Gargd07447a2020-11-24 08:09:17 +0530782 return gl_entries
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530783
784@frappe.whitelist()
785def get_regional_round_off_accounts(company, account_list):
786 country = frappe.get_cached_value('Company', company, 'country')
787
788 if country != 'India':
789 return
790
791 if isinstance(account_list, string_types):
792 account_list = json.loads(account_list)
793
794 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
795 return
796
797 gst_accounts = get_gst_accounts(company)
798 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
799 + gst_accounts.get('igst_account')
800
801 account_list.extend(gst_account_list)
802
803 return account_list