blob: 049486e9c991abecef4f9625e00f35e89307e955 [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
Rucha Mahabalab8df982022-06-10 18:22:07 +05307from frappe.utils import cint, cstr, date_diff, flt, getdate
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
Chillar Anand915b3432021-09-02 16:44:59 +053011from erpnext.regional.india import number_state_mapping, state_numbers, states
Ankush Menat7c4c42a2021-03-03 14:56:19 +053012
Ankush Menat494bd9e2022-03-28 18:52:46 +053013GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") # alphanumeric and - /
14GSTIN_FORMAT = re.compile(
15 "^[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}$"
16)
Ankush Menat7c4c42a2021-03-03 14:56:19 +053017GSTIN_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):
Ankush Menat494bd9e2022-03-28 18:52:46 +053022 if hasattr(doc, "gst_state"):
Deepesh Garg363e6762022-03-21 16:28:17 +053023 set_gst_state_and_state_number(doc)
24
Ankush Menat494bd9e2022-03-28 18:52:46 +053025 if not hasattr(doc, "gstin") or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053026 return
27
Deepesh Garg459155f2019-06-14 12:01:34 +053028 gst_category = []
29
Ankush Menat494bd9e2022-03-28 18:52:46 +053030 if hasattr(doc, "gst_category"):
Anuja Pawar59c31bb2021-10-22 19:26:31 +053031 if len(doc.links):
32 link_doctype = doc.links[0].get("link_doctype")
33 link_name = doc.links[0].get("link_name")
Deepesh Garg459155f2019-06-14 12:01:34 +053034
Anuja Pawar59c31bb2021-10-22 19:26:31 +053035 if link_doctype in ["Customer", "Supplier"]:
Ankush Menat494bd9e2022-03-28 18:52:46 +053036 gst_category = frappe.db.get_value(link_doctype, {"name": link_name}, ["gst_category"])
Deepesh Garg459155f2019-06-14 12:01:34 +053037
Sagar Vorad75095b2019-01-23 14:40:01 +053038 doc.gstin = doc.gstin.upper().strip()
Ankush Menat494bd9e2022-03-28 18:52:46 +053039 if not doc.gstin or doc.gstin == "NA":
Sagar Vora07cf4e82019-01-10 11:07:51 +053040 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053041
Sagar Vora07cf4e82019-01-10 11:07:51 +053042 if len(doc.gstin) != 15:
Saqib93203162021-04-12 17:55:46 +053043 frappe.throw(_("A GSTIN must have 15 characters."), title=_("Invalid GSTIN"))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053044
Ankush Menat494bd9e2022-03-28 18:52:46 +053045 if gst_category and gst_category == "UIN Holders":
Ankush Menat7c4c42a2021-03-03 14:56:19 +053046 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Ankush Menat494bd9e2022-03-28 18:52:46 +053047 frappe.throw(
48 _(
49 "The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"
50 ),
51 title=_("Invalid GSTIN"),
52 )
Deepesh Garg459155f2019-06-14 12:01:34 +053053 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053054 if not GSTIN_FORMAT.match(doc.gstin):
Ankush Menat494bd9e2022-03-28 18:52:46 +053055 frappe.throw(
56 _("The input you've entered doesn't match the format of GSTIN."), title=_("Invalid GSTIN")
57 )
Rushabh Mehta7231f292017-07-13 15:00:56 +053058
Deepesh Garg459155f2019-06-14 12:01:34 +053059 validate_gstin_check_digit(doc.gstin)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053060
Anurag Mishra1e396dc2021-01-13 14:01:57 +053061 if not doc.gst_state:
Saqib93203162021-04-12 17:55:46 +053062 frappe.throw(_("Please enter GST state"), title=_("Invalid State"))
Anurag Mishra1e396dc2021-01-13 14:01:57 +053063
Deepesh Garg459155f2019-06-14 12:01:34 +053064 if doc.gst_state_number != doc.gstin[:2]:
Ankush Menat494bd9e2022-03-28 18:52:46 +053065 frappe.throw(
66 _("First 2 digits of GSTIN should match with State number {0}.").format(doc.gst_state_number),
67 title=_("Invalid GSTIN"),
68 )
69
Sagar Vora07cf4e82019-01-10 11:07:51 +053070
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053071def validate_pan_for_india(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +053072 if doc.get("country") != "India" or not doc.get("pan"):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053073 return
74
Ankush Menat7c4c42a2021-03-03 14:56:19 +053075 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053076 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
77
Ankush Menat494bd9e2022-03-28 18:52:46 +053078
Deepesh Gargd07447a2020-11-24 08:09:17 +053079def validate_tax_category(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +053080 if doc.get("gst_state") and frappe.db.get_value(
81 "Tax Category",
82 {
83 "gst_state": doc.gst_state,
84 "is_inter_state": doc.is_inter_state,
85 "is_reverse_charge": doc.is_reverse_charge,
86 },
87 ):
Deepesh Gargd07447a2020-11-24 08:09:17 +053088 if doc.is_inter_state:
Ankush Menat494bd9e2022-03-28 18:52:46 +053089 frappe.throw(
90 _("Inter State tax category for GST State {0} already exists").format(doc.gst_state)
91 )
Deepesh Gargd07447a2020-11-24 08:09:17 +053092 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +053093 frappe.throw(
94 _("Intra State tax category for GST State {0} already exists").format(doc.gst_state)
95 )
96
Deepesh Gargd07447a2020-11-24 08:09:17 +053097
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053098def update_gst_category(doc, method):
Deepesh Garga38aca52021-11-19 11:03:13 +053099 for link in doc.links:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530100 if link.link_doctype in ["Customer", "Supplier"]:
Deepesh Garga38aca52021-11-19 11:03:13 +0530101 meta = frappe.get_meta(link.link_doctype)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530102 if doc.get("gstin") and meta.has_field("gst_category"):
103 frappe.db.set_value(
104 link.link_doctype,
105 {"name": link.link_name, "gst_category": "Unregistered"},
106 "gst_category",
107 "Registered Regular",
108 )
109
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530110
Nabin Hait34c551d2019-07-03 10:34:31 +0530111def set_gst_state_and_state_number(doc):
Deepesh Garg363e6762022-03-21 16:28:17 +0530112 if not doc.gst_state and doc.state:
Nabin Hait34c551d2019-07-03 10:34:31 +0530113 state = doc.state.lower()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530114 states_lowercase = {s.lower(): s for s in states}
Nabin Hait34c551d2019-07-03 10:34:31 +0530115 if state in states_lowercase:
116 doc.gst_state = states_lowercase[state]
117 else:
118 return
Deepesh Garg363e6762022-03-21 16:28:17 +0530119 doc.gst_state_number = state_numbers.get(doc.gst_state)
Nabin Hait34c551d2019-07-03 10:34:31 +0530120
Ankush Menat494bd9e2022-03-28 18:52:46 +0530121
122def validate_gstin_check_digit(gstin, label="GSTIN"):
123 """Function to validate the check digit of the GSTIN."""
karthikeyan52825b922019-01-09 19:15:10 +0530124 factor = 1
125 total = 0
Ankush Menat494bd9e2022-03-28 18:52:46 +0530126 code_point_chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
karthikeyan52825b922019-01-09 19:15:10 +0530127 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530128 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530129 for char in input_chars:
130 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530131 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530132 total += digit
133 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530134 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530135 frappe.throw(
136 _(
137 """Invalid {0}! The check digit validation has failed. Please ensure you've typed the {0} correctly."""
138 ).format(label)
139 )
140
Rushabh Mehta7231f292017-07-13 15:00:56 +0530141
Nabin Haitb962fc12017-07-17 18:02:31 +0530142def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530143 hsn_wise_in_gst_settings = frappe.db.get_single_value("GST Settings", "hsn_wise_tax_breakup")
144 if frappe.get_meta(item_doctype).has_field("gst_hsn_code") and hsn_wise_in_gst_settings:
Subin Tom530de122021-10-11 17:33:41 +0530145 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
146 else:
147 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530148
Ankush Menat494bd9e2022-03-28 18:52:46 +0530149
Subin Tomd49346a2021-09-17 10:39:03 +0530150def get_itemised_tax_breakup_data(doc, account_wise=False, hsn_wise=False):
Nabin Hait34c551d2019-07-03 10:34:31 +0530151 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530152
153 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530154
Ankush Menat494bd9e2022-03-28 18:52:46 +0530155 if not frappe.get_meta(doc.doctype + " Item").has_field("gst_hsn_code"):
Nabin Haitb962fc12017-07-17 18:02:31 +0530156 return itemised_tax, itemised_taxable_amount
157
Ankush Menat494bd9e2022-03-28 18:52:46 +0530158 hsn_wise_in_gst_settings = frappe.db.get_single_value("GST Settings", "hsn_wise_tax_breakup")
Subin Tom530de122021-10-11 17:33:41 +0530159
160 tax_breakup_hsn_wise = hsn_wise or hsn_wise_in_gst_settings
161 if tax_breakup_hsn_wise:
Subin Tomd49346a2021-09-17 10:39:03 +0530162 item_hsn_map = frappe._dict()
163 for d in doc.items:
164 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
Nabin Haitb962fc12017-07-17 18:02:31 +0530165
166 hsn_tax = {}
167 for item, taxes in itemised_tax.items():
Subin Tom530de122021-10-11 17:33:41 +0530168 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530169 hsn_tax.setdefault(item_or_hsn, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530170 for tax_desc, tax_detail in taxes.items():
171 key = tax_desc
172 if account_wise:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530173 key = tax_detail.get("tax_account")
Subin Tomd49346a2021-09-17 10:39:03 +0530174 hsn_tax[item_or_hsn].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
175 hsn_tax[item_or_hsn][key]["tax_rate"] = tax_detail.get("tax_rate")
176 hsn_tax[item_or_hsn][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530177
178 # set taxable amount
179 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530180 for item in itemised_taxable_amount:
Subin Tom530de122021-10-11 17:33:41 +0530181 item_or_hsn = item if not tax_breakup_hsn_wise else item_hsn_map.get(item)
Subin Tomd49346a2021-09-17 10:39:03 +0530182 hsn_taxable_amount.setdefault(item_or_hsn, 0)
183 hsn_taxable_amount[item_or_hsn] += itemised_taxable_amount.get(item)
Nabin Haitb962fc12017-07-17 18:02:31 +0530184
185 return hsn_tax, hsn_taxable_amount
186
Ankush Menat494bd9e2022-03-28 18:52:46 +0530187
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188def set_place_of_supply(doc, method=None):
189 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530190
Ankush Menat494bd9e2022-03-28 18:52:46 +0530191
Ankush Menata44df632021-03-01 17:12:53 +0530192def validate_document_name(doc, method=None):
193 """Validate GST invoice number requirements."""
Nabin Hait10c61372021-04-13 15:46:01 +0530194
Ankush Menata44df632021-03-01 17:12:53 +0530195 country = frappe.get_cached_value("Company", doc.company, "country")
196
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530197 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530198 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
199 return
200
201 if len(doc.name) > 16:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530202 frappe.throw(
203 _(
204 "Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."
205 )
206 )
Ankush Menata44df632021-03-01 17:12:53 +0530207
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530208 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530209 frappe.throw(
210 _(
211 "Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."
212 )
213 )
214
Ankush Menata44df632021-03-01 17:12:53 +0530215
Rushabh Mehta7231f292017-07-13 15:00:56 +0530216# don't remove this function it is used in tests
217def test_method():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530218 """test function"""
219 return "overridden"
220
Shreya Shah4fa600a2018-06-05 11:27:53 +0530221
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530222def get_place_of_supply(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530223 if not frappe.get_meta("Address").has_field("gst_state"):
224 return
Shreya Shah4fa600a2018-06-05 11:27:53 +0530225
Deepesh Garg03952f82022-03-23 18:47:58 +0530226 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530227 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530228 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
229 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530230
231 if address_name:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530232 address = frappe.db.get_value(
233 "Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1
234 )
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530235 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530236 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530237 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530238
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530240@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530241def get_regional_address_details(party_details, doctype, company):
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530242 if isinstance(party_details, str):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530243 party_details = json.loads(party_details)
244 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530245
Deepesh Garga7670852020-12-04 18:07:46 +0530246 update_party_details(party_details, doctype)
247
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530248 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530249
250 if is_internal_transfer(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530251 party_details.taxes_and_charges = ""
Deepesh Gargb4be2922021-01-28 13:09:56 +0530252 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530253 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530254
Deepesh Garg03952f82022-03-23 18:47:58 +0530255 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530256 master_doctype = "Sales Taxes and Charges Template"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530257 tax_template_by_category = get_tax_template_based_on_category(
258 master_doctype, company, party_details
259 )
Shreya Shah4fa600a2018-06-05 11:27:53 +0530260
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530261 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
262 master_doctype = "Purchase Taxes and Charges Template"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530263 tax_template_by_category = get_tax_template_based_on_category(
264 master_doctype, company, party_details
265 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530266
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530267 if tax_template_by_category:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530268 party_details["taxes_and_charges"] = tax_template_by_category
Deepesh Garg532961f2022-03-30 19:33:44 +0530269 party_details["taxes"] = get_taxes_and_charges(master_doctype, tax_template_by_category)
Deepesh Garg466e5492022-01-02 17:53:15 +0530270 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530271
Ankush Menat494bd9e2022-03-28 18:52:46 +0530272 if not party_details.place_of_supply:
273 return party_details
274 if not party_details.company_gstin:
275 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530276
Ankush Menat494bd9e2022-03-28 18:52:46 +0530277 if (
278 doctype in ("Sales Invoice", "Delivery Note", "Sales Order")
279 and party_details.company_gstin
280 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]
281 ) or (
282 doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt")
283 and party_details.supplier_gstin
284 and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2]
285 ):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530286 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530287 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530288 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530289
290 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530291 return party_details
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530292
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530293 party_details["taxes_and_charges"] = default_tax
Deepesh Garg532961f2022-03-30 19:33:44 +0530294 party_details["taxes"] = get_taxes_and_charges(master_doctype, default_tax)
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530295
pateljannatcd05b342020-11-19 11:37:08 +0530296 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530297
Ankush Menat494bd9e2022-03-28 18:52:46 +0530298
Deepesh Garga7670852020-12-04 18:07:46 +0530299def update_party_details(party_details, doctype):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 for address_field in [
301 "shipping_address",
302 "company_address",
303 "supplier_address",
304 "shipping_address_name",
305 "customer_address",
306 ]:
Deepesh Garga7670852020-12-04 18:07:46 +0530307 if party_details.get(address_field):
308 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
309
Ankush Menat494bd9e2022-03-28 18:52:46 +0530310
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530311def is_internal_transfer(party_details, doctype):
Deepesh Garg03952f82022-03-23 18:47:58 +0530312 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order", "Quotation"):
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530313 destination_gstin = party_details.company_gstin
314 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
315 destination_gstin = party_details.supplier_gstin
316
Deepesh Gargda47fe22021-09-30 13:28:53 +0530317 if not destination_gstin or party_details.gstin:
318 return False
319
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530320 if party_details.gstin == destination_gstin:
321 return True
322 else:
323 False
324
Ankush Menat494bd9e2022-03-28 18:52:46 +0530325
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530326def get_tax_template_based_on_category(master_doctype, company, party_details):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530327 if not party_details.get("tax_category"):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530328 return
329
Ankush Menat494bd9e2022-03-28 18:52:46 +0530330 default_tax = frappe.db.get_value(
331 master_doctype, {"company": company, "tax_category": party_details.get("tax_category")}, "name"
332 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530333
Deepesh Garg35e2bd82021-12-02 17:17:56 +0530334 return default_tax
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530335
Ankush Menat494bd9e2022-03-28 18:52:46 +0530336
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530337def get_tax_template(master_doctype, company, is_inter_state, state_code):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530338 tax_categories = frappe.get_all(
339 "Tax Category",
340 fields=["name", "is_inter_state", "gst_state"],
Deepesh Garg9a6a1812022-04-01 14:46:26 +0530341 filters={"is_inter_state": is_inter_state, "is_reverse_charge": 0, "disabled": 0},
Ankush Menat494bd9e2022-03-28 18:52:46 +0530342 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530343
Ankush Menat494bd9e2022-03-28 18:52:46 +0530344 default_tax = ""
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530345
346 for tax_category in tax_categories:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530347 if tax_category.gst_state == number_state_mapping[state_code] or (
348 not default_tax and not tax_category.gst_state
349 ):
350 default_tax = frappe.db.get_value(
351 master_doctype, {"company": company, "disabled": 0, "tax_category": tax_category.name}, "name"
352 )
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530353 return default_tax
354
Ankush Menat494bd9e2022-03-28 18:52:46 +0530355
Nabin Hait34c551d2019-07-03 10:34:31 +0530356def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530357
358 ewaybills = []
359 for doc_name in dn:
360 doc = frappe.get_doc(dt, doc_name)
361
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530362 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530363
Ankush Menat494bd9e2022-03-28 18:52:46 +0530364 data = frappe._dict(
365 {
366 "transporterId": "",
367 "TotNonAdvolVal": 0,
368 }
369 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530370
371 data.userGstin = data.fromGstin = doc.company_gstin
Ankush Menat494bd9e2022-03-28 18:52:46 +0530372 data.supplyType = "O"
Nabin Hait34c551d2019-07-03 10:34:31 +0530373
Ankush Menat494bd9e2022-03-28 18:52:46 +0530374 if dt == "Delivery Note":
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530375 data.subSupplyType = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530376 elif doc.gst_category in ["Registered Regular", "SEZ"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530377 data.subSupplyType = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530378 elif doc.gst_category in ["Overseas", "Deemed Export"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530379 data.subSupplyType = 3
380 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530381 frappe.throw(_("Unsupported GST Category for E-Way Bill JSON generation"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530382
Ankush Menat494bd9e2022-03-28 18:52:46 +0530383 data.docType = "INV"
384 data.docDate = frappe.utils.formatdate(doc.posting_date, "dd/mm/yyyy")
Nabin Hait34c551d2019-07-03 10:34:31 +0530385
Ankush Menat494bd9e2022-03-28 18:52:46 +0530386 company_address = frappe.get_doc("Address", doc.company_address)
387 billing_address = frappe.get_doc("Address", doc.customer_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530388
Ankush Menat494bd9e2022-03-28 18:52:46 +0530389 # added dispatch address
390 dispatch_address = (
391 frappe.get_doc("Address", doc.dispatch_address_name)
392 if doc.dispatch_address_name
393 else company_address
394 )
395 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Nabin Hait34c551d2019-07-03 10:34:31 +0530396
Subin Tom5265ba32021-07-13 14:58:17 +0530397 data = get_address_details(data, doc, company_address, billing_address, dispatch_address)
Nabin Hait34c551d2019-07-03 10:34:31 +0530398
399 data.itemList = []
Smit Vorae2d866d2021-11-01 15:55:19 +0530400 data.totalValue = doc.net_total
Nabin Hait34c551d2019-07-03 10:34:31 +0530401
Subin Tomd49346a2021-09-17 10:39:03 +0530402 data = get_item_list(data, doc, hsn_wise=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530403
Ankush Menat494bd9e2022-03-28 18:52:46 +0530404 disable_rounded = frappe.db.get_single_value("Global Defaults", "disable_rounded_total")
Nabin Hait34c551d2019-07-03 10:34:31 +0530405 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
406
407 data = get_transport_details(data, doc)
408
409 fields = {
410 "/. -": {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530411 "docNo": doc.name,
412 "fromTrdName": doc.company,
413 "toTrdName": doc.customer_name,
414 "transDocNo": doc.lr_no,
Nabin Hait34c551d2019-07-03 10:34:31 +0530415 },
416 "@#/,&. -": {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417 "fromAddr1": company_address.address_line1,
418 "fromAddr2": company_address.address_line2,
419 "fromPlace": company_address.city,
420 "toAddr1": shipping_address.address_line1,
421 "toAddr2": shipping_address.address_line2,
422 "toPlace": shipping_address.city,
423 "transporterName": doc.transporter_name,
424 },
Nabin Hait34c551d2019-07-03 10:34:31 +0530425 }
426
427 for allowed_chars, field_map in fields.items():
428 for key, value in field_map.items():
429 if not value:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530430 data[key] = ""
Nabin Hait34c551d2019-07-03 10:34:31 +0530431 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530432 data[key] = re.sub(r"[^\w" + allowed_chars + "]", "", value)
Nabin Hait34c551d2019-07-03 10:34:31 +0530433
434 ewaybills.append(data)
435
Ankush Menat494bd9e2022-03-28 18:52:46 +0530436 data = {"version": "1.0.0421", "billLists": ewaybills}
Nabin Hait34c551d2019-07-03 10:34:31 +0530437
438 return data
439
Ankush Menat494bd9e2022-03-28 18:52:46 +0530440
Nabin Hait34c551d2019-07-03 10:34:31 +0530441@frappe.whitelist()
442def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530443 dn = json.loads(dn)
444 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530445
Ankush Menat494bd9e2022-03-28 18:52:46 +0530446
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530447@frappe.whitelist()
448def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530449 data = json.loads(frappe.local.form_dict.data)
450 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530451 frappe.local.response.type = "download"
Nabin Hait34c551d2019-07-03 10:34:31 +0530452
Ankush Menat494bd9e2022-03-28 18:52:46 +0530453 filename_prefix = "Bulk"
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530454 docname = frappe.local.form_dict.docname
455 if docname:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530456 if docname.startswith("["):
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530457 docname = json.loads(docname)
458 if len(docname) == 1:
459 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530460
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530461 if not isinstance(docname, list):
462 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530463 filename_prefix = re.sub(r"[^\w_.)( -]", "", docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530464
Ankush Menat494bd9e2022-03-28 18:52:46 +0530465 frappe.local.response.filename = "{0}_e-WayBill_Data_{1}.json".format(
466 filename_prefix, frappe.utils.random_string(5)
467 )
468
Nabin Hait34c551d2019-07-03 10:34:31 +0530469
Prasann Shah829172c2019-06-06 12:08:09 +0530470@frappe.whitelist()
471def get_gstins_for_company(company):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530472 company_gstins = []
Prasann Shah829172c2019-06-06 12:08:09 +0530473 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530474 company_gstins = frappe.db.sql(
475 """select
Prasann Shah829172c2019-06-06 12:08:09 +0530476 distinct `tabAddress`.gstin
477 from
478 `tabAddress`, `tabDynamic Link`
479 where
480 `tabDynamic Link`.parent = `tabAddress`.name and
481 `tabDynamic Link`.parenttype = 'Address' and
482 `tabDynamic Link`.link_doctype = 'Company' and
Ankush Menat494bd9e2022-03-28 18:52:46 +0530483 `tabDynamic Link`.link_name = %(company)s""",
484 {"company": company},
485 )
Prasann Shah829172c2019-06-06 12:08:09 +0530486 return company_gstins
487
Ankush Menat494bd9e2022-03-28 18:52:46 +0530488
Subin Tom5265ba32021-07-13 14:58:17 +0530489def get_address_details(data, doc, company_address, billing_address, dispatch_address):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530490 data.fromPincode = validate_pincode(company_address.pincode, "Company Address")
491 data.fromStateCode = validate_state_code(company_address.gst_state_number, "Company Address")
492 data.actualFromStateCode = validate_state_code(
493 dispatch_address.gst_state_number, "Dispatch Address"
494 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530495
496 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530497 data.toGstin = "URP"
Nabin Hait34c551d2019-07-03 10:34:31 +0530498 set_gst_state_and_state_number(billing_address)
499 else:
500 data.toGstin = doc.billing_address_gstin
501
Ankush Menat494bd9e2022-03-28 18:52:46 +0530502 data.toPincode = validate_pincode(billing_address.pincode, "Customer Address")
503 data.toStateCode = validate_state_code(billing_address.gst_state_number, "Customer Address")
Nabin Hait34c551d2019-07-03 10:34:31 +0530504
505 if doc.customer_address != doc.shipping_address_name:
506 data.transType = 2
Ankush Menat494bd9e2022-03-28 18:52:46 +0530507 shipping_address = frappe.get_doc("Address", doc.shipping_address_name)
Nabin Hait34c551d2019-07-03 10:34:31 +0530508 set_gst_state_and_state_number(shipping_address)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509 data.toPincode = validate_pincode(shipping_address.pincode, "Shipping Address")
510 data.actualToStateCode = validate_state_code(
511 shipping_address.gst_state_number, "Shipping Address"
512 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530513 else:
514 data.transType = 1
515 data.actualToStateCode = data.toStateCode
516 shipping_address = billing_address
Deepesh Gargd07447a2020-11-24 08:09:17 +0530517
Ankush Menat494bd9e2022-03-28 18:52:46 +0530518 if doc.gst_category == "SEZ":
Smit Vorabbe49332020-11-18 20:58:59 +0530519 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530520
521 return data
522
Ankush Menat494bd9e2022-03-28 18:52:46 +0530523
Subin Tomd49346a2021-09-17 10:39:03 +0530524def get_item_list(data, doc, hsn_wise=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530525 for attr in ["cgstValue", "sgstValue", "igstValue", "cessValue", "OthValue"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530526 data[attr] = 0
527
528 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
529 tax_map = {
Ankush Menat494bd9e2022-03-28 18:52:46 +0530530 "sgst_account": ["sgstRate", "sgstValue"],
531 "cgst_account": ["cgstRate", "cgstValue"],
532 "igst_account": ["igstRate", "igstValue"],
533 "cess_account": ["cessRate", "cessValue"],
Nabin Hait34c551d2019-07-03 10:34:31 +0530534 }
Ankush Menat494bd9e2022-03-28 18:52:46 +0530535 item_data_attrs = ["sgstRate", "cgstRate", "igstRate", "cessRate", "cessNonAdvol"]
536 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(
537 doc, account_wise=True, hsn_wise=hsn_wise
538 )
Smit Vora520f33b2021-11-14 08:10:53 +0530539 for item_or_hsn, taxable_amount in hsn_taxable_amount.items():
Nabin Hait34c551d2019-07-03 10:34:31 +0530540 item_data = frappe._dict()
Smit Vora520f33b2021-11-14 08:10:53 +0530541 if not item_or_hsn:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530542 frappe.throw(_("GST HSN Code does not exist for one or more items"))
Smit Vora520f33b2021-11-14 08:10:53 +0530543 item_data.hsnCode = int(item_or_hsn) if hsn_wise else item_or_hsn
Nabin Hait34c551d2019-07-03 10:34:31 +0530544 item_data.taxableAmount = taxable_amount
545 item_data.qtyUnit = ""
546 for attr in item_data_attrs:
547 item_data[attr] = 0
548
Smit Vora520f33b2021-11-14 08:10:53 +0530549 for account, tax_detail in hsn_wise_charges.get(item_or_hsn, {}).items():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530550 account_type = gst_accounts.get(account, "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530551 for tax_acc, attrs in tax_map.items():
552 if account_type == tax_acc:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530553 item_data[attrs[0]] = tax_detail.get("tax_rate")
554 data[attrs[1]] += tax_detail.get("tax_amount")
Nabin Hait34c551d2019-07-03 10:34:31 +0530555 break
556 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530557 data.OthValue += tax_detail.get("tax_amount")
Nabin Hait34c551d2019-07-03 10:34:31 +0530558
559 data.itemList.append(item_data)
560
561 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
Ankush Menat494bd9e2022-03-28 18:52:46 +0530562 for attr in ["sgstValue", "cgstValue", "igstValue", "cessValue"]:
Nabin Hait34c551d2019-07-03 10:34:31 +0530563 data[attr] = flt(data[attr], 2)
564
565 return data
566
Ankush Menat494bd9e2022-03-28 18:52:46 +0530567
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530568def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530569 if doc.docstatus != 1:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530570 frappe.throw(_("E-Way Bill JSON can only be generated from submitted document"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530571
572 if doc.is_return:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530573 frappe.throw(_("E-Way Bill JSON cannot be generated for Sales Return as of now"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530574
575 if doc.ewaybill:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530576 frappe.throw(_("e-Way Bill already exists for this document"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530577
Ankush Menat494bd9e2022-03-28 18:52:46 +0530578 reqd_fields = [
579 "company_gstin",
580 "company_address",
581 "customer_address",
582 "shipping_address_name",
583 "mode_of_transport",
584 "distance",
585 ]
Nabin Hait34c551d2019-07-03 10:34:31 +0530586
587 for fieldname in reqd_fields:
588 if not doc.get(fieldname):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530589 frappe.throw(
590 _("{} is required to generate E-Way Bill JSON").format(doc.meta.get_label(fieldname))
591 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530592
593 if len(doc.company_gstin) < 15:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530594 frappe.throw(_("You must be a registered supplier to generate e-Way Bill"))
595
Nabin Hait34c551d2019-07-03 10:34:31 +0530596
597def get_transport_details(data, doc):
598 if doc.distance > 4000:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530599 frappe.throw(_("Distance cannot be greater than 4000 kms"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530600
601 data.transDistance = int(round(doc.distance))
602
Ankush Menat494bd9e2022-03-28 18:52:46 +0530603 transport_modes = {"Road": 1, "Rail": 2, "Air": 3, "Ship": 4}
Nabin Hait34c551d2019-07-03 10:34:31 +0530604
Ankush Menat494bd9e2022-03-28 18:52:46 +0530605 vehicle_types = {"Regular": "R", "Over Dimensional Cargo (ODC)": "O"}
Nabin Hait34c551d2019-07-03 10:34:31 +0530606
607 data.transMode = transport_modes.get(doc.mode_of_transport)
608
Ankush Menat494bd9e2022-03-28 18:52:46 +0530609 if doc.mode_of_transport == "Road":
Nabin Hait34c551d2019-07-03 10:34:31 +0530610 if not doc.gst_transporter_id and not doc.vehicle_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530611 frappe.throw(
612 _("Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road")
613 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530614 if doc.vehicle_no:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530615 data.vehicleNo = doc.vehicle_no.replace(" ", "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530616 if not doc.gst_vehicle_type:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530617 frappe.throw(_("Vehicle Type is required if Mode of Transport is Road"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530618 else:
619 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
620 else:
621 if not doc.lr_no or not doc.lr_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530622 frappe.throw(_("Transport Receipt No and Date are mandatory for your chosen Mode of Transport"))
Nabin Hait34c551d2019-07-03 10:34:31 +0530623
624 if doc.lr_no:
625 data.transDocNo = doc.lr_no
626
627 if doc.lr_date:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530628 data.transDocDate = frappe.utils.formatdate(doc.lr_date, "dd/mm/yyyy")
Nabin Hait34c551d2019-07-03 10:34:31 +0530629
630 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530631 if doc.gst_transporter_id[0:2] != "88":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530632 validate_gstin_check_digit(doc.gst_transporter_id, label="GST Transporter ID")
karthikeyan5ca46bed2020-05-30 15:00:56 +0530633 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530634
635 return data
636
637
638def validate_pincode(pincode, address):
639 pin_not_found = "Pin Code doesn't exist for {}"
640 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
641
642 if not pincode:
643 frappe.throw(_(pin_not_found.format(address)))
644
Ankush Menat494bd9e2022-03-28 18:52:46 +0530645 pincode = pincode.replace(" ", "")
Nabin Hait34c551d2019-07-03 10:34:31 +0530646 if not pincode.isdigit() or len(pincode) != 6:
647 frappe.throw(_(incorrect_pin.format(address)))
648 else:
649 return int(pincode)
650
Ankush Menat494bd9e2022-03-28 18:52:46 +0530651
Nabin Hait34c551d2019-07-03 10:34:31 +0530652def validate_state_code(state_code, address):
653 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
654 if not state_code:
655 frappe.throw(_(no_state_code.format(address)))
656 else:
657 return int(state_code)
658
Ankush Menat494bd9e2022-03-28 18:52:46 +0530659
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530660@frappe.whitelist()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530661def get_gst_accounts(
662 company=None, account_wise=False, only_reverse_charge=0, only_non_reverse_charge=0
663):
664 filters = {"parent": "GST Settings"}
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530665
666 if company:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530667 filters.update({"company": company})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530668 if only_reverse_charge:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530669 filters.update({"is_reverse_charge_account": 1})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530670 elif only_non_reverse_charge:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530671 filters.update({"is_reverse_charge_account": 0})
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530672
Nabin Hait34c551d2019-07-03 10:34:31 +0530673 gst_accounts = frappe._dict()
Ankush Menat494bd9e2022-03-28 18:52:46 +0530674 gst_settings_accounts = frappe.get_all(
675 "GST Account",
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530676 filters=filters,
Saqib Ansari45fca6b2022-04-07 13:09:05 +0530677 fields=["cgst_account", "sgst_account", "igst_account", "cess_account", "utgst_account"],
Ankush Menat494bd9e2022-03-28 18:52:46 +0530678 )
Nabin Hait34c551d2019-07-03 10:34:31 +0530679
Deepesh Garg44273902021-05-20 17:19:24 +0530680 if not gst_settings_accounts and not frappe.flags.in_test and not frappe.flags.in_migrate:
Nabin Hait34c551d2019-07-03 10:34:31 +0530681 frappe.throw(_("Please set GST Accounts in GST Settings"))
682
683 for d in gst_settings_accounts:
684 for acc, val in d.items():
685 if not account_wise:
686 gst_accounts.setdefault(acc, []).append(val)
687 elif val:
688 gst_accounts[val] = acc
689
Nabin Hait34c551d2019-07-03 10:34:31 +0530690 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530691
Deepesh Garg52c319c2020-07-15 23:57:03 +0530692
Deepesh Garg48175212022-05-13 18:08:32 +0530693def validate_sez_and_export_invoices(doc, method):
694 country = frappe.get_cached_value("Company", doc.company, "country")
695
696 if country != "India":
697 return
698
699 if (
700 doc.get("gst_category") in ("SEZ", "Overseas")
701 and doc.get("export_type") == "Without Payment of Tax"
702 ):
703 gst_accounts = get_gst_accounts(doc.company)
704
705 for tax in doc.get("taxes"):
706 for tax in doc.get("taxes"):
707 if (
708 tax.account_head
709 in gst_accounts.get("igst_account", [])
710 + gst_accounts.get("sgst_account", [])
711 + gst_accounts.get("cgst_account", [])
712 and tax.tax_amount_after_discount_amount
713 ):
714 frappe.throw(_("GST cannot be applied on SEZ or Export invoices without payment of tax"))
715
716
Ankush Menat494bd9e2022-03-28 18:52:46 +0530717def validate_reverse_charge_transaction(doc, method):
718 country = frappe.get_cached_value("Company", doc.company, "country")
719
720 if country != "India":
Deepesh Garg52c319c2020-07-15 23:57:03 +0530721 return
722
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530723 base_gst_tax = 0
724 base_reverse_charge_booked = 0
Deepesh Garg8aed48f2020-08-19 18:30:18 +0530725
Ankush Menat494bd9e2022-03-28 18:52:46 +0530726 if doc.reverse_charge == "Y":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530727 gst_accounts = get_gst_accounts(doc.company, only_reverse_charge=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530728 reverse_charge_accounts = (
729 gst_accounts.get("cgst_account")
730 + gst_accounts.get("sgst_account")
731 + gst_accounts.get("igst_account")
732 )
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530733
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530734 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530735 non_reverse_charge_accounts = (
736 gst_accounts.get("cgst_account")
737 + gst_accounts.get("sgst_account")
738 + gst_accounts.get("igst_account")
739 )
Deepesh Garg24f9a802020-06-03 10:59:37 +0530740
Ankush Menat494bd9e2022-03-28 18:52:46 +0530741 for tax in doc.get("taxes"):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530742 if tax.account_head in non_reverse_charge_accounts:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530743 if tax.add_deduct_tax == "Add":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530744 base_gst_tax += tax.base_tax_amount_after_discount_amount
745 else:
746 base_gst_tax += tax.base_tax_amount_after_discount_amount
747 elif tax.account_head in reverse_charge_accounts:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530748 if tax.add_deduct_tax == "Add":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530749 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
750 else:
751 base_reverse_charge_booked += tax.base_tax_amount_after_discount_amount
Deepesh Garg24f9a802020-06-03 10:59:37 +0530752
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530753 if base_gst_tax != base_reverse_charge_booked:
754 msg = _("Booked reverse charge is not equal to applied tax amount")
755 msg += "<br>"
Ankush Menat494bd9e2022-03-28 18:52:46 +0530756 msg += _(
757 "Please refer {gst_document_link} to learn more about how to setup and create reverse charge invoice"
758 ).format(
759 gst_document_link='<a href="https://docs.erpnext.com/docs/user/manual/en/regional/india/gst-setup">GST Documentation</a>'
760 )
Deepesh Garg24f9a802020-06-03 10:59:37 +0530761
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530762 frappe.throw(msg)
Deepesh Garg24f9a802020-06-03 10:59:37 +0530763
Deepesh Garg48175212022-05-13 18:08:32 +0530764 doc.eligibility_for_itc = "ITC on Reverse Charge"
765
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530766
Ankush Menat494bd9e2022-03-28 18:52:46 +0530767def update_itc_availed_fields(doc, method):
768 country = frappe.get_cached_value("Company", doc.company, "country")
769
770 if country != "India":
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530771 return
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530772
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530773 # Initialize values
774 doc.itc_integrated_tax = doc.itc_state_tax = doc.itc_central_tax = doc.itc_cess_amount = 0
775 gst_accounts = get_gst_accounts(doc.company, only_non_reverse_charge=1)
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530776
Ankush Menat494bd9e2022-03-28 18:52:46 +0530777 for tax in doc.get("taxes"):
778 if tax.account_head in gst_accounts.get("igst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530779 doc.itc_integrated_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530780 if tax.account_head in gst_accounts.get("sgst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530781 doc.itc_state_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530782 if tax.account_head in gst_accounts.get("cgst_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530783 doc.itc_central_tax += flt(tax.base_tax_amount_after_discount_amount)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530784 if tax.account_head in gst_accounts.get("cess_account", []):
Deepesh Garg55fe85d2021-05-14 12:17:41 +0530785 doc.itc_cess_amount += flt(tax.base_tax_amount_after_discount_amount)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530786
Ankush Menat494bd9e2022-03-28 18:52:46 +0530787
Deepesh Garg8b644d82021-07-15 15:36:54 +0530788def update_place_of_supply(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530789 country = frappe.get_cached_value("Company", doc.company, "country")
790 if country != "India":
Deepesh Garg8b644d82021-07-15 15:36:54 +0530791 return
792
Ankush Menat494bd9e2022-03-28 18:52:46 +0530793 address = frappe.db.get_value(
794 "Address", doc.get("customer_address"), ["gst_state", "gst_state_number"], as_dict=1
795 )
Deepesh Garg8b644d82021-07-15 15:36:54 +0530796 if address and address.gst_state and address.gst_state_number:
797 doc.place_of_supply = cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
798
Ankush Menat494bd9e2022-03-28 18:52:46 +0530799
Deepesh Garg004f9e62021-03-16 13:09:59 +0530800@frappe.whitelist()
801def get_regional_round_off_accounts(company, account_list):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530802 country = frappe.get_cached_value("Company", company, "country")
Deepesh Garg004f9e62021-03-16 13:09:59 +0530803
Ankush Menat494bd9e2022-03-28 18:52:46 +0530804 if country != "India":
Deepesh Garg004f9e62021-03-16 13:09:59 +0530805 return
806
Ankush Menat8fe5feb2021-11-04 19:48:32 +0530807 if isinstance(account_list, str):
Deepesh Garg004f9e62021-03-16 13:09:59 +0530808 account_list = json.loads(account_list)
809
Ankush Menat494bd9e2022-03-28 18:52:46 +0530810 if not frappe.db.get_single_value("GST Settings", "round_off_gst_values"):
Deepesh Garg004f9e62021-03-16 13:09:59 +0530811 return
812
813 gst_accounts = get_gst_accounts(company)
walstanb52403c52021-03-27 10:13:27 +0530814
815 gst_account_list = []
Ankush Menat494bd9e2022-03-28 18:52:46 +0530816 for account in ["cgst_account", "sgst_account", "igst_account"]:
walstanbab673d92021-03-27 12:52:23 +0530817 if account in gst_accounts:
walstanb52403c52021-03-27 10:13:27 +0530818 gst_account_list += gst_accounts.get(account)
Deepesh Garg004f9e62021-03-16 13:09:59 +0530819
820 account_list.extend(gst_account_list)
821
822 return account_list
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530823
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530824
Ankush Menat494bd9e2022-03-28 18:52:46 +0530825def update_taxable_values(doc, method):
826 country = frappe.get_cached_value("Company", doc.company, "country")
827
828 if country != "India":
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530829 return
830
831 gst_accounts = get_gst_accounts(doc.company)
832
833 # Only considering sgst account to avoid inflating taxable value
Ankush Menat494bd9e2022-03-28 18:52:46 +0530834 gst_account_list = (
835 gst_accounts.get("sgst_account", [])
836 + gst_accounts.get("sgst_account", [])
837 + gst_accounts.get("igst_account", [])
838 )
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530839
840 additional_taxes = 0
841 total_charges = 0
842 item_count = 0
843 considered_rows = []
844
Ankush Menat494bd9e2022-03-28 18:52:46 +0530845 for tax in doc.get("taxes"):
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530846 prev_row_id = cint(tax.row_id) - 1
847 if tax.account_head in gst_account_list and prev_row_id not in considered_rows:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530848 if tax.charge_type == "On Previous Row Amount":
849 additional_taxes += doc.get("taxes")[prev_row_id].tax_amount_after_discount_amount
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530850 considered_rows.append(prev_row_id)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530851 if tax.charge_type == "On Previous Row Total":
852 additional_taxes += doc.get("taxes")[prev_row_id].base_total - doc.base_net_total
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530853 considered_rows.append(prev_row_id)
854
Ankush Menat494bd9e2022-03-28 18:52:46 +0530855 for item in doc.get("items"):
Deepesh Garg4afda3c2021-06-01 13:13:04 +0530856 proportionate_value = item.base_net_amount if doc.base_net_total else item.qty
857 total_value = doc.base_net_total if doc.base_net_total else doc.total_qty
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530858
Ankush Menat494bd9e2022-03-28 18:52:46 +0530859 applicable_charges = flt(
860 flt(
861 proportionate_value * (flt(additional_taxes) / flt(total_value)),
862 item.precision("taxable_value"),
863 )
864 )
Deepesh Gargc36e48a2021-04-12 10:55:43 +0530865 item.taxable_value = applicable_charges + proportionate_value
866 total_charges += applicable_charges
867 item_count += 1
868
869 if total_charges != additional_taxes:
870 diff = additional_taxes - total_charges
Ankush Menat494bd9e2022-03-28 18:52:46 +0530871 doc.get("items")[item_count - 1].taxable_value += diff
872
Saqib9226cd32021-05-10 12:36:56 +0530873
874def get_depreciation_amount(asset, depreciable_value, row):
Saqib9226cd32021-05-10 12:36:56 +0530875 if row.depreciation_method in ("Straight Line", "Manual"):
GangaManoj2b93e542021-06-19 13:45:37 +0530876 # if the Depreciation Schedule is being prepared for the first time
GangaManojda8da9f2021-06-19 14:00:26 +0530877 if not asset.flags.increase_in_asset_life:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530878 depreciation_amount = (
879 flt(asset.gross_purchase_amount) - flt(row.expected_value_after_useful_life)
880 ) / flt(row.total_number_of_depreciations)
GangaManoj2b93e542021-06-19 13:45:37 +0530881
882 # if the Depreciation Schedule is being modified after Asset Repair
883 else:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530884 depreciation_amount = (
885 flt(row.value_after_depreciation) - flt(row.expected_value_after_useful_life)
886 ) / (date_diff(asset.to_date, asset.available_for_use_date) / 365)
Ankush Menat4551d7d2021-08-19 13:41:10 +0530887
Saqib9226cd32021-05-10 12:36:56 +0530888 else:
889 rate_of_depreciation = row.rate_of_depreciation
890 # if its the first depreciation
891 if depreciable_value == asset.gross_purchase_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530892 if row.finance_book and frappe.db.get_value("Finance Book", row.finance_book, "for_income_tax"):
Saqib424efd42021-09-28 18:12:02 +0530893 # as per IT act, if the asset is purchased in the 2nd half of fiscal year, then rate is divided by 2
894 diff = date_diff(row.depreciation_start_date, asset.available_for_use_date)
895 if diff <= 180:
896 rate_of_depreciation = rate_of_depreciation / 2
897 frappe.msgprint(
Ankush Menat494bd9e2022-03-28 18:52:46 +0530898 _(
899 "As per IT Act, the rate of depreciation for the first depreciation entry is reduced by 50%."
900 )
901 )
Saqib9226cd32021-05-10 12:36:56 +0530902
903 depreciation_amount = flt(depreciable_value * (flt(rate_of_depreciation) / 100))
904
Saqib3a504902021-08-03 15:57:11 +0530905 return depreciation_amount
906
Ankush Menat494bd9e2022-03-28 18:52:46 +0530907
Saqib3a504902021-08-03 15:57:11 +0530908def set_item_tax_from_hsn_code(item):
Ankush Menat4551d7d2021-08-19 13:41:10 +0530909 if not item.taxes and item.gst_hsn_code:
Saqib3a504902021-08-03 15:57:11 +0530910 hsn_doc = frappe.get_doc("GST HSN Code", item.gst_hsn_code)
911
912 for tax in hsn_doc.taxes:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530913 item.append(
914 "taxes",
915 {
916 "item_tax_template": tax.item_tax_template,
917 "tax_category": tax.tax_category,
918 "valid_from": tax.valid_from,
919 },
920 )
921
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530922
923def delete_gst_settings_for_company(doc, method):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530924 if doc.country != "India":
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530925 return
926
927 gst_settings = frappe.get_doc("GST Settings")
928 records_to_delete = []
929
Ankush Menat494bd9e2022-03-28 18:52:46 +0530930 for d in reversed(gst_settings.get("gst_accounts")):
Deepesh Garg2b2572b2021-08-20 14:40:12 +0530931 if d.company == doc.name:
932 records_to_delete.append(d)
933
934 for d in records_to_delete:
935 gst_settings.remove(d)
936
937 gst_settings.save()