blob: 052d7bdedf843a48bab5b1cf32f53d5ca0ae740d [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
208 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
209 get_tax_template_based_on_category(master_doctype, company, party_details)
210
pateljannatcd05b342020-11-19 11:37:08 +0530211 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530212 return party_details
213
214 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530215 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530216
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
218 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530219 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
220 get_tax_template_based_on_category(master_doctype, company, party_details)
221
pateljannatcd05b342020-11-19 11:37:08 +0530222 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530223 return party_details
224
225 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530226 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530227
pateljannatcd05b342020-11-19 11:37:08 +0530228 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530229
pateljannatcd05b342020-11-19 11:37:08 +0530230 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530231
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530232 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
233 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
234 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
235 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530236 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530237 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530238
239 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530240 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530241 party_details["taxes_and_charges"] = default_tax
242 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
243
pateljannatcd05b342020-11-19 11:37:08 +0530244 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530245
Deepesh Garga7670852020-12-04 18:07:46 +0530246def update_party_details(party_details, doctype):
247 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
248 if party_details.get(address_field):
249 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
250
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530251def is_internal_transfer(party_details, doctype):
252 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
253 destination_gstin = party_details.company_gstin
254 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
255 destination_gstin = party_details.supplier_gstin
256
257 if party_details.gstin == destination_gstin:
258 return True
259 else:
260 False
261
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530262def get_tax_template_based_on_category(master_doctype, company, party_details):
263 if not party_details.get('tax_category'):
264 return
265
266 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
267 'name')
268
269 if default_tax:
270 party_details["taxes_and_charges"] = default_tax
271 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
272
273def get_tax_template(master_doctype, company, is_inter_state, state_code):
274 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
275 filters = {'is_inter_state': is_inter_state})
276
277 default_tax = ''
278
279 for tax_category in tax_categories:
280 if tax_category.gst_state == number_state_mapping[state_code] or \
281 (not default_tax and not tax_category.gst_state):
282 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530283 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530284 return default_tax
285
286def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
287
288 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
289 ['gst_category', 'export_type'], as_dict=1)
290
291 if gst_details:
292 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
293 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
294 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
295
296 party_details["taxes_and_charges"] = default_tax
297 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
298
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530299
300def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530301 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530302 if not (basic_component and hra_component):
303 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530304 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530305 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530306 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530307 if assignment:
308 hra_component_exists = frappe.db.exists("Salary Detail", {
309 "parent": assignment.salary_structure,
310 "salary_component": hra_component,
311 "parentfield": "earnings",
312 "parenttype": "Salary Structure"
313 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530314
Nabin Hait04e7bf42019-04-25 18:44:10 +0530315 if hra_component_exists:
316 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
317 assignment.salary_structure, basic_component, hra_component)
318 if hra_amount:
319 if doc.monthly_house_rent:
320 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530321 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530322 if annual_exemption > 0:
323 monthly_exemption = annual_exemption / 12
324 else:
325 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530326
Nabin Hait04e7bf42019-04-25 18:44:10 +0530327 elif doc.docstatus == 1:
328 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
329
330 return frappe._dict({
331 "hra_amount": hra_amount,
332 "annual_exemption": annual_exemption,
333 "monthly_exemption": monthly_exemption
334 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530335
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530336def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530337 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530338 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530339 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530340 if earning.salary_component == basic_component:
341 basic_amt = earning.amount
342 elif earning.salary_component == hra_component:
343 hra_amt = earning.amount
344 if basic_amt and hra_amt:
345 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530346 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530347
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530348def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530349 # TODO make this configurable
350 exemptions = []
351 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
352 # case 1: The actual amount allotted by the employer as the HRA.
353 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530354
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530355 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530356 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530357
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530358 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530359 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530360 # 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 +0530361 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530362 # return minimum of 3 cases
363 return min(exemptions)
364
365def get_annual_component_pay(frequency, amount):
366 if frequency == "Daily":
367 return amount * 365
368 elif frequency == "Weekly":
369 return amount * 52
370 elif frequency == "Fortnightly":
371 return amount * 26
372 elif frequency == "Monthly":
373 return amount * 12
374 elif frequency == "Bimonthly":
375 return amount * 6
376
377def validate_house_rent_dates(doc):
378 if not doc.rented_to_date or not doc.rented_from_date:
379 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530380
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530381 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
382 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530383
384 proofs = frappe.db.sql("""
385 select name
386 from `tabEmployee Tax Exemption Proof Submission`
387 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530388 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
389 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
390 """, {
391 "employee": doc.employee,
392 "payroll_period": doc.payroll_period,
393 "from_date": doc.rented_from_date,
394 "to_date": doc.rented_to_date
395 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530396
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530397 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530398 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530399
400def calculate_hra_exemption_for_period(doc):
401 monthly_rent, eligible_hra = 0, 0
402 if doc.house_rent_payment_amount:
403 validate_house_rent_dates(doc)
404 # TODO receive rented months or validate dates are start and end of months?
405 # Calc monthly rent, round to nearest .5
406 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
407 factor = round(factor * 2)/2
408 monthly_rent = doc.house_rent_payment_amount / factor
409 # update field used by calculate_annual_eligible_hra_exemption
410 doc.monthly_house_rent = monthly_rent
411 exemptions = calculate_annual_eligible_hra_exemption(doc)
412
413 if exemptions["monthly_exemption"]:
414 # calc total exemption amount
415 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530416 exemptions["monthly_house_rent"] = monthly_rent
417 exemptions["total_eligible_hra_exemption"] = eligible_hra
418 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530419
Nabin Hait34c551d2019-07-03 10:34:31 +0530420def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530421
422 ewaybills = []
423 for doc_name in dn:
424 doc = frappe.get_doc(dt, doc_name)
425
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530426 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530427
428 data = frappe._dict({
429 "transporterId": "",
430 "TotNonAdvolVal": 0,
431 })
432
433 data.userGstin = data.fromGstin = doc.company_gstin
434 data.supplyType = 'O'
435
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530436 if dt == 'Delivery Note':
437 data.subSupplyType = 1
438 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530439 data.subSupplyType = 1
440 elif doc.gst_category in ['Overseas', 'Deemed Export']:
441 data.subSupplyType = 3
442 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530443 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530444
445 data.docType = 'INV'
446 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
447
448 company_address = frappe.get_doc('Address', doc.company_address)
449 billing_address = frappe.get_doc('Address', doc.customer_address)
450
451 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
452
453 data = get_address_details(data, doc, company_address, billing_address)
454
455 data.itemList = []
456 data.totalValue = doc.total
457
458 data = get_item_list(data, doc)
459
460 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
461 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
462
463 data = get_transport_details(data, doc)
464
465 fields = {
466 "/. -": {
467 'docNo': doc.name,
468 'fromTrdName': doc.company,
469 'toTrdName': doc.customer_name,
470 'transDocNo': doc.lr_no,
471 },
472 "@#/,&. -": {
473 'fromAddr1': company_address.address_line1,
474 'fromAddr2': company_address.address_line2,
475 'fromPlace': company_address.city,
476 'toAddr1': shipping_address.address_line1,
477 'toAddr2': shipping_address.address_line2,
478 'toPlace': shipping_address.city,
479 'transporterName': doc.transporter_name
480 }
481 }
482
483 for allowed_chars, field_map in fields.items():
484 for key, value in field_map.items():
485 if not value:
486 data[key] = ''
487 else:
488 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
489
490 ewaybills.append(data)
491
492 data = {
493 'version': '1.0.1118',
494 'billLists': ewaybills
495 }
496
497 return data
498
499@frappe.whitelist()
500def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530501 dn = json.loads(dn)
502 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530503
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530504@frappe.whitelist()
505def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530506 data = json.loads(frappe.local.form_dict.data)
507 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530508 frappe.local.response.type = 'download'
509
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530510 filename_prefix = 'Bulk'
511 docname = frappe.local.form_dict.docname
512 if docname:
513 if docname.startswith('['):
514 docname = json.loads(docname)
515 if len(docname) == 1:
516 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530517
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530518 if not isinstance(docname, list):
519 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
520 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530521
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530522 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 +0530523
Prasann Shah829172c2019-06-06 12:08:09 +0530524@frappe.whitelist()
525def get_gstins_for_company(company):
526 company_gstins =[]
527 if company:
528 company_gstins = frappe.db.sql("""select
529 distinct `tabAddress`.gstin
530 from
531 `tabAddress`, `tabDynamic Link`
532 where
533 `tabDynamic Link`.parent = `tabAddress`.name and
534 `tabDynamic Link`.parenttype = 'Address' and
535 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300536 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530537 return company_gstins
538
Nabin Hait34c551d2019-07-03 10:34:31 +0530539def get_address_details(data, doc, company_address, billing_address):
540 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
541 data.fromStateCode = data.actualFromStateCode = validate_state_code(
542 company_address.gst_state_number, 'Company Address')
543
544 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
545 data.toGstin = 'URP'
546 set_gst_state_and_state_number(billing_address)
547 else:
548 data.toGstin = doc.billing_address_gstin
549
550 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
551 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
552
553 if doc.customer_address != doc.shipping_address_name:
554 data.transType = 2
555 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
556 set_gst_state_and_state_number(shipping_address)
557 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
558 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
559 else:
560 data.transType = 1
561 data.actualToStateCode = data.toStateCode
562 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530563
Smit Vorabbe49332020-11-18 20:58:59 +0530564 if doc.gst_category == 'SEZ':
565 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530566
567 return data
568
569def get_item_list(data, doc):
570 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
571 data[attr] = 0
572
573 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
574 tax_map = {
575 'sgst_account': ['sgstRate', 'sgstValue'],
576 'cgst_account': ['cgstRate', 'cgstValue'],
577 'igst_account': ['igstRate', 'igstValue'],
578 'cess_account': ['cessRate', 'cessValue']
579 }
580 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
581 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
582 for hsn_code, taxable_amount in hsn_taxable_amount.items():
583 item_data = frappe._dict()
584 if not hsn_code:
585 frappe.throw(_('GST HSN Code does not exist for one or more items'))
586 item_data.hsnCode = int(hsn_code)
587 item_data.taxableAmount = taxable_amount
588 item_data.qtyUnit = ""
589 for attr in item_data_attrs:
590 item_data[attr] = 0
591
592 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
593 account_type = gst_accounts.get(account, '')
594 for tax_acc, attrs in tax_map.items():
595 if account_type == tax_acc:
596 item_data[attrs[0]] = tax_detail.get('tax_rate')
597 data[attrs[1]] += tax_detail.get('tax_amount')
598 break
599 else:
600 data.OthValue += tax_detail.get('tax_amount')
601
602 data.itemList.append(item_data)
603
604 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
605 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
606 data[attr] = flt(data[attr], 2)
607
608 return data
609
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530610def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530611 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530612 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530613
614 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530615 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530616
617 if doc.ewaybill:
618 frappe.throw(_('e-Way Bill already exists for this document'))
619
620 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
621 'shipping_address_name', 'mode_of_transport', 'distance']
622
623 for fieldname in reqd_fields:
624 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530625 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530626 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530627 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530628
629 if len(doc.company_gstin) < 15:
630 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
631
632def get_transport_details(data, doc):
633 if doc.distance > 4000:
634 frappe.throw(_('Distance cannot be greater than 4000 kms'))
635
636 data.transDistance = int(round(doc.distance))
637
638 transport_modes = {
639 'Road': 1,
640 'Rail': 2,
641 'Air': 3,
642 'Ship': 4
643 }
644
645 vehicle_types = {
646 'Regular': 'R',
647 'Over Dimensional Cargo (ODC)': 'O'
648 }
649
650 data.transMode = transport_modes.get(doc.mode_of_transport)
651
652 if doc.mode_of_transport == 'Road':
653 if not doc.gst_transporter_id and not doc.vehicle_no:
654 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
655 if doc.vehicle_no:
656 data.vehicleNo = doc.vehicle_no.replace(' ', '')
657 if not doc.gst_vehicle_type:
658 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
659 else:
660 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
661 else:
662 if not doc.lr_no or not doc.lr_date:
663 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
664
665 if doc.lr_no:
666 data.transDocNo = doc.lr_no
667
668 if doc.lr_date:
669 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
670
671 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530672 if doc.gst_transporter_id[0:2] != "88":
673 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
674 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530675
676 return data
677
678
679def validate_pincode(pincode, address):
680 pin_not_found = "Pin Code doesn't exist for {}"
681 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
682
683 if not pincode:
684 frappe.throw(_(pin_not_found.format(address)))
685
686 pincode = pincode.replace(' ', '')
687 if not pincode.isdigit() or len(pincode) != 6:
688 frappe.throw(_(incorrect_pin.format(address)))
689 else:
690 return int(pincode)
691
692def validate_state_code(state_code, address):
693 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
694 if not state_code:
695 frappe.throw(_(no_state_code.format(address)))
696 else:
697 return int(state_code)
698
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530699@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530700def get_gst_accounts(company, account_wise=False):
701 gst_accounts = frappe._dict()
702 gst_settings_accounts = frappe.get_all("GST Account",
703 filters={"parent": "GST Settings", "company": company},
704 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
705
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530706 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530707 frappe.throw(_("Please set GST Accounts in GST Settings"))
708
709 for d in gst_settings_accounts:
710 for acc, val in d.items():
711 if not account_wise:
712 gst_accounts.setdefault(acc, []).append(val)
713 elif val:
714 gst_accounts[val] = acc
715
Nabin Hait34c551d2019-07-03 10:34:31 +0530716 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530717
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530718def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530719 country = frappe.get_cached_value('Company', doc.company, 'country')
720
721 if country != 'India':
722 return
723
Deepesh Garg93f925f2021-03-15 18:04:42 +0530724 gst_tax, base_gst_tax = get_gst_tax_amount(doc)
725
726 if not base_gst_tax:
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530727 return
728
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530729 if doc.reverse_charge == 'Y':
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530730 doc.taxes_and_charges_added -= gst_tax
731 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530732 doc.base_taxes_and_charges_added -= base_gst_tax
733 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530734
Deepesh Garg1c146062020-08-18 19:32:52 +0530735 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530736
Deepesh Garg1c146062020-08-18 19:32:52 +0530737def update_totals(gst_tax, base_gst_tax, doc):
738 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530739 doc.grand_total -= gst_tax
740
741 if doc.meta.get_field("rounded_total"):
742 if doc.is_rounded_total_disabled():
743 doc.outstanding_amount = doc.grand_total
744 else:
745 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
746 doc.currency, doc.precision("rounded_total"))
747
748 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
749 doc.precision("rounding_adjustment"))
750
Deepesh Garg18827352020-07-17 11:31:15 +0530751 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530752
753 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530754 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530755 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530756
757def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530758 country = frappe.get_cached_value('Company', doc.company, 'country')
759
760 if country != 'India':
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530761 return gl_entries
762
Deepesh Garg93f925f2021-03-15 18:04:42 +0530763 gst_tax, base_gst_tax = get_gst_tax_amount(doc)
764
765 if not base_gst_tax:
766 return gl_entries
767
Deepesh Garg24f9a802020-06-03 10:59:37 +0530768 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530769 gst_accounts = get_gst_accounts(doc.company)
770 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
771 + gst_accounts.get('igst_account')
772
773 for tax in doc.get('taxes'):
774 if tax.category not in ("Total", "Valuation and Total"):
775 continue
776
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530777 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530778 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
779 account_currency = get_account_currency(tax.account_head)
780
781 gl_entries.append(doc.get_gl_dict(
782 {
783 "account": tax.account_head,
784 "cost_center": tax.cost_center,
785 "posting_date": doc.posting_date,
786 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530787 dr_or_cr: tax.base_tax_amount_after_discount_amount,
788 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530789 if account_currency==doc.company_currency \
790 else tax.tax_amount_after_discount_amount
791 }, account_currency, item=tax)
792 )
793
Deepesh Gargd07447a2020-11-24 08:09:17 +0530794 return gl_entries
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530795
Deepesh Garg93f925f2021-03-15 18:04:42 +0530796def get_gst_tax_amount(doc):
797 gst_accounts = get_gst_accounts(doc.company)
798 gst_account_list = gst_accounts.get('cgst_account', []) + gst_accounts.get('sgst_account', []) \
799 + gst_accounts.get('igst_account', [])
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530800
Deepesh Garg93f925f2021-03-15 18:04:42 +0530801 base_gst_tax = 0
802 gst_tax = 0
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530803
Deepesh Garg93f925f2021-03-15 18:04:42 +0530804 for tax in doc.get('taxes'):
805 if tax.category not in ("Total", "Valuation and Total"):
806 continue
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530807
Deepesh Garg93f925f2021-03-15 18:04:42 +0530808 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
809 base_gst_tax += tax.base_tax_amount_after_discount_amount
810 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530811
Deepesh Garg93f925f2021-03-15 18:04:42 +0530812 return gst_tax, base_gst_tax
Deepesh Garg004f9e62021-03-16 13:09:59 +0530813
814@frappe.whitelist()
815def get_regional_round_off_accounts(company, account_list):
816 country = frappe.get_cached_value('Company', company, 'country')
817
818 if country != 'India':
819 return
820
821 if isinstance(account_list, string_types):
822 account_list = json.loads(account_list)
823
824 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
825 return
826
827 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530828
829 gst_account_list = []
830 for account in ['cgst_account', 'sgst_account', 'igst_account']:
walstanbab673d92021-03-27 12:52:23 +0530831 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530832 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530833
834 account_list.extend(gst_account_list)
835
836 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530837
838def update_taxable_values(doc, method):
839 country = frappe.get_cached_value('Company', doc.company, 'country')
840
841 if country != 'India':
842 return
843
844 gst_accounts = get_gst_accounts(doc.company)
845
846 # Only considering sgst account to avoid inflating taxable value
847 gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
848 + gst_accounts.get('igst_account', [])
849
850 additional_taxes = 0
851 total_charges = 0
852 item_count = 0
853 considered_rows = []
854
855 for tax in doc.get('taxes'):
856 prev_row_id = cint(tax.row_id) - 1
857 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
858 if tax.charge_type == 'On Previous Row Amount':
859 additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
860 considered_rows.append(prev_row_id)
861 if tax.charge_type == 'On Previous Row Total':
862 additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
863 considered_rows.append(prev_row_id)
864
865 for item in doc.get('items'):
866 if doc.apply_discount_on == 'Grand Total' and doc.discount_amount:
867 proportionate_value = item.base_amount if doc.base_total else item.qty
868 total_value = doc.base_total if doc.base_total else doc.total_qty
869 else:
870 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
871 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
872
873 applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
874 item.precision('taxable_value')))
875 item.taxable_value = applicable_charges + proportionate_value
876 total_charges += applicable_charges
877 item_count += 1
878
879 if total_charges != additional_taxes:
880 diff = additional_taxes - total_charges
881 doc.get('items')[item_count - 1].taxable_value += diff
Saqib9226cd32021-05-10 12:36:56 +0530882
883def get_depreciation_amount(asset, depreciable_value, row):
884 depreciation_left = flt(row.total_number_of_depreciations) - flt(asset.number_of_depreciations_booked)
885
886 if row.depreciation_method in ("Straight Line", "Manual"):
887 depreciation_amount = (flt(row.value_after_depreciation) -
888 flt(row.expected_value_after_useful_life)) / depreciation_left
889 else:
890 rate_of_depreciation = row.rate_of_depreciation
891 # if its the first depreciation
892 if depreciable_value == asset.gross_purchase_amount:
893 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
894 diff = date_diff(asset.available_for_use_date, row.depreciation_start_date)
895 if diff <= 180:
896 rate_of_depreciation = rate_of_depreciation / 2
897 frappe.msgprint(
898 _('As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%.'))
899
900 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
901
902 return depreciation_amount