blob: 4e30b0ff6e7ef4419dccfd2c4269686c77d65b7f [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 frappe
Rohandb2d1962021-03-09 21:03:45 +05305from frappe import _
Chillar Anand915b3432021-09-02 16:44:59 +05306from frappe.utils import (
7 add_days,
8 cstr,
9 flt,
10 format_datetime,
11 formatdate,
12 get_datetime,
13 get_link_to_form,
14 getdate,
15 nowdate,
16 today,
17)
18
19import erpnext
20from erpnext.hr.doctype.employee.employee import (
21 InactiveEmployeeStatusError,
22 get_holiday_list_for_employee,
23)
24
Manas Solankib6988462018-05-10 18:07:20 +053025
Ankush Menat494bd9e2022-03-28 18:52:46 +053026class DuplicateDeclarationError(frappe.ValidationError):
27 pass
28
Nabin Hait58ee6c12020-04-26 17:45:57 +053029
Anand Doshic280d062014-05-30 14:43:36 +053030def set_employee_name(doc):
31 if doc.employee and not doc.employee_name:
32 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +053033
Ankush Menat494bd9e2022-03-28 18:52:46 +053034
Mohammed Yusuf Shaikh03bfc772021-10-21 10:15:09 +053035def update_employee_work_history(employee, details, date=None, cancel=False):
36 if not employee.internal_work_history and not cancel:
Ankush Menat494bd9e2022-03-28 18:52:46 +053037 employee.append(
38 "internal_work_history",
39 {
40 "branch": employee.branch,
41 "designation": employee.designation,
42 "department": employee.department,
43 "from_date": employee.date_of_joining,
44 },
45 )
Mohammed Yusuf Shaikh03bfc772021-10-21 10:15:09 +053046
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053047 internal_work_history = {}
Manas Solankib6988462018-05-10 18:07:20 +053048 for item in details:
Chillar Anand95460d92021-09-14 12:00:34 +053049 field = frappe.get_meta("Employee").get_field(item.fieldname)
50 if not field:
51 continue
52 fieldtype = field.fieldtype
Manas Solankib6988462018-05-10 18:07:20 +053053 new_data = item.new if not cancel else item.current
54 if fieldtype == "Date" and new_data:
55 new_data = getdate(new_data)
Ankush Menat494bd9e2022-03-28 18:52:46 +053056 elif fieldtype == "Datetime" and new_data:
Manas Solankib6988462018-05-10 18:07:20 +053057 new_data = get_datetime(new_data)
58 setattr(employee, item.fieldname, new_data)
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053059 if item.fieldname in ["department", "designation", "branch"]:
60 internal_work_history[item.fieldname] = item.new
Mohammed Yusuf Shaikh03bfc772021-10-21 10:15:09 +053061
Ranjith Kurungadame46639f2018-06-11 11:24:44 +053062 if internal_work_history and not cancel:
63 internal_work_history["from_date"] = date
64 employee.append("internal_work_history", internal_work_history)
Mohammed Yusuf Shaikh03bfc772021-10-21 10:15:09 +053065
66 if cancel:
67 delete_employee_work_history(details, employee, date)
68
Manas Solankib6988462018-05-10 18:07:20 +053069 return employee
70
Ankush Menat494bd9e2022-03-28 18:52:46 +053071
Mohammed Yusuf Shaikh03bfc772021-10-21 10:15:09 +053072def delete_employee_work_history(details, employee, date):
73 filters = {}
74 for d in details:
75 for history in employee.internal_work_history:
76 if d.property == "Department" and history.department == d.new:
77 department = d.new
78 filters["department"] = department
79 if d.property == "Designation" and history.designation == d.new:
80 designation = d.new
81 filters["designation"] = designation
82 if d.property == "Branch" and history.branch == d.new:
83 branch = d.new
84 filters["branch"] = branch
85 if date and date == history.from_date:
86 filters["from_date"] = date
87 if filters:
88 frappe.db.delete("Employee Internal Work History", filters)
89
90
Ranjithfddfffd2018-05-05 13:27:26 +053091@frappe.whitelist()
Ranjithfddfffd2018-05-05 13:27:26 +053092def get_employee_field_property(employee, fieldname):
93 if employee and fieldname:
94 field = frappe.get_meta("Employee").get_field(fieldname)
95 value = frappe.db.get_value("Employee", employee, fieldname)
96 options = field.options
97 if field.fieldtype == "Date":
98 value = formatdate(value)
99 elif field.fieldtype == "Datetime":
100 value = format_datetime(value)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530101 return {"value": value, "datatype": field.fieldtype, "label": field.label, "options": options}
Ranjithfddfffd2018-05-05 13:27:26 +0530102 else:
103 return False
104
Ankush Menat494bd9e2022-03-28 18:52:46 +0530105
Jamsheer0e2cc552018-05-08 11:48:25 +0530106def validate_dates(doc, from_date, to_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530107 date_of_joining, relieving_date = frappe.db.get_value(
108 "Employee", doc.employee, ["date_of_joining", "relieving_date"]
109 )
Jamsheer0e2cc552018-05-08 11:48:25 +0530110 if getdate(from_date) > getdate(to_date):
111 frappe.throw(_("To date can not be less than from date"))
112 elif getdate(from_date) > getdate(nowdate()):
113 frappe.throw(_("Future dates not allowed"))
114 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
115 frappe.throw(_("From date can not be less than employee's joining date"))
116 elif relieving_date and getdate(to_date) > getdate(relieving_date):
117 frappe.throw(_("To date can not greater than employee's relieving date"))
118
Ankush Menat494bd9e2022-03-28 18:52:46 +0530119
120def validate_overlap(doc, from_date, to_date, company=None):
Jamsheer0e2cc552018-05-08 11:48:25 +0530121 query = """
122 select name
123 from `tab{0}`
124 where name != %(name)s
125 """
126 query += get_doc_condition(doc.doctype)
127
128 if not doc.name:
129 # hack! if name is null, it could cause problems with !=
Ankush Menat494bd9e2022-03-28 18:52:46 +0530130 doc.name = "New " + doc.doctype
Jamsheer0e2cc552018-05-08 11:48:25 +0530131
Ankush Menat494bd9e2022-03-28 18:52:46 +0530132 overlap_doc = frappe.db.sql(
133 query.format(doc.doctype),
134 {
Nabin Haitd53c2c02018-07-30 20:16:48 +0530135 "employee": doc.get("employee"),
Jamsheer0e2cc552018-05-08 11:48:25 +0530136 "from_date": from_date,
137 "to_date": to_date,
138 "name": doc.name,
Ankush Menat494bd9e2022-03-28 18:52:46 +0530139 "company": company,
140 },
141 as_dict=1,
142 )
Jamsheer0e2cc552018-05-08 11:48:25 +0530143
144 if overlap_doc:
deepeshgarg00778b273a2018-10-31 18:12:03 +0530145 if doc.get("employee"):
146 exists_for = doc.employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530147 if company:
148 exists_for = company
149 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
150
Ankush Menat494bd9e2022-03-28 18:52:46 +0530151
Jamsheer0e2cc552018-05-08 11:48:25 +0530152def get_doc_condition(doctype):
153 if doctype == "Compensatory Leave Request":
154 return "and employee = %(employee)s and docstatus < 2 \
155 and (work_from_date between %(from_date)s and %(to_date)s \
156 or work_end_date between %(from_date)s and %(to_date)s \
157 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
158 elif doctype == "Leave Period":
159 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
160 or to_date between %(from_date)s and %(to_date)s \
161 or (from_date < %(from_date)s and to_date > %(to_date)s))"
162
Ankush Menat494bd9e2022-03-28 18:52:46 +0530163
Jamsheer0e2cc552018-05-08 11:48:25 +0530164def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530165 msg = (
166 _("A {0} exists between {1} and {2} (").format(
167 doc.doctype, formatdate(from_date), formatdate(to_date)
168 )
169 + """ <b><a href="/app/Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc)
Jamsheer0e2cc552018-05-08 11:48:25 +0530170 + _(") for {0}").format(exists_for)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530171 )
Jamsheer0e2cc552018-05-08 11:48:25 +0530172 frappe.throw(msg)
173
Ankush Menat494bd9e2022-03-28 18:52:46 +0530174
Nabin Hait58ee6c12020-04-26 17:45:57 +0530175def validate_duplicate_exemption_for_payroll_period(doctype, docname, payroll_period, employee):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530176 existing_record = frappe.db.exists(
177 doctype,
178 {
179 "payroll_period": payroll_period,
180 "employee": employee,
181 "docstatus": ["<", 2],
182 "name": ["!=", docname],
183 },
184 )
Nabin Hait58ee6c12020-04-26 17:45:57 +0530185 if existing_record:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530186 frappe.throw(
187 _("{0} already exists for employee {1} and period {2}").format(
188 doctype, employee, payroll_period
189 ),
190 DuplicateDeclarationError,
191 )
192
Nabin Hait58ee6c12020-04-26 17:45:57 +0530193
Ranjith5a8e6422018-05-10 15:06:49 +0530194def validate_tax_declaration(declarations):
195 subcategories = []
Nabin Hait04e7bf42019-04-25 18:44:10 +0530196 for d in declarations:
197 if d.exemption_sub_category in subcategories:
198 frappe.throw(_("More than one selection for {0} not allowed").format(d.exemption_sub_category))
199 subcategories.append(d.exemption_sub_category)
200
Ankush Menat494bd9e2022-03-28 18:52:46 +0530201
Nabin Hait04e7bf42019-04-25 18:44:10 +0530202def get_total_exemption_amount(declarations):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530203 exemptions = frappe._dict()
204 for d in declarations:
205 exemptions.setdefault(d.exemption_category, frappe._dict())
206 category_max_amount = exemptions.get(d.exemption_category).max_amount
207 if not category_max_amount:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530208 category_max_amount = frappe.db.get_value(
209 "Employee Tax Exemption Category", d.exemption_category, "max_amount"
210 )
Nabin Hait04e7bf42019-04-25 18:44:10 +0530211 exemptions.get(d.exemption_category).max_amount = category_max_amount
Ankush Menat494bd9e2022-03-28 18:52:46 +0530212 sub_category_exemption_amount = (
213 d.max_amount if (d.max_amount and flt(d.amount) > flt(d.max_amount)) else d.amount
214 )
Nabin Hait04e7bf42019-04-25 18:44:10 +0530215
216 exemptions.get(d.exemption_category).setdefault("total_exemption_amount", 0.0)
217 exemptions.get(d.exemption_category).total_exemption_amount += flt(sub_category_exemption_amount)
218
Ankush Menat494bd9e2022-03-28 18:52:46 +0530219 if (
220 category_max_amount
221 and exemptions.get(d.exemption_category).total_exemption_amount > category_max_amount
222 ):
Nabin Hait04e7bf42019-04-25 18:44:10 +0530223 exemptions.get(d.exemption_category).total_exemption_amount = category_max_amount
224
225 total_exemption_amount = sum([flt(d.total_exemption_amount) for d in exemptions.values()])
226 return total_exemption_amount
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530227
Ankush Menat494bd9e2022-03-28 18:52:46 +0530228
Jannat Patel1175e062021-06-01 10:53:00 +0530229@frappe.whitelist()
Jamsheer0e2cc552018-05-08 11:48:25 +0530230def get_leave_period(from_date, to_date, company):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530231 leave_period = frappe.db.sql(
232 """
Jamsheer0e2cc552018-05-08 11:48:25 +0530233 select name, from_date, to_date
234 from `tabLeave Period`
235 where company=%(company)s and is_active=1
236 and (from_date between %(from_date)s and %(to_date)s
237 or to_date between %(from_date)s and %(to_date)s
238 or (from_date < %(from_date)s and to_date > %(to_date)s))
Ankush Menat494bd9e2022-03-28 18:52:46 +0530239 """,
240 {"from_date": from_date, "to_date": to_date, "company": company},
241 as_dict=1,
242 )
Jamsheer0e2cc552018-05-08 11:48:25 +0530243
244 if leave_period:
245 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530246
Ankush Menat494bd9e2022-03-28 18:52:46 +0530247
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530248def generate_leave_encashment():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530249 """Generates a draft leave encashment on allocation expiry"""
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530250 from erpnext.hr.doctype.leave_encashment.leave_encashment import create_leave_encashment
Mangesh-Khairnar3662ed52019-08-08 19:47:17 +0530251
Ankush Menat494bd9e2022-03-28 18:52:46 +0530252 if frappe.db.get_single_value("HR Settings", "auto_leave_encashment"):
253 leave_type = frappe.get_all("Leave Type", filters={"allow_encashment": 1}, fields=["name"])
254 leave_type = [l["name"] for l in leave_type]
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530255
Ankush Menat494bd9e2022-03-28 18:52:46 +0530256 leave_allocation = frappe.get_all(
257 "Leave Allocation",
258 filters={"to_date": add_days(today(), -1), "leave_type": ("in", leave_type)},
259 fields=[
260 "employee",
261 "leave_period",
262 "leave_type",
263 "to_date",
264 "total_leaves_allocated",
265 "new_leaves_allocated",
266 ],
267 )
Mangesh-Khairnarf281f002019-08-05 14:47:02 +0530268
269 create_leave_encashment(leave_allocation=leave_allocation)
270
Ankush Menat494bd9e2022-03-28 18:52:46 +0530271
Rucha Mahabale25544f2022-02-06 20:30:46 +0530272def allocate_earned_leaves(ignore_duplicates=False):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530273 """Allocate earned leaves to Employees"""
Anurag Mishra755b7732020-11-25 16:05:17 +0530274 e_leave_types = get_earned_leaves()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530275 today = getdate()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530276
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530277 for e_leave_type in e_leave_types:
Anurag Mishra755b7732020-11-25 16:05:17 +0530278
279 leave_allocations = get_leave_allocations(today, e_leave_type.name)
280
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530281 for allocation in leave_allocations:
Anurag Mishra755b7732020-11-25 16:05:17 +0530282
283 if not allocation.leave_policy_assignment and not allocation.leave_policy:
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530284 continue
Anurag Mishra755b7732020-11-25 16:05:17 +0530285
Ankush Menat494bd9e2022-03-28 18:52:46 +0530286 leave_policy = (
287 allocation.leave_policy
288 if allocation.leave_policy
289 else frappe.db.get_value(
290 "Leave Policy Assignment", allocation.leave_policy_assignment, ["leave_policy"]
291 )
292 )
Anurag Mishra755b7732020-11-25 16:05:17 +0530293
Ankush Menat494bd9e2022-03-28 18:52:46 +0530294 annual_allocation = frappe.db.get_value(
295 "Leave Policy Detail",
296 filters={"parent": leave_policy, "leave_type": e_leave_type.name},
297 fieldname=["annual_allocation"],
298 )
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530299
Ankush Menat494bd9e2022-03-28 18:52:46 +0530300 from_date = allocation.from_date
Mangesh-Khairnar5d5f5b42020-02-20 13:25:55 +0530301
Rucha Mahabal7326d572022-02-08 17:14:11 +0530302 if e_leave_type.based_on_date_of_joining:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530303 from_date = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530304
Ankush Menat494bd9e2022-03-28 18:52:46 +0530305 if check_effective_date(
306 from_date, today, e_leave_type.earned_leave_frequency, e_leave_type.based_on_date_of_joining
307 ):
308 update_previous_leave_allocation(
309 allocation, annual_allocation, e_leave_type, ignore_duplicates
310 )
Anurag Mishra755b7732020-11-25 16:05:17 +0530311
Anurag Mishra755b7732020-11-25 16:05:17 +0530312
Ankush Menat494bd9e2022-03-28 18:52:46 +0530313def update_previous_leave_allocation(
314 allocation, annual_allocation, e_leave_type, ignore_duplicates=False
315):
316 earned_leaves = get_monthly_earned_leave(
317 annual_allocation, e_leave_type.earned_leave_frequency, e_leave_type.rounding
318 )
Anurag Mishra755b7732020-11-25 16:05:17 +0530319
Ankush Menat494bd9e2022-03-28 18:52:46 +0530320 allocation = frappe.get_doc("Leave Allocation", allocation.name)
321 new_allocation = flt(allocation.total_leaves_allocated) + flt(earned_leaves)
Anurag Mishra755b7732020-11-25 16:05:17 +0530322
Ankush Menat494bd9e2022-03-28 18:52:46 +0530323 if new_allocation > e_leave_type.max_leaves_allowed and e_leave_type.max_leaves_allowed > 0:
324 new_allocation = e_leave_type.max_leaves_allowed
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530325
Ankush Menat494bd9e2022-03-28 18:52:46 +0530326 if new_allocation != allocation.total_leaves_allocated:
327 today_date = today()
328
329 if ignore_duplicates or not is_earned_leave_already_allocated(allocation, annual_allocation):
330 allocation.db_set("total_leaves_allocated", new_allocation, update_modified=False)
331 create_additional_leave_ledger_entry(allocation, earned_leaves, today_date)
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530332
Rucha Mahabalec65af52022-04-07 10:07:39 +0530333 if e_leave_type.based_on_date_of_joining:
334 text = _("allocated {0} leave(s) via scheduler on {1} based on the date of joining").format(
335 frappe.bold(earned_leaves), frappe.bold(formatdate(today_date))
336 )
337 else:
338 text = _("allocated {0} leave(s) via scheduler on {1}").format(
339 frappe.bold(earned_leaves), frappe.bold(formatdate(today_date))
340 )
341
342 allocation.add_comment(comment_type="Info", text=text)
343
Anurag Mishra755b7732020-11-25 16:05:17 +0530344
Nabin Hait190106a2021-03-02 13:38:14 +0530345def get_monthly_earned_leave(annual_leaves, frequency, rounding):
346 earned_leaves = 0.0
347 divide_by_frequency = {"Yearly": 1, "Half-Yearly": 6, "Quarterly": 4, "Monthly": 12}
348 if annual_leaves:
349 earned_leaves = flt(annual_leaves) / divide_by_frequency[frequency]
350 if rounding:
351 if rounding == "0.25":
352 earned_leaves = round(earned_leaves * 4) / 4
353 elif rounding == "0.5":
354 earned_leaves = round(earned_leaves * 2) / 2
355 else:
356 earned_leaves = round(earned_leaves)
357
358 return earned_leaves
359
Anurag Mishra755b7732020-11-25 16:05:17 +0530360
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530361def is_earned_leave_already_allocated(allocation, annual_allocation):
Rucha Mahabala52ba0a2022-02-05 16:40:55 +0530362 from erpnext.hr.doctype.leave_policy_assignment.leave_policy_assignment import (
363 get_leave_type_details,
364 )
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530365
366 leave_type_details = get_leave_type_details()
367 date_of_joining = frappe.db.get_value("Employee", allocation.employee, "date_of_joining")
368
Rucha Mahabal9b0f9c32022-02-11 20:08:01 +0530369 assignment = frappe.get_doc("Leave Policy Assignment", allocation.leave_policy_assignment)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530370 leaves_for_passed_months = assignment.get_leaves_for_passed_months(
371 allocation.leave_type, annual_allocation, leave_type_details, date_of_joining
372 )
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530373
Rucha Mahabalbd1555b2022-02-08 14:36:31 +0530374 # exclude carry-forwarded leaves while checking for leave allocation for passed months
375 num_allocations = allocation.total_leaves_allocated
376 if allocation.unused_leaves:
377 num_allocations -= allocation.unused_leaves
378
379 if num_allocations >= leaves_for_passed_months:
Rucha Mahabal25c7f852022-02-05 16:05:46 +0530380 return True
381 return False
382
383
Anurag Mishra755b7732020-11-25 16:05:17 +0530384def get_leave_allocations(date, leave_type):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530385 return frappe.db.sql(
386 """select name, employee, from_date, to_date, leave_policy_assignment, leave_policy
Anurag Mishra755b7732020-11-25 16:05:17 +0530387 from `tabLeave Allocation`
388 where
389 %s between from_date and to_date and docstatus=1
390 and leave_type=%s""",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530391 (date, leave_type),
392 as_dict=1,
393 )
Anurag Mishra755b7732020-11-25 16:05:17 +0530394
395
396def get_earned_leaves():
Ankush Menat494bd9e2022-03-28 18:52:46 +0530397 return frappe.get_all(
398 "Leave Type",
399 fields=[
400 "name",
401 "max_leaves_allowed",
402 "earned_leave_frequency",
403 "rounding",
404 "based_on_date_of_joining",
405 ],
406 filters={"is_earned_leave": 1},
407 )
408
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530409
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530410def create_additional_leave_ledger_entry(allocation, leaves, date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530411 """Create leave ledger entry for leave types"""
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530412 allocation.new_leaves_allocated = leaves
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530413 allocation.from_date = date
Mangesh-Khairnar5cbe6162019-08-08 17:06:15 +0530414 allocation.unused_leaves = 0
Mangesh-Khairnar3863fc52019-06-06 20:34:10 +0530415 allocation.create_leave_ledger_entry()
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530416
Ankush Menat494bd9e2022-03-28 18:52:46 +0530417
Rucha Mahabal7326d572022-02-08 17:14:11 +0530418def check_effective_date(from_date, to_date, frequency, based_on_date_of_joining):
Anurag Mishra755b7732020-11-25 16:05:17 +0530419 import calendar
Chillar Anand915b3432021-09-02 16:44:59 +0530420
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530421 from dateutil import relativedelta
Anurag Mishra755b7732020-11-25 16:05:17 +0530422
423 from_date = get_datetime(from_date)
424 to_date = get_datetime(to_date)
425 rd = relativedelta.relativedelta(to_date, from_date)
Ankush Menat494bd9e2022-03-28 18:52:46 +0530426 # last day of month
427 last_day = calendar.monthrange(to_date.year, to_date.month)[1]
Anurag Mishra755b7732020-11-25 16:05:17 +0530428
Ankush Menat494bd9e2022-03-28 18:52:46 +0530429 if (from_date.day == to_date.day and based_on_date_of_joining) or (
430 not based_on_date_of_joining and to_date.day == last_day
431 ):
Anurag Mishra755b7732020-11-25 16:05:17 +0530432 if frequency == "Monthly":
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530433 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530434 elif frequency == "Quarterly" and rd.months % 3:
Joyce Babu3d012132019-03-06 13:04:45 +0530435 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530436 elif frequency == "Half-Yearly" and rd.months % 6:
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530437 return True
Anurag Mishra755b7732020-11-25 16:05:17 +0530438 elif frequency == "Yearly" and rd.months % 12:
439 return True
440
441 if frappe.flags.in_test:
442 return True
443
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530444 return False
Nabin Hait8c7af492018-06-04 11:23:36 +0530445
Anurag Mishra755b7732020-11-25 16:05:17 +0530446
Ranjith155ecc12018-05-30 13:37:15 +0530447def get_salary_assignment(employee, date):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530448 assignment = frappe.db.sql(
449 """
Ranjith155ecc12018-05-30 13:37:15 +0530450 select * from `tabSalary Structure Assignment`
451 where employee=%(employee)s
452 and docstatus = 1
Ankush Menat494bd9e2022-03-28 18:52:46 +0530453 and %(on_date)s >= from_date order by from_date desc limit 1""",
454 {
455 "employee": employee,
456 "on_date": date,
457 },
458 as_dict=1,
459 )
Ranjith155ecc12018-05-30 13:37:15 +0530460 return assignment[0] if assignment else None
Ranjith793f8e82018-05-30 20:50:48 +0530461
Ankush Menat494bd9e2022-03-28 18:52:46 +0530462
Jamsheer8d66f1e2018-06-12 11:30:59 +0530463def get_sal_slip_total_benefit_given(employee, payroll_period, component=False):
464 total_given_benefit_amount = 0
465 query = """
466 select sum(sd.amount) as 'total_amount'
467 from `tabSalary Slip` ss, `tabSalary Detail` sd
468 where ss.employee=%(employee)s
469 and ss.docstatus = 1 and ss.name = sd.parent
470 and sd.is_flexible_benefit = 1 and sd.parentfield = "earnings"
471 and sd.parenttype = "Salary Slip"
472 and (ss.start_date between %(start_date)s and %(end_date)s
473 or ss.end_date between %(start_date)s and %(end_date)s
474 or (ss.start_date < %(start_date)s and ss.end_date > %(end_date)s))
475 """
476
477 if component:
478 query += "and sd.salary_component = %(component)s"
479
Ankush Menat494bd9e2022-03-28 18:52:46 +0530480 sum_of_given_benefit = frappe.db.sql(
481 query,
482 {
483 "employee": employee,
484 "start_date": payroll_period.start_date,
485 "end_date": payroll_period.end_date,
486 "component": component,
487 },
488 as_dict=True,
489 )
Jamsheer8d66f1e2018-06-12 11:30:59 +0530490
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530491 if sum_of_given_benefit and flt(sum_of_given_benefit[0].total_amount) > 0:
Jamsheer8d66f1e2018-06-12 11:30:59 +0530492 total_given_benefit_amount = sum_of_given_benefit[0].total_amount
493 return total_given_benefit_amount
Jamsheercc25eb02018-06-13 15:14:24 +0530494
Ankush Menat494bd9e2022-03-28 18:52:46 +0530495
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530496def get_holiday_dates_for_employee(employee, start_date, end_date):
497 """return a list of holiday dates for the given employee between start_date and end_date"""
Ankush Menatb147b852021-09-01 16:45:57 +0530498 # return only date
499 holidays = get_holidays_for_employee(employee, start_date, end_date)
500
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530501 return [cstr(h.holiday_date) for h in holidays]
Mangesh-Khairnar43508462019-12-09 14:27:38 +0530502
Jamsheercc25eb02018-06-13 15:14:24 +0530503
Ankush Menat494bd9e2022-03-28 18:52:46 +0530504def get_holidays_for_employee(
505 employee, start_date, end_date, raise_exception=True, only_non_weekly=False
506):
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530507 """Get Holidays for a given employee
Jamsheercc25eb02018-06-13 15:14:24 +0530508
Ankush Menat494bd9e2022-03-28 18:52:46 +0530509 `employee` (str)
510 `start_date` (str or datetime)
511 `end_date` (str or datetime)
512 `raise_exception` (bool)
513 `only_non_weekly` (bool)
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530514
Ankush Menat494bd9e2022-03-28 18:52:46 +0530515 return: list of dicts with `holiday_date` and `description`
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530516 """
517 holiday_list = get_holiday_list_for_employee(employee, raise_exception=raise_exception)
518
519 if not holiday_list:
520 return []
521
Ankush Menat494bd9e2022-03-28 18:52:46 +0530522 filters = {"parent": holiday_list, "holiday_date": ("between", [start_date, end_date])}
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530523
524 if only_non_weekly:
Ankush Menat494bd9e2022-03-28 18:52:46 +0530525 filters["weekly_off"] = False
Frappe PR Bot255b99e2021-08-24 20:19:22 +0530526
Ankush Menat494bd9e2022-03-28 18:52:46 +0530527 holidays = frappe.get_all("Holiday", fields=["description", "holiday_date"], filters=filters)
Ankush Menatb147b852021-09-01 16:45:57 +0530528
Jamsheercc25eb02018-06-13 15:14:24 +0530529 return holidays
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530530
Ankush Menat494bd9e2022-03-28 18:52:46 +0530531
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530532@erpnext.allow_regional
533def calculate_annual_eligible_hra_exemption(doc):
534 # Don't delete this method, used for localization
535 # Indian HRA Exemption Calculation
536 return {}
537
Ankush Menat494bd9e2022-03-28 18:52:46 +0530538
Ranjith Kurungadama8e047a2018-06-14 17:56:16 +0530539@erpnext.allow_regional
540def calculate_hra_exemption_for_period(doc):
541 # Don't delete this method, used for localization
542 # Indian HRA Exemption Calculation
543 return {}
Jamsheer55a2f4d2018-06-20 11:04:21 +0530544
Ankush Menat494bd9e2022-03-28 18:52:46 +0530545
Jamsheer55a2f4d2018-06-20 11:04:21 +0530546def get_previous_claimed_amount(employee, payroll_period, non_pro_rata=False, component=False):
547 total_claimed_amount = 0
548 query = """
549 select sum(claimed_amount) as 'total_amount'
550 from `tabEmployee Benefit Claim`
551 where employee=%(employee)s
552 and docstatus = 1
553 and (claim_date between %(start_date)s and %(end_date)s)
554 """
555 if non_pro_rata:
556 query += "and pay_against_benefit_claim = 1"
557 if component:
558 query += "and earning_component = %(component)s"
559
Ankush Menat494bd9e2022-03-28 18:52:46 +0530560 sum_of_claimed_amount = frappe.db.sql(
561 query,
562 {
563 "employee": employee,
564 "start_date": payroll_period.start_date,
565 "end_date": payroll_period.end_date,
566 "component": component,
567 },
568 as_dict=True,
569 )
Rushabh Mehtadf23c7d2018-07-05 15:19:28 +0530570 if sum_of_claimed_amount and flt(sum_of_claimed_amount[0].total_amount) > 0:
Jamsheer55a2f4d2018-06-20 11:04:21 +0530571 total_claimed_amount = sum_of_claimed_amount[0].total_amount
572 return total_claimed_amount
Anurag Mishra755b7732020-11-25 16:05:17 +0530573
Ankush Menat494bd9e2022-03-28 18:52:46 +0530574
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530575def share_doc_with_approver(doc, user):
576 # if approver does not have permissions, share
577 if not frappe.has_permission(doc=doc, ptype="submit", user=user):
Ankush Menat494bd9e2022-03-28 18:52:46 +0530578 frappe.share.add(doc.doctype, doc.name, user, submit=1, flags={"ignore_share_permission": True})
Rucha Mahabal8c055b52021-04-04 18:45:06 +0530579
Ankush Menat494bd9e2022-03-28 18:52:46 +0530580 frappe.msgprint(
581 _("Shared with the user {0} with {1} access").format(user, frappe.bold("submit"), alert=True)
582 )
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530583
584 # remove shared doc if approver changes
585 doc_before_save = doc.get_doc_before_save()
586 if doc_before_save:
587 approvers = {
588 "Leave Application": "leave_approver",
589 "Expense Claim": "expense_approver",
Ankush Menat494bd9e2022-03-28 18:52:46 +0530590 "Shift Request": "approver",
Rucha Mahabalba10ef42021-04-04 17:16:48 +0530591 }
592
593 approver = approvers.get(doc.doctype)
594 if doc_before_save.get(approver) != doc.get(approver):
595 frappe.share.remove(doc.doctype, doc.name, doc_before_save.get(approver))
Rucha Mahabal821db5c2021-07-30 10:21:42 +0530596
Ankush Menat494bd9e2022-03-28 18:52:46 +0530597
Rucha Mahabal821db5c2021-07-30 10:21:42 +0530598def validate_active_employee(employee):
599 if frappe.db.get_value("Employee", employee, "status") == "Inactive":
Ankush Menat494bd9e2022-03-28 18:52:46 +0530600 frappe.throw(
601 _("Transactions cannot be created for an Inactive Employee {0}.").format(
602 get_link_to_form("Employee", employee)
603 ),
604 InactiveEmployeeStatusError,
605 )