blob: 266affb6d033b46095261639ee5a0fa7b11253f4 [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 _
Nabin Hait49446ba2019-04-25 19:54:20 +05304from frappe.utils import cstr, flt, date_diff, nowdate
Rushabh Mehtab3c8f442017-06-21 17:22:38 +05305from erpnext.regional.india import states, state_numbers
Nabin Haitb962fc12017-07-17 18:02:31 +05306from erpnext.controllers.taxes_and_totals import get_itemised_tax, get_itemised_taxable_amount
Shreya Shah4fa600a2018-06-05 11:27:53 +05307from erpnext.controllers.accounts_controller import get_taxes_and_charges
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +05308from erpnext.hr.utils import get_salary_assignment
9from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053010from erpnext.regional.india import number_state_mapping
11from six import string_types
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053012
13def validate_gstin_for_india(doc, method):
rushin2908a209b2019-03-15 15:28:50 +053014 if hasattr(doc, 'gst_state') and doc.gst_state:
15 doc.gst_state_number = state_numbers[doc.gst_state]
FinByz Tech Pvt. Ltd237a8712019-01-22 20:49:06 +053016 if not hasattr(doc, 'gstin') or not doc.gstin:
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053017 return
18
Deepesh Garg459155f2019-06-14 12:01:34 +053019 gst_category = []
20
21 if len(doc.links):
22 link_doctype = doc.links[0].get("link_doctype")
23 link_name = doc.links[0].get("link_name")
24
25 if link_doctype in ["Customer", "Supplier"]:
26 gst_category = frappe.db.get_value(link_doctype, {'name': link_name}, ['gst_category'])
27
Sagar Vorad75095b2019-01-23 14:40:01 +053028 doc.gstin = doc.gstin.upper().strip()
Sagar Vora07cf4e82019-01-10 11:07:51 +053029 if not doc.gstin or doc.gstin == 'NA':
30 return
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053031
Sagar Vora07cf4e82019-01-10 11:07:51 +053032 if len(doc.gstin) != 15:
33 frappe.throw(_("Invalid GSTIN! A GSTIN must have 15 characters."))
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053034
Deepesh Garg459155f2019-06-14 12:01:34 +053035 if gst_category and gst_category == 'UIN Holders':
36 p = re.compile("^[0-9]{4}[A-Z]{3}[0-9]{5}[0-9A-Z]{3}")
37 if not p.match(doc.gstin):
38 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the GSTIN format for UIN Holders or Non-Resident OIDAR Service Providers"))
39 else:
40 p = 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}$")
41 if not p.match(doc.gstin):
42 frappe.throw(_("Invalid GSTIN! The input you've entered doesn't match the format of GSTIN."))
Rushabh Mehta7231f292017-07-13 15:00:56 +053043
Deepesh Garg459155f2019-06-14 12:01:34 +053044 validate_gstin_check_digit(doc.gstin)
Nabin Hait34c551d2019-07-03 10:34:31 +053045 set_gst_state_and_state_number(doc)
Rushabh Mehtab3c8f442017-06-21 17:22:38 +053046
Deepesh Garg459155f2019-06-14 12:01:34 +053047 if doc.gst_state_number != doc.gstin[:2]:
48 frappe.throw(_("Invalid GSTIN! First 2 digits of GSTIN should match with State number {0}.")
49 .format(doc.gst_state_number))
Sagar Vora07cf4e82019-01-10 11:07:51 +053050
Deepesh Garg6e2c13f2019-12-10 15:55:05 +053051def update_gst_category(doc, method):
52 for link in doc.links:
53 if link.link_doctype in ['Customer', 'Supplier']:
54 if doc.get('gstin'):
55 frappe.db.sql("""
56 UPDATE `tab{0}` SET gst_category = %s WHERE name = %s AND gst_category = 'Unregistered'
57 """.format(link.link_doctype), ("Registered Regular", link.link_name)) #nosec
58
Nabin Hait34c551d2019-07-03 10:34:31 +053059def set_gst_state_and_state_number(doc):
60 if not doc.gst_state:
61 if not doc.state:
62 return
63 state = doc.state.lower()
64 states_lowercase = {s.lower():s for s in states}
65 if state in states_lowercase:
66 doc.gst_state = states_lowercase[state]
67 else:
68 return
69
70 doc.gst_state_number = state_numbers[doc.gst_state]
71
72def validate_gstin_check_digit(gstin, label='GSTIN'):
Sagar Vora07cf4e82019-01-10 11:07:51 +053073 ''' Function to validate the check digit of the GSTIN.'''
karthikeyan52825b922019-01-09 19:15:10 +053074 factor = 1
75 total = 0
76 code_point_chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ'
karthikeyan52825b922019-01-09 19:15:10 +053077 mod = len(code_point_chars)
Sagar Vora07cf4e82019-01-10 11:07:51 +053078 input_chars = gstin[:-1]
karthikeyan52825b922019-01-09 19:15:10 +053079 for char in input_chars:
80 digit = factor * code_point_chars.find(char)
Sagar Vora07cf4e82019-01-10 11:07:51 +053081 digit = (digit // mod) + (digit % mod)
karthikeyan52825b922019-01-09 19:15:10 +053082 total += digit
83 factor = 2 if factor == 1 else 1
Sagar Vora07cf4e82019-01-10 11:07:51 +053084 if gstin[-1] != code_point_chars[((mod - (total % mod)) % mod)]:
deepeshgarg00762fbf372019-11-07 21:54:25 +053085 frappe.throw(_("""Invalid {0}! The check digit validation has failed.
86 Please ensure you've typed the {0} correctly.""".format(label)))
Rushabh Mehta7231f292017-07-13 15:00:56 +053087
Nabin Haitb962fc12017-07-17 18:02:31 +053088def get_itemised_tax_breakup_header(item_doctype, tax_accounts):
89 if frappe.get_meta(item_doctype).has_field('gst_hsn_code'):
90 return [_("HSN/SAC"), _("Taxable Amount")] + tax_accounts
91 else:
92 return [_("Item"), _("Taxable Amount")] + tax_accounts
Nabin Haitb95ecd72018-02-16 13:19:04 +053093
Nabin Hait34c551d2019-07-03 10:34:31 +053094def get_itemised_tax_breakup_data(doc, account_wise=False):
95 itemised_tax = get_itemised_tax(doc.taxes, with_tax_account=account_wise)
Nabin Haitb962fc12017-07-17 18:02:31 +053096
97 itemised_taxable_amount = get_itemised_taxable_amount(doc.items)
Nabin Haitb95ecd72018-02-16 13:19:04 +053098
Nabin Haitb962fc12017-07-17 18:02:31 +053099 if not frappe.get_meta(doc.doctype + " Item").has_field('gst_hsn_code'):
100 return itemised_tax, itemised_taxable_amount
101
102 item_hsn_map = frappe._dict()
103 for d in doc.items:
104 item_hsn_map.setdefault(d.item_code or d.item_name, d.get("gst_hsn_code"))
105
106 hsn_tax = {}
107 for item, taxes in itemised_tax.items():
108 hsn_code = item_hsn_map.get(item)
109 hsn_tax.setdefault(hsn_code, frappe._dict())
Nabin Hait34c551d2019-07-03 10:34:31 +0530110 for tax_desc, tax_detail in taxes.items():
111 key = tax_desc
112 if account_wise:
113 key = tax_detail.get('tax_account')
114 hsn_tax[hsn_code].setdefault(key, {"tax_rate": 0, "tax_amount": 0})
115 hsn_tax[hsn_code][key]["tax_rate"] = tax_detail.get("tax_rate")
116 hsn_tax[hsn_code][key]["tax_amount"] += tax_detail.get("tax_amount")
Nabin Haitb962fc12017-07-17 18:02:31 +0530117
118 # set taxable amount
119 hsn_taxable_amount = frappe._dict()
Nabin Hait34c551d2019-07-03 10:34:31 +0530120 for item in itemised_taxable_amount:
Nabin Haitb962fc12017-07-17 18:02:31 +0530121 hsn_code = item_hsn_map.get(item)
122 hsn_taxable_amount.setdefault(hsn_code, 0)
123 hsn_taxable_amount[hsn_code] += itemised_taxable_amount.get(item)
124
125 return hsn_tax, hsn_taxable_amount
126
Shreya Shah4fa600a2018-06-05 11:27:53 +0530127def set_place_of_supply(doc, method=None):
128 doc.place_of_supply = get_place_of_supply(doc, doc.doctype)
Nabin Haitb95ecd72018-02-16 13:19:04 +0530129
Rushabh Mehta7231f292017-07-13 15:00:56 +0530130# don't remove this function it is used in tests
131def test_method():
132 '''test function'''
Nabin Haitb95ecd72018-02-16 13:19:04 +0530133 return 'overridden'
Shreya Shah4fa600a2018-06-05 11:27:53 +0530134
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530135def get_place_of_supply(party_details, doctype):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530136 if not frappe.get_meta('Address').has_field('gst_state'): return
137
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530138 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
139 address_name = party_details.shipping_address_name or party_details.customer_address
140 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
141 address_name = party_details.shipping_address or party_details.supplier_address
Shreya Shah4fa600a2018-06-05 11:27:53 +0530142
143 if address_name:
144 address = frappe.db.get_value("Address", address_name, ["gst_state", "gst_state_number"], as_dict=1)
Rohit Waghchaureb6a735e2018-10-11 10:40:34 +0530145 if address and address.gst_state and address.gst_state_number:
Nabin Hait2390da62018-08-30 16:16:35 +0530146 return cstr(address.gst_state_number) + "-" + cstr(address.gst_state)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530147
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530148@frappe.whitelist()
149def get_regional_address_details(party_details, doctype, company, return_taxes=None):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530150
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530151 if isinstance(party_details, string_types):
152 party_details = json.loads(party_details)
153 party_details = frappe._dict(party_details)
Shreya Shah4fa600a2018-06-05 11:27:53 +0530154
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530155 party_details.place_of_supply = get_place_of_supply(party_details, doctype)
156 if doctype in ("Sales Invoice", "Delivery Note", "Sales Order"):
Shreya Shah4fa600a2018-06-05 11:27:53 +0530157 master_doctype = "Sales Taxes and Charges Template"
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530158
159 get_tax_template_for_sez(party_details, master_doctype, company, 'Customer')
160 get_tax_template_based_on_category(master_doctype, company, party_details)
161
162 if party_details.get('taxes_and_charges') and return_taxes:
163 return party_details
164
165 if not party_details.company_gstin:
Shreya Shah4fa600a2018-06-05 11:27:53 +0530166 return
167
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530168 elif doctype in ("Purchase Invoice", "Purchase Order", "Purchase Receipt"):
169 master_doctype = "Purchase Taxes and Charges Template"
170
171 get_tax_template_for_sez(party_details, master_doctype, company, 'Supplier')
172 get_tax_template_based_on_category(master_doctype, company, party_details)
173
174 if party_details.get('taxes_and_charges') and return_taxes:
175 return party_details
176
177 if not party_details.supplier_gstin:
178 return
179
180 if not party_details.place_of_supply: return
181
deepeshgarg007c58dc872019-12-12 14:55:57 +0530182 if not party_details.company_gstin: return
183
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530184 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
185 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
186 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
187 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530189 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530190
191 if not default_tax:
192 return
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530193 party_details["taxes_and_charges"] = default_tax
194 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
195
196 if return_taxes:
197 return party_details
198
199def get_tax_template_based_on_category(master_doctype, company, party_details):
200 if not party_details.get('tax_category'):
201 return
202
203 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
204 'name')
205
206 if default_tax:
207 party_details["taxes_and_charges"] = default_tax
208 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
209
210def get_tax_template(master_doctype, company, is_inter_state, state_code):
211 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
212 filters = {'is_inter_state': is_inter_state})
213
214 default_tax = ''
215
216 for tax_category in tax_categories:
217 if tax_category.gst_state == number_state_mapping[state_code] or \
218 (not default_tax and not tax_category.gst_state):
219 default_tax = frappe.db.get_value(master_doctype,
220 {'disabled': 0, 'tax_category': tax_category.name}, 'name')
221
222 return default_tax
223
224def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
225
226 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
227 ['gst_category', 'export_type'], as_dict=1)
228
229 if gst_details:
230 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
231 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
232 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
233
234 party_details["taxes_and_charges"] = default_tax
235 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
236
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530237
238def calculate_annual_eligible_hra_exemption(doc):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530239 basic_component = frappe.get_cached_value('Company', doc.company, "basic_component")
240 hra_component = frappe.get_cached_value('Company', doc.company, "hra_component")
Nabin Hait04e7bf42019-04-25 18:44:10 +0530241 if not (basic_component and hra_component):
242 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530243 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530244 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530245 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530246 if assignment:
247 hra_component_exists = frappe.db.exists("Salary Detail", {
248 "parent": assignment.salary_structure,
249 "salary_component": hra_component,
250 "parentfield": "earnings",
251 "parenttype": "Salary Structure"
252 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530253
Nabin Hait04e7bf42019-04-25 18:44:10 +0530254 if hra_component_exists:
255 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
256 assignment.salary_structure, basic_component, hra_component)
257 if hra_amount:
258 if doc.monthly_house_rent:
259 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530260 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530261 if annual_exemption > 0:
262 monthly_exemption = annual_exemption / 12
263 else:
264 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530265
Nabin Hait04e7bf42019-04-25 18:44:10 +0530266 elif doc.docstatus == 1:
267 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
268
269 return frappe._dict({
270 "hra_amount": hra_amount,
271 "annual_exemption": annual_exemption,
272 "monthly_exemption": monthly_exemption
273 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530274
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530275def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530276 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530277 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530278 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530279 if earning.salary_component == basic_component:
280 basic_amt = earning.amount
281 elif earning.salary_component == hra_component:
282 hra_amt = earning.amount
283 if basic_amt and hra_amt:
284 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530285 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530286
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530287def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530288 # TODO make this configurable
289 exemptions = []
290 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
291 # case 1: The actual amount allotted by the employer as the HRA.
292 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530293
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530294 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530295 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530296
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530297 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530298 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530299 # 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 +0530300 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530301 # return minimum of 3 cases
302 return min(exemptions)
303
304def get_annual_component_pay(frequency, amount):
305 if frequency == "Daily":
306 return amount * 365
307 elif frequency == "Weekly":
308 return amount * 52
309 elif frequency == "Fortnightly":
310 return amount * 26
311 elif frequency == "Monthly":
312 return amount * 12
313 elif frequency == "Bimonthly":
314 return amount * 6
315
316def validate_house_rent_dates(doc):
317 if not doc.rented_to_date or not doc.rented_from_date:
318 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530319
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530320 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
321 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530322
323 proofs = frappe.db.sql("""
324 select name
325 from `tabEmployee Tax Exemption Proof Submission`
326 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530327 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
328 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
329 """, {
330 "employee": doc.employee,
331 "payroll_period": doc.payroll_period,
332 "from_date": doc.rented_from_date,
333 "to_date": doc.rented_to_date
334 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530335
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530336 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530337 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530338
339def calculate_hra_exemption_for_period(doc):
340 monthly_rent, eligible_hra = 0, 0
341 if doc.house_rent_payment_amount:
342 validate_house_rent_dates(doc)
343 # TODO receive rented months or validate dates are start and end of months?
344 # Calc monthly rent, round to nearest .5
345 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
346 factor = round(factor * 2)/2
347 monthly_rent = doc.house_rent_payment_amount / factor
348 # update field used by calculate_annual_eligible_hra_exemption
349 doc.monthly_house_rent = monthly_rent
350 exemptions = calculate_annual_eligible_hra_exemption(doc)
351
352 if exemptions["monthly_exemption"]:
353 # calc total exemption amount
354 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530355 exemptions["monthly_house_rent"] = monthly_rent
356 exemptions["total_eligible_hra_exemption"] = eligible_hra
357 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530358
Nabin Hait34c551d2019-07-03 10:34:31 +0530359def get_ewb_data(dt, dn):
360 if dt != 'Sales Invoice':
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530361 frappe.throw(_('E-Way Bill JSON can only be generated from Sales Invoice'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530362
363 dn = dn.split(',')
364
365 ewaybills = []
366 for doc_name in dn:
367 doc = frappe.get_doc(dt, doc_name)
368
369 validate_sales_invoice(doc)
370
371 data = frappe._dict({
372 "transporterId": "",
373 "TotNonAdvolVal": 0,
374 })
375
376 data.userGstin = data.fromGstin = doc.company_gstin
377 data.supplyType = 'O'
378
379 if doc.gst_category in ['Registered Regular', 'SEZ']:
380 data.subSupplyType = 1
381 elif doc.gst_category in ['Overseas', 'Deemed Export']:
382 data.subSupplyType = 3
383 else:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530384 frappe.throw(_('Unsupported GST Category for E-Way Bill JSON generation'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530385
386 data.docType = 'INV'
387 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
388
389 company_address = frappe.get_doc('Address', doc.company_address)
390 billing_address = frappe.get_doc('Address', doc.customer_address)
391
392 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
393
394 data = get_address_details(data, doc, company_address, billing_address)
395
396 data.itemList = []
397 data.totalValue = doc.total
398
399 data = get_item_list(data, doc)
400
401 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
402 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
403
404 data = get_transport_details(data, doc)
405
406 fields = {
407 "/. -": {
408 'docNo': doc.name,
409 'fromTrdName': doc.company,
410 'toTrdName': doc.customer_name,
411 'transDocNo': doc.lr_no,
412 },
413 "@#/,&. -": {
414 'fromAddr1': company_address.address_line1,
415 'fromAddr2': company_address.address_line2,
416 'fromPlace': company_address.city,
417 'toAddr1': shipping_address.address_line1,
418 'toAddr2': shipping_address.address_line2,
419 'toPlace': shipping_address.city,
420 'transporterName': doc.transporter_name
421 }
422 }
423
424 for allowed_chars, field_map in fields.items():
425 for key, value in field_map.items():
426 if not value:
427 data[key] = ''
428 else:
429 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
430
431 ewaybills.append(data)
432
433 data = {
434 'version': '1.0.1118',
435 'billLists': ewaybills
436 }
437
438 return data
439
440@frappe.whitelist()
441def generate_ewb_json(dt, dn):
442
443 data = get_ewb_data(dt, dn)
444
445 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
446 frappe.local.response.type = 'download'
447
448 if len(data['billLists']) > 1:
449 doc_name = 'Bulk'
450 else:
451 doc_name = dn
452
453 frappe.local.response.filename = '{0}_e-WayBill_Data_{1}.json'.format(doc_name, frappe.utils.random_string(5))
454
Prasann Shah829172c2019-06-06 12:08:09 +0530455@frappe.whitelist()
456def get_gstins_for_company(company):
457 company_gstins =[]
458 if company:
459 company_gstins = frappe.db.sql("""select
460 distinct `tabAddress`.gstin
461 from
462 `tabAddress`, `tabDynamic Link`
463 where
464 `tabDynamic Link`.parent = `tabAddress`.name and
465 `tabDynamic Link`.parenttype = 'Address' and
466 `tabDynamic Link`.link_doctype = 'Company' and
467 `tabDynamic Link`.link_name = '{0}'""".format(company))
468 return company_gstins
469
Nabin Hait34c551d2019-07-03 10:34:31 +0530470def get_address_details(data, doc, company_address, billing_address):
471 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
472 data.fromStateCode = data.actualFromStateCode = validate_state_code(
473 company_address.gst_state_number, 'Company Address')
474
475 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
476 data.toGstin = 'URP'
477 set_gst_state_and_state_number(billing_address)
478 else:
479 data.toGstin = doc.billing_address_gstin
480
481 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
482 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
483
484 if doc.customer_address != doc.shipping_address_name:
485 data.transType = 2
486 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
487 set_gst_state_and_state_number(shipping_address)
488 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
489 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
490 else:
491 data.transType = 1
492 data.actualToStateCode = data.toStateCode
493 shipping_address = billing_address
494
495 return data
496
497def get_item_list(data, doc):
498 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
499 data[attr] = 0
500
501 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
502 tax_map = {
503 'sgst_account': ['sgstRate', 'sgstValue'],
504 'cgst_account': ['cgstRate', 'cgstValue'],
505 'igst_account': ['igstRate', 'igstValue'],
506 'cess_account': ['cessRate', 'cessValue']
507 }
508 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
509 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
510 for hsn_code, taxable_amount in hsn_taxable_amount.items():
511 item_data = frappe._dict()
512 if not hsn_code:
513 frappe.throw(_('GST HSN Code does not exist for one or more items'))
514 item_data.hsnCode = int(hsn_code)
515 item_data.taxableAmount = taxable_amount
516 item_data.qtyUnit = ""
517 for attr in item_data_attrs:
518 item_data[attr] = 0
519
520 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
521 account_type = gst_accounts.get(account, '')
522 for tax_acc, attrs in tax_map.items():
523 if account_type == tax_acc:
524 item_data[attrs[0]] = tax_detail.get('tax_rate')
525 data[attrs[1]] += tax_detail.get('tax_amount')
526 break
527 else:
528 data.OthValue += tax_detail.get('tax_amount')
529
530 data.itemList.append(item_data)
531
532 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
533 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
534 data[attr] = flt(data[attr], 2)
535
536 return data
537
538def validate_sales_invoice(doc):
539 if doc.docstatus != 1:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530540 frappe.throw(_('E-Way Bill JSON can only be generated from submitted document'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530541
542 if doc.is_return:
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530543 frappe.throw(_('E-Way Bill JSON cannot be generated for Sales Return as of now'))
Nabin Hait34c551d2019-07-03 10:34:31 +0530544
545 if doc.ewaybill:
546 frappe.throw(_('e-Way Bill already exists for this document'))
547
548 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
549 'shipping_address_name', 'mode_of_transport', 'distance']
550
551 for fieldname in reqd_fields:
552 if not doc.get(fieldname):
Deepesh Gargcce3ac92020-02-02 21:25:58 +0530553 frappe.throw(_('{} is required to generate E-Way Bill JSON').format(
Nabin Hait34c551d2019-07-03 10:34:31 +0530554 doc.meta.get_label(fieldname)
Suraj Shettyda2c69e2020-01-29 15:34:06 +0530555 ))
Nabin Hait34c551d2019-07-03 10:34:31 +0530556
557 if len(doc.company_gstin) < 15:
558 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
559
560def get_transport_details(data, doc):
561 if doc.distance > 4000:
562 frappe.throw(_('Distance cannot be greater than 4000 kms'))
563
564 data.transDistance = int(round(doc.distance))
565
566 transport_modes = {
567 'Road': 1,
568 'Rail': 2,
569 'Air': 3,
570 'Ship': 4
571 }
572
573 vehicle_types = {
574 'Regular': 'R',
575 'Over Dimensional Cargo (ODC)': 'O'
576 }
577
578 data.transMode = transport_modes.get(doc.mode_of_transport)
579
580 if doc.mode_of_transport == 'Road':
581 if not doc.gst_transporter_id and not doc.vehicle_no:
582 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
583 if doc.vehicle_no:
584 data.vehicleNo = doc.vehicle_no.replace(' ', '')
585 if not doc.gst_vehicle_type:
586 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
587 else:
588 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
589 else:
590 if not doc.lr_no or not doc.lr_date:
591 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
592
593 if doc.lr_no:
594 data.transDocNo = doc.lr_no
595
596 if doc.lr_date:
597 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
598
599 if doc.gst_transporter_id:
600 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
601 data.transporterId = doc.gst_transporter_id
602
603 return data
604
605
606def validate_pincode(pincode, address):
607 pin_not_found = "Pin Code doesn't exist for {}"
608 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
609
610 if not pincode:
611 frappe.throw(_(pin_not_found.format(address)))
612
613 pincode = pincode.replace(' ', '')
614 if not pincode.isdigit() or len(pincode) != 6:
615 frappe.throw(_(incorrect_pin.format(address)))
616 else:
617 return int(pincode)
618
619def validate_state_code(state_code, address):
620 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
621 if not state_code:
622 frappe.throw(_(no_state_code.format(address)))
623 else:
624 return int(state_code)
625
626def get_gst_accounts(company, account_wise=False):
627 gst_accounts = frappe._dict()
628 gst_settings_accounts = frappe.get_all("GST Account",
629 filters={"parent": "GST Settings", "company": company},
630 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
631
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530632 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530633 frappe.throw(_("Please set GST Accounts in GST Settings"))
634
635 for d in gst_settings_accounts:
636 for acc, val in d.items():
637 if not account_wise:
638 gst_accounts.setdefault(acc, []).append(val)
639 elif val:
640 gst_accounts[val] = acc
641
642
643 return gst_accounts