blob: 25eecb4a5281eeb1b491456a0a280dd2ecfcc592 [file] [log] [blame]
Aditya Hasef3c22f32019-01-22 18:22:20 +05301from __future__ import unicode_literals
Nabin Hait34c551d2019-07-03 10:34:31 +05302import frappe, re, json
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05303from frappe import _
Deepesh Garg1c146062020-08-18 19:32:52 +05304import erpnext
Ankush Menata44df632021-03-01 17:12:53 +05305from frappe.utils import cstr, flt, date_diff, nowdate, round_based_on_smallest_currency_fraction, money_in_words, getdate
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05306from erpnext.regional.india import states, state_numbers
Nabin Haitb962fc12017-07-17 18:02:31 +05307from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Shreya Shah4fa600a2018-06-05 11:27:53 +05308from erpnext.controllers.accounts_controller import get_taxes_and_charges
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +05309from erpnext.hr.utils import get_salary_assignment
Anurag Mishra289c8222020-06-19 19:17:57 +053010from erpnext.payroll.doctype.salary_structure.salary_structure import make_salary_slip
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053011from erpnext.regional.india import number_state_mapping
12from six import string_types
Deepesh Garg24f9a802020-06-03 10:59:37 +053013from erpnext.accounts.general_ledger import make_gl_entries
14from erpnext.accounts.utils import get_account_currency
Deepesh Garga7670852020-12-04 18:07:46 +053015from frappe.model.utils import get_fetch_values
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053016
Ankush Menat7c4c42a2021-03-03 14:56:19 +053017
18GST_INVOICE_NUMBER_FORMAT = re.compile(r"^[a-zA-Z0-9\-/]+$") #alphanumeric and - /
19GSTIN_FORMAT = re.compile("^[0-9]{2}[A-Z]{4}[0-9A-Z]{1}[0-9]{4}[A-Z]{1}[1-9A-Z]{1}[1-9A-Z]{1}[0-9A-Z]{1}$")
20GSTIN_UIN_FORMAT = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
21PAN_NUMBER_FORMAT = re.compile("[A-Z]{5}[0-9]{4}[A-Z]{1}")
22
23
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053024def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053025 if hasattr(doc, 'gst_state') and doc.gst_state:
26 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053027 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053028 return
29
Deepesh Garg459155f2019-06-14 12:01:34 +053030 gst_category = []
31
32 if len(doc.links):
33 link_doctype = doc.links[0].get("link_doctype")
34 link_name = doc.links[0].get("link_name")
35
36 if link_doctype in ["Customer", "Supplier"]:
37 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
38
Sagar Vorad75095b2019-01-23 14:40:01 +053039 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053040 if not doc.gstin or doc.gstin == 'NA':
41 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053042
Sagar Vora07cf4e82019-01-10 11:07:51 +053043 if len(doc.gstin) != 15:
44 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053045
Deepesh Garg459155f2019-06-14 12:01:34 +053046 if gst_category and gst_category == 'UIN Holders':
Ankush Menat7c4c42a2021-03-03 14:56:19 +053047 if not GSTIN_UIN_FORMAT.match(doc.gstin):
Deepesh Garg459155f2019-06-14 12:01:34 +053048 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
49 else:
Ankush Menat7c4c42a2021-03-03 14:56:19 +053050 if not GSTIN_FORMAT.match(doc.gstin):
Deepesh Garg459155f2019-06-14 12:01:34 +053051 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053052
Deepesh Garg459155f2019-06-14 12:01:34 +053053 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053054 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053055
Anurag Mishra1e396dc2021-01-13 14:01:57 +053056 if not doc.gst_state:
57 frappe.throw(_("Please Enter GST state"))
58
Deepesh Garg459155f2019-06-14 12:01:34 +053059 if doc.gst_state_number != doc.gstin[:2]:
60 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
61 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053062
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053063def validate_pan_for_india(doc, method):
Nabin Hait866cf702021-02-22 21:35:00 +053064 if doc.get('country') != 'India' or not doc.pan:
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053065 return
66
Ankush Menat7c4c42a2021-03-03 14:56:19 +053067 if not PAN_NUMBER_FORMAT.match(doc.pan):
Deepesh Gargbb8cd1c2021-02-22 19:28:45 +053068 frappe.throw(_("Invalid PAN No. The input you've entered doesn't match the format of PAN."))
69
Deepesh Gargd07447a2020-11-24 08:09:17 +053070def validate_tax_category(doc, method):
Deepesh Garge77e3aa2020-12-17 18:46:59 +053071 if doc.get('gst_state') and frappe.db.get_value('Tax Category', {'gst_state': doc.gst_state, 'is_inter_state': doc.is_inter_state}):
Deepesh Gargd07447a2020-11-24 08:09:17 +053072 if doc.is_inter_state:
73 frappe.throw(_("Inter State tax category for GST State {0} already exists").format(doc.gst_state))
74 else:
75 frappe.throw(_("Intra State tax category for GST State {0} already exists").format(doc.gst_state))
76
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053077def update_gst_category(doc, method):
78 for link in doc.links:
79 if link.link_doctype in ['Customer', 'Supplier']:
80 if doc.get('gstin'):
81 frappe.db.sql("""
82 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
83 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
84
Nabin Hait34c551d2019-07-03 10:34:31 +053085def set_gst_state_and_state_number(doc):
86 if not doc.gst_state:
87 if not doc.state:
88 return
89 state = doc.state.lower()
90 states_lowercase = {s.lower():s for s in states}
91 if state in states_lowercase:
92 doc.gst_state = states_lowercase[state]
93 else:
94 return
95
96 doc.gst_state_number = state_numbers[doc.gst_state]
97
98def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053099 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +0530100 factor = 1
101 total = 0
102 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +0530103 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530104 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +0530105 for char in input_chars:
106 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +0530107 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +0530108 total += digit
109 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +0530110 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
Deepesh Gargd07447a2020-11-24 08:09:17 +0530111 frappe.throw(_("""Invalid {0}! The check digit validation has failed. Please ensure you've typed the {0} correctly.""").format(label))
Rushabh Mehta7231f292017-07-13 15:00:56 +0530112
Nabin Haitb962fc12017-07-17 18:02:31 +0530113def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
114 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
115 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
116 else:
117 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +0530118
Nabin Hait34c551d2019-07-03 10:34:31 +0530119def get_itemised_tax_breakup_data(doc, account_wise=False):
120 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +0530121
122 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530123
Nabin Haitb962fc12017-07-17 18:02:31 +0530124 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
125 return itemised_tax, itemised_taxable_amount
126
127 item_hsn_map = frappe._dict()
128 for d in doc.items:
129 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
130
131 hsn_tax = {}
132 for item, taxes in itemised_tax.items():
133 hsn_code = item_hsn_map.get(item)
134 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530135 for tax_desc, tax_detail in taxes.items():
136 key = tax_desc
137 if account_wise:
138 key = tax_detail.get('tax_account')
139 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
140 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
141 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530142
143 # set taxable amount
144 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530145 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530146 hsn_code = item_hsn_map.get(item)
147 hsn_taxable_amount.setdefault(hsn_code, 0)
148 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
149
150 return hsn_tax, hsn_taxable_amount
151
Shreya Shah4fa600a2018-06-05 11:27:53 +0530152def set_place_of_supply(doc, method=None):
153 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530154
Ankush Menata44df632021-03-01 17:12:53 +0530155def validate_document_name(doc, method=None):
156 """Validate GST invoice number requirements."""
157 country = frappe.get_cached_value("Company", doc.company, "country")
158
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530159 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530160 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
161 return
162
163 if len(doc.name) > 16:
164 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
165
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530166 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530167 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
168
Rushabh Mehta7231f292017-07-13 15:00:56 +0530169# don't remove this function it is used in tests
170def test_method():
171 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530172 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530173
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530174def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530175 if not frappe.get_meta('Address').has_field('gst_state'): return
176
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530177 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530178 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530179 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
180 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530181
182 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530183 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530184 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530185 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530186 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530187
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530188@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530189def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530190 if isinstance(party_details, string_types):
191 party_details = json.loads(party_details)
192 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530193
Deepesh Garga7670852020-12-04 18:07:46 +0530194 update_party_details(party_details, doctype)
195
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530196 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530197
198 if is_internal_transfer(party_details, doctype):
199 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530200 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530201 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530202
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530203 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530204 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530205
206 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
207 get_tax_template_based_on_category(master_doctype, company, party_details)
208
pateljannatcd05b342020-11-19 11:37:08 +0530209 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530210 return party_details
211
212 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530213 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530214
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530215 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
216 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530217 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
218 get_tax_template_based_on_category(master_doctype, company, party_details)
219
pateljannatcd05b342020-11-19 11:37:08 +0530220 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530221 return party_details
222
223 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530224 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530225
pateljannatcd05b342020-11-19 11:37:08 +0530226 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530227
pateljannatcd05b342020-11-19 11:37:08 +0530228 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530229
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530230 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
231 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
232 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
233 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530234 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530235 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530236
237 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530238 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530239 party_details["taxes_and_charges"] = default_tax
240 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
241
pateljannatcd05b342020-11-19 11:37:08 +0530242 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530243
Deepesh Garga7670852020-12-04 18:07:46 +0530244def update_party_details(party_details, doctype):
245 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
246 if party_details.get(address_field):
247 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530248
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530249def is_internal_transfer(party_details, doctype):
250 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
251 destination_gstin = party_details.company_gstin
252 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
253 destination_gstin = party_details.supplier_gstin
254
255 if party_details.gstin == destination_gstin:
256 return True
257 else:
258 False
259
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530260def get_tax_template_based_on_category(master_doctype, company, party_details):
261 if not party_details.get('tax_category'):
262 return
263
264 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
265 'name')
266
267 if default_tax:
268 party_details["taxes_and_charges"] = default_tax
269 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
270
271def get_tax_template(master_doctype, company, is_inter_state, state_code):
272 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
273 filters = {'is_inter_state': is_inter_state})
274
275 default_tax = ''
276
277 for tax_category in tax_categories:
278 if tax_category.gst_state == number_state_mapping[state_code] or \
279 (not default_tax and not tax_category.gst_state):
280 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530281 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530282 return default_tax
283
284def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
285
286 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
287 ['gst_category', 'export_type'], as_dict=1)
288
289 if gst_details:
290 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
291 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
292 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
293
294 party_details["taxes_and_charges"] = default_tax
295 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
296
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530297
298def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530299 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530300 if not (basic_component and hra_component):
301 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530302 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530303 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530304 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530305 if assignment:
306 hra_component_exists = frappe.db.exists("Salary Detail", {
307 "parent": assignment.salary_structure,
308 "salary_component": hra_component,
309 "parentfield": "earnings",
310 "parenttype": "Salary Structure"
311 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530312
Nabin Hait04e7bf42019-04-25 18:44:10 +0530313 if hra_component_exists:
314 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
315 assignment.salary_structure, basic_component, hra_component)
316 if hra_amount:
317 if doc.monthly_house_rent:
318 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530319 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530320 if annual_exemption > 0:
321 monthly_exemption = annual_exemption / 12
322 else:
323 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530324
Nabin Hait04e7bf42019-04-25 18:44:10 +0530325 elif doc.docstatus == 1:
326 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
327
328 return frappe._dict({
329 "hra_amount": hra_amount,
330 "annual_exemption": annual_exemption,
331 "monthly_exemption": monthly_exemption
332 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530333
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530334def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530335 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530336 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530337 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530338 if earning.salary_component == basic_component:
339 basic_amt = earning.amount
340 elif earning.salary_component == hra_component:
341 hra_amt = earning.amount
342 if basic_amt and hra_amt:
343 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530344 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530345
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530346def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530347 # TODO make this configurable
348 exemptions = []
349 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
350 # case 1: The actual amount allotted by the employer as the HRA.
351 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530352
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530353 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530354 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530355
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530356 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530357 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530358 # 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 +0530359 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530360 # return minimum of 3 cases
361 return min(exemptions)
362
363def get_annual_component_pay(frequency, amount):
364 if frequency == "Daily":
365 return amount * 365
366 elif frequency == "Weekly":
367 return amount * 52
368 elif frequency == "Fortnightly":
369 return amount * 26
370 elif frequency == "Monthly":
371 return amount * 12
372 elif frequency == "Bimonthly":
373 return amount * 6
374
375def validate_house_rent_dates(doc):
376 if not doc.rented_to_date or not doc.rented_from_date:
377 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530378
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530379 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
380 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530381
382 proofs = frappe.db.sql("""
383 select name
384 from `tabEmployee Tax Exemption Proof Submission`
385 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530386 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
387 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
388 """, {
389 "employee": doc.employee,
390 "payroll_period": doc.payroll_period,
391 "from_date": doc.rented_from_date,
392 "to_date": doc.rented_to_date
393 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530394
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530395 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530396 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530397
398def calculate_hra_exemption_for_period(doc):
399 monthly_rent, eligible_hra = 0, 0
400 if doc.house_rent_payment_amount:
401 validate_house_rent_dates(doc)
402 # TODO receive rented months or validate dates are start and end of months?
403 # Calc monthly rent, round to nearest .5
404 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
405 factor = round(factor * 2)/2
406 monthly_rent = doc.house_rent_payment_amount / factor
407 # update field used by calculate_annual_eligible_hra_exemption
408 doc.monthly_house_rent = monthly_rent
409 exemptions = calculate_annual_eligible_hra_exemption(doc)
410
411 if exemptions["monthly_exemption"]:
412 # calc total exemption amount
413 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530414 exemptions["monthly_house_rent"] = monthly_rent
415 exemptions["total_eligible_hra_exemption"] = eligible_hra
416 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530417
Nabin Hait34c551d2019-07-03 10:34:31 +0530418def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530419
420 ewaybills = []
421 for doc_name in dn:
422 doc = frappe.get_doc(dt, doc_name)
423
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530424 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530425
426 data = frappe._dict({
427 "transporterId": "",
428 "TotNonAdvolVal": 0,
429 })
430
431 data.userGstin = data.fromGstin = doc.company_gstin
432 data.supplyType = 'O'
433
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530434 if dt == 'Delivery Note':
435 data.subSupplyType = 1
436 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530437 data.subSupplyType = 1
438 elif doc.gst_category in ['Overseas', 'Deemed Export']:
439 data.subSupplyType = 3
440 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530441 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530442
443 data.docType = 'INV'
444 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
445
446 company_address = frappe.get_doc('Address', doc.company_address)
447 billing_address = frappe.get_doc('Address', doc.customer_address)
448
449 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
450
451 data = get_address_details(data, doc, company_address, billing_address)
452
453 data.itemList = []
454 data.totalValue = doc.total
455
456 data = get_item_list(data, doc)
457
458 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
459 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
460
461 data = get_transport_details(data, doc)
462
463 fields = {
464 "/. -": {
465 'docNo': doc.name,
466 'fromTrdName': doc.company,
467 'toTrdName': doc.customer_name,
468 'transDocNo': doc.lr_no,
469 },
470 "@#/,&. -": {
471 'fromAddr1': company_address.address_line1,
472 'fromAddr2': company_address.address_line2,
473 'fromPlace': company_address.city,
474 'toAddr1': shipping_address.address_line1,
475 'toAddr2': shipping_address.address_line2,
476 'toPlace': shipping_address.city,
477 'transporterName': doc.transporter_name
478 }
479 }
480
481 for allowed_chars, field_map in fields.items():
482 for key, value in field_map.items():
483 if not value:
484 data[key] = ''
485 else:
486 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
487
488 ewaybills.append(data)
489
490 data = {
491 'version': '1.0.1118',
492 'billLists': ewaybills
493 }
494
495 return data
496
497@frappe.whitelist()
498def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530499 dn = json.loads(dn)
500 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530501
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530502@frappe.whitelist()
503def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530504 data = json.loads(frappe.local.form_dict.data)
505 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530506 frappe.local.response.type = 'download'
507
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530508 filename_prefix = 'Bulk'
509 docname = frappe.local.form_dict.docname
510 if docname:
511 if docname.startswith('['):
512 docname = json.loads(docname)
513 if len(docname) == 1:
514 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530515
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530516 if not isinstance(docname, list):
517 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
518 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530519
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530520 frappe.local.response.filename = '{0}_e-WayBill_Data_{1}.json'.format(filename_prefix, frappe.utils.random_string(5))
Nabin Hait34c551d2019-07-03 10:34:31 +0530521
Prasann Shah829172c2019-06-06 12:08:09 +0530522@frappe.whitelist()
523def get_gstins_for_company(company):
524 company_gstins =[]
525 if company:
526 company_gstins = frappe.db.sql("""select
527 distinct `tabAddress`.gstin
528 from
529 `tabAddress`, `tabDynamic Link`
530 where
531 `tabDynamic Link`.parent = `tabAddress`.name and
532 `tabDynamic Link`.parenttype = 'Address' and
533 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300534 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530535 return company_gstins
536
Nabin Hait34c551d2019-07-03 10:34:31 +0530537def get_address_details(data, doc, company_address, billing_address):
538 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
539 data.fromStateCode = data.actualFromStateCode = validate_state_code(
540 company_address.gst_state_number, 'Company Address')
541
542 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
543 data.toGstin = 'URP'
544 set_gst_state_and_state_number(billing_address)
545 else:
546 data.toGstin = doc.billing_address_gstin
547
548 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
549 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
550
551 if doc.customer_address != doc.shipping_address_name:
552 data.transType = 2
553 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
554 set_gst_state_and_state_number(shipping_address)
555 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
556 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
557 else:
558 data.transType = 1
559 data.actualToStateCode = data.toStateCode
560 shipping_address = billing_address
561
Smit Vorabbe49332020-11-18 20:58:59 +0530562 if doc.gst_category == 'SEZ':
563 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530564
565 return data
566
567def get_item_list(data, doc):
568 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
569 data[attr] = 0
570
571 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
572 tax_map = {
573 'sgst_account': ['sgstRate', 'sgstValue'],
574 'cgst_account': ['cgstRate', 'cgstValue'],
575 'igst_account': ['igstRate', 'igstValue'],
576 'cess_account': ['cessRate', 'cessValue']
577 }
578 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
579 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
580 for hsn_code, taxable_amount in hsn_taxable_amount.items():
581 item_data = frappe._dict()
582 if not hsn_code:
583 frappe.throw(_('GST HSN Code does not exist for one or more items'))
584 item_data.hsnCode = int(hsn_code)
585 item_data.taxableAmount = taxable_amount
586 item_data.qtyUnit = ""
587 for attr in item_data_attrs:
588 item_data[attr] = 0
589
590 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
591 account_type = gst_accounts.get(account, '')
592 for tax_acc, attrs in tax_map.items():
593 if account_type == tax_acc:
594 item_data[attrs[0]] = tax_detail.get('tax_rate')
595 data[attrs[1]] += tax_detail.get('tax_amount')
596 break
597 else:
598 data.OthValue += tax_detail.get('tax_amount')
599
600 data.itemList.append(item_data)
601
602 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
603 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
604 data[attr] = flt(data[attr], 2)
605
606 return data
607
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530608def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530609 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530610 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530611
612 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530613 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530614
615 if doc.ewaybill:
616 frappe.throw(_('e-Way Bill already exists for this document'))
617
618 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
619 'shipping_address_name', 'mode_of_transport', 'distance']
620
621 for fieldname in reqd_fields:
622 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530623 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530624 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530625 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530626
627 if len(doc.company_gstin) < 15:
628 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
629
630def get_transport_details(data, doc):
631 if doc.distance > 4000:
632 frappe.throw(_('Distance cannot be greater than 4000 kms'))
633
634 data.transDistance = int(round(doc.distance))
635
636 transport_modes = {
637 'Road': 1,
638 'Rail': 2,
639 'Air': 3,
640 'Ship': 4
641 }
642
643 vehicle_types = {
644 'Regular': 'R',
645 'Over Dimensional Cargo (ODC)': 'O'
646 }
647
648 data.transMode = transport_modes.get(doc.mode_of_transport)
649
650 if doc.mode_of_transport == 'Road':
651 if not doc.gst_transporter_id and not doc.vehicle_no:
652 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
653 if doc.vehicle_no:
654 data.vehicleNo = doc.vehicle_no.replace(' ', '')
655 if not doc.gst_vehicle_type:
656 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
657 else:
658 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
659 else:
660 if not doc.lr_no or not doc.lr_date:
661 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
662
663 if doc.lr_no:
664 data.transDocNo = doc.lr_no
665
666 if doc.lr_date:
667 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
668
669 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530670 if doc.gst_transporter_id[0:2] != "88":
671 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
672 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530673
674 return data
675
676
677def validate_pincode(pincode, address):
678 pin_not_found = "Pin Code doesn't exist for {}"
679 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
680
681 if not pincode:
682 frappe.throw(_(pin_not_found.format(address)))
683
684 pincode = pincode.replace(' ', '')
685 if not pincode.isdigit() or len(pincode) != 6:
686 frappe.throw(_(incorrect_pin.format(address)))
687 else:
688 return int(pincode)
689
690def validate_state_code(state_code, address):
691 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
692 if not state_code:
693 frappe.throw(_(no_state_code.format(address)))
694 else:
695 return int(state_code)
696
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530697@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530698def get_gst_accounts(company, account_wise=False):
699 gst_accounts = frappe._dict()
700 gst_settings_accounts = frappe.get_all("GST Account",
701 filters={"parent": "GST Settings", "company": company},
702 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
703
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530704 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530705 frappe.throw(_("Please set GST Accounts in GST Settings"))
706
707 for d in gst_settings_accounts:
708 for acc, val in d.items():
709 if not account_wise:
710 gst_accounts.setdefault(acc, []).append(val)
711 elif val:
712 gst_accounts[val] = acc
713
Nabin Hait34c551d2019-07-03 10:34:31 +0530714 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530715
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530716def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530717 country = frappe.get_cached_value('Company', doc.company, 'country')
718
719 if country != 'India':
720 return
721
Deepesh Gargc3fb6822020-08-19 18:30:18 +0530722 if not doc.total_taxes_and_charges:
723 return
724
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530725 if doc.reverse_charge == 'Y':
726 gst_accounts = get_gst_accounts(doc.company)
727 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
728 + gst_accounts.get('igst_account')
729
Deepesh Garg1c146062020-08-18 19:32:52 +0530730 base_gst_tax = 0
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530731 gst_tax = 0
Deepesh Garg1c146062020-08-18 19:32:52 +0530732
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530733 for tax in doc.get('taxes'):
734 if tax.category not in ("Total", "Valuation and Total"):
735 continue
736
737 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
Deepesh Garg1c146062020-08-18 19:32:52 +0530738 base_gst_tax += tax.base_tax_amount_after_discount_amount
739 gst_tax += tax.tax_amount_after_discount_amount
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530740
741 doc.taxes_and_charges_added -= gst_tax
742 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530743 doc.base_taxes_and_charges_added -= base_gst_tax
744 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530745
Deepesh Garg1c146062020-08-18 19:32:52 +0530746 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530747
Deepesh Garg1c146062020-08-18 19:32:52 +0530748def update_totals(gst_tax, base_gst_tax, doc):
749 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530750 doc.grand_total -= gst_tax
751
752 if doc.meta.get_field("rounded_total"):
753 if doc.is_rounded_total_disabled():
754 doc.outstanding_amount = doc.grand_total
755 else:
756 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
757 doc.currency, doc.precision("rounded_total"))
758
759 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
760 doc.precision("rounding_adjustment"))
761
Deepesh Garg18827352020-07-17 11:31:15 +0530762 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530763
764 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530765 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530766 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530767
768def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530769 country = frappe.get_cached_value('Company', doc.company, 'country')
770
771 if country != 'India':
Deepesh Gargc3fb6822020-08-19 18:30:18 +0530772 return gl_entries
773
774 if not doc.total_taxes_and_charges:
775 return gl_entries
Deepesh Garg24f9a802020-06-03 10:59:37 +0530776
777 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530778 gst_accounts = get_gst_accounts(doc.company)
779 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
780 + gst_accounts.get('igst_account')
781
782 for tax in doc.get('taxes'):
783 if tax.category not in ("Total", "Valuation and Total"):
784 continue
785
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530786 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530787 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
788 account_currency = get_account_currency(tax.account_head)
789
790 gl_entries.append(doc.get_gl_dict(
791 {
792 "account": tax.account_head,
793 "cost_center": tax.cost_center,
794 "posting_date": doc.posting_date,
795 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530796 dr_or_cr: tax.base_tax_amount_after_discount_amount,
797 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530798 if account_currency==doc.company_currency \
799 else tax.tax_amount_after_discount_amount
800 }, account_currency, item=tax)
801 )
802
Deepesh Gargd07447a2020-11-24 08:09:17 +0530803 return gl_entries
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530804
805@frappe.whitelist()
806def get_regional_round_off_accounts(company, account_list):
807 country = frappe.get_cached_value('Company', company, 'country')
808
809 if country != 'India':
810 return
811
812 if isinstance(account_list, string_types):
813 account_list = json.loads(account_list)
814
815 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
816 return
817
818 gst_accounts = get_gst_accounts(company)
819 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
820 + gst_accounts.get('igst_account')
821
822 account_list.extend(gst_account_list)
823
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530824 return account_list