blob: 9fe29eba1b8ac69c25266b7ef14843d7dac04571 [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
Deepesh Garg24f9a802020-06-03 10:59:37 +053012from erpnext.accounts.general_ledger import make_gl_entries
13from erpnext.accounts.utils import get_account_currency
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053014
15def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053016 if hasattr(doc, 'gst_state') and doc.gst_state:
17 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053018 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053019 return
20
Deepesh Garg459155f2019-06-14 12:01:34 +053021 gst_category = []
22
23 if len(doc.links):
24 link_doctype = doc.links[0].get("link_doctype")
25 link_name = doc.links[0].get("link_name")
26
27 if link_doctype in ["Customer", "Supplier"]:
28 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
29
Sagar Vorad75095b2019-01-23 14:40:01 +053030 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053031 if not doc.gstin or doc.gstin == 'NA':
32 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053033
Sagar Vora07cf4e82019-01-10 11:07:51 +053034 if len(doc.gstin) != 15:
35 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053036
Deepesh Garg459155f2019-06-14 12:01:34 +053037 if gst_category and gst_category == 'UIN Holders':
38 p = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
39 if not p.match(doc.gstin):
40 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
41 else:
42 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}$")
43 if not p.match(doc.gstin):
44 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053045
Deepesh Garg459155f2019-06-14 12:01:34 +053046 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053047 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053048
Deepesh Garg459155f2019-06-14 12:01:34 +053049 if doc.gst_state_number != doc.gstin[:2]:
50 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
51 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053052
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053053def update_gst_category(doc, method):
54 for link in doc.links:
55 if link.link_doctype in ['Customer', 'Supplier']:
56 if doc.get('gstin'):
57 frappe.db.sql("""
58 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
59 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
60
Nabin Hait34c551d2019-07-03 10:34:31 +053061def set_gst_state_and_state_number(doc):
62 if not doc.gst_state:
63 if not doc.state:
64 return
65 state = doc.state.lower()
66 states_lowercase = {s.lower():s for s in states}
67 if state in states_lowercase:
68 doc.gst_state = states_lowercase[state]
69 else:
70 return
71
72 doc.gst_state_number = state_numbers[doc.gst_state]
73
74def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053075 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053076 factor = 1
77 total = 0
78 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053079 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053080 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053081 for char in input_chars:
82 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053083 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053084 total += digit
85 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053086 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
deepeshgarg00762fbf372019-11-07 21:54:25 +053087 frappe.throw(_("""Invalid {0}! The check digit validation has failed.
88 Please ensure you've typed the {0} correctly.""".format(label)))
Rushabh Mehta7231f292017-07-13 15:00:56 +053089
Nabin Haitb962fc12017-07-17 18:02:31 +053090def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
91 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
92 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
93 else:
94 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +053095
Nabin Hait34c551d2019-07-03 10:34:31 +053096def get_itemised_tax_breakup_data(doc, account_wise=False):
97 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +053098
99 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530100
Nabin Haitb962fc12017-07-17 18:02:31 +0530101 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
102 return itemised_tax, itemised_taxable_amount
103
104 item_hsn_map = frappe._dict()
105 for d in doc.items:
106 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
107
108 hsn_tax = {}
109 for item, taxes in itemised_tax.items():
110 hsn_code = item_hsn_map.get(item)
111 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530112 for tax_desc, tax_detail in taxes.items():
113 key = tax_desc
114 if account_wise:
115 key = tax_detail.get('tax_account')
116 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
117 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
118 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530119
120 # set taxable amount
121 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530122 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530123 hsn_code = item_hsn_map.get(item)
124 hsn_taxable_amount.setdefault(hsn_code, 0)
125 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
126
127 return hsn_tax, hsn_taxable_amount
128
Shreya Shah4fa600a2018-06-05 11:27:53 +0530129def set_place_of_supply(doc, method=None):
130 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530131
Rushabh Mehta7231f292017-07-13 15:00:56 +0530132# don't remove this function it is used in tests
133def test_method():
134 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530135 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530136
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530137def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530138 if not frappe.get_meta('Address').has_field('gst_state'): return
139
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530140 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
141 address_name = party_details.shipping_address_name or party_details.customer_address
142 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
143 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530144
145 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530146 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530147 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530148 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530149 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530150
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530151@frappe.whitelist()
152def get_regional_address_details(party_details, doctype, company, return_taxes=None):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530153 if isinstance(party_details, string_types):
154 party_details = json.loads(party_details)
155 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530156
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530157 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530158
159 if is_internal_transfer(party_details, doctype):
160 party_details.taxes_and_charges = ''
161 party_details.taxes = ''
162 return
163
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530164 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530165 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530166
167 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
168 get_tax_template_based_on_category(master_doctype, company, party_details)
169
170 if party_details.get('taxes_and_charges') and return_taxes:
171 return party_details
172
173 if not party_details.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530174 return
175
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530176 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
177 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530178 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
179 get_tax_template_based_on_category(master_doctype, company, party_details)
180
181 if party_details.get('taxes_and_charges') and return_taxes:
182 return party_details
183
184 if not party_details.supplier_gstin:
185 return
186
187 if not party_details.place_of_supply: return
188
deepeshgarg007c58dc872019-12-12 14:55:57 +0530189 if not party_details.company_gstin: return
190
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530191 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
192 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
193 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
194 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530195 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530196 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530197
198 if not default_tax:
199 return
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530200 party_details["taxes_and_charges"] = default_tax
201 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
202
203 if return_taxes:
204 return party_details
205
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530206def is_internal_transfer(party_details, doctype):
207 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
208 destination_gstin = party_details.company_gstin
209 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
210 destination_gstin = party_details.supplier_gstin
211
212 if party_details.gstin == destination_gstin:
213 return True
214 else:
215 False
216
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217def get_tax_template_based_on_category(master_doctype, company, party_details):
218 if not party_details.get('tax_category'):
219 return
220
221 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
222 'name')
223
224 if default_tax:
225 party_details["taxes_and_charges"] = default_tax
226 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
227
228def get_tax_template(master_doctype, company, is_inter_state, state_code):
229 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
230 filters = {'is_inter_state': is_inter_state})
231
232 default_tax = ''
233
234 for tax_category in tax_categories:
235 if tax_category.gst_state == number_state_mapping[state_code] or \
236 (not default_tax and not tax_category.gst_state):
237 default_tax = frappe.db.get_value(master_doctype,
238 {'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530239 return default_tax
240
241def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
242
243 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
244 ['gst_category', 'export_type'], as_dict=1)
245
246 if gst_details:
247 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
248 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
249 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
250
251 party_details["taxes_and_charges"] = default_tax
252 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
253
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530254
255def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530256 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530257 if not (basic_component and hra_component):
258 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530259 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530260 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530261 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530262 if assignment:
263 hra_component_exists = frappe.db.exists("Salary Detail", {
264 "parent": assignment.salary_structure,
265 "salary_component": hra_component,
266 "parentfield": "earnings",
267 "parenttype": "Salary Structure"
268 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530269
Nabin Hait04e7bf42019-04-25 18:44:10 +0530270 if hra_component_exists:
271 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
272 assignment.salary_structure, basic_component, hra_component)
273 if hra_amount:
274 if doc.monthly_house_rent:
275 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530276 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530277 if annual_exemption > 0:
278 monthly_exemption = annual_exemption / 12
279 else:
280 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530281
Nabin Hait04e7bf42019-04-25 18:44:10 +0530282 elif doc.docstatus == 1:
283 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
284
285 return frappe._dict({
286 "hra_amount": hra_amount,
287 "annual_exemption": annual_exemption,
288 "monthly_exemption": monthly_exemption
289 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530290
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530291def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530292 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530293 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530294 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530295 if earning.salary_component == basic_component:
296 basic_amt = earning.amount
297 elif earning.salary_component == hra_component:
298 hra_amt = earning.amount
299 if basic_amt and hra_amt:
300 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530301 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530302
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530303def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530304 # TODO make this configurable
305 exemptions = []
306 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
307 # case 1: The actual amount allotted by the employer as the HRA.
308 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530309
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530310 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530311 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530312
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530313 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530314 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530315 # 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 +0530316 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530317 # return minimum of 3 cases
318 return min(exemptions)
319
320def get_annual_component_pay(frequency, amount):
321 if frequency == "Daily":
322 return amount * 365
323 elif frequency == "Weekly":
324 return amount * 52
325 elif frequency == "Fortnightly":
326 return amount * 26
327 elif frequency == "Monthly":
328 return amount * 12
329 elif frequency == "Bimonthly":
330 return amount * 6
331
332def validate_house_rent_dates(doc):
333 if not doc.rented_to_date or not doc.rented_from_date:
334 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530335
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530336 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
337 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530338
339 proofs = frappe.db.sql("""
340 select name
341 from `tabEmployee Tax Exemption Proof Submission`
342 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530343 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
344 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
345 """, {
346 "employee": doc.employee,
347 "payroll_period": doc.payroll_period,
348 "from_date": doc.rented_from_date,
349 "to_date": doc.rented_to_date
350 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530351
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530352 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530353 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530354
355def calculate_hra_exemption_for_period(doc):
356 monthly_rent, eligible_hra = 0, 0
357 if doc.house_rent_payment_amount:
358 validate_house_rent_dates(doc)
359 # TODO receive rented months or validate dates are start and end of months?
360 # Calc monthly rent, round to nearest .5
361 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
362 factor = round(factor * 2)/2
363 monthly_rent = doc.house_rent_payment_amount / factor
364 # update field used by calculate_annual_eligible_hra_exemption
365 doc.monthly_house_rent = monthly_rent
366 exemptions = calculate_annual_eligible_hra_exemption(doc)
367
368 if exemptions["monthly_exemption"]:
369 # calc total exemption amount
370 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530371 exemptions["monthly_house_rent"] = monthly_rent
372 exemptions["total_eligible_hra_exemption"] = eligible_hra
373 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530374
Nabin Hait34c551d2019-07-03 10:34:31 +0530375def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530376
377 ewaybills = []
378 for doc_name in dn:
379 doc = frappe.get_doc(dt, doc_name)
380
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530381 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530382
383 data = frappe._dict({
384 "transporterId": "",
385 "TotNonAdvolVal": 0,
386 })
387
388 data.userGstin = data.fromGstin = doc.company_gstin
389 data.supplyType = 'O'
390
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530391 if dt == 'Delivery Note':
392 data.subSupplyType = 1
393 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530394 data.subSupplyType = 1
395 elif doc.gst_category in ['Overseas', 'Deemed Export']:
396 data.subSupplyType = 3
397 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530398 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530399
400 data.docType = 'INV'
401 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
402
403 company_address = frappe.get_doc('Address', doc.company_address)
404 billing_address = frappe.get_doc('Address', doc.customer_address)
405
406 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
407
408 data = get_address_details(data, doc, company_address, billing_address)
409
410 data.itemList = []
411 data.totalValue = doc.total
412
413 data = get_item_list(data, doc)
414
415 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
416 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
417
418 data = get_transport_details(data, doc)
419
420 fields = {
421 "/. -": {
422 'docNo': doc.name,
423 'fromTrdName': doc.company,
424 'toTrdName': doc.customer_name,
425 'transDocNo': doc.lr_no,
426 },
427 "@#/,&. -": {
428 'fromAddr1': company_address.address_line1,
429 'fromAddr2': company_address.address_line2,
430 'fromPlace': company_address.city,
431 'toAddr1': shipping_address.address_line1,
432 'toAddr2': shipping_address.address_line2,
433 'toPlace': shipping_address.city,
434 'transporterName': doc.transporter_name
435 }
436 }
437
438 for allowed_chars, field_map in fields.items():
439 for key, value in field_map.items():
440 if not value:
441 data[key] = ''
442 else:
443 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
444
445 ewaybills.append(data)
446
447 data = {
448 'version': '1.0.1118',
449 'billLists': ewaybills
450 }
451
452 return data
453
454@frappe.whitelist()
455def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530456 dn = json.loads(dn)
457 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530458
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530459@frappe.whitelist()
460def download_ewb_json():
461 data = frappe._dict(frappe.local.form_dict)
Nabin Hait34c551d2019-07-03 10:34:31 +0530462
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530463 frappe.local.response.filecontent = json.dumps(data['data'], indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530464 frappe.local.response.type = 'download'
465
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530466 billList = json.loads(data['data'])['billLists']
467
468 if len(billList) > 1:
Nabin Hait34c551d2019-07-03 10:34:31 +0530469 doc_name = 'Bulk'
470 else:
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530471 doc_name = data['docname']
Nabin Hait34c551d2019-07-03 10:34:31 +0530472
Deepesh Gargfe7e6f52020-04-27 14:05:45 +0530473 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 +0530474
Prasann Shah829172c2019-06-06 12:08:09 +0530475@frappe.whitelist()
476def get_gstins_for_company(company):
477 company_gstins =[]
478 if company:
479 company_gstins = frappe.db.sql("""select
480 distinct `tabAddress`.gstin
481 from
482 `tabAddress`, `tabDynamic Link`
483 where
484 `tabDynamic Link`.parent = `tabAddress`.name and
485 `tabDynamic Link`.parenttype = 'Address' and
486 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300487 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530488 return company_gstins
489
Nabin Hait34c551d2019-07-03 10:34:31 +0530490def get_address_details(data, doc, company_address, billing_address):
491 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
492 data.fromStateCode = data.actualFromStateCode = validate_state_code(
493 company_address.gst_state_number, 'Company Address')
494
495 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
496 data.toGstin = 'URP'
497 set_gst_state_and_state_number(billing_address)
498 else:
499 data.toGstin = doc.billing_address_gstin
500
501 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
502 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
503
504 if doc.customer_address != doc.shipping_address_name:
505 data.transType = 2
506 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
507 set_gst_state_and_state_number(shipping_address)
508 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
509 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
510 else:
511 data.transType = 1
512 data.actualToStateCode = data.toStateCode
513 shipping_address = billing_address
514
515 return data
516
517def get_item_list(data, doc):
518 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
519 data[attr] = 0
520
521 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
522 tax_map = {
523 'sgst_account': ['sgstRate', 'sgstValue'],
524 'cgst_account': ['cgstRate', 'cgstValue'],
525 'igst_account': ['igstRate', 'igstValue'],
526 'cess_account': ['cessRate', 'cessValue']
527 }
528 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
529 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
530 for hsn_code, taxable_amount in hsn_taxable_amount.items():
531 item_data = frappe._dict()
532 if not hsn_code:
533 frappe.throw(_('GST HSN Code does not exist for one or more items'))
534 item_data.hsnCode = int(hsn_code)
535 item_data.taxableAmount = taxable_amount
536 item_data.qtyUnit = ""
537 for attr in item_data_attrs:
538 item_data[attr] = 0
539
540 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
541 account_type = gst_accounts.get(account, '')
542 for tax_acc, attrs in tax_map.items():
543 if account_type == tax_acc:
544 item_data[attrs[0]] = tax_detail.get('tax_rate')
545 data[attrs[1]] += tax_detail.get('tax_amount')
546 break
547 else:
548 data.OthValue += tax_detail.get('tax_amount')
549
550 data.itemList.append(item_data)
551
552 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
553 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
554 data[attr] = flt(data[attr], 2)
555
556 return data
557
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530558def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530559 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530560 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530561
562 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530563 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530564
565 if doc.ewaybill:
566 frappe.throw(_('e-Way Bill already exists for this document'))
567
568 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
569 'shipping_address_name', 'mode_of_transport', 'distance']
570
571 for fieldname in reqd_fields:
572 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530573 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530574 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530575 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530576
577 if len(doc.company_gstin) < 15:
578 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
579
580def get_transport_details(data, doc):
581 if doc.distance > 4000:
582 frappe.throw(_('Distance cannot be greater than 4000 kms'))
583
584 data.transDistance = int(round(doc.distance))
585
586 transport_modes = {
587 'Road': 1,
588 'Rail': 2,
589 'Air': 3,
590 'Ship': 4
591 }
592
593 vehicle_types = {
594 'Regular': 'R',
595 'Over Dimensional Cargo (ODC)': 'O'
596 }
597
598 data.transMode = transport_modes.get(doc.mode_of_transport)
599
600 if doc.mode_of_transport == 'Road':
601 if not doc.gst_transporter_id and not doc.vehicle_no:
602 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
603 if doc.vehicle_no:
604 data.vehicleNo = doc.vehicle_no.replace(' ', '')
605 if not doc.gst_vehicle_type:
606 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
607 else:
608 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
609 else:
610 if not doc.lr_no or not doc.lr_date:
611 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
612
613 if doc.lr_no:
614 data.transDocNo = doc.lr_no
615
616 if doc.lr_date:
617 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
618
619 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530620 if doc.gst_transporter_id[0:2] != "88":
621 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
622 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530623
624 return data
625
626
627def validate_pincode(pincode, address):
628 pin_not_found = "Pin Code doesn't exist for {}"
629 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
630
631 if not pincode:
632 frappe.throw(_(pin_not_found.format(address)))
633
634 pincode = pincode.replace(' ', '')
635 if not pincode.isdigit() or len(pincode) != 6:
636 frappe.throw(_(incorrect_pin.format(address)))
637 else:
638 return int(pincode)
639
640def validate_state_code(state_code, address):
641 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
642 if not state_code:
643 frappe.throw(_(no_state_code.format(address)))
644 else:
645 return int(state_code)
646
647def get_gst_accounts(company, account_wise=False):
648 gst_accounts = frappe._dict()
649 gst_settings_accounts = frappe.get_all("GST Account",
650 filters={"parent": "GST Settings", "company": company},
651 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
652
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530653 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530654 frappe.throw(_("Please set GST Accounts in GST Settings"))
655
656 for d in gst_settings_accounts:
657 for acc, val in d.items():
658 if not account_wise:
659 gst_accounts.setdefault(acc, []).append(val)
660 elif val:
661 gst_accounts[val] = acc
662
Nabin Hait34c551d2019-07-03 10:34:31 +0530663 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530664
665def make_reverse_charge_entries(doc, method):
666 country = frappe.get_cached_value('Company', doc.company, 'country')
667
668 if country != 'India':
669 return
670
671 if doc.reverse_charge == 'Y':
672 gl_entries = []
673 gst_accounts = get_gst_accounts(doc.company)
674 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
675 + gst_accounts.get('igst_account')
676
677 for tax in doc.get('taxes'):
678 if tax.category not in ("Total", "Valuation and Total"):
679 continue
680
681 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
682 account_currency = get_account_currency(tax.account_head)
683
684 gl_entries.append(doc.get_gl_dict(
685 {
686 "account": tax.account_head,
687 "cost_center": tax.cost_center,
688 "posting_date": doc.posting_date,
689 "against": doc.supplier,
690 "credit": tax.base_tax_amount_after_discount_amount,
691 "credits_in_account_currency": tax.base_tax_amount_after_discount_amount \
692 if account_currency==doc.company_currency \
693 else tax.tax_amount_after_discount_amount
694 }, account_currency, item=tax)
695 )
696
697 gl_entries.append(doc.get_gl_dict(
698 {
699 "account": doc.credit_to if doc.doctype == 'Purchase Invoice' else doc.debit_to,
700 "cost_center": doc.cost_center,
701 "posting_date": doc.posting_date,
702 "party_type": 'Supplier',
703 "party": doc.supplier,
704 "against": tax.account_head,
705 "debit": tax.base_tax_amount_after_discount_amount,
706 "debit_in_account_currency": tax.base_tax_amount_after_discount_amount \
707 if account_currency==doc.company_currency \
708 else tax.tax_amount_after_discount_amount
709 }, account_currency, item=doc)
710 )
711
712 make_gl_entries(gl_entries)