blob: 0dafe01711ac0c0e4ca90fe5eb1660603963e065 [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 Gargc36e48a2021-04-12 10:55:43 +05305from frappe.utils import cstr, flt, cint, date_diff, nowdate, round_based_on_smallest_currency_fraction, money_in_words, getdate
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
Deepesh Garga7670852020-12-04 18:07:46 +053015from frappe.model.utils import get_fetch_values
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053016
Ankush Menat7c4c42a2021-03-03 14:56:19 +053017
18GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") #alphanumeric and - /
19GSTIN_FORMAT = 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}$")
20GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
21PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
22
23
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053024def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053025 if hasattr(doc, 'gst_state') and doc.gst_state:
26 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053027 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053028 return
29
Deepesh Garg459155f2019-06-14 12:01:34 +053030 gst_category = []
31
32 if len(doc.links):
33 link_doctype = doc.links[0].get("link_doctype")
34 link_name = doc.links[0].get("link_name")
35
36 if link_doctype in ["Customer", "Supplier"]:
37 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
38
Sagar Vorad75095b2019-01-23 14:40:01 +053039 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053040 if not doc.gstin or doc.gstin == 'NA':
41 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053042
Sagar Vora07cf4e82019-01-10 11:07:51 +053043 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053044 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053045
Deepesh Garg459155f2019-06-14 12:01:34 +053046 if gst_category and gst_category == 'UIN Holders':
Ankush Menat7c4c42a2021-03-03 14:56:19 +053047 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053048 frappe.throw(_("The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"),
49 title=_("Invalid GSTIN"))
Deepesh Garg459155f2019-06-14 12:01:34 +053050 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053051 if not GSTIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053052 frappe.throw(_("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN"))
Rushabh Mehta7231f292017-07-13 15:00:56 +053053
Deepesh Garg459155f2019-06-14 12:01:34 +053054 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053055 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053056
Anurag Mishra1e396dc2021-01-13 14:01:57 +053057 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053058 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053059
Deepesh Garg459155f2019-06-14 12:01:34 +053060 if doc.gst_state_number != doc.gstin[:2]:
Saqib93203162021-04-12 17:55:46 +053061 frappe.throw(_("First 2 digits of GSTIN should match with State number {0}.")
62 .format(doc.gst_state_number), title=_("Invalid GSTIN"))
Sagar Vora07cf4e82019-01-10 11:07:51 +053063
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053064def validate_pan_for_india(doc, method):
Nabin Hait866cf702021-02-22 21:35:00 +053065 if doc.get('country') != 'India' or not doc.pan:
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053066 return
67
Ankush Menat7c4c42a2021-03-03 14:56:19 +053068 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053069 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
70
Deepesh Gargd07447a2020-11-24 08:09:17 +053071def validate_tax_category(doc, method):
Deepesh Gargb0743342020-12-17 18:46:59 +053072 if doc.get('gst_state') and frappe.db.get_value('Tax Category', {'gst_state': doc.gst_state, 'is_inter_state': doc.is_inter_state}):
Deepesh Gargd07447a2020-11-24 08:09:17 +053073 if doc.is_inter_state:
74 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
75 else:
76 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
77
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053078def update_gst_category(doc, method):
79 for link in doc.links:
80 if link.link_doctype in ['Customer', 'Supplier']:
81 if doc.get('gstin'):
82 frappe.db.sql("""
83 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
84 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
85
Nabin Hait34c551d2019-07-03 10:34:31 +053086def set_gst_state_and_state_number(doc):
87 if not doc.gst_state:
88 if not doc.state:
89 return
90 state = doc.state.lower()
91 states_lowercase = {s.lower():s for s in states}
92 if state in states_lowercase:
93 doc.gst_state = states_lowercase[state]
94 else:
95 return
96
97 doc.gst_state_number = state_numbers[doc.gst_state]
98
99def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +0530100 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +0530101 factor = 1
102 total = 0
103 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +0530104 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530105 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530106 for char in input_chars:
107 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530108 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530109 total += digit
110 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530111 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530112 frappe.throw(_("""Invalid {0}! The check digit validation has failed. Please ensure you've typed the {0} correctly.""").format(label))
Rushabh Mehta7231f292017-07-13 15:00:56 +0530113
Nabin Haitb962fc12017-07-17 18:02:31 +0530114def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
115 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
116 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
117 else:
118 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530119
Nabin Hait34c551d2019-07-03 10:34:31 +0530120def get_itemised_tax_breakup_data(doc, account_wise=False):
121 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530122
123 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530124
Nabin Haitb962fc12017-07-17 18:02:31 +0530125 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
126 return itemised_tax, itemised_taxable_amount
127
128 item_hsn_map = frappe._dict()
129 for d in doc.items:
130 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
131
132 hsn_tax = {}
133 for item, taxes in itemised_tax.items():
134 hsn_code = item_hsn_map.get(item)
135 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530136 for tax_desc, tax_detail in taxes.items():
137 key = tax_desc
138 if account_wise:
139 key = tax_detail.get('tax_account')
140 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
141 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
142 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530143
144 # set taxable amount
145 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530146 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530147 hsn_code = item_hsn_map.get(item)
148 hsn_taxable_amount.setdefault(hsn_code, 0)
149 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
150
151 return hsn_tax, hsn_taxable_amount
152
Shreya Shah4fa600a2018-06-05 11:27:53 +0530153def set_place_of_supply(doc, method=None):
154 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530155
Ankush Menata44df632021-03-01 17:12:53 +0530156def validate_document_name(doc, method=None):
157 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530158
Ankush Menata44df632021-03-01 17:12:53 +0530159 country = frappe.get_cached_value("Company", doc.company, "country")
160
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530161 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530162 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
163 return
164
165 if len(doc.name) > 16:
166 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
167
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530168 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530169 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
170
Rushabh Mehta7231f292017-07-13 15:00:56 +0530171# don't remove this function it is used in tests
172def test_method():
173 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530174 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530175
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530176def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530177 if not frappe.get_meta('Address').has_field('gst_state'): return
178
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530180 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530181 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
182 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530183
184 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530185 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530186 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530187 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530188 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530189
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530190@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530191def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530192 if isinstance(party_details, string_types):
193 party_details = json.loads(party_details)
194 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530195
Deepesh Garga7670852020-12-04 18:07:46 +0530196 update_party_details(party_details, doctype)
197
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530198 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530199
200 if is_internal_transfer(party_details, doctype):
201 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530202 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530203 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530204
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530205 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530206 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530207 get_tax_template_based_on_category(master_doctype, company, party_details)
208
pateljannatcd05b342020-11-19 11:37:08 +0530209 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530210 return party_details
211
212 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530213 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530214
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530215 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
216 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217 get_tax_template_based_on_category(master_doctype, company, party_details)
218
pateljannatcd05b342020-11-19 11:37:08 +0530219 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530220 return party_details
221
222 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530223 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530224
pateljannatcd05b342020-11-19 11:37:08 +0530225 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530226
pateljannatcd05b342020-11-19 11:37:08 +0530227 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530228
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530229 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
230 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
231 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
232 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530233 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530234 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530235
236 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530237 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530238 party_details["taxes_and_charges"] = default_tax
239 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
240
pateljannatcd05b342020-11-19 11:37:08 +0530241 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530242
Deepesh Garga7670852020-12-04 18:07:46 +0530243def update_party_details(party_details, doctype):
244 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
245 if party_details.get(address_field):
246 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
247
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530248def is_internal_transfer(party_details, doctype):
249 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
250 destination_gstin = party_details.company_gstin
251 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
252 destination_gstin = party_details.supplier_gstin
253
254 if party_details.gstin == destination_gstin:
255 return True
256 else:
257 False
258
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530259def get_tax_template_based_on_category(master_doctype, company, party_details):
260 if not party_details.get('tax_category'):
261 return
262
263 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
264 'name')
265
266 if default_tax:
267 party_details["taxes_and_charges"] = default_tax
268 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
269
270def get_tax_template(master_doctype, company, is_inter_state, state_code):
271 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
272 filters = {'is_inter_state': is_inter_state})
273
274 default_tax = ''
275
276 for tax_category in tax_categories:
277 if tax_category.gst_state == number_state_mapping[state_code] or \
278 (not default_tax and not tax_category.gst_state):
279 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530280 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530281 return default_tax
282
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530283def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530284 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530285 if not (basic_component and hra_component):
286 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530287 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530288 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530289 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530290 if assignment:
291 hra_component_exists = frappe.db.exists("Salary Detail", {
292 "parent": assignment.salary_structure,
293 "salary_component": hra_component,
294 "parentfield": "earnings",
295 "parenttype": "Salary Structure"
296 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530297
Nabin Hait04e7bf42019-04-25 18:44:10 +0530298 if hra_component_exists:
299 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
300 assignment.salary_structure, basic_component, hra_component)
301 if hra_amount:
302 if doc.monthly_house_rent:
303 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530304 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530305 if annual_exemption > 0:
306 monthly_exemption = annual_exemption / 12
307 else:
308 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530309
Nabin Hait04e7bf42019-04-25 18:44:10 +0530310 elif doc.docstatus == 1:
311 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
312
313 return frappe._dict({
314 "hra_amount": hra_amount,
315 "annual_exemption": annual_exemption,
316 "monthly_exemption": monthly_exemption
317 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530318
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530319def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530320 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530321 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530322 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530323 if earning.salary_component == basic_component:
324 basic_amt = earning.amount
325 elif earning.salary_component == hra_component:
326 hra_amt = earning.amount
327 if basic_amt and hra_amt:
328 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530329 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530330
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530331def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530332 # TODO make this configurable
333 exemptions = []
334 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
335 # case 1: The actual amount allotted by the employer as the HRA.
336 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530337
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530339 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530340
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530341 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530342 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530343 # 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 +0530344 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530345 # return minimum of 3 cases
346 return min(exemptions)
347
348def get_annual_component_pay(frequency, amount):
349 if frequency == "Daily":
350 return amount * 365
351 elif frequency == "Weekly":
352 return amount * 52
353 elif frequency == "Fortnightly":
354 return amount * 26
355 elif frequency == "Monthly":
356 return amount * 12
357 elif frequency == "Bimonthly":
358 return amount * 6
359
360def validate_house_rent_dates(doc):
361 if not doc.rented_to_date or not doc.rented_from_date:
362 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530363
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530364 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
365 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530366
367 proofs = frappe.db.sql("""
368 select name
369 from `tabEmployee Tax Exemption Proof Submission`
370 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530371 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
372 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
373 """, {
374 "employee": doc.employee,
375 "payroll_period": doc.payroll_period,
376 "from_date": doc.rented_from_date,
377 "to_date": doc.rented_to_date
378 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530379
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530380 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530381 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530382
383def calculate_hra_exemption_for_period(doc):
384 monthly_rent, eligible_hra = 0, 0
385 if doc.house_rent_payment_amount:
386 validate_house_rent_dates(doc)
387 # TODO receive rented months or validate dates are start and end of months?
388 # Calc monthly rent, round to nearest .5
389 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
390 factor = round(factor * 2)/2
391 monthly_rent = doc.house_rent_payment_amount / factor
392 # update field used by calculate_annual_eligible_hra_exemption
393 doc.monthly_house_rent = monthly_rent
394 exemptions = calculate_annual_eligible_hra_exemption(doc)
395
396 if exemptions["monthly_exemption"]:
397 # calc total exemption amount
398 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530399 exemptions["monthly_house_rent"] = monthly_rent
400 exemptions["total_eligible_hra_exemption"] = eligible_hra
401 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530402
Nabin Hait34c551d2019-07-03 10:34:31 +0530403def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530404
405 ewaybills = []
406 for doc_name in dn:
407 doc = frappe.get_doc(dt, doc_name)
408
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530409 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530410
411 data = frappe._dict({
412 "transporterId": "",
413 "TotNonAdvolVal": 0,
414 })
415
416 data.userGstin = data.fromGstin = doc.company_gstin
417 data.supplyType = 'O'
418
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530419 if dt == 'Delivery Note':
420 data.subSupplyType = 1
421 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530422 data.subSupplyType = 1
423 elif doc.gst_category in ['Overseas', 'Deemed Export']:
424 data.subSupplyType = 3
425 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530426 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530427
428 data.docType = 'INV'
429 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
430
431 company_address = frappe.get_doc('Address', doc.company_address)
432 billing_address = frappe.get_doc('Address', doc.customer_address)
433
434 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
435
436 data = get_address_details(data, doc, company_address, billing_address)
437
438 data.itemList = []
439 data.totalValue = doc.total
440
441 data = get_item_list(data, doc)
442
443 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
444 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
445
446 data = get_transport_details(data, doc)
447
448 fields = {
449 "/. -": {
450 'docNo': doc.name,
451 'fromTrdName': doc.company,
452 'toTrdName': doc.customer_name,
453 'transDocNo': doc.lr_no,
454 },
455 "@#/,&. -": {
456 'fromAddr1': company_address.address_line1,
457 'fromAddr2': company_address.address_line2,
458 'fromPlace': company_address.city,
459 'toAddr1': shipping_address.address_line1,
460 'toAddr2': shipping_address.address_line2,
461 'toPlace': shipping_address.city,
462 'transporterName': doc.transporter_name
463 }
464 }
465
466 for allowed_chars, field_map in fields.items():
467 for key, value in field_map.items():
468 if not value:
469 data[key] = ''
470 else:
471 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
472
473 ewaybills.append(data)
474
475 data = {
476 'version': '1.0.1118',
477 'billLists': ewaybills
478 }
479
480 return data
481
482@frappe.whitelist()
483def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530484 dn = json.loads(dn)
485 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530486
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530487@frappe.whitelist()
488def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530489 data = json.loads(frappe.local.form_dict.data)
490 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530491 frappe.local.response.type = 'download'
492
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530493 filename_prefix = 'Bulk'
494 docname = frappe.local.form_dict.docname
495 if docname:
496 if docname.startswith('['):
497 docname = json.loads(docname)
498 if len(docname) == 1:
499 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530500
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530501 if not isinstance(docname, list):
502 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Suraj Shetty19c5fd72021-05-10 09:18:25 +0530503 filename_prefix = re.sub(r'[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530504
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530505 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 +0530506
Prasann Shah829172c2019-06-06 12:08:09 +0530507@frappe.whitelist()
508def get_gstins_for_company(company):
509 company_gstins =[]
510 if company:
511 company_gstins = frappe.db.sql("""select
512 distinct `tabAddress`.gstin
513 from
514 `tabAddress`, `tabDynamic Link`
515 where
516 `tabDynamic Link`.parent = `tabAddress`.name and
517 `tabDynamic Link`.parenttype = 'Address' and
518 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300519 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530520 return company_gstins
521
Nabin Hait34c551d2019-07-03 10:34:31 +0530522def get_address_details(data, doc, company_address, billing_address):
523 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
524 data.fromStateCode = data.actualFromStateCode = validate_state_code(
525 company_address.gst_state_number, 'Company Address')
526
527 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
528 data.toGstin = 'URP'
529 set_gst_state_and_state_number(billing_address)
530 else:
531 data.toGstin = doc.billing_address_gstin
532
533 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
534 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
535
536 if doc.customer_address != doc.shipping_address_name:
537 data.transType = 2
538 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
539 set_gst_state_and_state_number(shipping_address)
540 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
541 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
542 else:
543 data.transType = 1
544 data.actualToStateCode = data.toStateCode
545 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530546
Smit Vorabbe49332020-11-18 20:58:59 +0530547 if doc.gst_category == 'SEZ':
548 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530549
550 return data
551
552def get_item_list(data, doc):
553 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
554 data[attr] = 0
555
556 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
557 tax_map = {
558 'sgst_account': ['sgstRate', 'sgstValue'],
559 'cgst_account': ['cgstRate', 'cgstValue'],
560 'igst_account': ['igstRate', 'igstValue'],
561 'cess_account': ['cessRate', 'cessValue']
562 }
563 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
564 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
565 for hsn_code, taxable_amount in hsn_taxable_amount.items():
566 item_data = frappe._dict()
567 if not hsn_code:
568 frappe.throw(_('GST HSN Code does not exist for one or more items'))
569 item_data.hsnCode = int(hsn_code)
570 item_data.taxableAmount = taxable_amount
571 item_data.qtyUnit = ""
572 for attr in item_data_attrs:
573 item_data[attr] = 0
574
575 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
576 account_type = gst_accounts.get(account, '')
577 for tax_acc, attrs in tax_map.items():
578 if account_type == tax_acc:
579 item_data[attrs[0]] = tax_detail.get('tax_rate')
580 data[attrs[1]] += tax_detail.get('tax_amount')
581 break
582 else:
583 data.OthValue += tax_detail.get('tax_amount')
584
585 data.itemList.append(item_data)
586
587 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
588 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
589 data[attr] = flt(data[attr], 2)
590
591 return data
592
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530593def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530594 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530595 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530596
597 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530598 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530599
600 if doc.ewaybill:
601 frappe.throw(_('e-Way Bill already exists for this document'))
602
603 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
604 'shipping_address_name', 'mode_of_transport', 'distance']
605
606 for fieldname in reqd_fields:
607 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530608 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530609 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530610 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530611
612 if len(doc.company_gstin) < 15:
613 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
614
615def get_transport_details(data, doc):
616 if doc.distance > 4000:
617 frappe.throw(_('Distance cannot be greater than 4000 kms'))
618
619 data.transDistance = int(round(doc.distance))
620
621 transport_modes = {
622 'Road': 1,
623 'Rail': 2,
624 'Air': 3,
625 'Ship': 4
626 }
627
628 vehicle_types = {
629 'Regular': 'R',
630 'Over Dimensional Cargo (ODC)': 'O'
631 }
632
633 data.transMode = transport_modes.get(doc.mode_of_transport)
634
635 if doc.mode_of_transport == 'Road':
636 if not doc.gst_transporter_id and not doc.vehicle_no:
637 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
638 if doc.vehicle_no:
639 data.vehicleNo = doc.vehicle_no.replace(' ', '')
640 if not doc.gst_vehicle_type:
641 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
642 else:
643 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
644 else:
645 if not doc.lr_no or not doc.lr_date:
646 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
647
648 if doc.lr_no:
649 data.transDocNo = doc.lr_no
650
651 if doc.lr_date:
652 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
653
654 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530655 if doc.gst_transporter_id[0:2] != "88":
656 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
657 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530658
659 return data
660
661
662def validate_pincode(pincode, address):
663 pin_not_found = "Pin Code doesn't exist for {}"
664 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
665
666 if not pincode:
667 frappe.throw(_(pin_not_found.format(address)))
668
669 pincode = pincode.replace(' ', '')
670 if not pincode.isdigit() or len(pincode) != 6:
671 frappe.throw(_(incorrect_pin.format(address)))
672 else:
673 return int(pincode)
674
675def validate_state_code(state_code, address):
676 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
677 if not state_code:
678 frappe.throw(_(no_state_code.format(address)))
679 else:
680 return int(state_code)
681
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530682@frappe.whitelist()
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530683def get_gst_accounts(company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0):
684 filters={"parent": "GST Settings"}
685
686 if company:
687 filters.update({'company': company})
688 if only_reverse_charge:
689 filters.update({'is_reverse_charge_account': 1})
690 elif only_non_reverse_charge:
691 filters.update({'is_reverse_charge_account': 0})
692
Nabin Hait34c551d2019-07-03 10:34:31 +0530693 gst_accounts = frappe._dict()
694 gst_settings_accounts = frappe.get_all("GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530695 filters=filters,
Nabin Hait34c551d2019-07-03 10:34:31 +0530696 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
697
Deepesh Garg44273902021-05-20 17:19:24 +0530698 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530699 frappe.throw(_("Please set GST Accounts in GST Settings"))
700
701 for d in gst_settings_accounts:
702 for acc, val in d.items():
703 if not account_wise:
704 gst_accounts.setdefault(acc, []).append(val)
705 elif val:
706 gst_accounts[val] = acc
707
Nabin Hait34c551d2019-07-03 10:34:31 +0530708 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530709
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530710def validate_reverse_charge_transaction(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530711 country = frappe.get_cached_value('Company', doc.company, 'country')
712
713 if country != 'India':
714 return
715
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530716 base_gst_tax = 0
717 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530718
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530719 if doc.reverse_charge == 'Y':
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530720 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
721 reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
722 + gst_accounts.get('igst_account')
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530723
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530724 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
725 non_reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530726 + gst_accounts.get('igst_account')
727
728 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530729 if tax.account_head in non_reverse_charge_accounts:
730 if tax.add_deduct_tax == 'Add':
731 base_gst_tax += tax.base_tax_amount_after_discount_amount
732 else:
733 base_gst_tax += tax.base_tax_amount_after_discount_amount
734 elif tax.account_head in reverse_charge_accounts:
735 if tax.add_deduct_tax == 'Add':
736 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
737 else:
738 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530739
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530740 if base_gst_tax != base_reverse_charge_booked:
741 msg = _("Booked reverse charge is not equal to applied tax amount")
742 msg += "<br>"
743 msg += _("Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice").format(
744 gst_document_link='<a href="https://docs.erpnext.com/docs/user/manual/en/regional/india/gst-setup">GST Documentation</a>')
Deepesh Garg24f9a802020-06-03 10:59:37 +0530745
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530746 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530747
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530748def update_itc_availed_fields(doc, method):
749 country = frappe.get_cached_value('Company', doc.company, 'country')
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530750
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530751 if country != 'India':
752 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530753
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530754 # Initialize values
755 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
756 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530757
Deepesh Garg93f925f2021-03-15 18:04:42 +0530758 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530759 if tax.account_head in gst_accounts.get('igst_account', []):
760 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
761 if tax.account_head in gst_accounts.get('sgst_account', []):
762 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
763 if tax.account_head in gst_accounts.get('cgst_account', []):
764 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
765 if tax.account_head in gst_accounts.get('cess_account', []):
766 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530767
768@frappe.whitelist()
769def get_regional_round_off_accounts(company, account_list):
770 country = frappe.get_cached_value('Company', company, 'country')
771
772 if country != 'India':
773 return
774
775 if isinstance(account_list, string_types):
776 account_list = json.loads(account_list)
777
778 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
779 return
780
781 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530782
783 gst_account_list = []
784 for account in ['cgst_account', 'sgst_account', 'igst_account']:
walstanbab673d92021-03-27 12:52:23 +0530785 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530786 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530787
788 account_list.extend(gst_account_list)
789
790 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530791
792def update_taxable_values(doc, method):
793 country = frappe.get_cached_value('Company', doc.company, 'country')
794
795 if country != 'India':
796 return
797
798 gst_accounts = get_gst_accounts(doc.company)
799
800 # Only considering sgst account to avoid inflating taxable value
801 gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
802 + gst_accounts.get('igst_account', [])
803
804 additional_taxes = 0
805 total_charges = 0
806 item_count = 0
807 considered_rows = []
808
809 for tax in doc.get('taxes'):
810 prev_row_id = cint(tax.row_id) - 1
811 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
812 if tax.charge_type == 'On Previous Row Amount':
813 additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
814 considered_rows.append(prev_row_id)
815 if tax.charge_type == 'On Previous Row Total':
816 additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
817 considered_rows.append(prev_row_id)
818
819 for item in doc.get('items'):
820 if doc.apply_discount_on == 'Grand Total' and doc.discount_amount:
821 proportionate_value = item.base_amount if doc.base_total else item.qty
822 total_value = doc.base_total if doc.base_total else doc.total_qty
823 else:
824 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
825 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
826
827 applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
828 item.precision('taxable_value')))
829 item.taxable_value = applicable_charges + proportionate_value
830 total_charges += applicable_charges
831 item_count += 1
832
833 if total_charges != additional_taxes:
834 diff = additional_taxes - total_charges
835 doc.get('items')[item_count - 1].taxable_value += diff
Saqib9226cd32021-05-10 12:36:56 +0530836
837def get_depreciation_amount(asset, depreciable_value, row):
838 depreciation_left = flt(row.total_number_of_depreciations) - flt(asset.number_of_depreciations_booked)
839
840 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +0530841 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +0530842 if not asset.flags.increase_in_asset_life:
GangaManoj2b93e542021-06-19 13:45:37 +0530843 depreciation_amount = (flt(row.value_after_depreciation) -
844 flt(row.expected_value_after_useful_life)) / depreciation_left
845
846 # if the Depreciation Schedule is being modified after Asset Repair
847 else:
848 depreciation_amount = (flt(row.value_after_depreciation) -
849 flt(row.expected_value_after_useful_life)) / (date_diff(asset.to_date, asset.available_for_use_date) / 365)
850
Saqib9226cd32021-05-10 12:36:56 +0530851 else:
852 rate_of_depreciation = row.rate_of_depreciation
853 # if its the first depreciation
854 if depreciable_value == asset.gross_purchase_amount:
855 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
856 diff = date_diff(asset.available_for_use_date, row.depreciation_start_date)
857 if diff <= 180:
858 rate_of_depreciation = rate_of_depreciation / 2
859 frappe.msgprint(
860 _('As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%.'))
861
862 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
863
864 return depreciation_amount