blob: fc38ed0972e026291ef392f18cc78ed6133036a8 [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.
pateljannat410db042020-11-18 15:57:16 +053089 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
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530138def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530139 if not frappe.get_meta('Address').has_field('gst_state'): return
140
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530141 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530142 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530143 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
144 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530145
146 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530147 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530148 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530149 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530150 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530151
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530152@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530153def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530154 if isinstance(party_details, string_types):
155 party_details = json.loads(party_details)
156 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530157
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530158 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530159
160 if is_internal_transfer(party_details, doctype):
161 party_details.taxes_and_charges = ''
162 party_details.taxes = ''
pateljannatcd05b342020-11-19 11:37:08 +0530163 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530164
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530165 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530166 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530167
168 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
169 get_tax_template_based_on_category(master_doctype, company, party_details)
170
pateljannatcd05b342020-11-19 11:37:08 +0530171 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530172 return party_details
173
174 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530175 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530176
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530177 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
178 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
180 get_tax_template_based_on_category(master_doctype, company, party_details)
181
pateljannatcd05b342020-11-19 11:37:08 +0530182 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530183 return party_details
184
185 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530186 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530187
pateljannatcd05b342020-11-19 11:37:08 +0530188 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530189
pateljannatcd05b342020-11-19 11:37:08 +0530190 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530191
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530192 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
193 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
194 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
195 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530196 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530197 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530198
199 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530200 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530201 party_details["taxes_and_charges"] = default_tax
202 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
203
pateljannatcd05b342020-11-19 11:37:08 +0530204 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530205
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,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530238 {'company': company, '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():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530461 data = json.loads(frappe.local.form_dict.data)
462 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530463 frappe.local.response.type = 'download'
464
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530465 filename_prefix = 'Bulk'
466 docname = frappe.local.form_dict.docname
467 if docname:
468 if docname.startswith('['):
469 docname = json.loads(docname)
470 if len(docname) == 1:
471 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530472
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530473 if not isinstance(docname, list):
474 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
475 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530476
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530477 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 +0530478
Prasann Shah829172c2019-06-06 12:08:09 +0530479@frappe.whitelist()
480def get_gstins_for_company(company):
481 company_gstins =[]
482 if company:
483 company_gstins = frappe.db.sql("""select
484 distinct `tabAddress`.gstin
485 from
486 `tabAddress`, `tabDynamic Link`
487 where
488 `tabDynamic Link`.parent = `tabAddress`.name and
489 `tabDynamic Link`.parenttype = 'Address' and
490 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300491 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530492 return company_gstins
493
Nabin Hait34c551d2019-07-03 10:34:31 +0530494def get_address_details(data, doc, company_address, billing_address):
495 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
496 data.fromStateCode = data.actualFromStateCode = validate_state_code(
497 company_address.gst_state_number, 'Company Address')
498
499 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
500 data.toGstin = 'URP'
501 set_gst_state_and_state_number(billing_address)
502 else:
503 data.toGstin = doc.billing_address_gstin
504
505 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
506 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
507
508 if doc.customer_address != doc.shipping_address_name:
509 data.transType = 2
510 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
511 set_gst_state_and_state_number(shipping_address)
512 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
513 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
514 else:
515 data.transType = 1
516 data.actualToStateCode = data.toStateCode
517 shipping_address = billing_address
Smit Vorabbe49332020-11-18 20:58:59 +0530518
519 if doc.gst_category == 'SEZ':
520 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530521
522 return data
523
524def get_item_list(data, doc):
525 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
526 data[attr] = 0
527
528 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
529 tax_map = {
530 'sgst_account': ['sgstRate', 'sgstValue'],
531 'cgst_account': ['cgstRate', 'cgstValue'],
532 'igst_account': ['igstRate', 'igstValue'],
533 'cess_account': ['cessRate', 'cessValue']
534 }
535 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
536 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
537 for hsn_code, taxable_amount in hsn_taxable_amount.items():
538 item_data = frappe._dict()
539 if not hsn_code:
540 frappe.throw(_('GST HSN Code does not exist for one or more items'))
541 item_data.hsnCode = int(hsn_code)
542 item_data.taxableAmount = taxable_amount
543 item_data.qtyUnit = ""
544 for attr in item_data_attrs:
545 item_data[attr] = 0
546
547 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
548 account_type = gst_accounts.get(account, '')
549 for tax_acc, attrs in tax_map.items():
550 if account_type == tax_acc:
551 item_data[attrs[0]] = tax_detail.get('tax_rate')
552 data[attrs[1]] += tax_detail.get('tax_amount')
553 break
554 else:
555 data.OthValue += tax_detail.get('tax_amount')
556
557 data.itemList.append(item_data)
558
559 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
560 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
561 data[attr] = flt(data[attr], 2)
562
563 return data
564
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530565def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530566 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530567 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530568
569 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530570 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530571
572 if doc.ewaybill:
573 frappe.throw(_('e-Way Bill already exists for this document'))
574
575 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
576 'shipping_address_name', 'mode_of_transport', 'distance']
577
578 for fieldname in reqd_fields:
579 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530580 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530581 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530582 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530583
584 if len(doc.company_gstin) < 15:
585 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
586
587def get_transport_details(data, doc):
588 if doc.distance > 4000:
589 frappe.throw(_('Distance cannot be greater than 4000 kms'))
590
591 data.transDistance = int(round(doc.distance))
592
593 transport_modes = {
594 'Road': 1,
595 'Rail': 2,
596 'Air': 3,
597 'Ship': 4
598 }
599
600 vehicle_types = {
601 'Regular': 'R',
602 'Over Dimensional Cargo (ODC)': 'O'
603 }
604
605 data.transMode = transport_modes.get(doc.mode_of_transport)
606
607 if doc.mode_of_transport == 'Road':
608 if not doc.gst_transporter_id and not doc.vehicle_no:
609 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
610 if doc.vehicle_no:
611 data.vehicleNo = doc.vehicle_no.replace(' ', '')
612 if not doc.gst_vehicle_type:
613 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
614 else:
615 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
616 else:
617 if not doc.lr_no or not doc.lr_date:
618 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
619
620 if doc.lr_no:
621 data.transDocNo = doc.lr_no
622
623 if doc.lr_date:
624 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
625
626 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530627 if doc.gst_transporter_id[0:2] != "88":
628 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
629 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530630
631 return data
632
633
634def validate_pincode(pincode, address):
635 pin_not_found = "Pin Code doesn't exist for {}"
636 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
637
638 if not pincode:
639 frappe.throw(_(pin_not_found.format(address)))
640
641 pincode = pincode.replace(' ', '')
642 if not pincode.isdigit() or len(pincode) != 6:
643 frappe.throw(_(incorrect_pin.format(address)))
644 else:
645 return int(pincode)
646
647def validate_state_code(state_code, address):
648 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
649 if not state_code:
650 frappe.throw(_(no_state_code.format(address)))
651 else:
652 return int(state_code)
653
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530654@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530655def get_gst_accounts(company, account_wise=False):
656 gst_accounts = frappe._dict()
657 gst_settings_accounts = frappe.get_all("GST Account",
658 filters={"parent": "GST Settings", "company": company},
659 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
660
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530661 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530662 frappe.throw(_("Please set GST Accounts in GST Settings"))
663
664 for d in gst_settings_accounts:
665 for acc, val in d.items():
666 if not account_wise:
667 gst_accounts.setdefault(acc, []).append(val)
668 elif val:
669 gst_accounts[val] = acc
670
Nabin Hait34c551d2019-07-03 10:34:31 +0530671 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530672
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530673def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530674 country = frappe.get_cached_value('Company', doc.company, 'country')
675
676 if country != 'India':
677 return
678
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530679 if not doc.total_taxes_and_charges:
680 return
681
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530682 if doc.reverse_charge == 'Y':
683 gst_accounts = get_gst_accounts(doc.company)
684 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
685 + gst_accounts.get('igst_account')
686
Deepesh Garg1c146062020-08-18 19:32:52 +0530687 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530688 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530689
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530690 for tax in doc.get('taxes'):
691 if tax.category not in ("Total", "Valuation and Total"):
692 continue
693
694 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530695 base_gst_tax += tax.base_tax_amount_after_discount_amount
696 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530697
698 doc.taxes_and_charges_added -= gst_tax
699 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530700 doc.base_taxes_and_charges_added -= base_gst_tax
701 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530702
Deepesh Garg1c146062020-08-18 19:32:52 +0530703 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530704
Deepesh Garg1c146062020-08-18 19:32:52 +0530705def update_totals(gst_tax, base_gst_tax, doc):
706 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530707 doc.grand_total -= gst_tax
708
709 if doc.meta.get_field("rounded_total"):
710 if doc.is_rounded_total_disabled():
711 doc.outstanding_amount = doc.grand_total
712 else:
713 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
714 doc.currency, doc.precision("rounded_total"))
715
716 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
717 doc.precision("rounding_adjustment"))
718
Deepesh Garg18827352020-07-17 11:31:15 +0530719 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530720
721 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530722 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530723 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530724
725def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530726 country = frappe.get_cached_value('Company', doc.company, 'country')
727
728 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530729 return gl_entries
730
Deepesh Garg24f9a802020-06-03 10:59:37 +0530731 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530732 gst_accounts = get_gst_accounts(doc.company)
733 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
734 + gst_accounts.get('igst_account')
735
736 for tax in doc.get('taxes'):
737 if tax.category not in ("Total", "Valuation and Total"):
738 continue
739
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530740 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530741 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
742 account_currency = get_account_currency(tax.account_head)
743
744 gl_entries.append(doc.get_gl_dict(
745 {
746 "account": tax.account_head,
747 "cost_center": tax.cost_center,
748 "posting_date": doc.posting_date,
749 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530750 dr_or_cr: tax.base_tax_amount_after_discount_amount,
751 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530752 if account_currency==doc.company_currency \
753 else tax.tax_amount_after_discount_amount
754 }, account_currency, item=tax)
755 )
756
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530757 return gl_entries