blob: ee48ccb24a4acf8911873f78f94bbab63e5ae567 [file] [log] [blame]
Chillar Anand915b3432021-09-02 16:44:59 +05301import json
Rucha Mahabal34925a32022-05-04 17:21:19 +05302import math
Chillar Anand915b3432021-09-02 16:44:59 +05303import re
4
5import frappe
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05306from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05307from frappe.model.utils import get_fetch_values
Rucha Mahabal34925a32022-05-04 17:21:19 +05308from frappe.utils import (
9 add_days,
10 cint,
11 cstr,
12 date_diff,
13 flt,
14 get_link_to_form,
15 getdate,
16 month_diff,
17)
Chillar Anand915b3432021-09-02 16:44:59 +053018
Shreya Shah4fa600a2018-06-05 11:27:53 +053019from erpnext.controllers.accounts_controller import get_taxes_and_charges
Chillar Anand915b3432021-09-02 16:44:59 +053020from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Rucha Mahabal34925a32022-05-04 17:21:19 +053021from erpnext.hr.utils import get_salary_assignments
Anurag Mishra289c8222020-06-19 19:17:57 +053022from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Chillar Anand915b3432021-09-02 16:44:59 +053023from erpnext.regional.india import number_state_mapping, state_numbers, states
Ankush Menat7c4c42a2021-03-03 14:56:19 +053024
Ankush Menat494bd9e2022-03-28 18:52:46 +053025GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") # alphanumeric and - /
26GSTIN_FORMAT = re.compile(
27 "^[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}$"
28)
Ankush Menat7c4c42a2021-03-03 14:56:19 +053029GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
30PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
31
32
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053033def validate_gstin_for_india(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +053034 if hasattr(doc, "gst_state"):
Deepesh Garg363e6762022-03-21 16:28:17 +053035 set_gst_state_and_state_number(doc)
36
Ankush Menat494bd9e2022-03-28 18:52:46 +053037 if not hasattr(doc, "gstin") or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053038 return
39
Deepesh Garg459155f2019-06-14 12:01:34 +053040 gst_category = []
41
Ankush Menat494bd9e2022-03-28 18:52:46 +053042 if hasattr(doc, "gst_category"):
Anuja Pawar59c31bb2021-10-22 19:26:31 +053043 if len(doc.links):
44 link_doctype = doc.links[0].get("link_doctype")
45 link_name = doc.links[0].get("link_name")
Deepesh Garg459155f2019-06-14 12:01:34 +053046
Anuja Pawar59c31bb2021-10-22 19:26:31 +053047 if link_doctype in ["Customer", "Supplier"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +053048 gst_category = frappe.db.get_value(link_doctype, {"name": link_name}, ["gst_category"])
Deepesh Garg459155f2019-06-14 12:01:34 +053049
Sagar Vorad75095b2019-01-23 14:40:01 +053050 doc.gstin = doc.gstin.upper().strip()
Ankush Menat494bd9e2022-03-28 18:52:46 +053051 if not doc.gstin or doc.gstin == "NA":
Sagar Vora07cf4e82019-01-10 11:07:51 +053052 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053053
Sagar Vora07cf4e82019-01-10 11:07:51 +053054 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053055 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053056
Ankush Menat494bd9e2022-03-28 18:52:46 +053057 if gst_category and gst_category == "UIN Holders":
Ankush Menat7c4c42a2021-03-03 14:56:19 +053058 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Ankush Menat494bd9e2022-03-28 18:52:46 +053059 frappe.throw(
60 _(
61 "The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"
62 ),
63 title=_("Invalid GSTIN"),
64 )
Deepesh Garg459155f2019-06-14 12:01:34 +053065 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053066 if not GSTIN_FORMAT.match(doc.gstin):
Ankush Menat494bd9e2022-03-28 18:52:46 +053067 frappe.throw(
68 _("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN")
69 )
Rushabh Mehta7231f292017-07-13 15:00:56 +053070
Deepesh Garg459155f2019-06-14 12:01:34 +053071 validate_gstin_check_digit(doc.gstin)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053072
Anurag Mishra1e396dc2021-01-13 14:01:57 +053073 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053074 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053075
Deepesh Garg459155f2019-06-14 12:01:34 +053076 if doc.gst_state_number != doc.gstin[:2]:
Ankush Menat494bd9e2022-03-28 18:52:46 +053077 frappe.throw(
78 _("First 2 digits of GSTIN should match with State number {0}.").format(doc.gst_state_number),
79 title=_("Invalid GSTIN"),
80 )
81
Sagar Vora07cf4e82019-01-10 11:07:51 +053082
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053083def validate_pan_for_india(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +053084 if doc.get("country") != "India" or not doc.get("pan"):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053085 return
86
Ankush Menat7c4c42a2021-03-03 14:56:19 +053087 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053088 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
89
Ankush Menat494bd9e2022-03-28 18:52:46 +053090
Deepesh Gargd07447a2020-11-24 08:09:17 +053091def validate_tax_category(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +053092 if doc.get("gst_state") and frappe.db.get_value(
93 "Tax Category",
94 {
95 "gst_state": doc.gst_state,
96 "is_inter_state": doc.is_inter_state,
97 "is_reverse_charge": doc.is_reverse_charge,
98 },
99 ):
Deepesh Gargd07447a2020-11-24 08:09:17 +0530100 if doc.is_inter_state:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530101 frappe.throw(
102 _("Inter State tax category for GST State {0} already exists").format(doc.gst_state)
103 )
Deepesh Gargd07447a2020-11-24 08:09:17 +0530104 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530105 frappe.throw(
106 _("Intra State tax category for GST State {0} already exists").format(doc.gst_state)
107 )
108
Deepesh Gargd07447a2020-11-24 08:09:17 +0530109
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530110def update_gst_category(doc, method):
Deepesh Garga38aca52021-11-19 11:03:13 +0530111 for link in doc.links:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530112 if link.link_doctype in ["Customer", "Supplier"]:
Deepesh Garga38aca52021-11-19 11:03:13 +0530113 meta = frappe.get_meta(link.link_doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 if doc.get("gstin") and meta.has_field("gst_category"):
115 frappe.db.set_value(
116 link.link_doctype,
117 {"name": link.link_name, "gst_category": "Unregistered"},
118 "gst_category",
119 "Registered Regular",
120 )
121
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530122
Nabin Hait34c551d2019-07-03 10:34:31 +0530123def set_gst_state_and_state_number(doc):
Deepesh Garg363e6762022-03-21 16:28:17 +0530124 if not doc.gst_state and doc.state:
Nabin Hait34c551d2019-07-03 10:34:31 +0530125 state = doc.state.lower()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 states_lowercase = {s.lower(): s for s in states}
Nabin Hait34c551d2019-07-03 10:34:31 +0530127 if state in states_lowercase:
128 doc.gst_state = states_lowercase[state]
129 else:
130 return
Deepesh Garg363e6762022-03-21 16:28:17 +0530131 doc.gst_state_number = state_numbers.get(doc.gst_state)
Nabin Hait34c551d2019-07-03 10:34:31 +0530132
Ankush Menat494bd9e2022-03-28 18:52:46 +0530133
134def validate_gstin_check_digit(gstin, label="GSTIN"):
135 """Function to validate the check digit of the GSTIN."""
karthikeyan52825b922019-01-09 19:15:10 +0530136 factor = 1
137 total = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530138 code_point_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
karthikeyan52825b922019-01-09 19:15:10 +0530139 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530140 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530141 for char in input_chars:
142 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530143 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530144 total += digit
145 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530146 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530147 frappe.throw(
148 _(
149 """Invalid {0}! The check digit validation has failed. Please ensure you've typed the {0} correctly."""
150 ).format(label)
151 )
152
Rushabh Mehta7231f292017-07-13 15:00:56 +0530153
Nabin Haitb962fc12017-07-17 18:02:31 +0530154def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 hsn_wise_in_gst_settings = frappe.db.get_single_value("GST Settings", "hsn_wise_tax_breakup")
156 if frappe.get_meta(item_doctype).has_field("gst_hsn_code") and hsn_wise_in_gst_settings:
Subin Tom530de122021-10-11 17:33:41 +0530157 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
158 else:
159 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530160
Ankush Menat494bd9e2022-03-28 18:52:46 +0530161
Subin Tomd49346a2021-09-17 10:39:03 +0530162def get_itemised_tax_breakup_data(doc, account_wise=False, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530163 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530164
165 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530166
Ankush Menat494bd9e2022-03-28 18:52:46 +0530167 if not frappe.get_meta(doc.doctype + " Item").has_field("gst_hsn_code"):
Nabin Haitb962fc12017-07-17 18:02:31 +0530168 return itemised_tax, itemised_taxable_amount
169
Ankush Menat494bd9e2022-03-28 18:52:46 +0530170 hsn_wise_in_gst_settings = frappe.db.get_single_value("GST Settings", "hsn_wise_tax_breakup")
Subin Tom530de122021-10-11 17:33:41 +0530171
172 tax_breakup_hsn_wise = hsn_wise or hsn_wise_in_gst_settings
173 if tax_breakup_hsn_wise:
Subin Tomd49346a2021-09-17 10:39:03 +0530174 item_hsn_map = frappe._dict()
175 for d in doc.items:
176 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
Nabin Haitb962fc12017-07-17 18:02:31 +0530177
178 hsn_tax = {}
179 for item, taxes in itemised_tax.items():
Subin Tom530de122021-10-11 17:33:41 +0530180 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530181 hsn_tax.setdefault(item_or_hsn, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530182 for tax_desc, tax_detail in taxes.items():
183 key = tax_desc
184 if account_wise:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530185 key = tax_detail.get("tax_account")
Subin Tomd49346a2021-09-17 10:39:03 +0530186 hsn_tax[item_or_hsn].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
187 hsn_tax[item_or_hsn][key]["tax_rate"] = tax_detail.get("tax_rate")
188 hsn_tax[item_or_hsn][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530189
190 # set taxable amount
191 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530192 for item in itemised_taxable_amount:
Subin Tom530de122021-10-11 17:33:41 +0530193 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530194 hsn_taxable_amount.setdefault(item_or_hsn, 0)
195 hsn_taxable_amount[item_or_hsn] += itemised_taxable_amount.get(item)
Nabin Haitb962fc12017-07-17 18:02:31 +0530196
197 return hsn_tax, hsn_taxable_amount
198
Ankush Menat494bd9e2022-03-28 18:52:46 +0530199
Shreya Shah4fa600a2018-06-05 11:27:53 +0530200def set_place_of_supply(doc, method=None):
201 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530202
Ankush Menat494bd9e2022-03-28 18:52:46 +0530203
Ankush Menata44df632021-03-01 17:12:53 +0530204def validate_document_name(doc, method=None):
205 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530206
Ankush Menata44df632021-03-01 17:12:53 +0530207 country = frappe.get_cached_value("Company", doc.company, "country")
208
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530209 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530210 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
211 return
212
213 if len(doc.name) > 16:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530214 frappe.throw(
215 _(
216 "Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."
217 )
218 )
Ankush Menata44df632021-03-01 17:12:53 +0530219
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530220 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530221 frappe.throw(
222 _(
223 "Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."
224 )
225 )
226
Ankush Menata44df632021-03-01 17:12:53 +0530227
Rushabh Mehta7231f292017-07-13 15:00:56 +0530228# don't remove this function it is used in tests
229def test_method():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530230 """test function"""
231 return "overridden"
232
Shreya Shah4fa600a2018-06-05 11:27:53 +0530233
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530234def get_place_of_supply(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530235 if not frappe.get_meta("Address").has_field("gst_state"):
236 return
Shreya Shah4fa600a2018-06-05 11:27:53 +0530237
Deepesh Garg03952f82022-03-23 18:47:58 +0530238 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530239 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530240 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
241 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530242
243 if address_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530244 address = frappe.db.get_value(
245 "Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1
246 )
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530247 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530248 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530249 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530250
Ankush Menat494bd9e2022-03-28 18:52:46 +0530251
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530252@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530253def get_regional_address_details(party_details, doctype, company):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530254 if isinstance(party_details, str):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530255 party_details = json.loads(party_details)
256 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530257
Deepesh Garga7670852020-12-04 18:07:46 +0530258 update_party_details(party_details, doctype)
259
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530260 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530261
262 if is_internal_transfer(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 party_details.taxes_and_charges = ""
Deepesh Gargb4be2922021-01-28 13:09:56 +0530264 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530265 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530266
Deepesh Garg03952f82022-03-23 18:47:58 +0530267 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530268 master_doctype = "Sales Taxes and Charges Template"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530269 tax_template_by_category = get_tax_template_based_on_category(
270 master_doctype, company, party_details
271 )
Shreya Shah4fa600a2018-06-05 11:27:53 +0530272
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530273 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
274 master_doctype = "Purchase Taxes and Charges Template"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530275 tax_template_by_category = get_tax_template_based_on_category(
276 master_doctype, company, party_details
277 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530278
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530279 if tax_template_by_category:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530280 party_details["taxes_and_charges"] = tax_template_by_category
Deepesh Garg532961f2022-03-30 19:33:44 +0530281 party_details["taxes"] = get_taxes_and_charges(master_doctype, tax_template_by_category)
Deepesh Garg466e5492022-01-02 17:53:15 +0530282 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530283
Ankush Menat494bd9e2022-03-28 18:52:46 +0530284 if not party_details.place_of_supply:
285 return party_details
286 if not party_details.company_gstin:
287 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530288
Ankush Menat494bd9e2022-03-28 18:52:46 +0530289 if (
290 doctype in ("Sales Invoice", "Delivery Note", "Sales Order")
291 and party_details.company_gstin
292 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]
293 ) or (
294 doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt")
295 and party_details.supplier_gstin
296 and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2]
297 ):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530298 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530299 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530300 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530301
302 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530303 return party_details
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530304
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530305 party_details["taxes_and_charges"] = default_tax
Deepesh Garg532961f2022-03-30 19:33:44 +0530306 party_details["taxes"] = get_taxes_and_charges(master_doctype, default_tax)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530307
pateljannatcd05b342020-11-19 11:37:08 +0530308 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530309
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310
Deepesh Garga7670852020-12-04 18:07:46 +0530311def update_party_details(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530312 for address_field in [
313 "shipping_address",
314 "company_address",
315 "supplier_address",
316 "shipping_address_name",
317 "customer_address",
318 ]:
Deepesh Garga7670852020-12-04 18:07:46 +0530319 if party_details.get(address_field):
320 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
321
Ankush Menat494bd9e2022-03-28 18:52:46 +0530322
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530323def is_internal_transfer(party_details, doctype):
Deepesh Garg03952f82022-03-23 18:47:58 +0530324 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530325 destination_gstin = party_details.company_gstin
326 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
327 destination_gstin = party_details.supplier_gstin
328
Deepesh Gargda47fe22021-09-30 13:28:53 +0530329 if not destination_gstin or party_details.gstin:
330 return False
331
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530332 if party_details.gstin == destination_gstin:
333 return True
334 else:
335 False
336
Ankush Menat494bd9e2022-03-28 18:52:46 +0530337
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530338def get_tax_template_based_on_category(master_doctype, company, party_details):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530339 if not party_details.get("tax_category"):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530340 return
341
Ankush Menat494bd9e2022-03-28 18:52:46 +0530342 default_tax = frappe.db.get_value(
343 master_doctype, {"company": company, "tax_category": party_details.get("tax_category")}, "name"
344 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530345
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530346 return default_tax
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530347
Ankush Menat494bd9e2022-03-28 18:52:46 +0530348
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530349def get_tax_template(master_doctype, company, is_inter_state, state_code):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530350 tax_categories = frappe.get_all(
351 "Tax Category",
352 fields=["name", "is_inter_state", "gst_state"],
Deepesh Garg9a6a1812022-04-01 14:46:26 +0530353 filters={"is_inter_state": is_inter_state, "is_reverse_charge": 0, "disabled": 0},
Ankush Menat494bd9e2022-03-28 18:52:46 +0530354 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530355
Ankush Menat494bd9e2022-03-28 18:52:46 +0530356 default_tax = ""
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530357
358 for tax_category in tax_categories:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530359 if tax_category.gst_state == number_state_mapping[state_code] or (
360 not default_tax and not tax_category.gst_state
361 ):
362 default_tax = frappe.db.get_value(
363 master_doctype, {"company": company, "disabled": 0, "tax_category": tax_category.name}, "name"
364 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530365 return default_tax
366
Ankush Menat494bd9e2022-03-28 18:52:46 +0530367
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530368def calculate_annual_eligible_hra_exemption(doc):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530369 basic_component, hra_component = frappe.db.get_value(
370 "Company", doc.company, ["basic_component", "hra_component"]
371 )
Rucha Mahabal2e98e9e2022-05-23 14:15:36 +0530372
Nabin Hait04e7bf42019-04-25 18:44:10 +0530373 if not (basic_component and hra_component):
Rucha Mahabal34925a32022-05-04 17:21:19 +0530374 frappe.throw(
375 _("Please set Basic and HRA component in Company {0}").format(
376 get_link_to_form("Company", doc.company)
377 )
378 )
379
380 annual_exemption = monthly_exemption = hra_amount = basic_amount = 0
381
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530382 if hra_component and basic_component:
Rucha Mahabal34925a32022-05-04 17:21:19 +0530383 assignments = get_salary_assignments(doc.employee, doc.payroll_period)
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530384
Rucha Mahabal34925a32022-05-04 17:21:19 +0530385 if not assignments and doc.docstatus == 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386 frappe.throw(
Rucha Mahabal34925a32022-05-04 17:21:19 +0530387 _("Salary Structure must be submitted before submission of {0}").format(doc.doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530388 )
Nabin Hait04e7bf42019-04-25 18:44:10 +0530389
Rucha Mahabal34925a32022-05-04 17:21:19 +0530390 assignment_dates = [assignment.from_date for assignment in assignments]
391
392 for idx, assignment in enumerate(assignments):
393 if has_hra_component(assignment.salary_structure, hra_component):
394 basic_salary_amt, hra_salary_amt = get_component_amt_from_salary_slip(
395 doc.employee,
396 assignment.salary_structure,
397 basic_component,
398 hra_component,
399 assignment.from_date,
400 )
401 to_date = get_end_date_for_assignment(assignment_dates, idx, doc.payroll_period)
402
403 frequency = frappe.get_value(
404 "Salary Structure", assignment.salary_structure, "payroll_frequency"
405 )
406 basic_amount += get_component_pay(frequency, basic_salary_amt, assignment.from_date, to_date)
407 hra_amount += get_component_pay(frequency, hra_salary_amt, assignment.from_date, to_date)
408
409 if hra_amount:
410 if doc.monthly_house_rent:
411 annual_exemption = calculate_hra_exemption(
412 assignment.salary_structure,
413 basic_amount,
414 hra_amount,
415 doc.monthly_house_rent,
416 doc.rented_in_metro_city,
417 )
418 if annual_exemption > 0:
419 monthly_exemption = annual_exemption / 12
420 else:
421 annual_exemption = 0
422
Ankush Menat494bd9e2022-03-28 18:52:46 +0530423 return frappe._dict(
424 {
425 "hra_amount": hra_amount,
Rucha Mahabal00adda72022-05-11 18:26:33 +0530426 "annual_exemption": annual_exemption,
427 "monthly_exemption": monthly_exemption,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530428 }
429 )
430
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530431
Rucha Mahabal34925a32022-05-04 17:21:19 +0530432def has_hra_component(salary_structure, hra_component):
433 return frappe.db.exists(
434 "Salary Detail",
435 {
436 "parent": salary_structure,
437 "salary_component": hra_component,
438 "parentfield": "earnings",
439 "parenttype": "Salary Structure",
440 },
441 )
442
443
444def get_end_date_for_assignment(assignment_dates, idx, payroll_period):
445 end_date = None
446
447 try:
448 end_date = assignment_dates[idx + 1]
449 end_date = add_days(end_date, -1)
450 except IndexError:
451 pass
452
453 if not end_date:
454 end_date = frappe.db.get_value("Payroll Period", payroll_period, "end_date")
455
456 return end_date
457
458
459def get_component_amt_from_salary_slip(
460 employee, salary_structure, basic_component, hra_component, from_date
461):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462 salary_slip = make_salary_slip(
Rucha Mahabal2b65c962022-05-11 16:43:13 +0530463 salary_structure,
464 employee=employee,
465 for_preview=1,
466 ignore_permissions=True,
467 posting_date=from_date,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530468 )
Rucha Mahabal34925a32022-05-04 17:21:19 +0530469
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530470 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530471 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530472 if earning.salary_component == basic_component:
473 basic_amt = earning.amount
474 elif earning.salary_component == hra_component:
475 hra_amt = earning.amount
476 if basic_amt and hra_amt:
477 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530478 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530479
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480
481def calculate_hra_exemption(
Rucha Mahabal34925a32022-05-04 17:21:19 +0530482 salary_structure, annual_basic, annual_hra, monthly_house_rent, rented_in_metro_city
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530484 # TODO make this configurable
485 exemptions = []
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530486 # case 1: The actual amount allotted by the employer as the HRA.
Rucha Mahabal34925a32022-05-04 17:21:19 +0530487 exemptions.append(annual_hra)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530488
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530489 # case 2: Actual rent paid less 10% of the basic salary.
Rucha Mahabal34925a32022-05-04 17:21:19 +0530490 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530491 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Rucha Mahabal34925a32022-05-04 17:21:19 +0530492
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530493 # 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 +0530494 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Rucha Mahabal34925a32022-05-04 17:21:19 +0530495
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530496 # return minimum of 3 cases
497 return min(exemptions)
498
Ankush Menat494bd9e2022-03-28 18:52:46 +0530499
Rucha Mahabal34925a32022-05-04 17:21:19 +0530500def get_component_pay(frequency, amount, from_date, to_date):
501 days = date_diff(to_date, from_date) + 1
502
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530503 if frequency == "Daily":
Rucha Mahabal34925a32022-05-04 17:21:19 +0530504 return amount * days
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530505 elif frequency == "Weekly":
Rucha Mahabal2b65c962022-05-11 16:43:13 +0530506 return amount * math.floor(days / 7)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530507 elif frequency == "Fortnightly":
Rucha Mahabal2b65c962022-05-11 16:43:13 +0530508 return amount * math.floor(days / 14)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530509 elif frequency == "Monthly":
Rucha Mahabal34925a32022-05-04 17:21:19 +0530510 return amount * month_diff(to_date, from_date)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530511 elif frequency == "Bimonthly":
Rucha Mahabal2b65c962022-05-11 16:43:13 +0530512 return amount * (month_diff(to_date, from_date) / 2)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530513
Ankush Menat494bd9e2022-03-28 18:52:46 +0530514
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530515def validate_house_rent_dates(doc):
516 if not doc.rented_to_date or not doc.rented_from_date:
517 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530518
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530519 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
520 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530521
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 proofs = frappe.db.sql(
523 """
Nabin Hait04e7bf42019-04-25 18:44:10 +0530524 select name
525 from `tabEmployee Tax Exemption Proof Submission`
526 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530527 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
528 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530529 """,
530 {
531 "employee": doc.employee,
532 "payroll_period": doc.payroll_period,
533 "from_date": doc.rented_from_date,
534 "to_date": doc.rented_to_date,
535 },
536 )
Nabin Hait04e7bf42019-04-25 18:44:10 +0530537
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530538 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530539 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530540
Ankush Menat494bd9e2022-03-28 18:52:46 +0530541
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530542def calculate_hra_exemption_for_period(doc):
543 monthly_rent, eligible_hra = 0, 0
544 if doc.house_rent_payment_amount:
545 validate_house_rent_dates(doc)
546 # TODO receive rented months or validate dates are start and end of months?
547 # Calc monthly rent, round to nearest .5
Ankush Menat494bd9e2022-03-28 18:52:46 +0530548 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1) / 30
549 factor = round(factor * 2) / 2
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530550 monthly_rent = doc.house_rent_payment_amount / factor
551 # update field used by calculate_annual_eligible_hra_exemption
552 doc.monthly_house_rent = monthly_rent
553 exemptions = calculate_annual_eligible_hra_exemption(doc)
554
555 if exemptions["monthly_exemption"]:
556 # calc total exemption amount
557 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530558 exemptions["monthly_house_rent"] = monthly_rent
559 exemptions["total_eligible_hra_exemption"] = eligible_hra
560 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530561
Ankush Menat494bd9e2022-03-28 18:52:46 +0530562
Nabin Hait34c551d2019-07-03 10:34:31 +0530563def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530564
565 ewaybills = []
566 for doc_name in dn:
567 doc = frappe.get_doc(dt, doc_name)
568
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530569 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530570
Ankush Menat494bd9e2022-03-28 18:52:46 +0530571 data = frappe._dict(
572 {
573 "transporterId": "",
574 "TotNonAdvolVal": 0,
575 }
576 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530577
578 data.userGstin = data.fromGstin = doc.company_gstin
Ankush Menat494bd9e2022-03-28 18:52:46 +0530579 data.supplyType = "O"
Nabin Hait34c551d2019-07-03 10:34:31 +0530580
Ankush Menat494bd9e2022-03-28 18:52:46 +0530581 if dt == "Delivery Note":
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530582 data.subSupplyType = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530583 elif doc.gst_category in ["Registered Regular", "SEZ"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530584 data.subSupplyType = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530585 elif doc.gst_category in ["Overseas", "Deemed Export"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530586 data.subSupplyType = 3
587 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530588 frappe.throw(_("Unsupported GST Category for E-Way Bill JSON generation"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530589
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 data.docType = "INV"
591 data.docDate = frappe.utils.formatdate(doc.posting_date, "dd/mm/yyyy")
Nabin Hait34c551d2019-07-03 10:34:31 +0530592
Ankush Menat494bd9e2022-03-28 18:52:46 +0530593 company_address = frappe.get_doc("Address", doc.company_address)
594 billing_address = frappe.get_doc("Address", doc.customer_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530595
Ankush Menat494bd9e2022-03-28 18:52:46 +0530596 # added dispatch address
597 dispatch_address = (
598 frappe.get_doc("Address", doc.dispatch_address_name)
599 if doc.dispatch_address_name
600 else company_address
601 )
602 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Nabin Hait34c551d2019-07-03 10:34:31 +0530603
Subin Tom5265ba32021-07-13 14:58:17 +0530604 data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530605
606 data.itemList = []
Smit Vorae2d866d2021-11-01 15:55:19 +0530607 data.totalValue = doc.net_total
Nabin Hait34c551d2019-07-03 10:34:31 +0530608
Subin Tomd49346a2021-09-17 10:39:03 +0530609 data = get_item_list(data, doc, hsn_wise=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530610
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611 disable_rounded = frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
Nabin Hait34c551d2019-07-03 10:34:31 +0530612 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
613
614 data = get_transport_details(data, doc)
615
616 fields = {
617 "/. -": {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530618 "docNo": doc.name,
619 "fromTrdName": doc.company,
620 "toTrdName": doc.customer_name,
621 "transDocNo": doc.lr_no,
Nabin Hait34c551d2019-07-03 10:34:31 +0530622 },
623 "@#/,&. -": {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530624 "fromAddr1": company_address.address_line1,
625 "fromAddr2": company_address.address_line2,
626 "fromPlace": company_address.city,
627 "toAddr1": shipping_address.address_line1,
628 "toAddr2": shipping_address.address_line2,
629 "toPlace": shipping_address.city,
630 "transporterName": doc.transporter_name,
631 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530632 }
633
634 for allowed_chars, field_map in fields.items():
635 for key, value in field_map.items():
636 if not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530637 data[key] = ""
Nabin Hait34c551d2019-07-03 10:34:31 +0530638 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530639 data[key] = re.sub(r"[^\w" + allowed_chars + "]", "", value)
Nabin Hait34c551d2019-07-03 10:34:31 +0530640
641 ewaybills.append(data)
642
Ankush Menat494bd9e2022-03-28 18:52:46 +0530643 data = {"version": "1.0.0421", "billLists": ewaybills}
Nabin Hait34c551d2019-07-03 10:34:31 +0530644
645 return data
646
Ankush Menat494bd9e2022-03-28 18:52:46 +0530647
Nabin Hait34c551d2019-07-03 10:34:31 +0530648@frappe.whitelist()
649def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530650 dn = json.loads(dn)
651 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530652
Ankush Menat494bd9e2022-03-28 18:52:46 +0530653
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530654@frappe.whitelist()
655def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530656 data = json.loads(frappe.local.form_dict.data)
657 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530658 frappe.local.response.type = "download"
Nabin Hait34c551d2019-07-03 10:34:31 +0530659
Ankush Menat494bd9e2022-03-28 18:52:46 +0530660 filename_prefix = "Bulk"
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530661 docname = frappe.local.form_dict.docname
662 if docname:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530663 if docname.startswith("["):
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530664 docname = json.loads(docname)
665 if len(docname) == 1:
666 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530667
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530668 if not isinstance(docname, list):
669 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530670 filename_prefix = re.sub(r"[^\w_.)( -]", "", docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530671
Ankush Menat494bd9e2022-03-28 18:52:46 +0530672 frappe.local.response.filename = "{0}_e-WayBill_Data_{1}.json".format(
673 filename_prefix, frappe.utils.random_string(5)
674 )
675
Nabin Hait34c551d2019-07-03 10:34:31 +0530676
Prasann Shah829172c2019-06-06 12:08:09 +0530677@frappe.whitelist()
678def get_gstins_for_company(company):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530679 company_gstins = []
Prasann Shah829172c2019-06-06 12:08:09 +0530680 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530681 company_gstins = frappe.db.sql(
682 """select
Prasann Shah829172c2019-06-06 12:08:09 +0530683 distinct `tabAddress`.gstin
684 from
685 `tabAddress`, `tabDynamic Link`
686 where
687 `tabDynamic Link`.parent = `tabAddress`.name and
688 `tabDynamic Link`.parenttype = 'Address' and
689 `tabDynamic Link`.link_doctype = 'Company' and
Ankush Menat494bd9e2022-03-28 18:52:46 +0530690 `tabDynamic Link`.link_name = %(company)s""",
691 {"company": company},
692 )
Prasann Shah829172c2019-06-06 12:08:09 +0530693 return company_gstins
694
Ankush Menat494bd9e2022-03-28 18:52:46 +0530695
Subin Tom5265ba32021-07-13 14:58:17 +0530696def get_address_details(data, doc, company_address, billing_address, dispatch_address):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530697 data.fromPincode = validate_pincode(company_address.pincode, "Company Address")
698 data.fromStateCode = validate_state_code(company_address.gst_state_number, "Company Address")
699 data.actualFromStateCode = validate_state_code(
700 dispatch_address.gst_state_number, "Dispatch Address"
701 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530702
703 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530704 data.toGstin = "URP"
Nabin Hait34c551d2019-07-03 10:34:31 +0530705 set_gst_state_and_state_number(billing_address)
706 else:
707 data.toGstin = doc.billing_address_gstin
708
Ankush Menat494bd9e2022-03-28 18:52:46 +0530709 data.toPincode = validate_pincode(billing_address.pincode, "Customer Address")
710 data.toStateCode = validate_state_code(billing_address.gst_state_number, "Customer Address")
Nabin Hait34c551d2019-07-03 10:34:31 +0530711
712 if doc.customer_address != doc.shipping_address_name:
713 data.transType = 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530714 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Nabin Hait34c551d2019-07-03 10:34:31 +0530715 set_gst_state_and_state_number(shipping_address)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530716 data.toPincode = validate_pincode(shipping_address.pincode, "Shipping Address")
717 data.actualToStateCode = validate_state_code(
718 shipping_address.gst_state_number, "Shipping Address"
719 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530720 else:
721 data.transType = 1
722 data.actualToStateCode = data.toStateCode
723 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530724
Ankush Menat494bd9e2022-03-28 18:52:46 +0530725 if doc.gst_category == "SEZ":
Smit Vorabbe49332020-11-18 20:58:59 +0530726 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530727
728 return data
729
Ankush Menat494bd9e2022-03-28 18:52:46 +0530730
Subin Tomd49346a2021-09-17 10:39:03 +0530731def get_item_list(data, doc, hsn_wise=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530732 for attr in ["cgstValue", "sgstValue", "igstValue", "cessValue", "OthValue"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530733 data[attr] = 0
734
735 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
736 tax_map = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530737 "sgst_account": ["sgstRate", "sgstValue"],
738 "cgst_account": ["cgstRate", "cgstValue"],
739 "igst_account": ["igstRate", "igstValue"],
740 "cess_account": ["cessRate", "cessValue"],
Nabin Hait34c551d2019-07-03 10:34:31 +0530741 }
Ankush Menat494bd9e2022-03-28 18:52:46 +0530742 item_data_attrs = ["sgstRate", "cgstRate", "igstRate", "cessRate", "cessNonAdvol"]
743 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(
744 doc, account_wise=True, hsn_wise=hsn_wise
745 )
Smit Vora520f33b2021-11-14 08:10:53 +0530746 for item_or_hsn, taxable_amount in hsn_taxable_amount.items():
Nabin Hait34c551d2019-07-03 10:34:31 +0530747 item_data = frappe._dict()
Smit Vora520f33b2021-11-14 08:10:53 +0530748 if not item_or_hsn:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530749 frappe.throw(_("GST HSN Code does not exist for one or more items"))
Smit Vora520f33b2021-11-14 08:10:53 +0530750 item_data.hsnCode = int(item_or_hsn) if hsn_wise else item_or_hsn
Nabin Hait34c551d2019-07-03 10:34:31 +0530751 item_data.taxableAmount = taxable_amount
752 item_data.qtyUnit = ""
753 for attr in item_data_attrs:
754 item_data[attr] = 0
755
Smit Vora520f33b2021-11-14 08:10:53 +0530756 for account, tax_detail in hsn_wise_charges.get(item_or_hsn, {}).items():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530757 account_type = gst_accounts.get(account, "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530758 for tax_acc, attrs in tax_map.items():
759 if account_type == tax_acc:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530760 item_data[attrs[0]] = tax_detail.get("tax_rate")
761 data[attrs[1]] += tax_detail.get("tax_amount")
Nabin Hait34c551d2019-07-03 10:34:31 +0530762 break
763 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530764 data.OthValue += tax_detail.get("tax_amount")
Nabin Hait34c551d2019-07-03 10:34:31 +0530765
766 data.itemList.append(item_data)
767
768 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
Ankush Menat494bd9e2022-03-28 18:52:46 +0530769 for attr in ["sgstValue", "cgstValue", "igstValue", "cessValue"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530770 data[attr] = flt(data[attr], 2)
771
772 return data
773
Ankush Menat494bd9e2022-03-28 18:52:46 +0530774
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530775def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530776 if doc.docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530777 frappe.throw(_("E-Way Bill JSON can only be generated from submitted document"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530778
779 if doc.is_return:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 frappe.throw(_("E-Way Bill JSON cannot be generated for Sales Return as of now"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530781
782 if doc.ewaybill:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530783 frappe.throw(_("e-Way Bill already exists for this document"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530784
Ankush Menat494bd9e2022-03-28 18:52:46 +0530785 reqd_fields = [
786 "company_gstin",
787 "company_address",
788 "customer_address",
789 "shipping_address_name",
790 "mode_of_transport",
791 "distance",
792 ]
Nabin Hait34c551d2019-07-03 10:34:31 +0530793
794 for fieldname in reqd_fields:
795 if not doc.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530796 frappe.throw(
797 _("{} is required to generate E-Way Bill JSON").format(doc.meta.get_label(fieldname))
798 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530799
800 if len(doc.company_gstin) < 15:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530801 frappe.throw(_("You must be a registered supplier to generate e-Way Bill"))
802
Nabin Hait34c551d2019-07-03 10:34:31 +0530803
804def get_transport_details(data, doc):
805 if doc.distance > 4000:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530806 frappe.throw(_("Distance cannot be greater than 4000 kms"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530807
808 data.transDistance = int(round(doc.distance))
809
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 transport_modes = {"Road": 1, "Rail": 2, "Air": 3, "Ship": 4}
Nabin Hait34c551d2019-07-03 10:34:31 +0530811
Ankush Menat494bd9e2022-03-28 18:52:46 +0530812 vehicle_types = {"Regular": "R", "Over Dimensional Cargo (ODC)": "O"}
Nabin Hait34c551d2019-07-03 10:34:31 +0530813
814 data.transMode = transport_modes.get(doc.mode_of_transport)
815
Ankush Menat494bd9e2022-03-28 18:52:46 +0530816 if doc.mode_of_transport == "Road":
Nabin Hait34c551d2019-07-03 10:34:31 +0530817 if not doc.gst_transporter_id and not doc.vehicle_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530818 frappe.throw(
819 _("Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road")
820 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530821 if doc.vehicle_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530822 data.vehicleNo = doc.vehicle_no.replace(" ", "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530823 if not doc.gst_vehicle_type:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530824 frappe.throw(_("Vehicle Type is required if Mode of Transport is Road"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530825 else:
826 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
827 else:
828 if not doc.lr_no or not doc.lr_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530829 frappe.throw(_("Transport Receipt No and Date are mandatory for your chosen Mode of Transport"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530830
831 if doc.lr_no:
832 data.transDocNo = doc.lr_no
833
834 if doc.lr_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530835 data.transDocDate = frappe.utils.formatdate(doc.lr_date, "dd/mm/yyyy")
Nabin Hait34c551d2019-07-03 10:34:31 +0530836
837 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530838 if doc.gst_transporter_id[0:2] != "88":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530839 validate_gstin_check_digit(doc.gst_transporter_id, label="GST Transporter ID")
karthikeyan5ca46bed2020-05-30 15:00:56 +0530840 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530841
842 return data
843
844
845def validate_pincode(pincode, address):
846 pin_not_found = "Pin Code doesn't exist for {}"
847 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
848
849 if not pincode:
850 frappe.throw(_(pin_not_found.format(address)))
851
Ankush Menat494bd9e2022-03-28 18:52:46 +0530852 pincode = pincode.replace(" ", "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530853 if not pincode.isdigit() or len(pincode) != 6:
854 frappe.throw(_(incorrect_pin.format(address)))
855 else:
856 return int(pincode)
857
Ankush Menat494bd9e2022-03-28 18:52:46 +0530858
Nabin Hait34c551d2019-07-03 10:34:31 +0530859def validate_state_code(state_code, address):
860 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
861 if not state_code:
862 frappe.throw(_(no_state_code.format(address)))
863 else:
864 return int(state_code)
865
Ankush Menat494bd9e2022-03-28 18:52:46 +0530866
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530867@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530868def get_gst_accounts(
869 company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0
870):
871 filters = {"parent": "GST Settings"}
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530872
873 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530874 filters.update({"company": company})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530875 if only_reverse_charge:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530876 filters.update({"is_reverse_charge_account": 1})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530877 elif only_non_reverse_charge:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530878 filters.update({"is_reverse_charge_account": 0})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530879
Nabin Hait34c551d2019-07-03 10:34:31 +0530880 gst_accounts = frappe._dict()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530881 gst_settings_accounts = frappe.get_all(
882 "GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530883 filters=filters,
Saqib Ansari45fca6b2022-04-07 13:09:05 +0530884 fields=["cgst_account", "sgst_account", "igst_account", "cess_account", "utgst_account"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530885 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530886
Deepesh Garg44273902021-05-20 17:19:24 +0530887 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530888 frappe.throw(_("Please set GST Accounts in GST Settings"))
889
890 for d in gst_settings_accounts:
891 for acc, val in d.items():
892 if not account_wise:
893 gst_accounts.setdefault(acc, []).append(val)
894 elif val:
895 gst_accounts[val] = acc
896
Nabin Hait34c551d2019-07-03 10:34:31 +0530897 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530898
Deepesh Garg52c319c2020-07-15 23:57:03 +0530899
Deepesh Garg48175212022-05-13 18:08:32 +0530900def validate_sez_and_export_invoices(doc, method):
901 country = frappe.get_cached_value("Company", doc.company, "country")
902
903 if country != "India":
904 return
905
906 if (
907 doc.get("gst_category") in ("SEZ", "Overseas")
908 and doc.get("export_type") == "Without Payment of Tax"
909 ):
910 gst_accounts = get_gst_accounts(doc.company)
911
912 for tax in doc.get("taxes"):
913 for tax in doc.get("taxes"):
914 if (
915 tax.account_head
916 in gst_accounts.get("igst_account", [])
917 + gst_accounts.get("sgst_account", [])
918 + gst_accounts.get("cgst_account", [])
919 and tax.tax_amount_after_discount_amount
920 ):
921 frappe.throw(_("GST cannot be applied on SEZ or Export invoices without payment of tax"))
922
923
Ankush Menat494bd9e2022-03-28 18:52:46 +0530924def validate_reverse_charge_transaction(doc, method):
925 country = frappe.get_cached_value("Company", doc.company, "country")
926
927 if country != "India":
Deepesh Garg52c319c2020-07-15 23:57:03 +0530928 return
929
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530930 base_gst_tax = 0
931 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530932
Ankush Menat494bd9e2022-03-28 18:52:46 +0530933 if doc.reverse_charge == "Y":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530934 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530935 reverse_charge_accounts = (
936 gst_accounts.get("cgst_account")
937 + gst_accounts.get("sgst_account")
938 + gst_accounts.get("igst_account")
939 )
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530940
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530941 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530942 non_reverse_charge_accounts = (
943 gst_accounts.get("cgst_account")
944 + gst_accounts.get("sgst_account")
945 + gst_accounts.get("igst_account")
946 )
Deepesh Garg24f9a802020-06-03 10:59:37 +0530947
Ankush Menat494bd9e2022-03-28 18:52:46 +0530948 for tax in doc.get("taxes"):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530949 if tax.account_head in non_reverse_charge_accounts:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530950 if tax.add_deduct_tax == "Add":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530951 base_gst_tax += tax.base_tax_amount_after_discount_amount
952 else:
953 base_gst_tax += tax.base_tax_amount_after_discount_amount
954 elif tax.account_head in reverse_charge_accounts:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530955 if tax.add_deduct_tax == "Add":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530956 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
957 else:
958 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530959
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530960 if base_gst_tax != base_reverse_charge_booked:
961 msg = _("Booked reverse charge is not equal to applied tax amount")
962 msg += "<br>"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530963 msg += _(
964 "Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice"
965 ).format(
966 gst_document_link='<a href="https://docs.erpnext.com/docs/user/manual/en/regional/india/gst-setup">GST Documentation</a>'
967 )
Deepesh Garg24f9a802020-06-03 10:59:37 +0530968
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530969 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530970
Deepesh Garg48175212022-05-13 18:08:32 +0530971 doc.eligibility_for_itc = "ITC on Reverse Charge"
972
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530973
Ankush Menat494bd9e2022-03-28 18:52:46 +0530974def update_itc_availed_fields(doc, method):
975 country = frappe.get_cached_value("Company", doc.company, "country")
976
977 if country != "India":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530978 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530979
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530980 # Initialize values
981 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
982 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530983
Ankush Menat494bd9e2022-03-28 18:52:46 +0530984 for tax in doc.get("taxes"):
985 if tax.account_head in gst_accounts.get("igst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530986 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530987 if tax.account_head in gst_accounts.get("sgst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530988 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530989 if tax.account_head in gst_accounts.get("cgst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530990 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530991 if tax.account_head in gst_accounts.get("cess_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530992 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530993
Ankush Menat494bd9e2022-03-28 18:52:46 +0530994
Deepesh Garg8b644d82021-07-15 15:36:54 +0530995def update_place_of_supply(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530996 country = frappe.get_cached_value("Company", doc.company, "country")
997 if country != "India":
Deepesh Garg8b644d82021-07-15 15:36:54 +0530998 return
999
Ankush Menat494bd9e2022-03-28 18:52:46 +05301000 address = frappe.db.get_value(
1001 "Address", doc.get("customer_address"), ["gst_state", "gst_state_number"], as_dict=1
1002 )
Deepesh Garg8b644d82021-07-15 15:36:54 +05301003 if address and address.gst_state and address.gst_state_number:
1004 doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
1005
Ankush Menat494bd9e2022-03-28 18:52:46 +05301006
Deepesh Garg004f9e62021-03-16 13:09:59 +05301007@frappe.whitelist()
1008def get_regional_round_off_accounts(company, account_list):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301009 country = frappe.get_cached_value("Company", company, "country")
Deepesh Garg004f9e62021-03-16 13:09:59 +05301010
Ankush Menat494bd9e2022-03-28 18:52:46 +05301011 if country != "India":
Deepesh Garg004f9e62021-03-16 13:09:59 +05301012 return
1013
Ankush Menat8fe5feb2021-11-04 19:48:32 +05301014 if isinstance(account_list, str):
Deepesh Garg004f9e62021-03-16 13:09:59 +05301015 account_list = json.loads(account_list)
1016
Ankush Menat494bd9e2022-03-28 18:52:46 +05301017 if not frappe.db.get_single_value("GST Settings", "round_off_gst_values"):
Deepesh Garg004f9e62021-03-16 13:09:59 +05301018 return
1019
1020 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +05301021
1022 gst_account_list = []
Ankush Menat494bd9e2022-03-28 18:52:46 +05301023 for account in ["cgst_account", "sgst_account", "igst_account"]:
walstanbab673d92021-03-27 12:52:23 +05301024 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +05301025 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +05301026
1027 account_list.extend(gst_account_list)
1028
1029 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301030
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301031
Ankush Menat494bd9e2022-03-28 18:52:46 +05301032def update_taxable_values(doc, method):
1033 country = frappe.get_cached_value("Company", doc.company, "country")
1034
1035 if country != "India":
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301036 return
1037
1038 gst_accounts = get_gst_accounts(doc.company)
1039
1040 # Only considering sgst account to avoid inflating taxable value
Ankush Menat494bd9e2022-03-28 18:52:46 +05301041 gst_account_list = (
1042 gst_accounts.get("sgst_account", [])
1043 + gst_accounts.get("sgst_account", [])
1044 + gst_accounts.get("igst_account", [])
1045 )
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301046
1047 additional_taxes = 0
1048 total_charges = 0
1049 item_count = 0
1050 considered_rows = []
1051
Ankush Menat494bd9e2022-03-28 18:52:46 +05301052 for tax in doc.get("taxes"):
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301053 prev_row_id = cint(tax.row_id) - 1
1054 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301055 if tax.charge_type == "On Previous Row Amount":
1056 additional_taxes += doc.get("taxes")[prev_row_id].tax_amount_after_discount_amount
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301057 considered_rows.append(prev_row_id)
Ankush Menat494bd9e2022-03-28 18:52:46 +05301058 if tax.charge_type == "On Previous Row Total":
1059 additional_taxes += doc.get("taxes")[prev_row_id].base_total - doc.base_net_total
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301060 considered_rows.append(prev_row_id)
1061
Ankush Menat494bd9e2022-03-28 18:52:46 +05301062 for item in doc.get("items"):
Deepesh Garg4afda3c2021-06-01 13:13:04 +05301063 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
1064 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301065
Ankush Menat494bd9e2022-03-28 18:52:46 +05301066 applicable_charges = flt(
1067 flt(
1068 proportionate_value * (flt(additional_taxes) / flt(total_value)),
1069 item.precision("taxable_value"),
1070 )
1071 )
Deepesh Gargc36e48a2021-04-12 10:55:43 +05301072 item.taxable_value = applicable_charges + proportionate_value
1073 total_charges += applicable_charges
1074 item_count += 1
1075
1076 if total_charges != additional_taxes:
1077 diff = additional_taxes - total_charges
Ankush Menat494bd9e2022-03-28 18:52:46 +05301078 doc.get("items")[item_count - 1].taxable_value += diff
1079
Saqib9226cd32021-05-10 12:36:56 +05301080
1081def get_depreciation_amount(asset, depreciable_value, row):
Saqib9226cd32021-05-10 12:36:56 +05301082 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +05301083 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +05301084 if not asset.flags.increase_in_asset_life:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301085 depreciation_amount = (
1086 flt(asset.gross_purchase_amount) - flt(row.expected_value_after_useful_life)
1087 ) / flt(row.total_number_of_depreciations)
GangaManoj2b93e542021-06-19 13:45:37 +05301088
1089 # if the Depreciation Schedule is being modified after Asset Repair
1090 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301091 depreciation_amount = (
1092 flt(row.value_after_depreciation) - flt(row.expected_value_after_useful_life)
1093 ) / (date_diff(asset.to_date, asset.available_for_use_date) / 365)
Ankush Menat4551d7d2021-08-19 13:41:10 +05301094
Saqib9226cd32021-05-10 12:36:56 +05301095 else:
1096 rate_of_depreciation = row.rate_of_depreciation
1097 # if its the first depreciation
1098 if depreciable_value == asset.gross_purchase_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301099 if row.finance_book and frappe.db.get_value("Finance Book", row.finance_book, "for_income_tax"):
Saqib424efd42021-09-28 18:12:02 +05301100 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
1101 diff = date_diff(row.depreciation_start_date, asset.available_for_use_date)
1102 if diff <= 180:
1103 rate_of_depreciation = rate_of_depreciation / 2
1104 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +05301105 _(
1106 "As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%."
1107 )
1108 )
Saqib9226cd32021-05-10 12:36:56 +05301109
1110 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
1111
Saqib3a504902021-08-03 15:57:11 +05301112 return depreciation_amount
1113
Ankush Menat494bd9e2022-03-28 18:52:46 +05301114
Saqib3a504902021-08-03 15:57:11 +05301115def set_item_tax_from_hsn_code(item):
Ankush Menat4551d7d2021-08-19 13:41:10 +05301116 if not item.taxes and item.gst_hsn_code:
Saqib3a504902021-08-03 15:57:11 +05301117 hsn_doc = frappe.get_doc("GST HSN Code", item.gst_hsn_code)
1118
1119 for tax in hsn_doc.taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +05301120 item.append(
1121 "taxes",
1122 {
1123 "item_tax_template": tax.item_tax_template,
1124 "tax_category": tax.tax_category,
1125 "valid_from": tax.valid_from,
1126 },
1127 )
1128
Deepesh Garg2b2572b2021-08-20 14:40:12 +05301129
1130def delete_gst_settings_for_company(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +05301131 if doc.country != "India":
Deepesh Garg2b2572b2021-08-20 14:40:12 +05301132 return
1133
1134 gst_settings = frappe.get_doc("GST Settings")
1135 records_to_delete = []
1136
Ankush Menat494bd9e2022-03-28 18:52:46 +05301137 for d in reversed(gst_settings.get("gst_accounts")):
Deepesh Garg2b2572b2021-08-20 14:40:12 +05301138 if d.company == doc.name:
1139 records_to_delete.append(d)
1140
1141 for d in records_to_delete:
1142 gst_settings.remove(d)
1143
1144 gst_settings.save()