blob: 4e937c60a5fc7e34d42ada72d4c2ed581d478229 [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
4from __future__ import unicode_literals
Rushabh Mehta793ba6b2014-02-14 15:47:51 +05305import frappe
6from frappe import _
Ranjith Kurungadam375db612018-06-01 16:09:28 +05307from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt
Manas Solankib6988462018-05-10 18:07:20 +05308from frappe.model.document import Document
9from frappe.desk.form import assign_to
10
11class EmployeeBoardingController(Document):
12 '''
13 Create the project and the task for the boarding process
14 Assign to the concerned person and roles as per the onboarding/separation template
15 '''
16 def validate(self):
17 # remove the task if linked before submitting the form
18 if self.amended_from:
19 for activity in self.activities:
20 activity.task = ''
21
22 def on_submit(self):
23 # create the project for the given employee onboarding
Manas Solanki70899f52018-05-15 18:52:14 +053024 project_name = _(self.doctype) + " : "
Manas Solankib6988462018-05-10 18:07:20 +053025 if self.doctype == "Employee Onboarding":
Manas Solanki70899f52018-05-15 18:52:14 +053026 project_name += self.job_applicant
Manas Solankib6988462018-05-10 18:07:20 +053027 else:
Manas Solanki70899f52018-05-15 18:52:14 +053028 project_name += self.employee
Manas Solankib6988462018-05-10 18:07:20 +053029 project = frappe.get_doc({
30 "doctype": "Project",
31 "project_name": project_name,
32 "expected_start_date": self.date_of_joining if self.doctype == "Employee Onboarding" else self.resignation_letter_date,
33 "department": self.department,
34 "company": self.company
35 }).insert(ignore_permissions=True)
36 self.db_set("project", project.name)
37
38 # create the task for the given project and assign to the concerned person
39 for activity in self.activities:
40 task = frappe.get_doc({
41 "doctype": "Task",
42 "project": project.name,
Manas Solanki094e1842018-05-14 20:33:28 +053043 "subject": activity.activity_name + " : " + self.employee_name,
Manas Solankib6988462018-05-10 18:07:20 +053044 "description": activity.description,
45 "department": self.department,
46 "company": self.company
47 }).insert(ignore_permissions=True)
48 activity.db_set("task", task.name)
49 users = [activity.user] if activity.user else []
50 if activity.role:
51 user_list = frappe.db.sql_list('''select distinct(parent) from `tabHas Role`
52 where parenttype='User' and role=%s''', activity.role)
53 users = users + user_list
54
55 # assign the task the users
56 if users:
57 self.assign_task_to_users(task, set(users))
58
59 def assign_task_to_users(self, task, users):
60 for user in users:
61 args = {
62 'assign_to' : user,
63 'doctype' : task.doctype,
64 'name' : task.name,
65 'description' : task.description or task.subject,
66 }
67 assign_to.add(args)
68
69 def on_cancel(self):
70 # delete task project
71 for task in frappe.get_all("Task", filters={"project": self.project}):
72 frappe.delete_doc("Task", task.name)
73 frappe.delete_doc("Project", self.project)
74 self.db_set('project', '')
75 for activity in self.activities:
76 activity.db_set("task", "")
77
78
79@frappe.whitelist()
80def get_onboarding_details(parent, parenttype):
81 return frappe.get_list("Employee Boarding Activity",
82 fields=["activity_name", "role", "user", "required_for_employee_creation", "description"],
83 filters={"parent": parent, "parenttype": parenttype},
84 order_by= "idx")
Anand Doshi60666a22013-04-12 20:19:53 +053085
Anand Doshic280d062014-05-30 14:43:36 +053086def set_employee_name(doc):
87 if doc.employee and not doc.employee_name:
88 doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name")
Ranjithfddfffd2018-05-05 13:27:26 +053089
Manas Solankib6988462018-05-10 18:07:20 +053090def update_employee(employee, details, cancel=False):
91 for item in details:
92 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
93 new_data = item.new if not cancel else item.current
94 if fieldtype == "Date" and new_data:
95 new_data = getdate(new_data)
96 elif fieldtype =="Datetime" and new_data:
97 new_data = get_datetime(new_data)
98 setattr(employee, item.fieldname, new_data)
99 return employee
100
Ranjithfddfffd2018-05-05 13:27:26 +0530101@frappe.whitelist()
102def get_employee_fields_label():
103 fields = []
104 for df in frappe.get_meta("Employee").get("fields"):
105 if df.fieldtype in ["Data", "Date", "Datetime", "Float", "Int",
106 "Link", "Percent", "Select", "Small Text"] and df.fieldname not in ["lft", "rgt", "old_parent"]:
107 fields.append({"value": df.fieldname, "label": df.label})
108 return fields
109
110@frappe.whitelist()
111def get_employee_field_property(employee, fieldname):
112 if employee and fieldname:
113 field = frappe.get_meta("Employee").get_field(fieldname)
114 value = frappe.db.get_value("Employee", employee, fieldname)
115 options = field.options
116 if field.fieldtype == "Date":
117 value = formatdate(value)
118 elif field.fieldtype == "Datetime":
119 value = format_datetime(value)
120 return {
121 "value" : value,
122 "datatype" : field.fieldtype,
123 "label" : field.label,
124 "options" : options
125 }
126 else:
127 return False
128
129def update_employee(employee, details, cancel=False):
130 for item in details:
131 fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype
132 new_data = item.new if not cancel else item.current
133 if fieldtype == "Date" and new_data:
134 new_data = getdate(new_data)
135 elif fieldtype =="Datetime" and new_data:
136 new_data = get_datetime(new_data)
137 setattr(employee, item.fieldname, new_data)
138 return employee
Jamsheer0e2cc552018-05-08 11:48:25 +0530139
140def validate_dates(doc, from_date, to_date):
141 date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"])
142 if getdate(from_date) > getdate(to_date):
143 frappe.throw(_("To date can not be less than from date"))
144 elif getdate(from_date) > getdate(nowdate()):
145 frappe.throw(_("Future dates not allowed"))
146 elif date_of_joining and getdate(from_date) < getdate(date_of_joining):
147 frappe.throw(_("From date can not be less than employee's joining date"))
148 elif relieving_date and getdate(to_date) > getdate(relieving_date):
149 frappe.throw(_("To date can not greater than employee's relieving date"))
150
151def validate_overlap(doc, from_date, to_date, company = None):
152 query = """
153 select name
154 from `tab{0}`
155 where name != %(name)s
156 """
157 query += get_doc_condition(doc.doctype)
158
159 if not doc.name:
160 # hack! if name is null, it could cause problems with !=
161 doc.name = "New "+doc.doctype
162
163 overlap_doc = frappe.db.sql(query.format(doc.doctype),{
164 "employee": doc.employee,
165 "from_date": from_date,
166 "to_date": to_date,
167 "name": doc.name,
168 "company": company
169 }, as_dict = 1)
170
171 if overlap_doc:
172 exists_for = doc.employee
173 if company:
174 exists_for = company
175 throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date)
176
177def get_doc_condition(doctype):
178 if doctype == "Compensatory Leave Request":
179 return "and employee = %(employee)s and docstatus < 2 \
180 and (work_from_date between %(from_date)s and %(to_date)s \
181 or work_end_date between %(from_date)s and %(to_date)s \
182 or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))"
183 elif doctype == "Leave Period":
184 return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \
185 or to_date between %(from_date)s and %(to_date)s \
186 or (from_date < %(from_date)s and to_date > %(to_date)s))"
187
188def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date):
189 msg = _("A {0} exists between {1} and {2} (").format(doc.doctype,
190 formatdate(from_date), formatdate(to_date)) \
191 + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \
192 + _(") for {0}").format(exists_for)
193 frappe.throw(msg)
194
195def get_employee_leave_policy(employee):
196 leave_policy = frappe.db.get_value("Employee", employee, "leave_policy")
197 if not leave_policy:
198 employee_grade = frappe.db.get_value("Employee", employee, "grade")
199 if employee_grade:
200 leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy")
201 if not leave_policy:
202 frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade))
203 else:
204 frappe.throw(_("Employee {0} has no grade to get default leave policy").format(employee))
205 if leave_policy:
206 return frappe.get_doc("Leave Policy", leave_policy)
207
Ranjith5a8e6422018-05-10 15:06:49 +0530208def validate_tax_declaration(declarations):
209 subcategories = []
210 for declaration in declarations:
211 if declaration.exemption_sub_category in subcategories:
212 frappe.throw(_("More than one selection for {0} not \
213 allowed").format(declaration.exemption_sub_category), frappe.ValidationError)
214 subcategories.append(declaration.exemption_sub_category)
215 max_amount = frappe.db.get_value("Employee Tax Exemption Sub Category", \
216 declaration.exemption_sub_category, "max_amount")
217 if declaration.amount > max_amount:
218 frappe.throw(_("Max exemption amount for {0} is {1}").format(\
219 declaration.exemption_sub_category, max_amount), frappe.ValidationError)
rohitwaghchaure3f0c7352018-05-14 20:47:35 +0530220
Jamsheer0e2cc552018-05-08 11:48:25 +0530221def get_leave_period(from_date, to_date, company):
222 leave_period = frappe.db.sql("""
223 select name, from_date, to_date
224 from `tabLeave Period`
225 where company=%(company)s and is_active=1
226 and (from_date between %(from_date)s and %(to_date)s
227 or to_date between %(from_date)s and %(to_date)s
228 or (from_date < %(from_date)s and to_date > %(to_date)s))
229 """, {
230 "from_date": from_date,
231 "to_date": to_date,
232 "company": company
233 }, as_dict=1)
234
235 if leave_period:
236 return leave_period
Ranjithb485b1e2018-05-16 23:01:40 +0530237
238def get_payroll_period(from_date, to_date, company):
Ranjith58363e62018-05-17 10:00:33 +0530239 payroll_period = frappe.db.sql("""select pp.name, pd.start_date, pd.end_date from
Ranjithb485b1e2018-05-16 23:01:40 +0530240 `tabPayroll Period Date` pd join `tabPayroll Period` pp on
241 pd.parent=pp.name where pd.start_date<=%s and pd.end_date>= %s
242 and pp.company=%s""", (from_date, to_date, company), as_dict=1)
243 return payroll_period[0] if payroll_period else None
Ranjith Kurungadam375db612018-06-01 16:09:28 +0530244
245
246def allocate_earned_leaves():
247 '''Allocate earned leaves to Employees'''
248 e_leave_types = frappe.get_all("Leave Type",
249 fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"],
250 filters={'is_earned_leave' : 1})
251 today = getdate()
252 divide_by_frequency = {"Yearly": 1, "Quarterly": 4, "Monthly": 12}
253 if e_leave_types:
254 for e_leave_type in e_leave_types:
255 leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}'
256 between from_date and to_date and docstatus=1 and leave_type='{1}'"""
257 .format(today, e_leave_type.name), as_dict=1)
258 for allocation in leave_allocations:
259 leave_policy = get_employee_leave_policy(allocation.employee)
260 if not leave_policy:
261 continue
262 if not e_leave_type.earned_leave_frequency == "Monthly":
263 if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency):
264 continue
265 annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail`
266 where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name))
267 if annual_allocation and annual_allocation[0]:
268 earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency]
269 if e_leave_type.rounding == "0.5":
270 earned_leaves = round(earned_leaves * 2) / 2
271 else:
272 earned_leaves = round(earned_leaves)
273
274 allocated_leaves = frappe.db.get_value('Leave Allocation', allocation.name, 'total_leaves_allocated')
275 new_allocation = flt(allocated_leaves) + flt(earned_leaves)
276 new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed
277 frappe.db.set_value('Leave Allocation', allocation.name, 'total_leaves_allocated', new_allocation)
278
279def check_frequency_hit(from_date, to_date, frequency):
280 '''Return True if current date matches frequency'''
281 from_dt = get_datetime(from_date)
282 to_dt = get_datetime(to_date)
283 from dateutil import relativedelta
284 rd = relativedelta.relativedelta(to_dt, from_dt)
285 months = rd.months
286 if frequency == "Quarterly":
287 if not months % 3:
288 return True
289 elif frequency == "Yearly":
290 if not months % 12:
291 return True
292 return False