blob: fc2fc9658f88285887a0c7c9e09ccd4da6692ed3 [file] [log] [blame]
Aditya Hasef3c22f32019-01-22 18:22:20 +05301from __future__ import unicode_literals
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05302import frappe, re
3from frappe import _
Nabin Hait49446ba2019-04-25 19:54:20 +05304from frappe.utils import cstr, flt, date_diff, nowdate
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05305from erpnext.regional.india import states, state_numbers
Nabin Haitb962fc12017-07-17 18:02:31 +05306from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Shreya Shah4fa600a2018-06-05 11:27:53 +05307from erpnext.controllers.accounts_controller import get_taxes_and_charges
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +05308from erpnext.hr.utils import get_salary_assignment
9from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053010
11def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053012 if hasattr(doc, 'gst_state') and doc.gst_state:
13 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053014 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053015 return
16
Sagar Vorad75095b2019-01-23 14:40:01 +053017 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053018 if not doc.gstin or doc.gstin == 'NA':
19 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053020
Sagar Vora07cf4e82019-01-10 11:07:51 +053021 if len(doc.gstin) != 15:
22 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053023
Sagar Vora07cf4e82019-01-10 11:07:51 +053024 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}$")
25 if not p.match(doc.gstin):
26 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053027
Sagar Vora07cf4e82019-01-10 11:07:51 +053028 validate_gstin_check_digit(doc.gstin)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053029
30 if not doc.gst_state:
Sagar Voraf99e0132019-01-10 11:57:24 +053031 if not doc.state:
32 return
Sagar Vora07cf4e82019-01-10 11:07:51 +053033 state = doc.state.lower()
34 states_lowercase = {s.lower():s for s in states}
35 if state in states_lowercase:
36 doc.gst_state = states_lowercase[state]
37 else:
38 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053039
Sagar Vora07cf4e82019-01-10 11:07:51 +053040 doc.gst_state_number = state_numbers[doc.gst_state]
41 if doc.gst_state_number != doc.gstin[:2]:
42 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
43 .format(doc.gst_state_number))
44
45def validate_gstin_check_digit(gstin):
46 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053047 factor = 1
48 total = 0
49 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053050 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053051 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053052 for char in input_chars:
53 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053054 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053055 total += digit
56 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053057 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
58 frappe.throw(_("Invalid GSTIN! The check digit validation has failed. " +
59 "Please ensure you've typed the GSTIN correctly."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053060
Nabin Haitb962fc12017-07-17 18:02:31 +053061def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
62 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
63 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
64 else:
65 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +053066
Nabin Haitb962fc12017-07-17 18:02:31 +053067def get_itemised_tax_breakup_data(doc):
68 itemised_tax = get_itemised_tax(doc.taxes)
69
70 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +053071
Nabin Haitb962fc12017-07-17 18:02:31 +053072 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
73 return itemised_tax, itemised_taxable_amount
74
75 item_hsn_map = frappe._dict()
76 for d in doc.items:
77 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
78
79 hsn_tax = {}
80 for item, taxes in itemised_tax.items():
81 hsn_code = item_hsn_map.get(item)
82 hsn_tax.setdefault(hsn_code, frappe._dict())
83 for tax_account, tax_detail in taxes.items():
84 hsn_tax[hsn_code].setdefault(tax_account, {"tax_rate": 0, "tax_amount": 0})
85 hsn_tax[hsn_code][tax_account]["tax_rate"] = tax_detail.get("tax_rate")
86 hsn_tax[hsn_code][tax_account]["tax_amount"] += tax_detail.get("tax_amount")
87
88 # set taxable amount
89 hsn_taxable_amount = frappe._dict()
90 for item, taxable_amount in itemised_taxable_amount.items():
91 hsn_code = item_hsn_map.get(item)
92 hsn_taxable_amount.setdefault(hsn_code, 0)
93 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
94
95 return hsn_tax, hsn_taxable_amount
96
Shreya Shah4fa600a2018-06-05 11:27:53 +053097def set_place_of_supply(doc, method=None):
98 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +053099
Rushabh Mehta7231f292017-07-13 15:00:56 +0530100# don't remove this function it is used in tests
101def test_method():
102 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530103 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530104
105def get_place_of_supply(out, doctype):
106 if not frappe.get_meta('Address').has_field('gst_state'): return
107
108 if doctype in ("Sales Invoice", "Delivery Note"):
109 address_name = out.shipping_address_name or out.customer_address
110 elif doctype == "Purchase Invoice":
111 address_name = out.shipping_address or out.supplier_address
112
113 if address_name:
114 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530115 if address and address.gst_state and address.gst_state_number:
Nabin Hait2390da62018-08-30 16:16:35 +0530116 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530117
118def get_regional_address_details(out, doctype, company):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530119 out.place_of_supply = get_place_of_supply(out, doctype)
120
121 if not out.place_of_supply: return
122
123 if doctype in ("Sales Invoice", "Delivery Note"):
124 master_doctype = "Sales Taxes and Charges Template"
Shreya2ad81722018-06-05 16:49:29 +0530125 if not out.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530126 return
Shreya2ad81722018-06-05 16:49:29 +0530127 elif doctype == "Purchase Invoice":
Shreya Shah4fa600a2018-06-05 11:27:53 +0530128 master_doctype = "Purchase Taxes and Charges Template"
Shreya2ad81722018-06-05 16:49:29 +0530129 if not out.supplier_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530130 return
131
Rohit Waghchaurede82ad12018-06-07 13:20:57 +0530132 if ((doctype in ("Sales Invoice", "Delivery Note") and out.company_gstin
133 and out.company_gstin[:2] != out.place_of_supply[:2]) or (doctype == "Purchase Invoice"
134 and out.supplier_gstin and out.supplier_gstin[:2] != out.place_of_supply[:2])):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530135 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0})
136 else:
137 default_tax = frappe.db.get_value(master_doctype, {"company": company, "disabled":0, "is_default": 1})
138
139 if not default_tax:
140 return
141 out["taxes_and_charges"] = default_tax
142 out.taxes = get_taxes_and_charges(master_doctype, default_tax)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530143
144def calculate_annual_eligible_hra_exemption(doc):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530145 basic_component = frappe.get_cached_value('Company', doc.company, "basic_component")
146 hra_component = frappe.get_cached_value('Company', doc.company, "hra_component")
Nabin Hait04e7bf42019-04-25 18:44:10 +0530147 if not (basic_component and hra_component):
148 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530149 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530150 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530151 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530152 if assignment:
153 hra_component_exists = frappe.db.exists("Salary Detail", {
154 "parent": assignment.salary_structure,
155 "salary_component": hra_component,
156 "parentfield": "earnings",
157 "parenttype": "Salary Structure"
158 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530159
Nabin Hait04e7bf42019-04-25 18:44:10 +0530160 if hra_component_exists:
161 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
162 assignment.salary_structure, basic_component, hra_component)
163 if hra_amount:
164 if doc.monthly_house_rent:
165 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530166 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530167 if annual_exemption > 0:
168 monthly_exemption = annual_exemption / 12
169 else:
170 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530171
Nabin Hait04e7bf42019-04-25 18:44:10 +0530172 elif doc.docstatus == 1:
173 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
174
175 return frappe._dict({
176 "hra_amount": hra_amount,
177 "annual_exemption": annual_exemption,
178 "monthly_exemption": monthly_exemption
179 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530180
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530181def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530182 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530183 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530184 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530185 if earning.salary_component == basic_component:
186 basic_amt = earning.amount
187 elif earning.salary_component == hra_component:
188 hra_amt = earning.amount
189 if basic_amt and hra_amt:
190 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530191 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530192
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530193def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530194 # TODO make this configurable
195 exemptions = []
196 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
197 # case 1: The actual amount allotted by the employer as the HRA.
198 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530199
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530200 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530201 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530202
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530203 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530204 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530205 # 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 +0530206 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530207 # return minimum of 3 cases
208 return min(exemptions)
209
210def get_annual_component_pay(frequency, amount):
211 if frequency == "Daily":
212 return amount * 365
213 elif frequency == "Weekly":
214 return amount * 52
215 elif frequency == "Fortnightly":
216 return amount * 26
217 elif frequency == "Monthly":
218 return amount * 12
219 elif frequency == "Bimonthly":
220 return amount * 6
221
222def validate_house_rent_dates(doc):
223 if not doc.rented_to_date or not doc.rented_from_date:
224 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530225
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530226 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
227 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530228
229 proofs = frappe.db.sql("""
230 select name
231 from `tabEmployee Tax Exemption Proof Submission`
232 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530233 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
234 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
235 """, {
236 "employee": doc.employee,
237 "payroll_period": doc.payroll_period,
238 "from_date": doc.rented_from_date,
239 "to_date": doc.rented_to_date
240 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530241
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530242 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530243 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530244
245def calculate_hra_exemption_for_period(doc):
246 monthly_rent, eligible_hra = 0, 0
247 if doc.house_rent_payment_amount:
248 validate_house_rent_dates(doc)
249 # TODO receive rented months or validate dates are start and end of months?
250 # Calc monthly rent, round to nearest .5
251 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
252 factor = round(factor * 2)/2
253 monthly_rent = doc.house_rent_payment_amount / factor
254 # update field used by calculate_annual_eligible_hra_exemption
255 doc.monthly_house_rent = monthly_rent
256 exemptions = calculate_annual_eligible_hra_exemption(doc)
257
258 if exemptions["monthly_exemption"]:
259 # calc total exemption amount
260 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530261 exemptions["monthly_house_rent"] = monthly_rent
262 exemptions["total_eligible_hra_exemption"] = eligible_hra
263 return exemptions