blob: ddcedd5e4f43a0f25884f4e0fd8054c3fb4284bc [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."""
Rucha Mahabal67177732021-04-01 15:30:34 +0530157
Ankush Menata44df632021-03-01 17:12:53 +0530158 country = frappe.get_cached_value("Company", doc.company, "country")
159
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530160 # Date was chosen as start of next FY to avoid irritating current users.
Ankush Menata44df632021-03-01 17:12:53 +0530161 if country != "India" or getdate(doc.posting_date) < getdate("2021-04-01"):
162 return
163
164 if len(doc.name) > 16:
165 frappe.throw(_("Maximum length of document number should be 16 characters as per GST rules. Please change the naming series."))
166
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530167 if not GST_INVOICE_NUMBER_FORMAT.match(doc.name):
Ankush Menata44df632021-03-01 17:12:53 +0530168 frappe.throw(_("Document name should only contain alphanumeric values, dash(-) and slash(/) characters as per GST rules. Please change the naming series."))
169
Rushabh Mehta7231f292017-07-13 15:00:56 +0530170# don't remove this function it is used in tests
171def test_method():
172 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530173 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530174
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530175def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530176 if not frappe.get_meta('Address').has_field('gst_state'): return
177
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530178 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Deepesh Gargeacfd792020-10-30 22:12:24 +0530179 address_name = party_details.customer_address or party_details.shipping_address_name
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530180 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
181 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530182
183 if address_name:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530184 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number", "gstin"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530185 if address and address.gst_state and address.gst_state_number:
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530186 party_details.gstin = address.gstin
Nabin Hait2390da62018-08-30 16:16:35 +0530187 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530189@frappe.whitelist()
pateljannat1d5d8632020-11-19 20:11:45 +0530190def get_regional_address_details(party_details, doctype, company):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530191 if isinstance(party_details, string_types):
192 party_details = json.loads(party_details)
193 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530194
Deepesh Garga7670852020-12-04 18:07:46 +0530195 update_party_details(party_details, doctype)
196
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530197 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530198
199 if is_internal_transfer(party_details, doctype):
200 party_details.taxes_and_charges = ''
Deepesh Gargb4be2922021-01-28 13:09:56 +0530201 party_details.taxes = []
pateljannatcd05b342020-11-19 11:37:08 +0530202 return party_details
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530203
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530204 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530205 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530206
207 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
208 get_tax_template_based_on_category(master_doctype, company, party_details)
209
pateljannatcd05b342020-11-19 11:37:08 +0530210 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530211 return party_details
212
213 if not party_details.company_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530214 return party_details
Shreya Shah4fa600a2018-06-05 11:27:53 +0530215
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530216 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
217 master_doctype = "Purchase Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530218 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
219 get_tax_template_based_on_category(master_doctype, company, party_details)
220
pateljannatcd05b342020-11-19 11:37:08 +0530221 if party_details.get('taxes_and_charges'):
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530222 return party_details
223
224 if not party_details.supplier_gstin:
pateljannatcd05b342020-11-19 11:37:08 +0530225 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530226
pateljannatcd05b342020-11-19 11:37:08 +0530227 if not party_details.place_of_supply: return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530228
pateljannatcd05b342020-11-19 11:37:08 +0530229 if not party_details.company_gstin: return party_details
deepeshgarg007c58dc872019-12-12 14:55:57 +0530230
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530231 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
232 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
233 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
234 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530235 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530236 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530237
238 if not default_tax:
pateljannatcd05b342020-11-19 11:37:08 +0530239 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530240 party_details["taxes_and_charges"] = default_tax
241 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
242
pateljannatcd05b342020-11-19 11:37:08 +0530243 return party_details
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530244
Deepesh Garga7670852020-12-04 18:07:46 +0530245def update_party_details(party_details, doctype):
246 for address_field in ['shipping_address', 'company_address', 'supplier_address', 'shipping_address_name', 'customer_address']:
247 if party_details.get(address_field):
248 party_details.update(get_fetch_values(doctype, address_field, party_details.get(address_field)))
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530249
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530250def is_internal_transfer(party_details, doctype):
251 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
252 destination_gstin = party_details.company_gstin
253 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
254 destination_gstin = party_details.supplier_gstin
255
256 if party_details.gstin == destination_gstin:
257 return True
258 else:
259 False
260
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530261def get_tax_template_based_on_category(master_doctype, company, party_details):
262 if not party_details.get('tax_category'):
263 return
264
265 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
266 'name')
267
268 if default_tax:
269 party_details["taxes_and_charges"] = default_tax
270 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
271
272def get_tax_template(master_doctype, company, is_inter_state, state_code):
273 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
274 filters = {'is_inter_state': is_inter_state})
275
276 default_tax = ''
277
278 for tax_category in tax_categories:
279 if tax_category.gst_state == number_state_mapping[state_code] or \
280 (not default_tax and not tax_category.gst_state):
281 default_tax = frappe.db.get_value(master_doctype,
Deepesh Garg59ccb642020-11-05 16:29:34 +0530282 {'company': company, 'disabled': 0, 'tax_category': tax_category.name}, 'name')
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530283 return default_tax
284
285def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
286
287 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
288 ['gst_category', 'export_type'], as_dict=1)
289
290 if gst_details:
291 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
292 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
293 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
294
295 party_details["taxes_and_charges"] = default_tax
296 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
297
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530298
299def calculate_annual_eligible_hra_exemption(doc):
Nabin Hait10df3d52020-05-14 17:15:16 +0530300 basic_component, hra_component = frappe.db.get_value('Company', doc.company, ["basic_component", "hra_component"])
Nabin Hait04e7bf42019-04-25 18:44:10 +0530301 if not (basic_component and hra_component):
302 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530303 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530304 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530305 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530306 if assignment:
307 hra_component_exists = frappe.db.exists("Salary Detail", {
308 "parent": assignment.salary_structure,
309 "salary_component": hra_component,
310 "parentfield": "earnings",
311 "parenttype": "Salary Structure"
312 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530313
Nabin Hait04e7bf42019-04-25 18:44:10 +0530314 if hra_component_exists:
315 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
316 assignment.salary_structure, basic_component, hra_component)
317 if hra_amount:
318 if doc.monthly_house_rent:
319 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530320 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530321 if annual_exemption > 0:
322 monthly_exemption = annual_exemption / 12
323 else:
324 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530325
Nabin Hait04e7bf42019-04-25 18:44:10 +0530326 elif doc.docstatus == 1:
327 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
328
329 return frappe._dict({
330 "hra_amount": hra_amount,
331 "annual_exemption": annual_exemption,
332 "monthly_exemption": monthly_exemption
333 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530334
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530335def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Anurag Mishra33793d42020-04-29 11:48:41 +0530336 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1, ignore_permissions=True)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530337 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530339 if earning.salary_component == basic_component:
340 basic_amt = earning.amount
341 elif earning.salary_component == hra_component:
342 hra_amt = earning.amount
343 if basic_amt and hra_amt:
344 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530345 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530346
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530347def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530348 # TODO make this configurable
349 exemptions = []
350 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
351 # case 1: The actual amount allotted by the employer as the HRA.
352 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530353
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530354 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530355 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530356
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530357 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530358 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530359 # 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 +0530360 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530361 # return minimum of 3 cases
362 return min(exemptions)
363
364def get_annual_component_pay(frequency, amount):
365 if frequency == "Daily":
366 return amount * 365
367 elif frequency == "Weekly":
368 return amount * 52
369 elif frequency == "Fortnightly":
370 return amount * 26
371 elif frequency == "Monthly":
372 return amount * 12
373 elif frequency == "Bimonthly":
374 return amount * 6
375
376def validate_house_rent_dates(doc):
377 if not doc.rented_to_date or not doc.rented_from_date:
378 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530379
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530380 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
381 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530382
383 proofs = frappe.db.sql("""
384 select name
385 from `tabEmployee Tax Exemption Proof Submission`
386 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530387 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
388 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
389 """, {
390 "employee": doc.employee,
391 "payroll_period": doc.payroll_period,
392 "from_date": doc.rented_from_date,
393 "to_date": doc.rented_to_date
394 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530395
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530396 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530397 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530398
399def calculate_hra_exemption_for_period(doc):
400 monthly_rent, eligible_hra = 0, 0
401 if doc.house_rent_payment_amount:
402 validate_house_rent_dates(doc)
403 # TODO receive rented months or validate dates are start and end of months?
404 # Calc monthly rent, round to nearest .5
405 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
406 factor = round(factor * 2)/2
407 monthly_rent = doc.house_rent_payment_amount / factor
408 # update field used by calculate_annual_eligible_hra_exemption
409 doc.monthly_house_rent = monthly_rent
410 exemptions = calculate_annual_eligible_hra_exemption(doc)
411
412 if exemptions["monthly_exemption"]:
413 # calc total exemption amount
414 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530415 exemptions["monthly_house_rent"] = monthly_rent
416 exemptions["total_eligible_hra_exemption"] = eligible_hra
417 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530418
Nabin Hait34c551d2019-07-03 10:34:31 +0530419def get_ewb_data(dt, dn):
Nabin Hait34c551d2019-07-03 10:34:31 +0530420
421 ewaybills = []
422 for doc_name in dn:
423 doc = frappe.get_doc(dt, doc_name)
424
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530425 validate_doc(doc)
Nabin Hait34c551d2019-07-03 10:34:31 +0530426
427 data = frappe._dict({
428 "transporterId": "",
429 "TotNonAdvolVal": 0,
430 })
431
432 data.userGstin = data.fromGstin = doc.company_gstin
433 data.supplyType = 'O'
434
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530435 if dt == 'Delivery Note':
436 data.subSupplyType = 1
437 elif doc.gst_category in ['Registered Regular', 'SEZ']:
Nabin Hait34c551d2019-07-03 10:34:31 +0530438 data.subSupplyType = 1
439 elif doc.gst_category in ['Overseas', 'Deemed Export']:
440 data.subSupplyType = 3
441 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530442 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530443
444 data.docType = 'INV'
445 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
446
447 company_address = frappe.get_doc('Address', doc.company_address)
448 billing_address = frappe.get_doc('Address', doc.customer_address)
449
450 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
451
452 data = get_address_details(data, doc, company_address, billing_address)
453
454 data.itemList = []
455 data.totalValue = doc.total
456
457 data = get_item_list(data, doc)
458
459 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
460 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
461
462 data = get_transport_details(data, doc)
463
464 fields = {
465 "/. -": {
466 'docNo': doc.name,
467 'fromTrdName': doc.company,
468 'toTrdName': doc.customer_name,
469 'transDocNo': doc.lr_no,
470 },
471 "@#/,&. -": {
472 'fromAddr1': company_address.address_line1,
473 'fromAddr2': company_address.address_line2,
474 'fromPlace': company_address.city,
475 'toAddr1': shipping_address.address_line1,
476 'toAddr2': shipping_address.address_line2,
477 'toPlace': shipping_address.city,
478 'transporterName': doc.transporter_name
479 }
480 }
481
482 for allowed_chars, field_map in fields.items():
483 for key, value in field_map.items():
484 if not value:
485 data[key] = ''
486 else:
487 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
488
489 ewaybills.append(data)
490
491 data = {
492 'version': '1.0.1118',
493 'billLists': ewaybills
494 }
495
496 return data
497
498@frappe.whitelist()
499def generate_ewb_json(dt, dn):
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530500 dn = json.loads(dn)
501 return get_ewb_data(dt, dn)
Nabin Hait34c551d2019-07-03 10:34:31 +0530502
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530503@frappe.whitelist()
504def download_ewb_json():
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530505 data = json.loads(frappe.local.form_dict.data)
506 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
Nabin Hait34c551d2019-07-03 10:34:31 +0530507 frappe.local.response.type = 'download'
508
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530509 filename_prefix = 'Bulk'
510 docname = frappe.local.form_dict.docname
511 if docname:
512 if docname.startswith('['):
513 docname = json.loads(docname)
514 if len(docname) == 1:
515 docname = docname[0]
Deepesh Garg00ea59b2020-04-27 10:50:40 +0530516
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530517 if not isinstance(docname, list):
518 # removes characters not allowed in a filename (https://stackoverflow.com/a/38766141/4767738)
519 filename_prefix = re.sub('[^\w_.)( -]', '', docname)
Nabin Hait34c551d2019-07-03 10:34:31 +0530520
Sagar Vorac9b4ba62020-07-11 17:44:20 +0530521 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 +0530522
Prasann Shah829172c2019-06-06 12:08:09 +0530523@frappe.whitelist()
524def get_gstins_for_company(company):
525 company_gstins =[]
526 if company:
527 company_gstins = frappe.db.sql("""select
528 distinct `tabAddress`.gstin
529 from
530 `tabAddress`, `tabDynamic Link`
531 where
532 `tabDynamic Link`.parent = `tabAddress`.name and
533 `tabDynamic Link`.parenttype = 'Address' and
534 `tabDynamic Link`.link_doctype = 'Company' and
Don-Leopardo2b6a20a2020-03-16 14:06:44 -0300535 `tabDynamic Link`.link_name = %(company)s""", {"company": company})
Prasann Shah829172c2019-06-06 12:08:09 +0530536 return company_gstins
537
Nabin Hait34c551d2019-07-03 10:34:31 +0530538def get_address_details(data, doc, company_address, billing_address):
539 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
540 data.fromStateCode = data.actualFromStateCode = validate_state_code(
541 company_address.gst_state_number, 'Company Address')
542
543 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
544 data.toGstin = 'URP'
545 set_gst_state_and_state_number(billing_address)
546 else:
547 data.toGstin = doc.billing_address_gstin
548
549 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
550 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
551
552 if doc.customer_address != doc.shipping_address_name:
553 data.transType = 2
554 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
555 set_gst_state_and_state_number(shipping_address)
556 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
557 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
558 else:
559 data.transType = 1
560 data.actualToStateCode = data.toStateCode
561 shipping_address = billing_address
562
Smit Vorabbe49332020-11-18 20:58:59 +0530563 if doc.gst_category == 'SEZ':
564 data.toStateCode = 99
Nabin Hait34c551d2019-07-03 10:34:31 +0530565
566 return data
567
568def get_item_list(data, doc):
569 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
570 data[attr] = 0
571
572 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
573 tax_map = {
574 'sgst_account': ['sgstRate', 'sgstValue'],
575 'cgst_account': ['cgstRate', 'cgstValue'],
576 'igst_account': ['igstRate', 'igstValue'],
577 'cess_account': ['cessRate', 'cessValue']
578 }
579 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
580 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
581 for hsn_code, taxable_amount in hsn_taxable_amount.items():
582 item_data = frappe._dict()
583 if not hsn_code:
584 frappe.throw(_('GST HSN Code does not exist for one or more items'))
585 item_data.hsnCode = int(hsn_code)
586 item_data.taxableAmount = taxable_amount
587 item_data.qtyUnit = ""
588 for attr in item_data_attrs:
589 item_data[attr] = 0
590
591 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
592 account_type = gst_accounts.get(account, '')
593 for tax_acc, attrs in tax_map.items():
594 if account_type == tax_acc:
595 item_data[attrs[0]] = tax_detail.get('tax_rate')
596 data[attrs[1]] += tax_detail.get('tax_amount')
597 break
598 else:
599 data.OthValue += tax_detail.get('tax_amount')
600
601 data.itemList.append(item_data)
602
603 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
604 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
605 data[attr] = flt(data[attr], 2)
606
607 return data
608
Deepesh Garg15ff6a52020-02-18 12:28:41 +0530609def validate_doc(doc):
Nabin Hait34c551d2019-07-03 10:34:31 +0530610 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530611 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530612
613 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530614 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530615
616 if doc.ewaybill:
617 frappe.throw(_('e-Way Bill already exists for this document'))
618
619 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
620 'shipping_address_name', 'mode_of_transport', 'distance']
621
622 for fieldname in reqd_fields:
623 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530624 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530625 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530626 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530627
628 if len(doc.company_gstin) < 15:
629 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
630
631def get_transport_details(data, doc):
632 if doc.distance > 4000:
633 frappe.throw(_('Distance cannot be greater than 4000 kms'))
634
635 data.transDistance = int(round(doc.distance))
636
637 transport_modes = {
638 'Road': 1,
639 'Rail': 2,
640 'Air': 3,
641 'Ship': 4
642 }
643
644 vehicle_types = {
645 'Regular': 'R',
646 'Over Dimensional Cargo (ODC)': 'O'
647 }
648
649 data.transMode = transport_modes.get(doc.mode_of_transport)
650
651 if doc.mode_of_transport == 'Road':
652 if not doc.gst_transporter_id and not doc.vehicle_no:
653 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
654 if doc.vehicle_no:
655 data.vehicleNo = doc.vehicle_no.replace(' ', '')
656 if not doc.gst_vehicle_type:
657 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
658 else:
659 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
660 else:
661 if not doc.lr_no or not doc.lr_date:
662 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
663
664 if doc.lr_no:
665 data.transDocNo = doc.lr_no
666
667 if doc.lr_date:
668 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
669
670 if doc.gst_transporter_id:
karthikeyan5ca46bed2020-05-30 15:00:56 +0530671 if doc.gst_transporter_id[0:2] != "88":
672 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
673 data.transporterId = doc.gst_transporter_id
Nabin Hait34c551d2019-07-03 10:34:31 +0530674
675 return data
676
677
678def validate_pincode(pincode, address):
679 pin_not_found = "Pin Code doesn't exist for {}"
680 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
681
682 if not pincode:
683 frappe.throw(_(pin_not_found.format(address)))
684
685 pincode = pincode.replace(' ', '')
686 if not pincode.isdigit() or len(pincode) != 6:
687 frappe.throw(_(incorrect_pin.format(address)))
688 else:
689 return int(pincode)
690
691def validate_state_code(state_code, address):
692 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
693 if not state_code:
694 frappe.throw(_(no_state_code.format(address)))
695 else:
696 return int(state_code)
697
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530698@frappe.whitelist()
Nabin Hait34c551d2019-07-03 10:34:31 +0530699def get_gst_accounts(company, account_wise=False):
700 gst_accounts = frappe._dict()
701 gst_settings_accounts = frappe.get_all("GST Account",
702 filters={"parent": "GST Settings", "company": company},
703 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
704
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530705 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530706 frappe.throw(_("Please set GST Accounts in GST Settings"))
707
708 for d in gst_settings_accounts:
709 for acc, val in d.items():
710 if not account_wise:
711 gst_accounts.setdefault(acc, []).append(val)
712 elif val:
713 gst_accounts[val] = acc
714
Nabin Hait34c551d2019-07-03 10:34:31 +0530715 return gst_accounts
Deepesh Garg24f9a802020-06-03 10:59:37 +0530716
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530717def update_grand_total_for_rcm(doc, method):
Deepesh Garg52c319c2020-07-15 23:57:03 +0530718 country = frappe.get_cached_value('Company', doc.company, 'country')
719
720 if country != 'India':
721 return
722
Deepesh Garg7f2e45e2021-03-15 18:04:47 +0530723 gst_tax, base_gst_tax = get_gst_tax_amount(doc)
724
725 if not base_gst_tax:
Deepesh Gargc3fb6822020-08-19 18:30:18 +0530726 return
727
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530728 if doc.reverse_charge == 'Y':
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530729 doc.taxes_and_charges_added -= gst_tax
730 doc.total_taxes_and_charges -= gst_tax
Deepesh Garg1c146062020-08-18 19:32:52 +0530731 doc.base_taxes_and_charges_added -= base_gst_tax
732 doc.base_total_taxes_and_charges -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530733
Deepesh Garg1c146062020-08-18 19:32:52 +0530734 update_totals(gst_tax, base_gst_tax, doc)
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530735
Deepesh Garg1c146062020-08-18 19:32:52 +0530736def update_totals(gst_tax, base_gst_tax, doc):
737 doc.base_grand_total -= base_gst_tax
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530738 doc.grand_total -= gst_tax
739
740 if doc.meta.get_field("rounded_total"):
741 if doc.is_rounded_total_disabled():
742 doc.outstanding_amount = doc.grand_total
743 else:
744 doc.rounded_total = round_based_on_smallest_currency_fraction(doc.grand_total,
745 doc.currency, doc.precision("rounded_total"))
746
747 doc.rounding_adjustment += flt(doc.rounded_total - doc.grand_total,
748 doc.precision("rounding_adjustment"))
749
Deepesh Garg18827352020-07-17 11:31:15 +0530750 doc.outstanding_amount = doc.rounded_total or doc.grand_total
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530751
752 doc.in_words = money_in_words(doc.grand_total, doc.currency)
Deepesh Garg1c146062020-08-18 19:32:52 +0530753 doc.base_in_words = money_in_words(doc.base_grand_total, erpnext.get_company_currency(doc.company))
Deepesh Garg18827352020-07-17 11:31:15 +0530754 doc.set_payment_schedule()
Deepesh Garg3c004ad2020-07-02 21:18:29 +0530755
756def make_regional_gl_entries(gl_entries, doc):
Deepesh Garg24f9a802020-06-03 10:59:37 +0530757 country = frappe.get_cached_value('Company', doc.company, 'country')
758
759 if country != 'India':
Deepesh Gargc3fb6822020-08-19 18:30:18 +0530760 return gl_entries
761
Deepesh Garg7f2e45e2021-03-15 18:04:47 +0530762 gst_tax, base_gst_tax = get_gst_tax_amount(doc)
763
764 if not base_gst_tax:
Deepesh Gargc3fb6822020-08-19 18:30:18 +0530765 return gl_entries
Deepesh Garg24f9a802020-06-03 10:59:37 +0530766
767 if doc.reverse_charge == 'Y':
Deepesh Garg24f9a802020-06-03 10:59:37 +0530768 gst_accounts = get_gst_accounts(doc.company)
769 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
770 + gst_accounts.get('igst_account')
771
772 for tax in doc.get('taxes'):
773 if tax.category not in ("Total", "Valuation and Total"):
774 continue
775
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530776 dr_or_cr = "credit" if tax.add_deduct_tax == "Add" else "debit"
Deepesh Garg24f9a802020-06-03 10:59:37 +0530777 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
778 account_currency = get_account_currency(tax.account_head)
779
780 gl_entries.append(doc.get_gl_dict(
781 {
782 "account": tax.account_head,
783 "cost_center": tax.cost_center,
784 "posting_date": doc.posting_date,
785 "against": doc.supplier,
Deepesh Gargafd2dd32020-08-20 16:31:38 +0530786 dr_or_cr: tax.base_tax_amount_after_discount_amount,
787 dr_or_cr + "_in_account_currency": tax.base_tax_amount_after_discount_amount \
Deepesh Garg24f9a802020-06-03 10:59:37 +0530788 if account_currency==doc.company_currency \
789 else tax.tax_amount_after_discount_amount
790 }, account_currency, item=tax)
791 )
792
Deepesh Gargd07447a2020-11-24 08:09:17 +0530793 return gl_entries
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530794
Deepesh Garg635c4802021-03-16 13:09:59 +0530795def get_gst_tax_amount(doc):
796 gst_accounts = get_gst_accounts(doc.company)
797 gst_account_list = gst_accounts.get('cgst_account', []) + gst_accounts.get('sgst_account', []) \
798 + gst_accounts.get('igst_account', [])
799
800 base_gst_tax = 0
801 gst_tax = 0
802
803 for tax in doc.get('taxes'):
804 if tax.category not in ("Total", "Valuation and Total"):
805 continue
806
807 if flt(tax.base_tax_amount_after_discount_amount) and tax.account_head in gst_account_list:
808 base_gst_tax += tax.base_tax_amount_after_discount_amount
809 gst_tax += tax.tax_amount_after_discount_amount
810
811 return gst_tax, base_gst_tax
812
Deepesh Garg6a5ef262021-02-19 14:30:23 +0530813@frappe.whitelist()
814def get_regional_round_off_accounts(company, account_list):
815 country = frappe.get_cached_value('Company', company, 'country')
816
817 if country != 'India':
818 return
819
820 if isinstance(account_list, string_types):
821 account_list = json.loads(account_list)
822
823 if not frappe.db.get_single_value('GST Settings', 'round_off_gst_values'):
824 return
825
826 gst_accounts = get_gst_accounts(company)
827 gst_account_list = gst_accounts.get('cgst_account') + gst_accounts.get('sgst_account') \
828 + gst_accounts.get('igst_account')
829
830 account_list.extend(gst_account_list)
831
Ankush Menat7c4c42a2021-03-03 14:56:19 +0530832 return account_list