blob: e89885f3805ee75ef6c1b1f1ead6083883f29361 [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 Gargd07447a2020-11-24 08:09:17 +053058def validate_tax_category(doc, method):
Deepesh Gargb0743342020-12-17 18:46:59 +053059 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 +053060 if doc.is_inter_state:
61 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
62 else:
63 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
64
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053065def update_gst_category(doc, method):
66 for link in doc.links:
67 if link.link_doctype in ['Customer', 'Supplier']:
68 if doc.get('gstin'):
69 frappe.db.sql("""
70 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
71 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
72
Nabin Hait34c551d2019-07-03 10:34:31 +053073def set_gst_state_and_state_number(doc):
74 if not doc.gst_state:
75 if not doc.state:
76 return
77 state = doc.state.lower()
78 states_lowercase = {s.lower():s for s in states}
79 if state in states_lowercase:
80 doc.gst_state = states_lowercase[state]
81 else:
82 return
83
84 doc.gst_state_number = state_numbers[doc.gst_state]
85
86def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053087 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053088 factor = 1
89 total = 0
90 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053091 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053092 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053093 for char in input_chars:
94 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053095 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053096 total += digit
97 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053098 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +053099 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 +0530100
Nabin Haitb962fc12017-07-17 18:02:31 +0530101def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
102 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
103 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
104 else:
105 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530106
Nabin Hait34c551d2019-07-03 10:34:31 +0530107def get_itemised_tax_breakup_data(doc, account_wise=False):
108 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530109
110 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530111
Nabin Haitb962fc12017-07-17 18:02:31 +0530112 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
113 return itemised_tax, itemised_taxable_amount
114
115 item_hsn_map = frappe._dict()
116 for d in doc.items:
117 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
118
119 hsn_tax = {}
120 for item, taxes in itemised_tax.items():
121 hsn_code = item_hsn_map.get(item)
122 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530123 for tax_desc, tax_detail in taxes.items():
124 key = tax_desc
125 if account_wise:
126 key = tax_detail.get('tax_account')
127 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
128 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
129 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530130
131 # set taxable amount
132 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530133 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530134 hsn_code = item_hsn_map.get(item)
135 hsn_taxable_amount.setdefault(hsn_code, 0)
136 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
137
138 return hsn_tax, hsn_taxable_amount
139
Shreya Shah4fa600a2018-06-05 11:27:53 +0530140def set_place_of_supply(doc, method=None):
141 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530142
Rushabh Mehta7231f292017-07-13 15:00:56 +0530143# don't remove this function it is used in tests
144def test_method():
145 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530146 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530147
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530148def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530149 if not frappe.get_meta('Address').has_field('gst_state'): return
150
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530151 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530152 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530153 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
154 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530155
156 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530157 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530158 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530159 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530160 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530161
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530162@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530163def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530164 if isinstance(party_details, string_types):
165 party_details = json.loads(party_details)
166 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530167
Deepesh Garga7670852020-12-04 18:07:46 +0530168 update_party_details(party_details, doctype)
169
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530170 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530171
172 if is_internal_transfer(party_details, doctype):
173 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530174 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530175 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530176
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530177 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530178 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179
180 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
181 get_tax_template_based_on_category(master_doctype, company, party_details)
182
pateljannatcd05b342020-11-19 11:37:08 +0530183 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530184 return party_details
185
186 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530187 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530189 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
190 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530191 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
192 get_tax_template_based_on_category(master_doctype, company, party_details)
193
pateljannatcd05b342020-11-19 11:37:08 +0530194 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530195 return party_details
196
197 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530198 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530199
pateljannatcd05b342020-11-19 11:37:08 +0530200 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530201
pateljannatcd05b342020-11-19 11:37:08 +0530202 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530203
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530204 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
205 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
206 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
207 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530208 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530209 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530210
211 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530212 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530213 party_details["taxes_and_charges"] = default_tax
214 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
215
pateljannatcd05b342020-11-19 11:37:08 +0530216 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217
Deepesh Garga7670852020-12-04 18:07:46 +0530218def update_party_details(party_details, doctype):
219 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
220 if party_details.get(address_field):
221 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
222
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530223def is_internal_transfer(party_details, doctype):
224 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
225 destination_gstin = party_details.company_gstin
226 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
227 destination_gstin = party_details.supplier_gstin
228
229 if party_details.gstin == destination_gstin:
230 return True
231 else:
232 False
233
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530234def get_tax_template_based_on_category(master_doctype, company, party_details):
235 if not party_details.get('tax_category'):
236 return
237
238 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
239 'name')
240
241 if default_tax:
242 party_details["taxes_and_charges"] = default_tax
243 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
244
245def get_tax_template(master_doctype, company, is_inter_state, state_code):
246 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
247 filters = {'is_inter_state': is_inter_state})
248
249 default_tax = ''
250
251 for tax_category in tax_categories:
252 if tax_category.gst_state == number_state_mapping[state_code] or \
253 (not default_tax and not tax_category.gst_state):
254 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530255 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530256 return default_tax
257
258def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
259
260 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
261 ['gst_category', 'export_type'], as_dict=1)
262
263 if gst_details:
264 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
265 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
266 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
267
268 party_details["taxes_and_charges"] = default_tax
269 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
270
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530271
272def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530273 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530274 if not (basic_component and hra_component):
275 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530276 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530277 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530278 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530279 if assignment:
280 hra_component_exists = frappe.db.exists("Salary Detail", {
281 "parent": assignment.salary_structure,
282 "salary_component": hra_component,
283 "parentfield": "earnings",
284 "parenttype": "Salary Structure"
285 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530286
Nabin Hait04e7bf42019-04-25 18:44:10 +0530287 if hra_component_exists:
288 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
289 assignment.salary_structure, basic_component, hra_component)
290 if hra_amount:
291 if doc.monthly_house_rent:
292 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530293 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530294 if annual_exemption > 0:
295 monthly_exemption = annual_exemption / 12
296 else:
297 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530298
Nabin Hait04e7bf42019-04-25 18:44:10 +0530299 elif doc.docstatus == 1:
300 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
301
302 return frappe._dict({
303 "hra_amount": hra_amount,
304 "annual_exemption": annual_exemption,
305 "monthly_exemption": monthly_exemption
306 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530307
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530308def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530309 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530310 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530311 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530312 if earning.salary_component == basic_component:
313 basic_amt = earning.amount
314 elif earning.salary_component == hra_component:
315 hra_amt = earning.amount
316 if basic_amt and hra_amt:
317 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530318 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530319
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530320def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530321 # TODO make this configurable
322 exemptions = []
323 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
324 # case 1: The actual amount allotted by the employer as the HRA.
325 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530326
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530327 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530328 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530329
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530330 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530331 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530332 # 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 +0530333 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530334 # return minimum of 3 cases
335 return min(exemptions)
336
337def get_annual_component_pay(frequency, amount):
338 if frequency == "Daily":
339 return amount * 365
340 elif frequency == "Weekly":
341 return amount * 52
342 elif frequency == "Fortnightly":
343 return amount * 26
344 elif frequency == "Monthly":
345 return amount * 12
346 elif frequency == "Bimonthly":
347 return amount * 6
348
349def validate_house_rent_dates(doc):
350 if not doc.rented_to_date or not doc.rented_from_date:
351 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530352
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530353 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
354 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530355
356 proofs = frappe.db.sql("""
357 select name
358 from `tabEmployee Tax Exemption Proof Submission`
359 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530360 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
361 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
362 """, {
363 "employee": doc.employee,
364 "payroll_period": doc.payroll_period,
365 "from_date": doc.rented_from_date,
366 "to_date": doc.rented_to_date
367 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530368
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530369 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530370 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530371
372def calculate_hra_exemption_for_period(doc):
373 monthly_rent, eligible_hra = 0, 0
374 if doc.house_rent_payment_amount:
375 validate_house_rent_dates(doc)
376 # TODO receive rented months or validate dates are start and end of months?
377 # Calc monthly rent, round to nearest .5
378 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
379 factor = round(factor * 2)/2
380 monthly_rent = doc.house_rent_payment_amount / factor
381 # update field used by calculate_annual_eligible_hra_exemption
382 doc.monthly_house_rent = monthly_rent
383 exemptions = calculate_annual_eligible_hra_exemption(doc)
384
385 if exemptions["monthly_exemption"]:
386 # calc total exemption amount
387 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530388 exemptions["monthly_house_rent"] = monthly_rent
389 exemptions["total_eligible_hra_exemption"] = eligible_hra
390 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530391
Nabin Hait34c551d2019-07-03 10:34:31 +0530392def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530393
394 ewaybills = []
395 for doc_name in dn:
396 doc = frappe.get_doc(dt, doc_name)
397
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530398 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530399
400 data = frappe._dict({
401 "transporterId": "",
402 "TotNonAdvolVal": 0,
403 })
404
405 data.userGstin = data.fromGstin = doc.company_gstin
406 data.supplyType = 'O'
407
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530408 if dt == 'Delivery Note':
409 data.subSupplyType = 1
410 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530411 data.subSupplyType = 1
412 elif doc.gst_category in ['Overseas', 'Deemed Export']:
413 data.subSupplyType = 3
414 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530415 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530416
417 data.docType = 'INV'
418 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
419
420 company_address = frappe.get_doc('Address', doc.company_address)
421 billing_address = frappe.get_doc('Address', doc.customer_address)
422
423 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
424
425 data = get_address_details(data, doc, company_address, billing_address)
426
427 data.itemList = []
428 data.totalValue = doc.total
429
430 data = get_item_list(data, doc)
431
432 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
433 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
434
435 data = get_transport_details(data, doc)
436
437 fields = {
438 "/. -": {
439 'docNo': doc.name,
440 'fromTrdName': doc.company,
441 'toTrdName': doc.customer_name,
442 'transDocNo': doc.lr_no,
443 },
444 "@#/,&. -": {
445 'fromAddr1': company_address.address_line1,
446 'fromAddr2': company_address.address_line2,
447 'fromPlace': company_address.city,
448 'toAddr1': shipping_address.address_line1,
449 'toAddr2': shipping_address.address_line2,
450 'toPlace': shipping_address.city,
451 'transporterName': doc.transporter_name
452 }
453 }
454
455 for allowed_chars, field_map in fields.items():
456 for key, value in field_map.items():
457 if not value:
458 data[key] = ''
459 else:
460 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
461
462 ewaybills.append(data)
463
464 data = {
465 'version': '1.0.1118',
466 'billLists': ewaybills
467 }
468
469 return data
470
471@frappe.whitelist()
472def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530473 dn = json.loads(dn)
474 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530475
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530476@frappe.whitelist()
477def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530478 data = json.loads(frappe.local.form_dict.data)
479 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530480 frappe.local.response.type = 'download'
481
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530482 filename_prefix = 'Bulk'
483 docname = frappe.local.form_dict.docname
484 if docname:
485 if docname.startswith('['):
486 docname = json.loads(docname)
487 if len(docname) == 1:
488 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530489
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530490 if not isinstance(docname, list):
491 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
492 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530493
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530494 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 +0530495
Prasann Shah829172c2019-06-06 12:08:09 +0530496@frappe.whitelist()
497def get_gstins_for_company(company):
498 company_gstins =[]
499 if company:
500 company_gstins = frappe.db.sql("""select
501 distinct `tabAddress`.gstin
502 from
503 `tabAddress`, `tabDynamic Link`
504 where
505 `tabDynamic Link`.parent = `tabAddress`.name and
506 `tabDynamic Link`.parenttype = 'Address' and
507 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300508 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530509 return company_gstins
510
Nabin Hait34c551d2019-07-03 10:34:31 +0530511def get_address_details(data, doc, company_address, billing_address):
512 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
513 data.fromStateCode = data.actualFromStateCode = validate_state_code(
514 company_address.gst_state_number, 'Company Address')
515
516 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
517 data.toGstin = 'URP'
518 set_gst_state_and_state_number(billing_address)
519 else:
520 data.toGstin = doc.billing_address_gstin
521
522 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
523 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
524
525 if doc.customer_address != doc.shipping_address_name:
526 data.transType = 2
527 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
528 set_gst_state_and_state_number(shipping_address)
529 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
530 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
531 else:
532 data.transType = 1
533 data.actualToStateCode = data.toStateCode
534 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530535
Smit Vorabbe49332020-11-18 20:58:59 +0530536 if doc.gst_category == 'SEZ':
537 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530538
539 return data
540
541def get_item_list(data, doc):
542 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
543 data[attr] = 0
544
545 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
546 tax_map = {
547 'sgst_account': ['sgstRate', 'sgstValue'],
548 'cgst_account': ['cgstRate', 'cgstValue'],
549 'igst_account': ['igstRate', 'igstValue'],
550 'cess_account': ['cessRate', 'cessValue']
551 }
552 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
553 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
554 for hsn_code, taxable_amount in hsn_taxable_amount.items():
555 item_data = frappe._dict()
556 if not hsn_code:
557 frappe.throw(_('GST HSN Code does not exist for one or more items'))
558 item_data.hsnCode = int(hsn_code)
559 item_data.taxableAmount = taxable_amount
560 item_data.qtyUnit = ""
561 for attr in item_data_attrs:
562 item_data[attr] = 0
563
564 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
565 account_type = gst_accounts.get(account, '')
566 for tax_acc, attrs in tax_map.items():
567 if account_type == tax_acc:
568 item_data[attrs[0]] = tax_detail.get('tax_rate')
569 data[attrs[1]] += tax_detail.get('tax_amount')
570 break
571 else:
572 data.OthValue += tax_detail.get('tax_amount')
573
574 data.itemList.append(item_data)
575
576 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
577 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
578 data[attr] = flt(data[attr], 2)
579
580 return data
581
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530582def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530583 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530584 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530585
586 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530587 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530588
589 if doc.ewaybill:
590 frappe.throw(_('e-Way Bill already exists for this document'))
591
592 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
593 'shipping_address_name', 'mode_of_transport', 'distance']
594
595 for fieldname in reqd_fields:
596 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530597 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530598 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530599 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530600
601 if len(doc.company_gstin) < 15:
602 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
603
604def get_transport_details(data, doc):
605 if doc.distance > 4000:
606 frappe.throw(_('Distance cannot be greater than 4000 kms'))
607
608 data.transDistance = int(round(doc.distance))
609
610 transport_modes = {
611 'Road': 1,
612 'Rail': 2,
613 'Air': 3,
614 'Ship': 4
615 }
616
617 vehicle_types = {
618 'Regular': 'R',
619 'Over Dimensional Cargo (ODC)': 'O'
620 }
621
622 data.transMode = transport_modes.get(doc.mode_of_transport)
623
624 if doc.mode_of_transport == 'Road':
625 if not doc.gst_transporter_id and not doc.vehicle_no:
626 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
627 if doc.vehicle_no:
628 data.vehicleNo = doc.vehicle_no.replace(' ', '')
629 if not doc.gst_vehicle_type:
630 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
631 else:
632 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
633 else:
634 if not doc.lr_no or not doc.lr_date:
635 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
636
637 if doc.lr_no:
638 data.transDocNo = doc.lr_no
639
640 if doc.lr_date:
641 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
642
643 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530644 if doc.gst_transporter_id[0:2] != "88":
645 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
646 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530647
648 return data
649
650
651def validate_pincode(pincode, address):
652 pin_not_found = "Pin Code doesn't exist for {}"
653 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
654
655 if not pincode:
656 frappe.throw(_(pin_not_found.format(address)))
657
658 pincode = pincode.replace(' ', '')
659 if not pincode.isdigit() or len(pincode) != 6:
660 frappe.throw(_(incorrect_pin.format(address)))
661 else:
662 return int(pincode)
663
664def validate_state_code(state_code, address):
665 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
666 if not state_code:
667 frappe.throw(_(no_state_code.format(address)))
668 else:
669 return int(state_code)
670
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530671@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530672def get_gst_accounts(company, account_wise=False):
673 gst_accounts = frappe._dict()
674 gst_settings_accounts = frappe.get_all("GST Account",
675 filters={"parent": "GST Settings", "company": company},
676 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
677
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530678 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530679 frappe.throw(_("Please set GST Accounts in GST Settings"))
680
681 for d in gst_settings_accounts:
682 for acc, val in d.items():
683 if not account_wise:
684 gst_accounts.setdefault(acc, []).append(val)
685 elif val:
686 gst_accounts[val] = acc
687
Nabin Hait34c551d2019-07-03 10:34:31 +0530688 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530689
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530690def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530691 country = frappe.get_cached_value('Company', doc.company, 'country')
692
693 if country != 'India':
694 return
695
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530696 if not doc.total_taxes_and_charges:
697 return
698
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530699 if doc.reverse_charge == 'Y':
700 gst_accounts = get_gst_accounts(doc.company)
701 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
702 + gst_accounts.get('igst_account')
703
Deepesh Garg1c146062020-08-18 19:32:52 +0530704 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530705 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530706
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530707 for tax in doc.get('taxes'):
708 if tax.category not in ("Total", "Valuation and Total"):
709 continue
710
711 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530712 base_gst_tax += tax.base_tax_amount_after_discount_amount
713 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530714
715 doc.taxes_and_charges_added -= gst_tax
716 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530717 doc.base_taxes_and_charges_added -= base_gst_tax
718 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530719
Deepesh Garg1c146062020-08-18 19:32:52 +0530720 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530721
Deepesh Garg1c146062020-08-18 19:32:52 +0530722def update_totals(gst_tax, base_gst_tax, doc):
723 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530724 doc.grand_total -= gst_tax
725
726 if doc.meta.get_field("rounded_total"):
727 if doc.is_rounded_total_disabled():
728 doc.outstanding_amount = doc.grand_total
729 else:
730 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
731 doc.currency, doc.precision("rounded_total"))
732
733 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
734 doc.precision("rounding_adjustment"))
735
Deepesh Garg18827352020-07-17 11:31:15 +0530736 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530737
738 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530739 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530740 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530741
742def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530743 country = frappe.get_cached_value('Company', doc.company, 'country')
744
745 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530746 return gl_entries
747
Deepesh Garg24f9a802020-06-03 10:59:37 +0530748 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530749 gst_accounts = get_gst_accounts(doc.company)
750 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
751 + gst_accounts.get('igst_account')
752
753 for tax in doc.get('taxes'):
754 if tax.category not in ("Total", "Valuation and Total"):
755 continue
756
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530757 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530758 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
759 account_currency = get_account_currency(tax.account_head)
760
761 gl_entries.append(doc.get_gl_dict(
762 {
763 "account": tax.account_head,
764 "cost_center": tax.cost_center,
765 "posting_date": doc.posting_date,
766 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530767 dr_or_cr: tax.base_tax_amount_after_discount_amount,
768 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530769 if account_currency==doc.company_currency \
770 else tax.tax_amount_after_discount_amount
771 }, account_currency, item=tax)
772 )
773
Deepesh Gargd07447a2020-11-24 08:09:17 +0530774 return gl_entries