blob: 3cc1a014d76ffb2b3e76642f3a7b1b913582e836 [file] [log] [blame]
Anand Doshi885e0742015-03-03 14:55:30 +05301# Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors
Rushabh Mehtae67d1fb2013-08-05 14:59:54 +05302# License: GNU General Public License v3. See license.txt
Anand Doshi60666a22013-04-12 20:19:53 +05303
Rohandb2d1962021-03-09 21:03:45 +05304import erpnext
5import frappe
Jamsheercc25eb02018-06-13 15:14:24 +05306from erpnext.hr.doctype.employee.employee import get_holiday_list_for_employee
Rohandb2d1962021-03-09 21:03:45 +05307from frappe import _
8from frappe.desk.form import assign_to
9from frappe.model.document import Document
10from frappe.utils import (add_days, cstr, flt, format_datetime, formatdate,
11 get_datetime, getdate, nowdate, today, unique)
12
Manas Solankib6988462018-05-10 18:07:20 +053013
Nabin Hait58ee6c12020-04-26 17:45:57 +053014class DuplicateDeclarationError(frappe.ValidationError): pass
15
Anand Doshic280d062014-05-30 14:43:36 +053016def set_employee_name(doc):
17 if doc.employee and not doc.employee_name:
18 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +053019
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053020def update_employee(employee, details, date=None, cancel=False):
21 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +053022 for item in details:
23 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
24 new_data = item.new if not cancel else item.current
25 if fieldtype == "Date" and new_data:
26 new_data = getdate(new_data)
27 elif fieldtype =="Datetime" and new_data:
28 new_data = get_datetime(new_data)
29 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053030 if item.fieldname in ["department", "designation", "branch"]:
31 internal_work_history[item.fieldname] = item.new
32 if internal_work_history and not cancel:
33 internal_work_history["from_date"] = date
34 employee.append("internal_work_history", internal_work_history)
Manas Solankib6988462018-05-10 18:07:20 +053035 return employee
36
Ranjithfddfffd2018-05-05 13:27:26 +053037@frappe.whitelist()
38def get_employee_fields_label():
39 fields = []
40 for df in frappe.get_meta("Employee").get("fields"):
Ranjith Kurungadamc1030a32018-06-20 12:42:58 +053041 if df.fieldname in ["salutation", "user_id", "employee_number", "employment_type",
Nabin Hait6b9d64c2019-05-16 11:23:04 +053042 "holiday_list", "branch", "department", "designation", "grade",
43 "notice_number_of_days", "reports_to", "leave_policy", "company_email"]:
44 fields.append({"value": df.fieldname, "label": df.label})
Ranjithfddfffd2018-05-05 13:27:26 +053045 return fields
46
47@frappe.whitelist()
48def get_employee_field_property(employee, fieldname):
49 if employee and fieldname:
50 field = frappe.get_meta("Employee").get_field(fieldname)
51 value = frappe.db.get_value("Employee", employee, fieldname)
52 options = field.options
53 if field.fieldtype == "Date":
54 value = formatdate(value)
55 elif field.fieldtype == "Datetime":
56 value = format_datetime(value)
57 return {
58 "value" : value,
59 "datatype" : field.fieldtype,
60 "label" : field.label,
61 "options" : options
62 }
63 else:
64 return False
65
Jamsheer0e2cc552018-05-08 11:48:25 +053066def validate_dates(doc, from_date, to_date):
67 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
68 if getdate(from_date) > getdate(to_date):
69 frappe.throw(_("To date can not be less than from date"))
70 elif getdate(from_date) > getdate(nowdate()):
71 frappe.throw(_("Future dates not allowed"))
72 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
73 frappe.throw(_("From date can not be less than employee's joining date"))
74 elif relieving_date and getdate(to_date) > getdate(relieving_date):
75 frappe.throw(_("To date can not greater than employee's relieving date"))
76
77def validate_overlap(doc, from_date, to_date, company = None):
78 query = """
79 select name
80 from `tab{0}`
81 where name != %(name)s
82 """
83 query += get_doc_condition(doc.doctype)
84
85 if not doc.name:
86 # hack! if name is null, it could cause problems with !=
87 doc.name = "New "+doc.doctype
88
89 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
Nabin Haitd53c2c02018-07-30 20:16:48 +053090 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +053091 "from_date": from_date,
92 "to_date": to_date,
93 "name": doc.name,
94 "company": company
95 }, as_dict = 1)
96
97 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +053098 if doc.get("employee"):
99 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530100 if company:
101 exists_for = company
102 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
103
104def get_doc_condition(doctype):
105 if doctype == "Compensatory Leave Request":
106 return "and employee = %(employee)s and docstatus < 2 \
107 and (work_from_date between %(from_date)s and %(to_date)s \
108 or work_end_date between %(from_date)s and %(to_date)s \
109 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
110 elif doctype == "Leave Period":
111 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
112 or to_date between %(from_date)s and %(to_date)s \
113 or (from_date < %(from_date)s and to_date > %(to_date)s))"
114
115def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
116 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
117 formatdate(from_date), formatdate(to_date)) \
Rushabh Mehta542bc012020-11-18 15:00:34 +0530118 + """ <b><a href="/app/Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
Jamsheer0e2cc552018-05-08 11:48:25 +0530119 + _(") for {0}").format(exists_for)
120 frappe.throw(msg)
121
Nabin Hait58ee6c12020-04-26 17:45:57 +0530122def validate_duplicate_exemption_for_payroll_period(doctype, docname, payroll_period, employee):
123 existing_record = frappe.db.exists(doctype, {
124 "payroll_period": payroll_period,
125 "employee": employee,
126 'docstatus': ['<', 2],
127 'name': ['!=', docname]
128 })
129 if existing_record:
130 frappe.throw(_("{0} already exists for employee {1} and period {2}")
131 .format(doctype, employee, payroll_period), DuplicateDeclarationError)
132
Ranjith5a8e6422018-05-10 15:06:49 +0530133def validate_tax_declaration(declarations):
134 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530135 for d in declarations:
136 if d.exemption_sub_category in subcategories:
137 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
138 subcategories.append(d.exemption_sub_category)
139
140def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530141 exemptions = frappe._dict()
142 for d in declarations:
143 exemptions.setdefault(d.exemption_category, frappe._dict())
144 category_max_amount = exemptions.get(d.exemption_category).max_amount
145 if not category_max_amount:
146 category_max_amount = frappe.db.get_value("Employee Tax Exemption Category", d.exemption_category, "max_amount")
147 exemptions.get(d.exemption_category).max_amount = category_max_amount
148 sub_category_exemption_amount = d.max_amount \
149 if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
150
151 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
152 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
153
154 if category_max_amount and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount:
155 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
156
157 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
158 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530159
Jannat Patel1175e062021-06-01 10:53:00 +0530160@frappe.whitelist()
Jamsheer0e2cc552018-05-08 11:48:25 +0530161def get_leave_period(from_date, to_date, company):
162 leave_period = frappe.db.sql("""
163 select name, from_date, to_date
164 from `tabLeave Period`
165 where company=%(company)s and is_active=1
166 and (from_date between %(from_date)s and %(to_date)s
167 or to_date between %(from_date)s and %(to_date)s
168 or (from_date < %(from_date)s and to_date > %(to_date)s))
169 """, {
170 "from_date": from_date,
171 "to_date": to_date,
172 "company": company
173 }, as_dict=1)
174
175 if leave_period:
176 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530177
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530178def generate_leave_encashment():
179 ''' Generates a draft leave encashment on allocation expiry '''
180 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530181
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530182 if frappe.db.get_single_value('HR Settings', 'auto_leave_encashment'):
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530183 leave_type = frappe.get_all('Leave Type', filters={'allow_encashment': 1}, fields=['name'])
184 leave_type=[l['name'] for l in leave_type]
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530185
186 leave_allocation = frappe.get_all("Leave Allocation", filters={
187 'to_date': add_days(today(), -1),
188 'leave_type': ('in', leave_type)
189 }, fields=['employee', 'leave_period', 'leave_type', 'to_date', 'total_leaves_allocated', 'new_leaves_allocated'])
190
191 create_leave_encashment(leave_allocation=leave_allocation)
192
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530193def allocate_earned_leaves():
194 '''Allocate earned leaves to Employees'''
Anurag Mishra755b7732020-11-25 16:05:17 +0530195 e_leave_types = get_earned_leaves()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530196 today = getdate()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530197
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530198 for e_leave_type in e_leave_types:
Anurag Mishra755b7732020-11-25 16:05:17 +0530199
200 leave_allocations = get_leave_allocations(today, e_leave_type.name)
201
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530202 for allocation in leave_allocations:
Anurag Mishra755b7732020-11-25 16:05:17 +0530203
204 if not allocation.leave_policy_assignment and not allocation.leave_policy:
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530205 continue
Anurag Mishra755b7732020-11-25 16:05:17 +0530206
207 leave_policy = allocation.leave_policy if allocation.leave_policy else frappe.db.get_value(
208 "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"])
209
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530210 annual_allocation = frappe.db.get_value("Leave Policy Detail", filters={
Anurag Mishra755b7732020-11-25 16:05:17 +0530211 'parent': leave_policy,
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530212 'leave_type': e_leave_type.name
Mangesh-Khairnar261d1322019-08-09 13:18:52 +0530213 }, fieldname=['annual_allocation'])
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530214
Anurag Mishra755b7732020-11-25 16:05:17 +0530215 from_date=allocation.from_date
Mangesh-Khairnar5d5f5b42020-02-20 13:25:55 +0530216
Anurag Mishra755b7732020-11-25 16:05:17 +0530217 if e_leave_type.based_on_date_of_joining_date:
218 from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530219
Anurag Mishra755b7732020-11-25 16:05:17 +0530220 if check_effective_date(from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining_date):
221 update_previous_leave_allocation(allocation, annual_allocation, e_leave_type)
222
223def update_previous_leave_allocation(allocation, annual_allocation, e_leave_type):
Nabin Hait190106a2021-03-02 13:38:14 +0530224 earned_leaves = get_monthly_earned_leave(annual_allocation, e_leave_type.earned_leave_frequency, e_leave_type.rounding)
Anurag Mishra755b7732020-11-25 16:05:17 +0530225
226 allocation = frappe.get_doc('Leave Allocation', allocation.name)
227 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
228
229 if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0:
230 new_allocation = e_leave_type.max_leaves_allowed
231
232 if new_allocation != allocation.total_leaves_allocated:
233 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
234 today_date = today()
235 create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
236
Nabin Hait190106a2021-03-02 13:38:14 +0530237def get_monthly_earned_leave(annual_leaves, frequency, rounding):
238 earned_leaves = 0.0
239 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
240 if annual_leaves:
241 earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency]
242 if rounding:
243 if rounding == "0.25":
244 earned_leaves = round(earned_leaves * 4) / 4
245 elif rounding == "0.5":
246 earned_leaves = round(earned_leaves * 2) / 2
247 else:
248 earned_leaves = round(earned_leaves)
249
250 return earned_leaves
251
Anurag Mishra755b7732020-11-25 16:05:17 +0530252
253def get_leave_allocations(date, leave_type):
254 return frappe.db.sql("""select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
255 from `tabLeave Allocation`
256 where
257 %s between from_date and to_date and docstatus=1
258 and leave_type=%s""",
259 (date, leave_type), as_dict=1)
260
261
262def get_earned_leaves():
263 return frappe.get_all("Leave Type",
264 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding", "based_on_date_of_joining"],
265 filters={'is_earned_leave' : 1})
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530266
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530267def create_additional_leave_ledger_entry(allocation, leaves, date):
268 ''' Create leave ledger entry for leave types '''
269 allocation.new_leaves_allocated = leaves
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530270 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530271 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530272 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530273
Anurag Mishra755b7732020-11-25 16:05:17 +0530274def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining_date):
275 import calendar
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530276 from dateutil import relativedelta
Anurag Mishra755b7732020-11-25 16:05:17 +0530277
278 from_date = get_datetime(from_date)
279 to_date = get_datetime(to_date)
280 rd = relativedelta.relativedelta(to_date, from_date)
281 #last day of month
282 last_day = calendar.monthrange(to_date.year, to_date.month)[1]
283
284 if (from_date.day == to_date.day and based_on_date_of_joining_date) or (not based_on_date_of_joining_date and to_date.day == last_day):
285 if frequency == "Monthly":
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530286 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530287 elif frequency == "Quarterly" and rd.months % 3:
Joyce Babu3d012132019-03-06 13:04:45 +0530288 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530289 elif frequency == "Half-Yearly" and rd.months % 6:
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530290 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530291 elif frequency == "Yearly" and rd.months % 12:
292 return True
293
294 if frappe.flags.in_test:
295 return True
296
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530297 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530298
Anurag Mishra755b7732020-11-25 16:05:17 +0530299
Ranjith155ecc12018-05-30 13:37:15 +0530300def get_salary_assignment(employee, date):
301 assignment = frappe.db.sql("""
302 select * from `tabSalary Structure Assignment`
303 where employee=%(employee)s
304 and docstatus = 1
Ranjith Kurungadamb4ad3c32018-06-25 10:29:54 +0530305 and %(on_date)s >= from_date order by from_date desc limit 1""", {
Ranjith155ecc12018-05-30 13:37:15 +0530306 'employee': employee,
307 'on_date': date,
308 }, as_dict=1)
309 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530310
Jamsheer8d66f1e2018-06-12 11:30:59 +0530311def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
312 total_given_benefit_amount = 0
313 query = """
314 select sum(sd.amount) as 'total_amount'
315 from `tabSalary Slip` ss, `tabSalary Detail` sd
316 where ss.employee=%(employee)s
317 and ss.docstatus = 1 and ss.name = sd.parent
318 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
319 and sd.parenttype = "Salary Slip"
320 and (ss.start_date between %(start_date)s and %(end_date)s
321 or ss.end_date between %(start_date)s and %(end_date)s
322 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
323 """
324
325 if component:
326 query += "and sd.salary_component = %(component)s"
327
328 sum_of_given_benefit = frappe.db.sql(query, {
329 'employee': employee,
330 'start_date': payroll_period.start_date,
331 'end_date': payroll_period.end_date,
332 'component': component
333 }, as_dict=True)
334
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530335 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530336 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
337 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530338
339def get_holidays_for_employee(employee, start_date, end_date):
340 holiday_list = get_holiday_list_for_employee(employee)
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530341
Jamsheercc25eb02018-06-13 15:14:24 +0530342 holidays = frappe.db.sql_list('''select holiday_date from `tabHoliday`
343 where
344 parent=%(holiday_list)s
345 and holiday_date >= %(start_date)s
346 and holiday_date <= %(end_date)s''', {
347 "holiday_list": holiday_list,
348 "start_date": start_date,
349 "end_date": end_date
350 })
351
352 holidays = [cstr(i) for i in holidays]
353
354 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530355
356@erpnext.allow_regional
357def calculate_annual_eligible_hra_exemption(doc):
358 # Don't delete this method, used for localization
359 # Indian HRA Exemption Calculation
360 return {}
361
362@erpnext.allow_regional
363def calculate_hra_exemption_for_period(doc):
364 # Don't delete this method, used for localization
365 # Indian HRA Exemption Calculation
366 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530367
368def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
369 total_claimed_amount = 0
370 query = """
371 select sum(claimed_amount) as 'total_amount'
372 from `tabEmployee Benefit Claim`
373 where employee=%(employee)s
374 and docstatus = 1
375 and (claim_date between %(start_date)s and %(end_date)s)
376 """
377 if non_pro_rata:
378 query += "and pay_against_benefit_claim = 1"
379 if component:
380 query += "and earning_component = %(component)s"
381
382 sum_of_claimed_amount = frappe.db.sql(query, {
383 'employee': employee,
384 'start_date': payroll_period.start_date,
385 'end_date': payroll_period.end_date,
386 'component': component
387 }, as_dict=True)
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530388 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530389 total_claimed_amount = sum_of_claimed_amount[0].total_amount
390 return total_claimed_amount
Anurag Mishra755b7732020-11-25 16:05:17 +0530391
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530392def share_doc_with_approver(doc, user):
393 # if approver does not have permissions, share
394 if not frappe.has_permission(doc=doc, ptype="submit", user=user):
Rucha Mahabal8c055b52021-04-04 18:45:06 +0530395 frappe.share.add(doc.doctype, doc.name, user, submit=1,
396 flags={"ignore_share_permission": True})
397
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530398 frappe.msgprint(_("Shared with the user {0} with {1} access").format(
399 user, frappe.bold("submit"), alert=True))
400
401 # remove shared doc if approver changes
402 doc_before_save = doc.get_doc_before_save()
403 if doc_before_save:
404 approvers = {
405 "Leave Application": "leave_approver",
406 "Expense Claim": "expense_approver",
407 "Shift Request": "approver"
408 }
409
410 approver = approvers.get(doc.doctype)
411 if doc_before_save.get(approver) != doc.get(approver):
412 frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver))