blob: 77bcc80abab559e869b75528710b5aed1058a18d [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
182 if ((doctype in ("Sales Invoice", "Delivery Note", "Sales Order") and party_details.company_gstin
183 and party_details.company_gstin[:2] != party_details.place_of_supply[:2]) or (doctype in ("Purchase Invoice",
184 "Purchase Order", "Purchase Receipt") and party_details.supplier_gstin and party_details.supplier_gstin[:2] != party_details.place_of_supply[:2])):
185 default_tax = get_tax_template(master_doctype, company, 1, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530186 else:
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530187 default_tax = get_tax_template(master_doctype, company, 0, party_details.company_gstin[:2])
Shreya Shah4fa600a2018-06-05 11:27:53 +0530188
189 if not default_tax:
190 return
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530191 party_details["taxes_and_charges"] = default_tax
192 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
193
194 if return_taxes:
195 return party_details
196
197def get_tax_template_based_on_category(master_doctype, company, party_details):
198 if not party_details.get('tax_category'):
199 return
200
201 default_tax = frappe.db.get_value(master_doctype, {'company': company, 'tax_category': party_details.get('tax_category')},
202 'name')
203
204 if default_tax:
205 party_details["taxes_and_charges"] = default_tax
206 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
207
208def get_tax_template(master_doctype, company, is_inter_state, state_code):
209 tax_categories = frappe.get_all('Tax Category', fields = ['name', 'is_inter_state', 'gst_state'],
210 filters = {'is_inter_state': is_inter_state})
211
212 default_tax = ''
213
214 for tax_category in tax_categories:
215 if tax_category.gst_state == number_state_mapping[state_code] or \
216 (not default_tax and not tax_category.gst_state):
217 default_tax = frappe.db.get_value(master_doctype,
218 {'disabled': 0, 'tax_category': tax_category.name}, 'name')
219
220 return default_tax
221
222def get_tax_template_for_sez(party_details, master_doctype, company, party_type):
223
224 gst_details = frappe.db.get_value(party_type, {'name': party_details.get(frappe.scrub(party_type))},
225 ['gst_category', 'export_type'], as_dict=1)
226
227 if gst_details:
228 if gst_details.gst_category == 'SEZ' and gst_details.export_type == 'With Payment of Tax':
229 default_tax = frappe.db.get_value(master_doctype, {"company": company, "is_inter_state":1, "disabled":0,
230 "gst_state": number_state_mapping[party_details.company_gstin[:2]]})
231
232 party_details["taxes_and_charges"] = default_tax
233 party_details.taxes = get_taxes_and_charges(master_doctype, default_tax)
234
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530235
236def calculate_annual_eligible_hra_exemption(doc):
Rushabh Mehta708e47a2018-08-08 16:37:31 +0530237 basic_component = frappe.get_cached_value('Company', doc.company, "basic_component")
238 hra_component = frappe.get_cached_value('Company', doc.company, "hra_component")
Nabin Hait04e7bf42019-04-25 18:44:10 +0530239 if not (basic_component and hra_component):
240 frappe.throw(_("Please mention Basic and HRA component in Company"))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530241 annual_exemption, monthly_exemption, hra_amount = 0, 0, 0
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530242 if hra_component and basic_component:
Nabin Hait04e7bf42019-04-25 18:44:10 +0530243 assignment = get_salary_assignment(doc.employee, nowdate())
Nabin Hait04e7bf42019-04-25 18:44:10 +0530244 if assignment:
245 hra_component_exists = frappe.db.exists("Salary Detail", {
246 "parent": assignment.salary_structure,
247 "salary_component": hra_component,
248 "parentfield": "earnings",
249 "parenttype": "Salary Structure"
250 })
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530251
Nabin Hait04e7bf42019-04-25 18:44:10 +0530252 if hra_component_exists:
253 basic_amount, hra_amount = get_component_amt_from_salary_slip(doc.employee,
254 assignment.salary_structure, basic_component, hra_component)
255 if hra_amount:
256 if doc.monthly_house_rent:
257 annual_exemption = calculate_hra_exemption(assignment.salary_structure,
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530258 basic_amount, hra_amount, doc.monthly_house_rent, doc.rented_in_metro_city)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530259 if annual_exemption > 0:
260 monthly_exemption = annual_exemption / 12
261 else:
262 annual_exemption = 0
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530263
Nabin Hait04e7bf42019-04-25 18:44:10 +0530264 elif doc.docstatus == 1:
265 frappe.throw(_("Salary Structure must be submitted before submission of Tax Ememption Declaration"))
266
267 return frappe._dict({
268 "hra_amount": hra_amount,
269 "annual_exemption": annual_exemption,
270 "monthly_exemption": monthly_exemption
271 })
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530272
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530273def get_component_amt_from_salary_slip(employee, salary_structure, basic_component, hra_component):
Nabin Hait6b9d64c2019-05-16 11:23:04 +0530274 salary_slip = make_salary_slip(salary_structure, employee=employee, for_preview=1)
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530275 basic_amt, hra_amt = 0, 0
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530276 for earning in salary_slip.earnings:
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530277 if earning.salary_component == basic_component:
278 basic_amt = earning.amount
279 elif earning.salary_component == hra_component:
280 hra_amt = earning.amount
281 if basic_amt and hra_amt:
282 return basic_amt, hra_amt
Ranjith Kurungadam14e94f82018-07-16 16:12:46 +0530283 return basic_amt, hra_amt
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530284
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530285def calculate_hra_exemption(salary_structure, basic, monthly_hra, monthly_house_rent, rented_in_metro_city):
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530286 # TODO make this configurable
287 exemptions = []
288 frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency")
289 # case 1: The actual amount allotted by the employer as the HRA.
290 exemptions.append(get_annual_component_pay(frequency, monthly_hra))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530291
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530292 actual_annual_rent = monthly_house_rent * 12
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530293 annual_basic = get_annual_component_pay(frequency, basic)
Nabin Hait04e7bf42019-04-25 18:44:10 +0530294
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530295 # case 2: Actual rent paid less 10% of the basic salary.
Ranjith Kurungadamb1a756c2018-07-01 16:42:38 +0530296 exemptions.append(flt(actual_annual_rent) - flt(annual_basic * 0.1))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530297 # 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 +0530298 exemptions.append(annual_basic * 0.5 if rented_in_metro_city else annual_basic * 0.4)
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530299 # return minimum of 3 cases
300 return min(exemptions)
301
302def get_annual_component_pay(frequency, amount):
303 if frequency == "Daily":
304 return amount * 365
305 elif frequency == "Weekly":
306 return amount * 52
307 elif frequency == "Fortnightly":
308 return amount * 26
309 elif frequency == "Monthly":
310 return amount * 12
311 elif frequency == "Bimonthly":
312 return amount * 6
313
314def validate_house_rent_dates(doc):
315 if not doc.rented_to_date or not doc.rented_from_date:
316 frappe.throw(_("House rented dates required for exemption calculation"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530317
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530318 if date_diff(doc.rented_to_date, doc.rented_from_date) < 14:
319 frappe.throw(_("House rented dates should be atleast 15 days apart"))
Nabin Hait04e7bf42019-04-25 18:44:10 +0530320
321 proofs = frappe.db.sql("""
322 select name
323 from `tabEmployee Tax Exemption Proof Submission`
324 where
Nabin Hait49446ba2019-04-25 19:54:20 +0530325 docstatus=1 and employee=%(employee)s and payroll_period=%(payroll_period)s
326 and (rented_from_date between %(from_date)s and %(to_date)s or rented_to_date between %(from_date)s and %(to_date)s)
327 """, {
328 "employee": doc.employee,
329 "payroll_period": doc.payroll_period,
330 "from_date": doc.rented_from_date,
331 "to_date": doc.rented_to_date
332 })
Nabin Hait04e7bf42019-04-25 18:44:10 +0530333
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530334 if proofs:
Nabin Hait49446ba2019-04-25 19:54:20 +0530335 frappe.throw(_("House rent paid days overlapping with {0}").format(proofs[0][0]))
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530336
337def calculate_hra_exemption_for_period(doc):
338 monthly_rent, eligible_hra = 0, 0
339 if doc.house_rent_payment_amount:
340 validate_house_rent_dates(doc)
341 # TODO receive rented months or validate dates are start and end of months?
342 # Calc monthly rent, round to nearest .5
343 factor = flt(date_diff(doc.rented_to_date, doc.rented_from_date) + 1)/30
344 factor = round(factor * 2)/2
345 monthly_rent = doc.house_rent_payment_amount / factor
346 # update field used by calculate_annual_eligible_hra_exemption
347 doc.monthly_house_rent = monthly_rent
348 exemptions = calculate_annual_eligible_hra_exemption(doc)
349
350 if exemptions["monthly_exemption"]:
351 # calc total exemption amount
352 eligible_hra = exemptions["monthly_exemption"] * factor
Ranjith Kurungadam4f9744a2018-06-20 11:10:56 +0530353 exemptions["monthly_house_rent"] = monthly_rent
354 exemptions["total_eligible_hra_exemption"] = eligible_hra
355 return exemptions
Prasann Shah829172c2019-06-06 12:08:09 +0530356
Nabin Hait34c551d2019-07-03 10:34:31 +0530357def get_ewb_data(dt, dn):
358 if dt != 'Sales Invoice':
359 frappe.throw(_('e-Way Bill JSON can only be generated from Sales Invoice'))
360
361 dn = dn.split(',')
362
363 ewaybills = []
364 for doc_name in dn:
365 doc = frappe.get_doc(dt, doc_name)
366
367 validate_sales_invoice(doc)
368
369 data = frappe._dict({
370 "transporterId": "",
371 "TotNonAdvolVal": 0,
372 })
373
374 data.userGstin = data.fromGstin = doc.company_gstin
375 data.supplyType = 'O'
376
377 if doc.gst_category in ['Registered Regular', 'SEZ']:
378 data.subSupplyType = 1
379 elif doc.gst_category in ['Overseas', 'Deemed Export']:
380 data.subSupplyType = 3
381 else:
382 frappe.throw(_('Unsupported GST Category for e-Way Bill JSON generation'))
383
384 data.docType = 'INV'
385 data.docDate = frappe.utils.formatdate(doc.posting_date, 'dd/mm/yyyy')
386
387 company_address = frappe.get_doc('Address', doc.company_address)
388 billing_address = frappe.get_doc('Address', doc.customer_address)
389
390 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
391
392 data = get_address_details(data, doc, company_address, billing_address)
393
394 data.itemList = []
395 data.totalValue = doc.total
396
397 data = get_item_list(data, doc)
398
399 disable_rounded = frappe.db.get_single_value('Global Defaults', 'disable_rounded_total')
400 data.totInvValue = doc.grand_total if disable_rounded else doc.rounded_total
401
402 data = get_transport_details(data, doc)
403
404 fields = {
405 "/. -": {
406 'docNo': doc.name,
407 'fromTrdName': doc.company,
408 'toTrdName': doc.customer_name,
409 'transDocNo': doc.lr_no,
410 },
411 "@#/,&. -": {
412 'fromAddr1': company_address.address_line1,
413 'fromAddr2': company_address.address_line2,
414 'fromPlace': company_address.city,
415 'toAddr1': shipping_address.address_line1,
416 'toAddr2': shipping_address.address_line2,
417 'toPlace': shipping_address.city,
418 'transporterName': doc.transporter_name
419 }
420 }
421
422 for allowed_chars, field_map in fields.items():
423 for key, value in field_map.items():
424 if not value:
425 data[key] = ''
426 else:
427 data[key] = re.sub(r'[^\w' + allowed_chars + ']', '', value)
428
429 ewaybills.append(data)
430
431 data = {
432 'version': '1.0.1118',
433 'billLists': ewaybills
434 }
435
436 return data
437
438@frappe.whitelist()
439def generate_ewb_json(dt, dn):
440
441 data = get_ewb_data(dt, dn)
442
443 frappe.local.response.filecontent = json.dumps(data, indent=4, sort_keys=True)
444 frappe.local.response.type = 'download'
445
446 if len(data['billLists']) > 1:
447 doc_name = 'Bulk'
448 else:
449 doc_name = dn
450
451 frappe.local.response.filename = '{0}_e-WayBill_Data_{1}.json'.format(doc_name, frappe.utils.random_string(5))
452
Prasann Shah829172c2019-06-06 12:08:09 +0530453@frappe.whitelist()
454def get_gstins_for_company(company):
455 company_gstins =[]
456 if company:
457 company_gstins = frappe.db.sql("""select
458 distinct `tabAddress`.gstin
459 from
460 `tabAddress`, `tabDynamic Link`
461 where
462 `tabDynamic Link`.parent = `tabAddress`.name and
463 `tabDynamic Link`.parenttype = 'Address' and
464 `tabDynamic Link`.link_doctype = 'Company' and
465 `tabDynamic Link`.link_name = '{0}'""".format(company))
466 return company_gstins
467
Nabin Hait34c551d2019-07-03 10:34:31 +0530468def get_address_details(data, doc, company_address, billing_address):
469 data.fromPincode = validate_pincode(company_address.pincode, 'Company Address')
470 data.fromStateCode = data.actualFromStateCode = validate_state_code(
471 company_address.gst_state_number, 'Company Address')
472
473 if not doc.billing_address_gstin or len(doc.billing_address_gstin) < 15:
474 data.toGstin = 'URP'
475 set_gst_state_and_state_number(billing_address)
476 else:
477 data.toGstin = doc.billing_address_gstin
478
479 data.toPincode = validate_pincode(billing_address.pincode, 'Customer Address')
480 data.toStateCode = validate_state_code(billing_address.gst_state_number, 'Customer Address')
481
482 if doc.customer_address != doc.shipping_address_name:
483 data.transType = 2
484 shipping_address = frappe.get_doc('Address', doc.shipping_address_name)
485 set_gst_state_and_state_number(shipping_address)
486 data.toPincode = validate_pincode(shipping_address.pincode, 'Shipping Address')
487 data.actualToStateCode = validate_state_code(shipping_address.gst_state_number, 'Shipping Address')
488 else:
489 data.transType = 1
490 data.actualToStateCode = data.toStateCode
491 shipping_address = billing_address
492
493 return data
494
495def get_item_list(data, doc):
496 for attr in ['cgstValue', 'sgstValue', 'igstValue', 'cessValue', 'OthValue']:
497 data[attr] = 0
498
499 gst_accounts = get_gst_accounts(doc.company, account_wise=True)
500 tax_map = {
501 'sgst_account': ['sgstRate', 'sgstValue'],
502 'cgst_account': ['cgstRate', 'cgstValue'],
503 'igst_account': ['igstRate', 'igstValue'],
504 'cess_account': ['cessRate', 'cessValue']
505 }
506 item_data_attrs = ['sgstRate', 'cgstRate', 'igstRate', 'cessRate', 'cessNonAdvol']
507 hsn_wise_charges, hsn_taxable_amount = get_itemised_tax_breakup_data(doc, account_wise=True)
508 for hsn_code, taxable_amount in hsn_taxable_amount.items():
509 item_data = frappe._dict()
510 if not hsn_code:
511 frappe.throw(_('GST HSN Code does not exist for one or more items'))
512 item_data.hsnCode = int(hsn_code)
513 item_data.taxableAmount = taxable_amount
514 item_data.qtyUnit = ""
515 for attr in item_data_attrs:
516 item_data[attr] = 0
517
518 for account, tax_detail in hsn_wise_charges.get(hsn_code, {}).items():
519 account_type = gst_accounts.get(account, '')
520 for tax_acc, attrs in tax_map.items():
521 if account_type == tax_acc:
522 item_data[attrs[0]] = tax_detail.get('tax_rate')
523 data[attrs[1]] += tax_detail.get('tax_amount')
524 break
525 else:
526 data.OthValue += tax_detail.get('tax_amount')
527
528 data.itemList.append(item_data)
529
530 # Tax amounts rounded to 2 decimals to avoid exceeding max character limit
531 for attr in ['sgstValue', 'cgstValue', 'igstValue', 'cessValue']:
532 data[attr] = flt(data[attr], 2)
533
534 return data
535
536def validate_sales_invoice(doc):
537 if doc.docstatus != 1:
538 frappe.throw(_('e-Way Bill JSON can only be generated from submitted document'))
539
540 if doc.is_return:
541 frappe.throw(_('e-Way Bill JSON cannot be generated for Sales Return as of now'))
542
543 if doc.ewaybill:
544 frappe.throw(_('e-Way Bill already exists for this document'))
545
546 reqd_fields = ['company_gstin', 'company_address', 'customer_address',
547 'shipping_address_name', 'mode_of_transport', 'distance']
548
549 for fieldname in reqd_fields:
550 if not doc.get(fieldname):
551 frappe.throw(_('{} is required to generate e-Way Bill JSON'.format(
552 doc.meta.get_label(fieldname)
553 )))
554
555 if len(doc.company_gstin) < 15:
556 frappe.throw(_('You must be a registered supplier to generate e-Way Bill'))
557
558def get_transport_details(data, doc):
559 if doc.distance > 4000:
560 frappe.throw(_('Distance cannot be greater than 4000 kms'))
561
562 data.transDistance = int(round(doc.distance))
563
564 transport_modes = {
565 'Road': 1,
566 'Rail': 2,
567 'Air': 3,
568 'Ship': 4
569 }
570
571 vehicle_types = {
572 'Regular': 'R',
573 'Over Dimensional Cargo (ODC)': 'O'
574 }
575
576 data.transMode = transport_modes.get(doc.mode_of_transport)
577
578 if doc.mode_of_transport == 'Road':
579 if not doc.gst_transporter_id and not doc.vehicle_no:
580 frappe.throw(_('Either GST Transporter ID or Vehicle No is required if Mode of Transport is Road'))
581 if doc.vehicle_no:
582 data.vehicleNo = doc.vehicle_no.replace(' ', '')
583 if not doc.gst_vehicle_type:
584 frappe.throw(_('Vehicle Type is required if Mode of Transport is Road'))
585 else:
586 data.vehicleType = vehicle_types.get(doc.gst_vehicle_type)
587 else:
588 if not doc.lr_no or not doc.lr_date:
589 frappe.throw(_('Transport Receipt No and Date are mandatory for your chosen Mode of Transport'))
590
591 if doc.lr_no:
592 data.transDocNo = doc.lr_no
593
594 if doc.lr_date:
595 data.transDocDate = frappe.utils.formatdate(doc.lr_date, 'dd/mm/yyyy')
596
597 if doc.gst_transporter_id:
598 validate_gstin_check_digit(doc.gst_transporter_id, label='GST Transporter ID')
599 data.transporterId = doc.gst_transporter_id
600
601 return data
602
603
604def validate_pincode(pincode, address):
605 pin_not_found = "Pin Code doesn't exist for {}"
606 incorrect_pin = "Pin Code for {} is incorrecty formatted. It must be 6 digits (without spaces)"
607
608 if not pincode:
609 frappe.throw(_(pin_not_found.format(address)))
610
611 pincode = pincode.replace(' ', '')
612 if not pincode.isdigit() or len(pincode) != 6:
613 frappe.throw(_(incorrect_pin.format(address)))
614 else:
615 return int(pincode)
616
617def validate_state_code(state_code, address):
618 no_state_code = "GST State Code not found for {0}. Please set GST State in {0}"
619 if not state_code:
620 frappe.throw(_(no_state_code.format(address)))
621 else:
622 return int(state_code)
623
624def get_gst_accounts(company, account_wise=False):
625 gst_accounts = frappe._dict()
626 gst_settings_accounts = frappe.get_all("GST Account",
627 filters={"parent": "GST Settings", "company": company},
628 fields=["cgst_account", "sgst_account", "igst_account", "cess_account"])
629
Deepesh Garg6e2c13f2019-12-10 15:55:05 +0530630 if not gst_settings_accounts and not frappe.flags.in_test:
Nabin Hait34c551d2019-07-03 10:34:31 +0530631 frappe.throw(_("Please set GST Accounts in GST Settings"))
632
633 for d in gst_settings_accounts:
634 for acc, val in d.items():
635 if not account_wise:
636 gst_accounts.setdefault(acc, []).append(val)
637 elif val:
638 gst_accounts[val] = acc
639
640
641 return gst_accounts