blob: 6164e066cdcc3433556060d3619ca6173442bdac [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
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()
153def get_regional_address_details(party_details, doctype, company, return_taxes=None):
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 = ''
163 return
164
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
171 if party_details.get('taxes_and_charges') and return_taxes:
172 return party_details
173
174 if not party_details.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530175 return
176
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
182 if party_details.get('taxes_and_charges') and return_taxes:
183 return party_details
184
185 if not party_details.supplier_gstin:
186 return
187
188 if not party_details.place_of_supply: return
189
deepeshgarg007c58dc872019-12-12 14:55:57 +0530190 if not party_details.company_gstin: return
191
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:
200 return
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
204 if return_taxes:
205 return party_details
206
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530207def is_internal_transfer(party_details, doctype):
208 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
209 destination_gstin = party_details.company_gstin
210 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
211 destination_gstin = party_details.supplier_gstin
212
213 if party_details.gstin == destination_gstin:
214 return True
215 else:
216 False
217
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530218def get_tax_template_based_on_category(master_doctype, company, party_details):
219 if not party_details.get('tax_category'):
220 return
221
222 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
223 'name')
224
225 if default_tax:
226 party_details["taxes_and_charges"] = default_tax
227 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
228
229def get_tax_template(master_doctype, company, is_inter_state, state_code):
230 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
231 filters = {'is_inter_state': is_inter_state})
232
233 default_tax = ''
234
235 for tax_category in tax_categories:
236 if tax_category.gst_state == number_state_mapping[state_code] or \
237 (not default_tax and not tax_category.gst_state):
238 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530239 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530240 return default_tax
241
242def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
243
244 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
245 ['gst_category', 'export_type'], as_dict=1)
246
247 if gst_details:
248 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
249 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
250 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
251
252 party_details["taxes_and_charges"] = default_tax
253 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
254
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530255
256def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530257 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530258 if not (basic_component and hra_component):
259 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530260 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530261 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530262 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530263 if assignment:
264 hra_component_exists = frappe.db.exists("Salary Detail", {
265 "parent": assignment.salary_structure,
266 "salary_component": hra_component,
267 "parentfield": "earnings",
268 "parenttype": "Salary Structure"
269 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530270
Nabin Hait04e7bf42019-04-25 18:44:10 +0530271 if hra_component_exists:
272 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
273 assignment.salary_structure, basic_component, hra_component)
274 if hra_amount:
275 if doc.monthly_house_rent:
276 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530277 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530278 if annual_exemption > 0:
279 monthly_exemption = annual_exemption / 12
280 else:
281 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530282
Nabin Hait04e7bf42019-04-25 18:44:10 +0530283 elif doc.docstatus == 1:
284 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
285
286 return frappe._dict({
287 "hra_amount": hra_amount,
288 "annual_exemption": annual_exemption,
289 "monthly_exemption": monthly_exemption
290 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530291
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530292def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530293 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530294 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530295 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530296 if earning.salary_component == basic_component:
297 basic_amt = earning.amount
298 elif earning.salary_component == hra_component:
299 hra_amt = earning.amount
300 if basic_amt and hra_amt:
301 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530302 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530303
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530304def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530305 # TODO make this configurable
306 exemptions = []
307 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
308 # case 1: The actual amount allotted by the employer as the HRA.
309 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530310
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530311 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530312 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530313
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530314 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530315 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530316 # 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 +0530317 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530318 # return minimum of 3 cases
319 return min(exemptions)
320
321def get_annual_component_pay(frequency, amount):
322 if frequency == "Daily":
323 return amount * 365
324 elif frequency == "Weekly":
325 return amount * 52
326 elif frequency == "Fortnightly":
327 return amount * 26
328 elif frequency == "Monthly":
329 return amount * 12
330 elif frequency == "Bimonthly":
331 return amount * 6
332
333def validate_house_rent_dates(doc):
334 if not doc.rented_to_date or not doc.rented_from_date:
335 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530336
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530337 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
338 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530339
340 proofs = frappe.db.sql("""
341 select name
342 from `tabEmployee Tax Exemption Proof Submission`
343 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530344 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
345 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
346 """, {
347 "employee": doc.employee,
348 "payroll_period": doc.payroll_period,
349 "from_date": doc.rented_from_date,
350 "to_date": doc.rented_to_date
351 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530352
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530353 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530354 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530355
356def calculate_hra_exemption_for_period(doc):
357 monthly_rent, eligible_hra = 0, 0
358 if doc.house_rent_payment_amount:
359 validate_house_rent_dates(doc)
360 # TODO receive rented months or validate dates are start and end of months?
361 # Calc monthly rent, round to nearest .5
362 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
363 factor = round(factor * 2)/2
364 monthly_rent = doc.house_rent_payment_amount / factor
365 # update field used by calculate_annual_eligible_hra_exemption
366 doc.monthly_house_rent = monthly_rent
367 exemptions = calculate_annual_eligible_hra_exemption(doc)
368
369 if exemptions["monthly_exemption"]:
370 # calc total exemption amount
371 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530372 exemptions["monthly_house_rent"] = monthly_rent
373 exemptions["total_eligible_hra_exemption"] = eligible_hra
374 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530375
Nabin Hait34c551d2019-07-03 10:34:31 +0530376def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530377
378 ewaybills = []
379 for doc_name in dn:
380 doc = frappe.get_doc(dt, doc_name)
381
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530382 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530383
384 data = frappe._dict({
385 "transporterId": "",
386 "TotNonAdvolVal": 0,
387 })
388
389 data.userGstin = data.fromGstin = doc.company_gstin
390 data.supplyType = 'O'
391
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530392 if dt == 'Delivery Note':
393 data.subSupplyType = 1
394 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530395 data.subSupplyType = 1
396 elif doc.gst_category in ['Overseas', 'Deemed Export']:
397 data.subSupplyType = 3
398 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530399 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530400
401 data.docType = 'INV'
402 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
403
404 company_address = frappe.get_doc('Address', doc.company_address)
405 billing_address = frappe.get_doc('Address', doc.customer_address)
406
407 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
408
409 data = get_address_details(data, doc, company_address, billing_address)
410
411 data.itemList = []
412 data.totalValue = doc.total
413
414 data = get_item_list(data, doc)
415
416 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
417 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
418
419 data = get_transport_details(data, doc)
420
421 fields = {
422 "/. -": {
423 'docNo': doc.name,
424 'fromTrdName': doc.company,
425 'toTrdName': doc.customer_name,
426 'transDocNo': doc.lr_no,
427 },
428 "@#/,&. -": {
429 'fromAddr1': company_address.address_line1,
430 'fromAddr2': company_address.address_line2,
431 'fromPlace': company_address.city,
432 'toAddr1': shipping_address.address_line1,
433 'toAddr2': shipping_address.address_line2,
434 'toPlace': shipping_address.city,
435 'transporterName': doc.transporter_name
436 }
437 }
438
439 for allowed_chars, field_map in fields.items():
440 for key, value in field_map.items():
441 if not value:
442 data[key] = ''
443 else:
444 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
445
446 ewaybills.append(data)
447
448 data = {
449 'version': '1.0.1118',
450 'billLists': ewaybills
451 }
452
453 return data
454
455@frappe.whitelist()
456def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530457 dn = json.loads(dn)
458 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530459
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530460@frappe.whitelist()
461def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530462 data = json.loads(frappe.local.form_dict.data)
463 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530464 frappe.local.response.type = 'download'
465
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530466 filename_prefix = 'Bulk'
467 docname = frappe.local.form_dict.docname
468 if docname:
469 if docname.startswith('['):
470 docname = json.loads(docname)
471 if len(docname) == 1:
472 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530473
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530474 if not isinstance(docname, list):
475 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
476 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530477
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530478 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 +0530479
Prasann Shah829172c2019-06-06 12:08:09 +0530480@frappe.whitelist()
481def get_gstins_for_company(company):
482 company_gstins =[]
483 if company:
484 company_gstins = frappe.db.sql("""select
485 distinct `tabAddress`.gstin
486 from
487 `tabAddress`, `tabDynamic Link`
488 where
489 `tabDynamic Link`.parent = `tabAddress`.name and
490 `tabDynamic Link`.parenttype = 'Address' and
491 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300492 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530493 return company_gstins
494
Nabin Hait34c551d2019-07-03 10:34:31 +0530495def get_address_details(data, doc, company_address, billing_address):
496 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
497 data.fromStateCode = data.actualFromStateCode = validate_state_code(
498 company_address.gst_state_number, 'Company Address')
499
500 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
501 data.toGstin = 'URP'
502 set_gst_state_and_state_number(billing_address)
503 else:
504 data.toGstin = doc.billing_address_gstin
505
506 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
507 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
508
509 if doc.customer_address != doc.shipping_address_name:
510 data.transType = 2
511 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
512 set_gst_state_and_state_number(shipping_address)
513 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
514 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
515 else:
516 data.transType = 1
517 data.actualToStateCode = data.toStateCode
518 shipping_address = billing_address
519
520 return data
521
522def get_item_list(data, doc):
523 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
524 data[attr] = 0
525
526 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
527 tax_map = {
528 'sgst_account': ['sgstRate', 'sgstValue'],
529 'cgst_account': ['cgstRate', 'cgstValue'],
530 'igst_account': ['igstRate', 'igstValue'],
531 'cess_account': ['cessRate', 'cessValue']
532 }
533 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
534 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
535 for hsn_code, taxable_amount in hsn_taxable_amount.items():
536 item_data = frappe._dict()
537 if not hsn_code:
538 frappe.throw(_('GST HSN Code does not exist for one or more items'))
539 item_data.hsnCode = int(hsn_code)
540 item_data.taxableAmount = taxable_amount
541 item_data.qtyUnit = ""
542 for attr in item_data_attrs:
543 item_data[attr] = 0
544
545 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
546 account_type = gst_accounts.get(account, '')
547 for tax_acc, attrs in tax_map.items():
548 if account_type == tax_acc:
549 item_data[attrs[0]] = tax_detail.get('tax_rate')
550 data[attrs[1]] += tax_detail.get('tax_amount')
551 break
552 else:
553 data.OthValue += tax_detail.get('tax_amount')
554
555 data.itemList.append(item_data)
556
557 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
558 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
559 data[attr] = flt(data[attr], 2)
560
561 return data
562
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530563def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530564 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530565 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530566
567 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530568 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530569
570 if doc.ewaybill:
571 frappe.throw(_('e-Way Bill already exists for this document'))
572
573 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
574 'shipping_address_name', 'mode_of_transport', 'distance']
575
576 for fieldname in reqd_fields:
577 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530578 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530579 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530580 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530581
582 if len(doc.company_gstin) < 15:
583 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
584
585def get_transport_details(data, doc):
586 if doc.distance > 4000:
587 frappe.throw(_('Distance cannot be greater than 4000 kms'))
588
589 data.transDistance = int(round(doc.distance))
590
591 transport_modes = {
592 'Road': 1,
593 'Rail': 2,
594 'Air': 3,
595 'Ship': 4
596 }
597
598 vehicle_types = {
599 'Regular': 'R',
600 'Over Dimensional Cargo (ODC)': 'O'
601 }
602
603 data.transMode = transport_modes.get(doc.mode_of_transport)
604
605 if doc.mode_of_transport == 'Road':
606 if not doc.gst_transporter_id and not doc.vehicle_no:
607 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
608 if doc.vehicle_no:
609 data.vehicleNo = doc.vehicle_no.replace(' ', '')
610 if not doc.gst_vehicle_type:
611 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
612 else:
613 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
614 else:
615 if not doc.lr_no or not doc.lr_date:
616 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
617
618 if doc.lr_no:
619 data.transDocNo = doc.lr_no
620
621 if doc.lr_date:
622 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
623
624 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530625 if doc.gst_transporter_id[0:2] != "88":
626 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
627 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530628
629 return data
630
631
632def validate_pincode(pincode, address):
633 pin_not_found = "Pin Code doesn't exist for {}"
634 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
635
636 if not pincode:
637 frappe.throw(_(pin_not_found.format(address)))
638
639 pincode = pincode.replace(' ', '')
640 if not pincode.isdigit() or len(pincode) != 6:
641 frappe.throw(_(incorrect_pin.format(address)))
642 else:
643 return int(pincode)
644
645def validate_state_code(state_code, address):
646 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
647 if not state_code:
648 frappe.throw(_(no_state_code.format(address)))
649 else:
650 return int(state_code)
651
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530652@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530653def get_gst_accounts(company, account_wise=False):
654 gst_accounts = frappe._dict()
655 gst_settings_accounts = frappe.get_all("GST Account",
656 filters={"parent": "GST Settings", "company": company},
657 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
658
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530659 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530660 frappe.throw(_("Please set GST Accounts in GST Settings"))
661
662 for d in gst_settings_accounts:
663 for acc, val in d.items():
664 if not account_wise:
665 gst_accounts.setdefault(acc, []).append(val)
666 elif val:
667 gst_accounts[val] = acc
668
Nabin Hait34c551d2019-07-03 10:34:31 +0530669 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530670
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530671def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530672 country = frappe.get_cached_value('Company', doc.company, 'country')
673
674 if country != 'India':
675 return
676
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530677 if not doc.total_taxes_and_charges:
678 return
679
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530680 if doc.reverse_charge == 'Y':
681 gst_accounts = get_gst_accounts(doc.company)
682 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
683 + gst_accounts.get('igst_account')
684
Deepesh Garg1c146062020-08-18 19:32:52 +0530685 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530686 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530687
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530688 for tax in doc.get('taxes'):
689 if tax.category not in ("Total", "Valuation and Total"):
690 continue
691
692 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530693 base_gst_tax += tax.base_tax_amount_after_discount_amount
694 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530695
696 doc.taxes_and_charges_added -= gst_tax
697 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530698 doc.base_taxes_and_charges_added -= base_gst_tax
699 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530700
Deepesh Garg1c146062020-08-18 19:32:52 +0530701 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530702
Deepesh Garg1c146062020-08-18 19:32:52 +0530703def update_totals(gst_tax, base_gst_tax, doc):
704 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530705 doc.grand_total -= gst_tax
706
707 if doc.meta.get_field("rounded_total"):
708 if doc.is_rounded_total_disabled():
709 doc.outstanding_amount = doc.grand_total
710 else:
711 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
712 doc.currency, doc.precision("rounded_total"))
713
714 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
715 doc.precision("rounding_adjustment"))
716
Deepesh Garg18827352020-07-17 11:31:15 +0530717 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530718
719 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530720 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530721 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530722
723def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530724 country = frappe.get_cached_value('Company', doc.company, 'country')
725
726 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530727 return gl_entries
728
Deepesh Garg24f9a802020-06-03 10:59:37 +0530729 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530730 gst_accounts = get_gst_accounts(doc.company)
731 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
732 + gst_accounts.get('igst_account')
733
734 for tax in doc.get('taxes'):
735 if tax.category not in ("Total", "Valuation and Total"):
736 continue
737
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530738 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530739 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
740 account_currency = get_account_currency(tax.account_head)
741
742 gl_entries.append(doc.get_gl_dict(
743 {
744 "account": tax.account_head,
745 "cost_center": tax.cost_center,
746 "posting_date": doc.posting_date,
747 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530748 dr_or_cr: tax.base_tax_amount_after_discount_amount,
749 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530750 if account_currency==doc.company_currency \
751 else tax.tax_amount_after_discount_amount
752 }, account_currency, item=tax)
753 )
754
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530755 return gl_entries