blob: 8715ef57babbc637d53d9eb0f5136341d452f896 [file] [log] [blame]
Chillar Anand915b3432021-09-02 16:44:59 +05301import json
2import re
3
4import frappe
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05305from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05306from frappe.model.utils import get_fetch_values
7from frappe.utils import cint, cstr, date_diff, flt, getdate, nowdate
Chillar Anand915b3432021-09-02 16:44:59 +05308
Shreya Shah4fa600a2018-06-05 11:27:53 +05309from erpnext.controllers.accounts_controller import get_taxes_and_charges
Chillar Anand915b3432021-09-02 16:44:59 +053010from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +053011from erpnext.hr.utils import get_salary_assignment
Anurag Mishra289c8222020-06-19 19:17:57 +053012from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Chillar Anand915b3432021-09-02 16:44:59 +053013from erpnext.regional.india import number_state_mapping, state_numbers, states
Ankush Menat7c4c42a2021-03-03 14:56:19 +053014
15GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") #alphanumeric and - /
16GSTIN_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}$")
17GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
18PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
19
20
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053021def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053022 if hasattr(doc, 'gst_state') and doc.gst_state:
23 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053024 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053025 return
26
Deepesh Garg459155f2019-06-14 12:01:34 +053027 gst_category = []
28
Anuja Pawar59c31bb2021-10-22 19:26:31 +053029 if hasattr(doc, 'gst_category'):
30 if len(doc.links):
31 link_doctype = doc.links[0].get("link_doctype")
32 link_name = doc.links[0].get("link_name")
Deepesh Garg459155f2019-06-14 12:01:34 +053033
Anuja Pawar59c31bb2021-10-22 19:26:31 +053034 if link_doctype in ["Customer", "Supplier"]:
35 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
Deepesh Garg459155f2019-06-14 12:01:34 +053036
Sagar Vorad75095b2019-01-23 14:40:01 +053037 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053038 if not doc.gstin or doc.gstin == 'NA':
39 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053040
Sagar Vora07cf4e82019-01-10 11:07:51 +053041 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053042 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053043
Deepesh Garg459155f2019-06-14 12:01:34 +053044 if gst_category and gst_category == 'UIN Holders':
Ankush Menat7c4c42a2021-03-03 14:56:19 +053045 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053046 frappe.throw(_("The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"),
47 title=_("Invalid GSTIN"))
Deepesh Garg459155f2019-06-14 12:01:34 +053048 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053049 if not GSTIN_FORMAT.match(doc.gstin):
Saqib93203162021-04-12 17:55:46 +053050 frappe.throw(_("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN"))
Rushabh Mehta7231f292017-07-13 15:00:56 +053051
Deepesh Garg459155f2019-06-14 12:01:34 +053052 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053053 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053054
Anurag Mishra1e396dc2021-01-13 14:01:57 +053055 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053056 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053057
Deepesh Garg459155f2019-06-14 12:01:34 +053058 if doc.gst_state_number != doc.gstin[:2]:
Saqib93203162021-04-12 17:55:46 +053059 frappe.throw(_("First 2 digits of GSTIN should match with State number {0}.")
60 .format(doc.gst_state_number), title=_("Invalid GSTIN"))
Sagar Vora07cf4e82019-01-10 11:07:51 +053061
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053062def validate_pan_for_india(doc, method):
Deepesh Gargcd4b2032021-10-25 11:21:55 +053063 if doc.get('country') != 'India' or not doc.get('pan'):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053064 return
65
Ankush Menat7c4c42a2021-03-03 14:56:19 +053066 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053067 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
68
Deepesh Gargd07447a2020-11-24 08:09:17 +053069def validate_tax_category(doc, method):
Deepesh Garg12a65ee2021-12-17 15:59:21 +053070 if doc.get('gst_state') and frappe.db.get_value('Tax Category', {'gst_state': doc.gst_state, 'is_inter_state': doc.is_inter_state,
71 'is_reverse_charge': doc.is_reverse_charge}):
Deepesh Gargd07447a2020-11-24 08:09:17 +053072 if doc.is_inter_state:
73 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
74 else:
75 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
76
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053077def update_gst_category(doc, method):
Deepesh Garga38aca52021-11-19 11:03:13 +053078 for link in doc.links:
79 if link.link_doctype in ['Customer', 'Supplier']:
80 meta = frappe.get_meta(link.link_doctype)
81 if doc.get('gstin') and meta.has_field('gst_category'):
82 frappe.db.set_value(link.link_doctype, {'name': link.link_name, 'gst_category': 'Unregistered'}, 'gst_category', 'Registered Regular')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053083
Nabin Hait34c551d2019-07-03 10:34:31 +053084def set_gst_state_and_state_number(doc):
85 if not doc.gst_state:
86 if not doc.state:
87 return
88 state = doc.state.lower()
89 states_lowercase = {s.lower():s for s in states}
90 if state in states_lowercase:
91 doc.gst_state = states_lowercase[state]
92 else:
93 return
94
95 doc.gst_state_number = state_numbers[doc.gst_state]
96
97def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053098 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053099 factor = 1
100 total = 0
101 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +0530102 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530103 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530104 for char in input_chars:
105 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530106 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530107 total += digit
108 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530109 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530110 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 +0530111
Nabin Haitb962fc12017-07-17 18:02:31 +0530112def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
Subin Tom530de122021-10-11 17:33:41 +0530113 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
114 if frappe.get_meta(item_doctype).has_field('gst_hsn_code') and hsn_wise_in_gst_settings:
115 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
116 else:
117 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530118
Subin Tomd49346a2021-09-17 10:39:03 +0530119def get_itemised_tax_breakup_data(doc, account_wise=False, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530120 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530121
122 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530123
Nabin Haitb962fc12017-07-17 18:02:31 +0530124 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
125 return itemised_tax, itemised_taxable_amount
126
Subin Tom530de122021-10-11 17:33:41 +0530127 hsn_wise_in_gst_settings = frappe.db.get_single_value('GST Settings','hsn_wise_tax_breakup')
128
129 tax_breakup_hsn_wise = hsn_wise or hsn_wise_in_gst_settings
130 if tax_breakup_hsn_wise:
Subin Tomd49346a2021-09-17 10:39:03 +0530131 item_hsn_map = frappe._dict()
132 for d in doc.items:
133 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
Nabin Haitb962fc12017-07-17 18:02:31 +0530134
135 hsn_tax = {}
136 for item, taxes in itemised_tax.items():
Subin Tom530de122021-10-11 17:33:41 +0530137 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530138 hsn_tax.setdefault(item_or_hsn, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530139 for tax_desc, tax_detail in taxes.items():
140 key = tax_desc
141 if account_wise:
142 key = tax_detail.get('tax_account')
Subin Tomd49346a2021-09-17 10:39:03 +0530143 hsn_tax[item_or_hsn].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
144 hsn_tax[item_or_hsn][key]["tax_rate"] = tax_detail.get("tax_rate")
145 hsn_tax[item_or_hsn][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530146
147 # set taxable amount
148 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530149 for item in itemised_taxable_amount:
Subin Tom530de122021-10-11 17:33:41 +0530150 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530151 hsn_taxable_amount.setdefault(item_or_hsn, 0)
152 hsn_taxable_amount[item_or_hsn] += itemised_taxable_amount.get(item)
Nabin Haitb962fc12017-07-17 18:02:31 +0530153
154 return hsn_tax, hsn_taxable_amount
155
Shreya Shah4fa600a2018-06-05 11:27:53 +0530156def set_place_of_supply(doc, method=None):
157 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530158
Ankush Menata44df632021-03-01 17:12:53 +0530159def validate_document_name(doc, method=None):
160 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530161
Ankush Menata44df632021-03-01 17:12:53 +0530162 country = frappe.get_cached_value("Company", doc.company, "country")
163
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530164 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530165 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
166 return
167
168 if len(doc.name) > 16:
169 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
170
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530171 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530172 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
173
Rushabh Mehta7231f292017-07-13 15:00:56 +0530174# don't remove this function it is used in tests
175def test_method():
176 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530177 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530178
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530180 if not frappe.get_meta('Address').has_field('gst_state'): return
181
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530182 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530183 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530184 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
185 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530186
187 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530188 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530189 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530190 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530191 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530192
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530193@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530194def get_regional_address_details(party_details, doctype, company):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530195 if isinstance(party_details, str):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530196 party_details = json.loads(party_details)
197 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530198
Deepesh Garga7670852020-12-04 18:07:46 +0530199 update_party_details(party_details, doctype)
200
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530201 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530202
203 if is_internal_transfer(party_details, doctype):
204 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530205 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530206 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530207
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530208 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530209 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530210 tax_template_by_category = get_tax_template_based_on_category(master_doctype, company, party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530211
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530212 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
213 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530214 tax_template_by_category = get_tax_template_based_on_category(master_doctype, company, party_details)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530215
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530216 if tax_template_by_category:
Deepesh Gargd5380dd2021-12-08 14:06:34 +0530217 party_details['taxes_and_charges'] = tax_template_by_category
Deepesh Garg466e5492022-01-02 17:53:15 +0530218 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530219
pateljannatcd05b342020-11-19 11:37:08 +0530220 if not party_details.place_of_supply: return party_details
Deepesh Gargcb21dff2021-12-07 18:44:05 +0530221 if not party_details.company_gstin: return party_details
Deepesh Garge45c3832022-01-28 16:10:30 +0530222 if not party_details.supplier_gstin: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530223
224 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
225 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
226 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
227 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530228 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530229 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530230
231 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530232 return party_details
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530233
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530234 party_details["taxes_and_charges"] = default_tax
235 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
236
pateljannatcd05b342020-11-19 11:37:08 +0530237 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530238
Deepesh Garga7670852020-12-04 18:07:46 +0530239def update_party_details(party_details, doctype):
240 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
241 if party_details.get(address_field):
242 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
243
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530244def is_internal_transfer(party_details, doctype):
245 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
246 destination_gstin = party_details.company_gstin
247 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
248 destination_gstin = party_details.supplier_gstin
249
Deepesh Gargda47fe22021-09-30 13:28:53 +0530250 if not destination_gstin or party_details.gstin:
251 return False
252
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530253 if party_details.gstin == destination_gstin:
254 return True
255 else:
256 False
257
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530258def get_tax_template_based_on_category(master_doctype, company, party_details):
259 if not party_details.get('tax_category'):
260 return
261
262 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
263 'name')
264
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530265 return default_tax
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530266
267def get_tax_template(master_doctype, company, is_inter_state, state_code):
268 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
Deepesh Garg12a65ee2021-12-17 15:59:21 +0530269 filters = {'is_inter_state': is_inter_state, 'is_reverse_charge': 0})
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530270
271 default_tax = ''
272
273 for tax_category in tax_categories:
274 if tax_category.gst_state == number_state_mapping[state_code] or \
275 (not default_tax and not tax_category.gst_state):
276 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530277 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530278 return default_tax
279
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530280def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530281 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530282 if not (basic_component and hra_component):
283 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530284 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530285 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530286 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530287 if assignment:
288 hra_component_exists = frappe.db.exists("Salary Detail", {
289 "parent": assignment.salary_structure,
290 "salary_component": hra_component,
291 "parentfield": "earnings",
292 "parenttype": "Salary Structure"
293 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530294
Nabin Hait04e7bf42019-04-25 18:44:10 +0530295 if hra_component_exists:
296 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
297 assignment.salary_structure, basic_component, hra_component)
298 if hra_amount:
299 if doc.monthly_house_rent:
300 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530301 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530302 if annual_exemption > 0:
303 monthly_exemption = annual_exemption / 12
304 else:
305 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530306
Nabin Hait04e7bf42019-04-25 18:44:10 +0530307 elif doc.docstatus == 1:
308 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
309
310 return frappe._dict({
311 "hra_amount": hra_amount,
312 "annual_exemption": annual_exemption,
313 "monthly_exemption": monthly_exemption
314 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530315
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530316def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530317 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530318 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530319 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530320 if earning.salary_component == basic_component:
321 basic_amt = earning.amount
322 elif earning.salary_component == hra_component:
323 hra_amt = earning.amount
324 if basic_amt and hra_amt:
325 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530326 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530327
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530328def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530329 # TODO make this configurable
330 exemptions = []
331 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
332 # case 1: The actual amount allotted by the employer as the HRA.
333 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530334
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530335 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530336 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530337
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530339 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530340 # 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 +0530341 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530342 # return minimum of 3 cases
343 return min(exemptions)
344
345def get_annual_component_pay(frequency, amount):
346 if frequency == "Daily":
347 return amount * 365
348 elif frequency == "Weekly":
349 return amount * 52
350 elif frequency == "Fortnightly":
351 return amount * 26
352 elif frequency == "Monthly":
353 return amount * 12
354 elif frequency == "Bimonthly":
355 return amount * 6
356
357def validate_house_rent_dates(doc):
358 if not doc.rented_to_date or not doc.rented_from_date:
359 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530360
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530361 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
362 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530363
364 proofs = frappe.db.sql("""
365 select name
366 from `tabEmployee Tax Exemption Proof Submission`
367 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530368 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
369 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
370 """, {
371 "employee": doc.employee,
372 "payroll_period": doc.payroll_period,
373 "from_date": doc.rented_from_date,
374 "to_date": doc.rented_to_date
375 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530376
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530377 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530378 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530379
380def calculate_hra_exemption_for_period(doc):
381 monthly_rent, eligible_hra = 0, 0
382 if doc.house_rent_payment_amount:
383 validate_house_rent_dates(doc)
384 # TODO receive rented months or validate dates are start and end of months?
385 # Calc monthly rent, round to nearest .5
386 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
387 factor = round(factor * 2)/2
388 monthly_rent = doc.house_rent_payment_amount / factor
389 # update field used by calculate_annual_eligible_hra_exemption
390 doc.monthly_house_rent = monthly_rent
391 exemptions = calculate_annual_eligible_hra_exemption(doc)
392
393 if exemptions["monthly_exemption"]:
394 # calc total exemption amount
395 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530396 exemptions["monthly_house_rent"] = monthly_rent
397 exemptions["total_eligible_hra_exemption"] = eligible_hra
398 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530399
Nabin Hait34c551d2019-07-03 10:34:31 +0530400def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530401
402 ewaybills = []
403 for doc_name in dn:
404 doc = frappe.get_doc(dt, doc_name)
405
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530406 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530407
408 data = frappe._dict({
409 "transporterId": "",
410 "TotNonAdvolVal": 0,
411 })
412
413 data.userGstin = data.fromGstin = doc.company_gstin
414 data.supplyType = 'O'
415
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530416 if dt == 'Delivery Note':
417 data.subSupplyType = 1
418 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530419 data.subSupplyType = 1
420 elif doc.gst_category in ['Overseas', 'Deemed Export']:
421 data.subSupplyType = 3
422 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530423 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530424
425 data.docType = 'INV'
426 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
427
428 company_address = frappe.get_doc('Address', doc.company_address)
429 billing_address = frappe.get_doc('Address', doc.customer_address)
430
Subin Tom5265ba32021-07-13 14:58:17 +0530431 #added dispatch address
Subin Tomb24a1492021-07-19 14:37:12 +0530432 dispatch_address = frappe.get_doc('Address', doc.dispatch_address_name) if doc.dispatch_address_name else company_address
Nabin Hait34c551d2019-07-03 10:34:31 +0530433 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
434
Subin Tom5265ba32021-07-13 14:58:17 +0530435 data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530436
437 data.itemList = []
Smit Vorae2d866d2021-11-01 15:55:19 +0530438 data.totalValue = doc.net_total
Nabin Hait34c551d2019-07-03 10:34:31 +0530439
Subin Tomd49346a2021-09-17 10:39:03 +0530440 data = get_item_list(data, doc, hsn_wise=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530441
442 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
443 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
444
445 data = get_transport_details(data, doc)
446
447 fields = {
448 "/. -": {
449 'docNo': doc.name,
450 'fromTrdName': doc.company,
451 'toTrdName': doc.customer_name,
452 'transDocNo': doc.lr_no,
453 },
454 "@#/,&. -": {
455 'fromAddr1': company_address.address_line1,
456 'fromAddr2': company_address.address_line2,
457 'fromPlace': company_address.city,
458 'toAddr1': shipping_address.address_line1,
459 'toAddr2': shipping_address.address_line2,
460 'toPlace': shipping_address.city,
461 'transporterName': doc.transporter_name
462 }
463 }
464
465 for allowed_chars, field_map in fields.items():
466 for key, value in field_map.items():
467 if not value:
468 data[key] = ''
469 else:
470 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
471
472 ewaybills.append(data)
473
474 data = {
Subin Tom8b2fe9e2021-08-23 11:17:31 +0530475 'version': '1.0.0421',
Nabin Hait34c551d2019-07-03 10:34:31 +0530476 'billLists': ewaybills
477 }
478
479 return data
480
481@frappe.whitelist()
482def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530483 dn = json.loads(dn)
484 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530485
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530486@frappe.whitelist()
487def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530488 data = json.loads(frappe.local.form_dict.data)
489 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530490 frappe.local.response.type = 'download'
491
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530492 filename_prefix = 'Bulk'
493 docname = frappe.local.form_dict.docname
494 if docname:
495 if docname.startswith('['):
496 docname = json.loads(docname)
497 if len(docname) == 1:
498 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530499
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530500 if not isinstance(docname, list):
501 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Suraj Shetty19c5fd72021-05-10 09:18:25 +0530502 filename_prefix = re.sub(r'[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530503
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530504 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 +0530505
Prasann Shah829172c2019-06-06 12:08:09 +0530506@frappe.whitelist()
507def get_gstins_for_company(company):
508 company_gstins =[]
509 if company:
510 company_gstins = frappe.db.sql("""select
511 distinct `tabAddress`.gstin
512 from
513 `tabAddress`, `tabDynamic Link`
514 where
515 `tabDynamic Link`.parent = `tabAddress`.name and
516 `tabDynamic Link`.parenttype = 'Address' and
517 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300518 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530519 return company_gstins
520
Subin Tom5265ba32021-07-13 14:58:17 +0530521def get_address_details(data, doc, company_address, billing_address, dispatch_address):
Nabin Hait34c551d2019-07-03 10:34:31 +0530522 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
Subin Tom5265ba32021-07-13 14:58:17 +0530523 data.fromStateCode = validate_state_code(company_address.gst_state_number, 'Company Address')
Subin Tomb24a1492021-07-19 14:37:12 +0530524 data.actualFromStateCode = validate_state_code(dispatch_address.gst_state_number, 'Dispatch Address')
Nabin Hait34c551d2019-07-03 10:34:31 +0530525
526 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
527 data.toGstin = 'URP'
528 set_gst_state_and_state_number(billing_address)
529 else:
530 data.toGstin = doc.billing_address_gstin
531
532 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
533 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
534
535 if doc.customer_address != doc.shipping_address_name:
536 data.transType = 2
537 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
538 set_gst_state_and_state_number(shipping_address)
539 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
540 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
541 else:
542 data.transType = 1
543 data.actualToStateCode = data.toStateCode
544 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530545
Smit Vorabbe49332020-11-18 20:58:59 +0530546 if doc.gst_category == 'SEZ':
547 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530548
549 return data
550
Subin Tomd49346a2021-09-17 10:39:03 +0530551def get_item_list(data, doc, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530552 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
553 data[attr] = 0
554
555 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
556 tax_map = {
557 'sgst_account': ['sgstRate', 'sgstValue'],
558 'cgst_account': ['cgstRate', 'cgstValue'],
559 'igst_account': ['igstRate', 'igstValue'],
560 'cess_account': ['cessRate', 'cessValue']
561 }
562 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
Subin Tomd49346a2021-09-17 10:39:03 +0530563 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True, hsn_wise=hsn_wise)
Smit Vora520f33b2021-11-14 08:10:53 +0530564 for item_or_hsn, taxable_amount in hsn_taxable_amount.items():
Nabin Hait34c551d2019-07-03 10:34:31 +0530565 item_data = frappe._dict()
Smit Vora520f33b2021-11-14 08:10:53 +0530566 if not item_or_hsn:
Nabin Hait34c551d2019-07-03 10:34:31 +0530567 frappe.throw(_('GST HSN Code does not exist for one or more items'))
Smit Vora520f33b2021-11-14 08:10:53 +0530568 item_data.hsnCode = int(item_or_hsn) if hsn_wise else item_or_hsn
Nabin Hait34c551d2019-07-03 10:34:31 +0530569 item_data.taxableAmount = taxable_amount
570 item_data.qtyUnit = ""
571 for attr in item_data_attrs:
572 item_data[attr] = 0
573
Smit Vora520f33b2021-11-14 08:10:53 +0530574 for account, tax_detail in hsn_wise_charges.get(item_or_hsn, {}).items():
Nabin Hait34c551d2019-07-03 10:34:31 +0530575 account_type = gst_accounts.get(account, '')
576 for tax_acc, attrs in tax_map.items():
577 if account_type == tax_acc:
578 item_data[attrs[0]] = tax_detail.get('tax_rate')
579 data[attrs[1]] += tax_detail.get('tax_amount')
580 break
581 else:
582 data.OthValue += tax_detail.get('tax_amount')
583
584 data.itemList.append(item_data)
585
586 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
587 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
588 data[attr] = flt(data[attr], 2)
589
590 return data
591
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530592def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530593 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530594 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530595
596 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530597 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530598
599 if doc.ewaybill:
600 frappe.throw(_('e-Way Bill already exists for this document'))
601
602 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
603 'shipping_address_name', 'mode_of_transport', 'distance']
604
605 for fieldname in reqd_fields:
606 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530607 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530608 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530609 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530610
611 if len(doc.company_gstin) < 15:
612 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
613
614def get_transport_details(data, doc):
615 if doc.distance > 4000:
616 frappe.throw(_('Distance cannot be greater than 4000 kms'))
617
618 data.transDistance = int(round(doc.distance))
619
620 transport_modes = {
621 'Road': 1,
622 'Rail': 2,
623 'Air': 3,
624 'Ship': 4
625 }
626
627 vehicle_types = {
628 'Regular': 'R',
629 'Over Dimensional Cargo (ODC)': 'O'
630 }
631
632 data.transMode = transport_modes.get(doc.mode_of_transport)
633
634 if doc.mode_of_transport == 'Road':
635 if not doc.gst_transporter_id and not doc.vehicle_no:
636 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
637 if doc.vehicle_no:
638 data.vehicleNo = doc.vehicle_no.replace(' ', '')
639 if not doc.gst_vehicle_type:
640 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
641 else:
642 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
643 else:
644 if not doc.lr_no or not doc.lr_date:
645 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
646
647 if doc.lr_no:
648 data.transDocNo = doc.lr_no
649
650 if doc.lr_date:
651 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
652
653 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530654 if doc.gst_transporter_id[0:2] != "88":
655 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
656 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530657
658 return data
659
660
661def validate_pincode(pincode, address):
662 pin_not_found = "Pin Code doesn't exist for {}"
663 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
664
665 if not pincode:
666 frappe.throw(_(pin_not_found.format(address)))
667
668 pincode = pincode.replace(' ', '')
669 if not pincode.isdigit() or len(pincode) != 6:
670 frappe.throw(_(incorrect_pin.format(address)))
671 else:
672 return int(pincode)
673
674def validate_state_code(state_code, address):
675 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
676 if not state_code:
677 frappe.throw(_(no_state_code.format(address)))
678 else:
679 return int(state_code)
680
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530681@frappe.whitelist()
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530682def get_gst_accounts(company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0):
683 filters={"parent": "GST Settings"}
684
685 if company:
686 filters.update({'company': company})
687 if only_reverse_charge:
688 filters.update({'is_reverse_charge_account': 1})
689 elif only_non_reverse_charge:
690 filters.update({'is_reverse_charge_account': 0})
691
Nabin Hait34c551d2019-07-03 10:34:31 +0530692 gst_accounts = frappe._dict()
693 gst_settings_accounts = frappe.get_all("GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530694 filters=filters,
Nabin Hait34c551d2019-07-03 10:34:31 +0530695 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
696
Deepesh Garg44273902021-05-20 17:19:24 +0530697 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530698 frappe.throw(_("Please set GST Accounts in GST Settings"))
699
700 for d in gst_settings_accounts:
701 for acc, val in d.items():
702 if not account_wise:
703 gst_accounts.setdefault(acc, []).append(val)
704 elif val:
705 gst_accounts[val] = acc
706
Nabin Hait34c551d2019-07-03 10:34:31 +0530707 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530708
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530709def validate_reverse_charge_transaction(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530710 country = frappe.get_cached_value('Company', doc.company, 'country')
711
712 if country != 'India':
713 return
714
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530715 base_gst_tax = 0
716 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530717
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530718 if doc.reverse_charge == 'Y':
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530719 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
720 reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
721 + gst_accounts.get('igst_account')
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530722
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530723 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
724 non_reverse_charge_accounts = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530725 + gst_accounts.get('igst_account')
726
727 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530728 if tax.account_head in non_reverse_charge_accounts:
729 if tax.add_deduct_tax == 'Add':
730 base_gst_tax += tax.base_tax_amount_after_discount_amount
731 else:
732 base_gst_tax += tax.base_tax_amount_after_discount_amount
733 elif tax.account_head in reverse_charge_accounts:
734 if tax.add_deduct_tax == 'Add':
735 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
736 else:
737 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530738
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530739 if base_gst_tax != base_reverse_charge_booked:
740 msg = _("Booked reverse charge is not equal to applied tax amount")
741 msg += "<br>"
742 msg += _("Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice").format(
743 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 +0530744
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530745 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530746
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530747def update_itc_availed_fields(doc, method):
748 country = frappe.get_cached_value('Company', doc.company, 'country')
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530749
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530750 if country != 'India':
751 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530752
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530753 # Initialize values
754 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
755 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530756
Deepesh Garg93f925f2021-03-15 18:04:42 +0530757 for tax in doc.get('taxes'):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530758 if tax.account_head in gst_accounts.get('igst_account', []):
759 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
760 if tax.account_head in gst_accounts.get('sgst_account', []):
761 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
762 if tax.account_head in gst_accounts.get('cgst_account', []):
763 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
764 if tax.account_head in gst_accounts.get('cess_account', []):
765 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530766
Deepesh Garg8b644d82021-07-15 15:36:54 +0530767def update_place_of_supply(doc, method):
768 country = frappe.get_cached_value('Company', doc.company, 'country')
769 if country != 'India':
770 return
771
Deepesh Garga06a70d2021-09-03 12:40:13 +0530772 address = frappe.db.get_value("Address", doc.get('customer_address'), ["gst_state", "gst_state_number"], as_dict=1)
Deepesh Garg8b644d82021-07-15 15:36:54 +0530773 if address and address.gst_state and address.gst_state_number:
774 doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
775
Deepesh Garg004f9e62021-03-16 13:09:59 +0530776@frappe.whitelist()
777def get_regional_round_off_accounts(company, account_list):
778 country = frappe.get_cached_value('Company', company, 'country')
779
780 if country != 'India':
781 return
782
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530783 if isinstance(account_list, str):
Deepesh Garg004f9e62021-03-16 13:09:59 +0530784 account_list = json.loads(account_list)
785
786 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
787 return
788
789 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530790
791 gst_account_list = []
792 for account in ['cgst_account', 'sgst_account', 'igst_account']:
walstanbab673d92021-03-27 12:52:23 +0530793 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530794 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530795
796 account_list.extend(gst_account_list)
797
798 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530799
800def update_taxable_values(doc, method):
801 country = frappe.get_cached_value('Company', doc.company, 'country')
802
803 if country != 'India':
804 return
805
806 gst_accounts = get_gst_accounts(doc.company)
807
808 # Only considering sgst account to avoid inflating taxable value
809 gst_account_list = gst_accounts.get('sgst_account', []) + gst_accounts.get('sgst_account', []) \
810 + gst_accounts.get('igst_account', [])
811
812 additional_taxes = 0
813 total_charges = 0
814 item_count = 0
815 considered_rows = []
816
817 for tax in doc.get('taxes'):
818 prev_row_id = cint(tax.row_id) - 1
819 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
820 if tax.charge_type == 'On Previous Row Amount':
821 additional_taxes += doc.get('taxes')[prev_row_id].tax_amount_after_discount_amount
822 considered_rows.append(prev_row_id)
823 if tax.charge_type == 'On Previous Row Total':
824 additional_taxes += doc.get('taxes')[prev_row_id].base_total - doc.base_net_total
825 considered_rows.append(prev_row_id)
826
827 for item in doc.get('items'):
Deepesh Garg4afda3c2021-06-01 13:13:04 +0530828 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
829 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530830
831 applicable_charges = flt(flt(proportionate_value * (flt(additional_taxes) / flt(total_value)),
832 item.precision('taxable_value')))
833 item.taxable_value = applicable_charges + proportionate_value
834 total_charges += applicable_charges
835 item_count += 1
836
837 if total_charges != additional_taxes:
838 diff = additional_taxes - total_charges
839 doc.get('items')[item_count - 1].taxable_value += diff
Saqib9226cd32021-05-10 12:36:56 +0530840
841def get_depreciation_amount(asset, depreciable_value, row):
Saqib9226cd32021-05-10 12:36:56 +0530842 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +0530843 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +0530844 if not asset.flags.increase_in_asset_life:
GangaManoj22cc8d22021-12-01 21:46:09 +0530845 depreciation_amount = (flt(asset.gross_purchase_amount) -
GangaManoj828769c2021-12-02 01:09:15 +0530846 flt(row.expected_value_after_useful_life)) / flt(row.total_number_of_depreciations)
GangaManoj2b93e542021-06-19 13:45:37 +0530847
848 # if the Depreciation Schedule is being modified after Asset Repair
849 else:
850 depreciation_amount = (flt(row.value_after_depreciation) -
851 flt(row.expected_value_after_useful_life)) / (date_diff(asset.to_date, asset.available_for_use_date) / 365)
Ankush Menat4551d7d2021-08-19 13:41:10 +0530852
Saqib9226cd32021-05-10 12:36:56 +0530853 else:
854 rate_of_depreciation = row.rate_of_depreciation
855 # if its the first depreciation
856 if depreciable_value == asset.gross_purchase_amount:
Saqib424efd42021-09-28 18:12:02 +0530857 if row.finance_book and frappe.db.get_value('Finance Book', row.finance_book, 'for_income_tax'):
858 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
859 diff = date_diff(row.depreciation_start_date, asset.available_for_use_date)
860 if diff <= 180:
861 rate_of_depreciation = rate_of_depreciation / 2
862 frappe.msgprint(
863 _('As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%.'))
Saqib9226cd32021-05-10 12:36:56 +0530864
865 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
866
Saqib3a504902021-08-03 15:57:11 +0530867 return depreciation_amount
868
869def set_item_tax_from_hsn_code(item):
Ankush Menat4551d7d2021-08-19 13:41:10 +0530870 if not item.taxes and item.gst_hsn_code:
Saqib3a504902021-08-03 15:57:11 +0530871 hsn_doc = frappe.get_doc("GST HSN Code", item.gst_hsn_code)
872
873 for tax in hsn_doc.taxes:
874 item.append('taxes', {
875 'item_tax_template': tax.item_tax_template,
876 'tax_category': tax.tax_category,
877 'valid_from': tax.valid_from
Ankush Menat4551d7d2021-08-19 13:41:10 +0530878 })
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530879
880def delete_gst_settings_for_company(doc, method):
881 if doc.country != 'India':
882 return
883
884 gst_settings = frappe.get_doc("GST Settings")
885 records_to_delete = []
886
887 for d in reversed(gst_settings.get('gst_accounts')):
888 if d.company == doc.name:
889 records_to_delete.append(d)
890
891 for d in records_to_delete:
892 gst_settings.remove(d)
893
894 gst_settings.save()