blob: 3085a310c41f1759e50b907675e1d940db0adcc3 [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 _
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
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053010from erpnext.regional.india import number_state_mapping
11from six import string_types
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053012
13def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053014 if hasattr(doc, 'gst_state') and doc.gst_state:
15 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053016 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053017 return
18
Deepesh Garg459155f2019-06-14 12:01:34 +053019 gst_category = []
20
21 if len(doc.links):
22 link_doctype = doc.links[0].get("link_doctype")
23 link_name = doc.links[0].get("link_name")
24
25 if link_doctype in ["Customer", "Supplier"]:
26 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
27
Sagar Vorad75095b2019-01-23 14:40:01 +053028 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053029 if not doc.gstin or doc.gstin == 'NA':
30 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053031
Sagar Vora07cf4e82019-01-10 11:07:51 +053032 if len(doc.gstin) != 15:
33 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053034
Deepesh Garg459155f2019-06-14 12:01:34 +053035 if gst_category and gst_category == 'UIN Holders':
36 p = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
37 if not p.match(doc.gstin):
38 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
39 else:
40 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}$")
41 if not p.match(doc.gstin):
42 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053043
Deepesh Garg459155f2019-06-14 12:01:34 +053044 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053045 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053046
Deepesh Garg459155f2019-06-14 12:01:34 +053047 if doc.gst_state_number != doc.gstin[:2]:
48 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
49 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053050
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053051def update_gst_category(doc, method):
52 for link in doc.links:
53 if link.link_doctype in ['Customer', 'Supplier']:
54 if doc.get('gstin'):
55 frappe.db.sql("""
56 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
57 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
58
Nabin Hait34c551d2019-07-03 10:34:31 +053059def set_gst_state_and_state_number(doc):
60 if not doc.gst_state:
61 if not doc.state:
62 return
63 state = doc.state.lower()
64 states_lowercase = {s.lower():s for s in states}
65 if state in states_lowercase:
66 doc.gst_state = states_lowercase[state]
67 else:
68 return
69
70 doc.gst_state_number = state_numbers[doc.gst_state]
71
72def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053073 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053074 factor = 1
75 total = 0
76 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053077 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053078 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053079 for char in input_chars:
80 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053081 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053082 total += digit
83 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053084 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
deepeshgarg00762fbf372019-11-07 21:54:25 +053085 frappe.throw(_("""Invalid {0}! The check digit validation has failed.
86 Please ensure you've typed the {0} correctly.""".format(label)))
Rushabh Mehta7231f292017-07-13 15:00:56 +053087
Nabin Haitb962fc12017-07-17 18:02:31 +053088def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
89 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
90 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
91 else:
92 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +053093
Nabin Hait34c551d2019-07-03 10:34:31 +053094def get_itemised_tax_breakup_data(doc, account_wise=False):
95 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +053096
97 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +053098
Nabin Haitb962fc12017-07-17 18:02:31 +053099 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
100 return itemised_tax, itemised_taxable_amount
101
102 item_hsn_map = frappe._dict()
103 for d in doc.items:
104 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
105
106 hsn_tax = {}
107 for item, taxes in itemised_tax.items():
108 hsn_code = item_hsn_map.get(item)
109 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530110 for tax_desc, tax_detail in taxes.items():
111 key = tax_desc
112 if account_wise:
113 key = tax_detail.get('tax_account')
114 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
115 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
116 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530117
118 # set taxable amount
119 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530120 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530121 hsn_code = item_hsn_map.get(item)
122 hsn_taxable_amount.setdefault(hsn_code, 0)
123 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
124
125 return hsn_tax, hsn_taxable_amount
126
Shreya Shah4fa600a2018-06-05 11:27:53 +0530127def set_place_of_supply(doc, method=None):
128 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530129
Rushabh Mehta7231f292017-07-13 15:00:56 +0530130# don't remove this function it is used in tests
131def test_method():
132 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530133 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530134
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530135def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530136 if not frappe.get_meta('Address').has_field('gst_state'): return
137
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530138 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
139 address_name = party_details.shipping_address_name or party_details.customer_address
140 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
141 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530142
143 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530144 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530145 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530146 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530147 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530148
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530149@frappe.whitelist()
150def get_regional_address_details(party_details, doctype, company, return_taxes=None):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530151 if isinstance(party_details, string_types):
152 party_details = json.loads(party_details)
153 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530154
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530155 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530156
157 if is_internal_transfer(party_details, doctype):
158 party_details.taxes_and_charges = ''
159 party_details.taxes = ''
160 return
161
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530162 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530163 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530164
165 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
166 get_tax_template_based_on_category(master_doctype, company, party_details)
167
168 if party_details.get('taxes_and_charges') and return_taxes:
169 return party_details
170
171 if not party_details.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530172 return
173
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530174 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
175 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530176 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
177 get_tax_template_based_on_category(master_doctype, company, party_details)
178
179 if party_details.get('taxes_and_charges') and return_taxes:
180 return party_details
181
182 if not party_details.supplier_gstin:
183 return
184
185 if not party_details.place_of_supply: return
186
deepeshgarg007c58dc872019-12-12 14:55:57 +0530187 if not party_details.company_gstin: return
188
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530189 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
190 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
191 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
192 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530193 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530194 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530195
196 if not default_tax:
197 return
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530198 party_details["taxes_and_charges"] = default_tax
199 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
200
201 if return_taxes:
202 return party_details
203
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530204def is_internal_transfer(party_details, doctype):
205 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
206 destination_gstin = party_details.company_gstin
207 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
208 destination_gstin = party_details.supplier_gstin
209
210 if party_details.gstin == destination_gstin:
211 return True
212 else:
213 False
214
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530215def get_tax_template_based_on_category(master_doctype, company, party_details):
216 if not party_details.get('tax_category'):
217 return
218
219 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
220 'name')
221
222 if default_tax:
223 party_details["taxes_and_charges"] = default_tax
224 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
225
226def get_tax_template(master_doctype, company, is_inter_state, state_code):
227 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
228 filters = {'is_inter_state': is_inter_state})
229
230 default_tax = ''
231
232 for tax_category in tax_categories:
233 if tax_category.gst_state == number_state_mapping[state_code] or \
234 (not default_tax and not tax_category.gst_state):
235 default_tax = frappe.db.get_value(master_doctype,
236 {'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530237 return default_tax
238
239def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
240
241 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
242 ['gst_category', 'export_type'], as_dict=1)
243
244 if gst_details:
245 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
246 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
247 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
248
249 party_details["taxes_and_charges"] = default_tax
250 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
251
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530252
253def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530254 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530255 if not (basic_component and hra_component):
256 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530257 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530258 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530259 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530260 if assignment:
261 hra_component_exists = frappe.db.exists("Salary Detail", {
262 "parent": assignment.salary_structure,
263 "salary_component": hra_component,
264 "parentfield": "earnings",
265 "parenttype": "Salary Structure"
266 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530267
Nabin Hait04e7bf42019-04-25 18:44:10 +0530268 if hra_component_exists:
269 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
270 assignment.salary_structure, basic_component, hra_component)
271 if hra_amount:
272 if doc.monthly_house_rent:
273 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530274 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530275 if annual_exemption > 0:
276 monthly_exemption = annual_exemption / 12
277 else:
278 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530279
Nabin Hait04e7bf42019-04-25 18:44:10 +0530280 elif doc.docstatus == 1:
281 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
282
283 return frappe._dict({
284 "hra_amount": hra_amount,
285 "annual_exemption": annual_exemption,
286 "monthly_exemption": monthly_exemption
287 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530288
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530289def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530290 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530291 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530292 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530293 if earning.salary_component == basic_component:
294 basic_amt = earning.amount
295 elif earning.salary_component == hra_component:
296 hra_amt = earning.amount
297 if basic_amt and hra_amt:
298 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530299 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530300
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530301def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530302 # TODO make this configurable
303 exemptions = []
304 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
305 # case 1: The actual amount allotted by the employer as the HRA.
306 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530307
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530308 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530309 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530310
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530311 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530312 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530313 # 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 +0530314 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530315 # return minimum of 3 cases
316 return min(exemptions)
317
318def get_annual_component_pay(frequency, amount):
319 if frequency == "Daily":
320 return amount * 365
321 elif frequency == "Weekly":
322 return amount * 52
323 elif frequency == "Fortnightly":
324 return amount * 26
325 elif frequency == "Monthly":
326 return amount * 12
327 elif frequency == "Bimonthly":
328 return amount * 6
329
330def validate_house_rent_dates(doc):
331 if not doc.rented_to_date or not doc.rented_from_date:
332 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530333
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530334 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
335 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530336
337 proofs = frappe.db.sql("""
338 select name
339 from `tabEmployee Tax Exemption Proof Submission`
340 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530341 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
342 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
343 """, {
344 "employee": doc.employee,
345 "payroll_period": doc.payroll_period,
346 "from_date": doc.rented_from_date,
347 "to_date": doc.rented_to_date
348 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530349
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530350 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530351 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530352
353def calculate_hra_exemption_for_period(doc):
354 monthly_rent, eligible_hra = 0, 0
355 if doc.house_rent_payment_amount:
356 validate_house_rent_dates(doc)
357 # TODO receive rented months or validate dates are start and end of months?
358 # Calc monthly rent, round to nearest .5
359 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
360 factor = round(factor * 2)/2
361 monthly_rent = doc.house_rent_payment_amount / factor
362 # update field used by calculate_annual_eligible_hra_exemption
363 doc.monthly_house_rent = monthly_rent
364 exemptions = calculate_annual_eligible_hra_exemption(doc)
365
366 if exemptions["monthly_exemption"]:
367 # calc total exemption amount
368 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530369 exemptions["monthly_house_rent"] = monthly_rent
370 exemptions["total_eligible_hra_exemption"] = eligible_hra
371 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530372
Nabin Hait34c551d2019-07-03 10:34:31 +0530373def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530374
375 ewaybills = []
376 for doc_name in dn:
377 doc = frappe.get_doc(dt, doc_name)
378
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530379 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530380
381 data = frappe._dict({
382 "transporterId": "",
383 "TotNonAdvolVal": 0,
384 })
385
386 data.userGstin = data.fromGstin = doc.company_gstin
387 data.supplyType = 'O'
388
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530389 if dt == 'Delivery Note':
390 data.subSupplyType = 1
391 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530392 data.subSupplyType = 1
393 elif doc.gst_category in ['Overseas', 'Deemed Export']:
394 data.subSupplyType = 3
395 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530396 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530397
398 data.docType = 'INV'
399 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
400
401 company_address = frappe.get_doc('Address', doc.company_address)
402 billing_address = frappe.get_doc('Address', doc.customer_address)
403
404 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
405
406 data = get_address_details(data, doc, company_address, billing_address)
407
408 data.itemList = []
409 data.totalValue = doc.total
410
411 data = get_item_list(data, doc)
412
413 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
414 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
415
416 data = get_transport_details(data, doc)
417
418 fields = {
419 "/. -": {
420 'docNo': doc.name,
421 'fromTrdName': doc.company,
422 'toTrdName': doc.customer_name,
423 'transDocNo': doc.lr_no,
424 },
425 "@#/,&. -": {
426 'fromAddr1': company_address.address_line1,
427 'fromAddr2': company_address.address_line2,
428 'fromPlace': company_address.city,
429 'toAddr1': shipping_address.address_line1,
430 'toAddr2': shipping_address.address_line2,
431 'toPlace': shipping_address.city,
432 'transporterName': doc.transporter_name
433 }
434 }
435
436 for allowed_chars, field_map in fields.items():
437 for key, value in field_map.items():
438 if not value:
439 data[key] = ''
440 else:
441 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
442
443 ewaybills.append(data)
444
445 data = {
446 'version': '1.0.1118',
447 'billLists': ewaybills
448 }
449
450 return data
451
452@frappe.whitelist()
453def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530454 dn = json.loads(dn)
455 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530456
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530457@frappe.whitelist()
458def download_ewb_json():
459 data = frappe._dict(frappe.local.form_dict)
Nabin Hait34c551d2019-07-03 10:34:31 +0530460
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530461 frappe.local.response.filecontent = json.dumps(data['data'], indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530462 frappe.local.response.type = 'download'
463
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530464 billList = json.loads(data['data'])['billLists']
465
466 if len(billList) > 1:
Nabin Hait34c551d2019-07-03 10:34:31 +0530467 doc_name = 'Bulk'
468 else:
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530469 doc_name = data['docname']
Nabin Hait34c551d2019-07-03 10:34:31 +0530470
Deepesh Gargfe7e6f52020-04-27 14:05:45 +0530471 frappe.local.response.filename = '{0}_e-WayBill_Data_{1}.json'.format(doc_name, frappe.utils.random_string(5))
Nabin Hait34c551d2019-07-03 10:34:31 +0530472
Prasann Shah829172c2019-06-06 12:08:09 +0530473@frappe.whitelist()
474def get_gstins_for_company(company):
475 company_gstins =[]
476 if company:
477 company_gstins = frappe.db.sql("""select
478 distinct `tabAddress`.gstin
479 from
480 `tabAddress`, `tabDynamic Link`
481 where
482 `tabDynamic Link`.parent = `tabAddress`.name and
483 `tabDynamic Link`.parenttype = 'Address' and
484 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300485 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530486 return company_gstins
487
Nabin Hait34c551d2019-07-03 10:34:31 +0530488def get_address_details(data, doc, company_address, billing_address):
489 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
490 data.fromStateCode = data.actualFromStateCode = validate_state_code(
491 company_address.gst_state_number, 'Company Address')
492
493 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
494 data.toGstin = 'URP'
495 set_gst_state_and_state_number(billing_address)
496 else:
497 data.toGstin = doc.billing_address_gstin
498
499 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
500 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
501
502 if doc.customer_address != doc.shipping_address_name:
503 data.transType = 2
504 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
505 set_gst_state_and_state_number(shipping_address)
506 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
507 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
508 else:
509 data.transType = 1
510 data.actualToStateCode = data.toStateCode
511 shipping_address = billing_address
512
513 return data
514
515def get_item_list(data, doc):
516 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
517 data[attr] = 0
518
519 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
520 tax_map = {
521 'sgst_account': ['sgstRate', 'sgstValue'],
522 'cgst_account': ['cgstRate', 'cgstValue'],
523 'igst_account': ['igstRate', 'igstValue'],
524 'cess_account': ['cessRate', 'cessValue']
525 }
526 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
527 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
528 for hsn_code, taxable_amount in hsn_taxable_amount.items():
529 item_data = frappe._dict()
530 if not hsn_code:
531 frappe.throw(_('GST HSN Code does not exist for one or more items'))
532 item_data.hsnCode = int(hsn_code)
533 item_data.taxableAmount = taxable_amount
534 item_data.qtyUnit = ""
535 for attr in item_data_attrs:
536 item_data[attr] = 0
537
538 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
539 account_type = gst_accounts.get(account, '')
540 for tax_acc, attrs in tax_map.items():
541 if account_type == tax_acc:
542 item_data[attrs[0]] = tax_detail.get('tax_rate')
543 data[attrs[1]] += tax_detail.get('tax_amount')
544 break
545 else:
546 data.OthValue += tax_detail.get('tax_amount')
547
548 data.itemList.append(item_data)
549
550 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
551 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
552 data[attr] = flt(data[attr], 2)
553
554 return data
555
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530556def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530557 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530558 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530559
560 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530561 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530562
563 if doc.ewaybill:
564 frappe.throw(_('e-Way Bill already exists for this document'))
565
566 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
567 'shipping_address_name', 'mode_of_transport', 'distance']
568
569 for fieldname in reqd_fields:
570 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530571 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530572 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530573 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530574
575 if len(doc.company_gstin) < 15:
576 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
577
578def get_transport_details(data, doc):
579 if doc.distance > 4000:
580 frappe.throw(_('Distance cannot be greater than 4000 kms'))
581
582 data.transDistance = int(round(doc.distance))
583
584 transport_modes = {
585 'Road': 1,
586 'Rail': 2,
587 'Air': 3,
588 'Ship': 4
589 }
590
591 vehicle_types = {
592 'Regular': 'R',
593 'Over Dimensional Cargo (ODC)': 'O'
594 }
595
596 data.transMode = transport_modes.get(doc.mode_of_transport)
597
598 if doc.mode_of_transport == 'Road':
599 if not doc.gst_transporter_id and not doc.vehicle_no:
600 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
601 if doc.vehicle_no:
602 data.vehicleNo = doc.vehicle_no.replace(' ', '')
603 if not doc.gst_vehicle_type:
604 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
605 else:
606 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
607 else:
608 if not doc.lr_no or not doc.lr_date:
609 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
610
611 if doc.lr_no:
612 data.transDocNo = doc.lr_no
613
614 if doc.lr_date:
615 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
616
617 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530618 if doc.gst_transporter_id[0:2] != "88":
619 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
620 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530621
622 return data
623
624
625def validate_pincode(pincode, address):
626 pin_not_found = "Pin Code doesn't exist for {}"
627 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
628
629 if not pincode:
630 frappe.throw(_(pin_not_found.format(address)))
631
632 pincode = pincode.replace(' ', '')
633 if not pincode.isdigit() or len(pincode) != 6:
634 frappe.throw(_(incorrect_pin.format(address)))
635 else:
636 return int(pincode)
637
638def validate_state_code(state_code, address):
639 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
640 if not state_code:
641 frappe.throw(_(no_state_code.format(address)))
642 else:
643 return int(state_code)
644
645def get_gst_accounts(company, account_wise=False):
646 gst_accounts = frappe._dict()
647 gst_settings_accounts = frappe.get_all("GST Account",
648 filters={"parent": "GST Settings", "company": company},
649 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
650
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530651 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530652 frappe.throw(_("Please set GST Accounts in GST Settings"))
653
654 for d in gst_settings_accounts:
655 for acc, val in d.items():
656 if not account_wise:
657 gst_accounts.setdefault(acc, []).append(val)
658 elif val:
659 gst_accounts[val] = acc
660
661
662 return gst_accounts