blob: 7ad1c07f93aec34f8b9400f7b438c8bc8111f7d9 [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
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053015
16def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053017 if hasattr(doc, 'gst_state') and doc.gst_state:
18 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053019 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053020 return
21
Deepesh Garg459155f2019-06-14 12:01:34 +053022 gst_category = []
23
24 if len(doc.links):
25 link_doctype = doc.links[0].get("link_doctype")
26 link_name = doc.links[0].get("link_name")
27
28 if link_doctype in ["Customer", "Supplier"]:
29 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
30
Sagar Vorad75095b2019-01-23 14:40:01 +053031 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053032 if not doc.gstin or doc.gstin == 'NA':
33 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053034
Sagar Vora07cf4e82019-01-10 11:07:51 +053035 if len(doc.gstin) != 15:
36 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053037
Deepesh Garg459155f2019-06-14 12:01:34 +053038 if gst_category and gst_category == 'UIN Holders':
39 p = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
40 if not p.match(doc.gstin):
41 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
42 else:
43 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}$")
44 if not p.match(doc.gstin):
45 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053046
Deepesh Garg459155f2019-06-14 12:01:34 +053047 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053048 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053049
Deepesh Garg459155f2019-06-14 12:01:34 +053050 if doc.gst_state_number != doc.gstin[:2]:
51 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
52 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053053
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053054def update_gst_category(doc, method):
55 for link in doc.links:
56 if link.link_doctype in ['Customer', 'Supplier']:
57 if doc.get('gstin'):
58 frappe.db.sql("""
59 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
60 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
61
Nabin Hait34c551d2019-07-03 10:34:31 +053062def set_gst_state_and_state_number(doc):
63 if not doc.gst_state:
64 if not doc.state:
65 return
66 state = doc.state.lower()
67 states_lowercase = {s.lower():s for s in states}
68 if state in states_lowercase:
69 doc.gst_state = states_lowercase[state]
70 else:
71 return
72
73 doc.gst_state_number = state_numbers[doc.gst_state]
74
75def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053076 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053077 factor = 1
78 total = 0
79 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053080 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053081 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053082 for char in input_chars:
83 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053084 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053085 total += digit
86 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053087 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
deepeshgarg00762fbf372019-11-07 21:54:25 +053088 frappe.throw(_("""Invalid {0}! The check digit validation has failed.
89 Please ensure you've typed the {0} correctly.""".format(label)))
Rushabh Mehta7231f292017-07-13 15:00:56 +053090
Nabin Haitb962fc12017-07-17 18:02:31 +053091def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
92 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
93 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
94 else:
95 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +053096
Nabin Hait34c551d2019-07-03 10:34:31 +053097def get_itemised_tax_breakup_data(doc, account_wise=False):
98 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +053099
100 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530101
Nabin Haitb962fc12017-07-17 18:02:31 +0530102 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
103 return itemised_tax, itemised_taxable_amount
104
105 item_hsn_map = frappe._dict()
106 for d in doc.items:
107 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
108
109 hsn_tax = {}
110 for item, taxes in itemised_tax.items():
111 hsn_code = item_hsn_map.get(item)
112 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530113 for tax_desc, tax_detail in taxes.items():
114 key = tax_desc
115 if account_wise:
116 key = tax_detail.get('tax_account')
117 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
118 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
119 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530120
121 # set taxable amount
122 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530123 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530124 hsn_code = item_hsn_map.get(item)
125 hsn_taxable_amount.setdefault(hsn_code, 0)
126 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
127
128 return hsn_tax, hsn_taxable_amount
129
Shreya Shah4fa600a2018-06-05 11:27:53 +0530130def set_place_of_supply(doc, method=None):
131 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530132
Rushabh Mehta7231f292017-07-13 15:00:56 +0530133# don't remove this function it is used in tests
134def test_method():
135 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530136 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530137
pateljannat642819b2020-11-17 09:47:10 +0530138@frappe.whitelist()
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530139def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530140 if not frappe.get_meta('Address').has_field('gst_state'): return
pateljannat6b10d872020-11-17 20:34:51 +0530141 if isinstance(party_details, string_types):
142 party_details = json.loads(party_details)
143 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530144
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530145 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530146 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530147 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
148 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530149
150 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530151 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530152 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530153 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530154 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530155
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530156@frappe.whitelist()
157def get_regional_address_details(party_details, doctype, company, return_taxes=None):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530158 if isinstance(party_details, string_types):
159 party_details = json.loads(party_details)
160 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530161
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530162 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530163
164 if is_internal_transfer(party_details, doctype):
165 party_details.taxes_and_charges = ''
166 party_details.taxes = ''
167 return
168
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530169 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530170 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530171
172 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
173 get_tax_template_based_on_category(master_doctype, company, party_details)
174
175 if party_details.get('taxes_and_charges') and return_taxes:
176 return party_details
177
178 if not party_details.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530179 return
180
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530181 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
182 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530183 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
184 get_tax_template_based_on_category(master_doctype, company, party_details)
185
186 if party_details.get('taxes_and_charges') and return_taxes:
187 return party_details
188
189 if not party_details.supplier_gstin:
190 return
191
192 if not party_details.place_of_supply: return
193
deepeshgarg007c58dc872019-12-12 14:55:57 +0530194 if not party_details.company_gstin: return
195
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530196 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
197 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
198 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
199 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530200 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530201 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530202
203 if not default_tax:
204 return
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530205 party_details["taxes_and_charges"] = default_tax
206 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
207
208 if return_taxes:
209 return party_details
210
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530211def is_internal_transfer(party_details, doctype):
212 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
213 destination_gstin = party_details.company_gstin
214 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
215 destination_gstin = party_details.supplier_gstin
216
217 if party_details.gstin == destination_gstin:
218 return True
219 else:
220 False
221
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530222def get_tax_template_based_on_category(master_doctype, company, party_details):
223 if not party_details.get('tax_category'):
224 return
225
226 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
227 'name')
228
229 if default_tax:
230 party_details["taxes_and_charges"] = default_tax
231 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
232
233def get_tax_template(master_doctype, company, is_inter_state, state_code):
234 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
235 filters = {'is_inter_state': is_inter_state})
236
237 default_tax = ''
238
239 for tax_category in tax_categories:
240 if tax_category.gst_state == number_state_mapping[state_code] or \
241 (not default_tax and not tax_category.gst_state):
242 default_tax = frappe.db.get_value(master_doctype,
243 {'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530244 return default_tax
245
246def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
247
248 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
249 ['gst_category', 'export_type'], as_dict=1)
250
251 if gst_details:
252 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
253 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
254 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
255
256 party_details["taxes_and_charges"] = default_tax
257 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
258
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530259
260def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530261 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530262 if not (basic_component and hra_component):
263 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530264 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530265 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530266 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530267 if assignment:
268 hra_component_exists = frappe.db.exists("Salary Detail", {
269 "parent": assignment.salary_structure,
270 "salary_component": hra_component,
271 "parentfield": "earnings",
272 "parenttype": "Salary Structure"
273 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530274
Nabin Hait04e7bf42019-04-25 18:44:10 +0530275 if hra_component_exists:
276 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
277 assignment.salary_structure, basic_component, hra_component)
278 if hra_amount:
279 if doc.monthly_house_rent:
280 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530281 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530282 if annual_exemption > 0:
283 monthly_exemption = annual_exemption / 12
284 else:
285 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530286
Nabin Hait04e7bf42019-04-25 18:44:10 +0530287 elif doc.docstatus == 1:
288 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
289
290 return frappe._dict({
291 "hra_amount": hra_amount,
292 "annual_exemption": annual_exemption,
293 "monthly_exemption": monthly_exemption
294 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530295
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530296def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530297 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530298 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530299 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530300 if earning.salary_component == basic_component:
301 basic_amt = earning.amount
302 elif earning.salary_component == hra_component:
303 hra_amt = earning.amount
304 if basic_amt and hra_amt:
305 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530306 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530307
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530308def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530309 # TODO make this configurable
310 exemptions = []
311 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
312 # case 1: The actual amount allotted by the employer as the HRA.
313 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530314
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530315 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530316 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530317
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530318 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530319 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530320 # 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 +0530321 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530322 # return minimum of 3 cases
323 return min(exemptions)
324
325def get_annual_component_pay(frequency, amount):
326 if frequency == "Daily":
327 return amount * 365
328 elif frequency == "Weekly":
329 return amount * 52
330 elif frequency == "Fortnightly":
331 return amount * 26
332 elif frequency == "Monthly":
333 return amount * 12
334 elif frequency == "Bimonthly":
335 return amount * 6
336
337def validate_house_rent_dates(doc):
338 if not doc.rented_to_date or not doc.rented_from_date:
339 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530340
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530341 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
342 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530343
344 proofs = frappe.db.sql("""
345 select name
346 from `tabEmployee Tax Exemption Proof Submission`
347 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530348 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
349 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
350 """, {
351 "employee": doc.employee,
352 "payroll_period": doc.payroll_period,
353 "from_date": doc.rented_from_date,
354 "to_date": doc.rented_to_date
355 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530356
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530357 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530358 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530359
360def calculate_hra_exemption_for_period(doc):
361 monthly_rent, eligible_hra = 0, 0
362 if doc.house_rent_payment_amount:
363 validate_house_rent_dates(doc)
364 # TODO receive rented months or validate dates are start and end of months?
365 # Calc monthly rent, round to nearest .5
366 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
367 factor = round(factor * 2)/2
368 monthly_rent = doc.house_rent_payment_amount / factor
369 # update field used by calculate_annual_eligible_hra_exemption
370 doc.monthly_house_rent = monthly_rent
371 exemptions = calculate_annual_eligible_hra_exemption(doc)
372
373 if exemptions["monthly_exemption"]:
374 # calc total exemption amount
375 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530376 exemptions["monthly_house_rent"] = monthly_rent
377 exemptions["total_eligible_hra_exemption"] = eligible_hra
378 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530379
Nabin Hait34c551d2019-07-03 10:34:31 +0530380def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530381
382 ewaybills = []
383 for doc_name in dn:
384 doc = frappe.get_doc(dt, doc_name)
385
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530386 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530387
388 data = frappe._dict({
389 "transporterId": "",
390 "TotNonAdvolVal": 0,
391 })
392
393 data.userGstin = data.fromGstin = doc.company_gstin
394 data.supplyType = 'O'
395
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530396 if dt == 'Delivery Note':
397 data.subSupplyType = 1
398 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530399 data.subSupplyType = 1
400 elif doc.gst_category in ['Overseas', 'Deemed Export']:
401 data.subSupplyType = 3
402 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530403 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530404
405 data.docType = 'INV'
406 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
407
408 company_address = frappe.get_doc('Address', doc.company_address)
409 billing_address = frappe.get_doc('Address', doc.customer_address)
410
411 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
412
413 data = get_address_details(data, doc, company_address, billing_address)
414
415 data.itemList = []
416 data.totalValue = doc.total
417
418 data = get_item_list(data, doc)
419
420 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
421 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
422
423 data = get_transport_details(data, doc)
424
425 fields = {
426 "/. -": {
427 'docNo': doc.name,
428 'fromTrdName': doc.company,
429 'toTrdName': doc.customer_name,
430 'transDocNo': doc.lr_no,
431 },
432 "@#/,&. -": {
433 'fromAddr1': company_address.address_line1,
434 'fromAddr2': company_address.address_line2,
435 'fromPlace': company_address.city,
436 'toAddr1': shipping_address.address_line1,
437 'toAddr2': shipping_address.address_line2,
438 'toPlace': shipping_address.city,
439 'transporterName': doc.transporter_name
440 }
441 }
442
443 for allowed_chars, field_map in fields.items():
444 for key, value in field_map.items():
445 if not value:
446 data[key] = ''
447 else:
448 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
449
450 ewaybills.append(data)
451
452 data = {
453 'version': '1.0.1118',
454 'billLists': ewaybills
455 }
456
457 return data
458
459@frappe.whitelist()
460def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530461 dn = json.loads(dn)
462 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530463
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530464@frappe.whitelist()
465def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530466 data = json.loads(frappe.local.form_dict.data)
467 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530468 frappe.local.response.type = 'download'
469
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530470 filename_prefix = 'Bulk'
471 docname = frappe.local.form_dict.docname
472 if docname:
473 if docname.startswith('['):
474 docname = json.loads(docname)
475 if len(docname) == 1:
476 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530477
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530478 if not isinstance(docname, list):
479 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
480 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530481
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530482 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 +0530483
Prasann Shah829172c2019-06-06 12:08:09 +0530484@frappe.whitelist()
485def get_gstins_for_company(company):
486 company_gstins =[]
487 if company:
488 company_gstins = frappe.db.sql("""select
489 distinct `tabAddress`.gstin
490 from
491 `tabAddress`, `tabDynamic Link`
492 where
493 `tabDynamic Link`.parent = `tabAddress`.name and
494 `tabDynamic Link`.parenttype = 'Address' and
495 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300496 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530497 return company_gstins
498
Nabin Hait34c551d2019-07-03 10:34:31 +0530499def get_address_details(data, doc, company_address, billing_address):
500 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
501 data.fromStateCode = data.actualFromStateCode = validate_state_code(
502 company_address.gst_state_number, 'Company Address')
503
504 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
505 data.toGstin = 'URP'
506 set_gst_state_and_state_number(billing_address)
507 else:
508 data.toGstin = doc.billing_address_gstin
509
510 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
511 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
512
513 if doc.customer_address != doc.shipping_address_name:
514 data.transType = 2
515 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
516 set_gst_state_and_state_number(shipping_address)
517 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
518 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
519 else:
520 data.transType = 1
521 data.actualToStateCode = data.toStateCode
522 shipping_address = billing_address
523
524 return data
525
526def get_item_list(data, doc):
527 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
528 data[attr] = 0
529
530 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
531 tax_map = {
532 'sgst_account': ['sgstRate', 'sgstValue'],
533 'cgst_account': ['cgstRate', 'cgstValue'],
534 'igst_account': ['igstRate', 'igstValue'],
535 'cess_account': ['cessRate', 'cessValue']
536 }
537 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
538 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
539 for hsn_code, taxable_amount in hsn_taxable_amount.items():
540 item_data = frappe._dict()
541 if not hsn_code:
542 frappe.throw(_('GST HSN Code does not exist for one or more items'))
543 item_data.hsnCode = int(hsn_code)
544 item_data.taxableAmount = taxable_amount
545 item_data.qtyUnit = ""
546 for attr in item_data_attrs:
547 item_data[attr] = 0
548
549 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
550 account_type = gst_accounts.get(account, '')
551 for tax_acc, attrs in tax_map.items():
552 if account_type == tax_acc:
553 item_data[attrs[0]] = tax_detail.get('tax_rate')
554 data[attrs[1]] += tax_detail.get('tax_amount')
555 break
556 else:
557 data.OthValue += tax_detail.get('tax_amount')
558
559 data.itemList.append(item_data)
560
561 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
562 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
563 data[attr] = flt(data[attr], 2)
564
565 return data
566
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530567def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530568 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530569 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530570
571 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530572 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530573
574 if doc.ewaybill:
575 frappe.throw(_('e-Way Bill already exists for this document'))
576
577 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
578 'shipping_address_name', 'mode_of_transport', 'distance']
579
580 for fieldname in reqd_fields:
581 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530582 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530583 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530584 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530585
586 if len(doc.company_gstin) < 15:
587 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
588
589def get_transport_details(data, doc):
590 if doc.distance > 4000:
591 frappe.throw(_('Distance cannot be greater than 4000 kms'))
592
593 data.transDistance = int(round(doc.distance))
594
595 transport_modes = {
596 'Road': 1,
597 'Rail': 2,
598 'Air': 3,
599 'Ship': 4
600 }
601
602 vehicle_types = {
603 'Regular': 'R',
604 'Over Dimensional Cargo (ODC)': 'O'
605 }
606
607 data.transMode = transport_modes.get(doc.mode_of_transport)
608
609 if doc.mode_of_transport == 'Road':
610 if not doc.gst_transporter_id and not doc.vehicle_no:
611 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
612 if doc.vehicle_no:
613 data.vehicleNo = doc.vehicle_no.replace(' ', '')
614 if not doc.gst_vehicle_type:
615 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
616 else:
617 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
618 else:
619 if not doc.lr_no or not doc.lr_date:
620 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
621
622 if doc.lr_no:
623 data.transDocNo = doc.lr_no
624
625 if doc.lr_date:
626 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
627
628 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530629 if doc.gst_transporter_id[0:2] != "88":
630 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
631 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530632
633 return data
634
635
636def validate_pincode(pincode, address):
637 pin_not_found = "Pin Code doesn't exist for {}"
638 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
639
640 if not pincode:
641 frappe.throw(_(pin_not_found.format(address)))
642
643 pincode = pincode.replace(' ', '')
644 if not pincode.isdigit() or len(pincode) != 6:
645 frappe.throw(_(incorrect_pin.format(address)))
646 else:
647 return int(pincode)
648
649def validate_state_code(state_code, address):
650 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
651 if not state_code:
652 frappe.throw(_(no_state_code.format(address)))
653 else:
654 return int(state_code)
655
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530656@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530657def get_gst_accounts(company, account_wise=False):
658 gst_accounts = frappe._dict()
659 gst_settings_accounts = frappe.get_all("GST Account",
660 filters={"parent": "GST Settings", "company": company},
661 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
662
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530663 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530664 frappe.throw(_("Please set GST Accounts in GST Settings"))
665
666 for d in gst_settings_accounts:
667 for acc, val in d.items():
668 if not account_wise:
669 gst_accounts.setdefault(acc, []).append(val)
670 elif val:
671 gst_accounts[val] = acc
672
Nabin Hait34c551d2019-07-03 10:34:31 +0530673 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530674
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530675def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530676 country = frappe.get_cached_value('Company', doc.company, 'country')
677
678 if country != 'India':
679 return
680
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530681 if not doc.total_taxes_and_charges:
682 return
683
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530684 if doc.reverse_charge == 'Y':
685 gst_accounts = get_gst_accounts(doc.company)
686 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
687 + gst_accounts.get('igst_account')
688
Deepesh Garg1c146062020-08-18 19:32:52 +0530689 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530690 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530691
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530692 for tax in doc.get('taxes'):
693 if tax.category not in ("Total", "Valuation and Total"):
694 continue
695
696 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530697 base_gst_tax += tax.base_tax_amount_after_discount_amount
698 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530699
700 doc.taxes_and_charges_added -= gst_tax
701 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530702 doc.base_taxes_and_charges_added -= base_gst_tax
703 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530704
Deepesh Garg1c146062020-08-18 19:32:52 +0530705 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530706
Deepesh Garg1c146062020-08-18 19:32:52 +0530707def update_totals(gst_tax, base_gst_tax, doc):
708 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530709 doc.grand_total -= gst_tax
710
711 if doc.meta.get_field("rounded_total"):
712 if doc.is_rounded_total_disabled():
713 doc.outstanding_amount = doc.grand_total
714 else:
715 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
716 doc.currency, doc.precision("rounded_total"))
717
718 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
719 doc.precision("rounding_adjustment"))
720
Deepesh Garg18827352020-07-17 11:31:15 +0530721 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530722
723 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530724 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530725 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530726
727def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530728 country = frappe.get_cached_value('Company', doc.company, 'country')
729
730 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530731 return gl_entries
732
Deepesh Garg24f9a802020-06-03 10:59:37 +0530733 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530734 gst_accounts = get_gst_accounts(doc.company)
735 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
736 + gst_accounts.get('igst_account')
737
738 for tax in doc.get('taxes'):
739 if tax.category not in ("Total", "Valuation and Total"):
740 continue
741
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530742 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530743 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
744 account_currency = get_account_currency(tax.account_head)
745
746 gl_entries.append(doc.get_gl_dict(
747 {
748 "account": tax.account_head,
749 "cost_center": tax.cost_center,
750 "posting_date": doc.posting_date,
751 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530752 dr_or_cr: tax.base_tax_amount_after_discount_amount,
753 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530754 if account_currency==doc.company_currency \
755 else tax.tax_amount_after_discount_amount
756 }, account_currency, item=tax)
757 )
758
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530759 return gl_entries