Anand Doshi | 885e074 | 2015-03-03 14:55:30 +0530 | [diff] [blame] | 1 | # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and Contributors |
Rushabh Mehta | e67d1fb | 2013-08-05 14:59:54 +0530 | [diff] [blame] | 2 | # License: GNU General Public License v3. See license.txt |
Anand Doshi | 60666a2 | 2013-04-12 20:19:53 +0530 | [diff] [blame] | 3 | |
| 4 | from __future__ import unicode_literals |
Rushabh Mehta | 793ba6b | 2014-02-14 15:47:51 +0530 | [diff] [blame] | 5 | import frappe |
| 6 | from frappe import _ |
Ranjith Kurungadam | 375db61 | 2018-06-01 16:09:28 +0530 | [diff] [blame] | 7 | from frappe.utils import formatdate, format_datetime, getdate, get_datetime, nowdate, flt |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 8 | from frappe.model.document import Document |
| 9 | from frappe.desk.form import assign_to |
Ranjith | 793f8e8 | 2018-05-30 20:50:48 +0530 | [diff] [blame] | 10 | from erpnext.hr.doctype.salary_structure.salary_structure import make_salary_slip |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 11 | |
| 12 | class EmployeeBoardingController(Document): |
| 13 | ''' |
| 14 | Create the project and the task for the boarding process |
| 15 | Assign to the concerned person and roles as per the onboarding/separation template |
| 16 | ''' |
| 17 | def validate(self): |
| 18 | # remove the task if linked before submitting the form |
| 19 | if self.amended_from: |
| 20 | for activity in self.activities: |
| 21 | activity.task = '' |
| 22 | |
| 23 | def on_submit(self): |
| 24 | # create the project for the given employee onboarding |
Manas Solanki | 70899f5 | 2018-05-15 18:52:14 +0530 | [diff] [blame] | 25 | project_name = _(self.doctype) + " : " |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 26 | if self.doctype == "Employee Onboarding": |
Manas Solanki | 70899f5 | 2018-05-15 18:52:14 +0530 | [diff] [blame] | 27 | project_name += self.job_applicant |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 28 | else: |
Manas Solanki | 70899f5 | 2018-05-15 18:52:14 +0530 | [diff] [blame] | 29 | project_name += self.employee |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 30 | project = frappe.get_doc({ |
| 31 | "doctype": "Project", |
| 32 | "project_name": project_name, |
| 33 | "expected_start_date": self.date_of_joining if self.doctype == "Employee Onboarding" else self.resignation_letter_date, |
| 34 | "department": self.department, |
| 35 | "company": self.company |
| 36 | }).insert(ignore_permissions=True) |
| 37 | self.db_set("project", project.name) |
| 38 | |
| 39 | # create the task for the given project and assign to the concerned person |
| 40 | for activity in self.activities: |
| 41 | task = frappe.get_doc({ |
| 42 | "doctype": "Task", |
| 43 | "project": project.name, |
Manas Solanki | 094e184 | 2018-05-14 20:33:28 +0530 | [diff] [blame] | 44 | "subject": activity.activity_name + " : " + self.employee_name, |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 45 | "description": activity.description, |
| 46 | "department": self.department, |
| 47 | "company": self.company |
| 48 | }).insert(ignore_permissions=True) |
| 49 | activity.db_set("task", task.name) |
| 50 | users = [activity.user] if activity.user else [] |
| 51 | if activity.role: |
| 52 | user_list = frappe.db.sql_list('''select distinct(parent) from `tabHas Role` |
| 53 | where parenttype='User' and role=%s''', activity.role) |
| 54 | users = users + user_list |
| 55 | |
| 56 | # assign the task the users |
| 57 | if users: |
| 58 | self.assign_task_to_users(task, set(users)) |
| 59 | |
| 60 | def assign_task_to_users(self, task, users): |
| 61 | for user in users: |
| 62 | args = { |
| 63 | 'assign_to' : user, |
| 64 | 'doctype' : task.doctype, |
| 65 | 'name' : task.name, |
| 66 | 'description' : task.description or task.subject, |
| 67 | } |
| 68 | assign_to.add(args) |
| 69 | |
| 70 | def on_cancel(self): |
| 71 | # delete task project |
| 72 | for task in frappe.get_all("Task", filters={"project": self.project}): |
| 73 | frappe.delete_doc("Task", task.name) |
| 74 | frappe.delete_doc("Project", self.project) |
| 75 | self.db_set('project', '') |
| 76 | for activity in self.activities: |
| 77 | activity.db_set("task", "") |
| 78 | |
| 79 | |
| 80 | @frappe.whitelist() |
| 81 | def get_onboarding_details(parent, parenttype): |
| 82 | return frappe.get_list("Employee Boarding Activity", |
| 83 | fields=["activity_name", "role", "user", "required_for_employee_creation", "description"], |
| 84 | filters={"parent": parent, "parenttype": parenttype}, |
| 85 | order_by= "idx") |
Anand Doshi | 60666a2 | 2013-04-12 20:19:53 +0530 | [diff] [blame] | 86 | |
Anand Doshi | c280d06 | 2014-05-30 14:43:36 +0530 | [diff] [blame] | 87 | def set_employee_name(doc): |
| 88 | if doc.employee and not doc.employee_name: |
| 89 | doc.employee_name = frappe.db.get_value("Employee", doc.employee, "employee_name") |
Ranjith | fddfffd | 2018-05-05 13:27:26 +0530 | [diff] [blame] | 90 | |
Manas Solanki | b698846 | 2018-05-10 18:07:20 +0530 | [diff] [blame] | 91 | def update_employee(employee, details, cancel=False): |
| 92 | for item in details: |
| 93 | fieldtype = frappe.get_meta("Employee").get_field(item.fieldname).fieldtype |
| 94 | new_data = item.new if not cancel else item.current |
| 95 | if fieldtype == "Date" and new_data: |
| 96 | new_data = getdate(new_data) |
| 97 | elif fieldtype =="Datetime" and new_data: |
| 98 | new_data = get_datetime(new_data) |
| 99 | setattr(employee, item.fieldname, new_data) |
| 100 | return employee |
| 101 | |
Ranjith | fddfffd | 2018-05-05 13:27:26 +0530 | [diff] [blame] | 102 | @frappe.whitelist() |
| 103 | def get_employee_fields_label(): |
| 104 | fields = [] |
| 105 | for df in frappe.get_meta("Employee").get("fields"): |
| 106 | if df.fieldtype in ["Data", "Date", "Datetime", "Float", "Int", |
| 107 | "Link", "Percent", "Select", "Small Text"] and df.fieldname not in ["lft", "rgt", "old_parent"]: |
| 108 | fields.append({"value": df.fieldname, "label": df.label}) |
| 109 | return fields |
| 110 | |
| 111 | @frappe.whitelist() |
| 112 | def get_employee_field_property(employee, fieldname): |
| 113 | if employee and fieldname: |
| 114 | field = frappe.get_meta("Employee").get_field(fieldname) |
| 115 | value = frappe.db.get_value("Employee", employee, fieldname) |
| 116 | options = field.options |
| 117 | if field.fieldtype == "Date": |
| 118 | value = formatdate(value) |
| 119 | elif field.fieldtype == "Datetime": |
| 120 | value = format_datetime(value) |
| 121 | return { |
| 122 | "value" : value, |
| 123 | "datatype" : field.fieldtype, |
| 124 | "label" : field.label, |
| 125 | "options" : options |
| 126 | } |
| 127 | else: |
| 128 | return False |
| 129 | |
Jamsheer | 0e2cc55 | 2018-05-08 11:48:25 +0530 | [diff] [blame] | 130 | def validate_dates(doc, from_date, to_date): |
| 131 | date_of_joining, relieving_date = frappe.db.get_value("Employee", doc.employee, ["date_of_joining", "relieving_date"]) |
| 132 | if getdate(from_date) > getdate(to_date): |
| 133 | frappe.throw(_("To date can not be less than from date")) |
| 134 | elif getdate(from_date) > getdate(nowdate()): |
| 135 | frappe.throw(_("Future dates not allowed")) |
| 136 | elif date_of_joining and getdate(from_date) < getdate(date_of_joining): |
| 137 | frappe.throw(_("From date can not be less than employee's joining date")) |
| 138 | elif relieving_date and getdate(to_date) > getdate(relieving_date): |
| 139 | frappe.throw(_("To date can not greater than employee's relieving date")) |
| 140 | |
| 141 | def validate_overlap(doc, from_date, to_date, company = None): |
| 142 | query = """ |
| 143 | select name |
| 144 | from `tab{0}` |
| 145 | where name != %(name)s |
| 146 | """ |
| 147 | query += get_doc_condition(doc.doctype) |
| 148 | |
| 149 | if not doc.name: |
| 150 | # hack! if name is null, it could cause problems with != |
| 151 | doc.name = "New "+doc.doctype |
| 152 | |
| 153 | overlap_doc = frappe.db.sql(query.format(doc.doctype),{ |
| 154 | "employee": doc.employee, |
| 155 | "from_date": from_date, |
| 156 | "to_date": to_date, |
| 157 | "name": doc.name, |
| 158 | "company": company |
| 159 | }, as_dict = 1) |
| 160 | |
| 161 | if overlap_doc: |
| 162 | exists_for = doc.employee |
| 163 | if company: |
| 164 | exists_for = company |
| 165 | throw_overlap_error(doc, exists_for, overlap_doc[0].name, from_date, to_date) |
| 166 | |
| 167 | def get_doc_condition(doctype): |
| 168 | if doctype == "Compensatory Leave Request": |
| 169 | return "and employee = %(employee)s and docstatus < 2 \ |
| 170 | and (work_from_date between %(from_date)s and %(to_date)s \ |
| 171 | or work_end_date between %(from_date)s and %(to_date)s \ |
| 172 | or (work_from_date < %(from_date)s and work_end_date > %(to_date)s))" |
| 173 | elif doctype == "Leave Period": |
| 174 | return "and company = %(company)s and (from_date between %(from_date)s and %(to_date)s \ |
| 175 | or to_date between %(from_date)s and %(to_date)s \ |
| 176 | or (from_date < %(from_date)s and to_date > %(to_date)s))" |
| 177 | |
| 178 | def throw_overlap_error(doc, exists_for, overlap_doc, from_date, to_date): |
| 179 | msg = _("A {0} exists between {1} and {2} (").format(doc.doctype, |
| 180 | formatdate(from_date), formatdate(to_date)) \ |
| 181 | + """ <b><a href="#Form/{0}/{1}">{1}</a></b>""".format(doc.doctype, overlap_doc) \ |
| 182 | + _(") for {0}").format(exists_for) |
| 183 | frappe.throw(msg) |
| 184 | |
| 185 | def get_employee_leave_policy(employee): |
| 186 | leave_policy = frappe.db.get_value("Employee", employee, "leave_policy") |
| 187 | if not leave_policy: |
| 188 | employee_grade = frappe.db.get_value("Employee", employee, "grade") |
| 189 | if employee_grade: |
| 190 | leave_policy = frappe.db.get_value("Employee Grade", employee_grade, "default_leave_policy") |
| 191 | if not leave_policy: |
| 192 | frappe.throw(_("Employee {0} of grade {1} have no default leave policy").format(employee, employee_grade)) |
| 193 | else: |
| 194 | frappe.throw(_("Employee {0} has no grade to get default leave policy").format(employee)) |
| 195 | if leave_policy: |
| 196 | return frappe.get_doc("Leave Policy", leave_policy) |
| 197 | |
Ranjith | 5a8e642 | 2018-05-10 15:06:49 +0530 | [diff] [blame] | 198 | def validate_tax_declaration(declarations): |
| 199 | subcategories = [] |
| 200 | for declaration in declarations: |
| 201 | if declaration.exemption_sub_category in subcategories: |
| 202 | frappe.throw(_("More than one selection for {0} not \ |
| 203 | allowed").format(declaration.exemption_sub_category), frappe.ValidationError) |
| 204 | subcategories.append(declaration.exemption_sub_category) |
| 205 | max_amount = frappe.db.get_value("Employee Tax Exemption Sub Category", \ |
| 206 | declaration.exemption_sub_category, "max_amount") |
| 207 | if declaration.amount > max_amount: |
| 208 | frappe.throw(_("Max exemption amount for {0} is {1}").format(\ |
| 209 | declaration.exemption_sub_category, max_amount), frappe.ValidationError) |
rohitwaghchaure | 3f0c735 | 2018-05-14 20:47:35 +0530 | [diff] [blame] | 210 | |
Jamsheer | 0e2cc55 | 2018-05-08 11:48:25 +0530 | [diff] [blame] | 211 | def get_leave_period(from_date, to_date, company): |
| 212 | leave_period = frappe.db.sql(""" |
| 213 | select name, from_date, to_date |
| 214 | from `tabLeave Period` |
| 215 | where company=%(company)s and is_active=1 |
| 216 | and (from_date between %(from_date)s and %(to_date)s |
| 217 | or to_date between %(from_date)s and %(to_date)s |
| 218 | or (from_date < %(from_date)s and to_date > %(to_date)s)) |
| 219 | """, { |
| 220 | "from_date": from_date, |
| 221 | "to_date": to_date, |
| 222 | "company": company |
| 223 | }, as_dict=1) |
| 224 | |
| 225 | if leave_period: |
| 226 | return leave_period |
Ranjith | b485b1e | 2018-05-16 23:01:40 +0530 | [diff] [blame] | 227 | |
| 228 | def get_payroll_period(from_date, to_date, company): |
Jamsheer | cf414cc | 2018-05-22 14:22:42 +0530 | [diff] [blame] | 229 | payroll_period = frappe.db.sql("""select name, start_date, end_date from |
| 230 | `tabPayroll Period` |
| 231 | where start_date<=%s and end_date>= %s and company=%s""", (from_date, to_date, company), as_dict=1) |
Ranjith | b485b1e | 2018-05-16 23:01:40 +0530 | [diff] [blame] | 232 | return payroll_period[0] if payroll_period else None |
Ranjith Kurungadam | 375db61 | 2018-06-01 16:09:28 +0530 | [diff] [blame] | 233 | |
Ranjith Kurungadam | 375db61 | 2018-06-01 16:09:28 +0530 | [diff] [blame] | 234 | def allocate_earned_leaves(): |
| 235 | '''Allocate earned leaves to Employees''' |
| 236 | e_leave_types = frappe.get_all("Leave Type", |
| 237 | fields=["name", "max_leaves_allowed", "earned_leave_frequency", "rounding"], |
| 238 | filters={'is_earned_leave' : 1}) |
| 239 | today = getdate() |
| 240 | divide_by_frequency = {"Yearly": 1, "Quarterly": 4, "Monthly": 12} |
| 241 | if e_leave_types: |
| 242 | for e_leave_type in e_leave_types: |
| 243 | leave_allocations = frappe.db.sql("""select name, employee, from_date, to_date from `tabLeave Allocation` where '{0}' |
| 244 | between from_date and to_date and docstatus=1 and leave_type='{1}'""" |
| 245 | .format(today, e_leave_type.name), as_dict=1) |
| 246 | for allocation in leave_allocations: |
| 247 | leave_policy = get_employee_leave_policy(allocation.employee) |
| 248 | if not leave_policy: |
| 249 | continue |
| 250 | if not e_leave_type.earned_leave_frequency == "Monthly": |
| 251 | if not check_frequency_hit(allocation.from_date, today, e_leave_type.earned_leave_frequency): |
| 252 | continue |
| 253 | annual_allocation = frappe.db.sql("""select annual_allocation from `tabLeave Policy Detail` |
| 254 | where parent=%s and leave_type=%s""", (leave_policy.name, e_leave_type.name)) |
| 255 | if annual_allocation and annual_allocation[0]: |
| 256 | earned_leaves = flt(annual_allocation[0][0]) / divide_by_frequency[e_leave_type.earned_leave_frequency] |
| 257 | if e_leave_type.rounding == "0.5": |
| 258 | earned_leaves = round(earned_leaves * 2) / 2 |
| 259 | else: |
| 260 | earned_leaves = round(earned_leaves) |
| 261 | |
| 262 | allocated_leaves = frappe.db.get_value('Leave Allocation', allocation.name, 'total_leaves_allocated') |
| 263 | new_allocation = flt(allocated_leaves) + flt(earned_leaves) |
| 264 | new_allocation = new_allocation if new_allocation <= e_leave_type.max_leaves_allowed else e_leave_type.max_leaves_allowed |
| 265 | frappe.db.set_value('Leave Allocation', allocation.name, 'total_leaves_allocated', new_allocation) |
| 266 | |
| 267 | def check_frequency_hit(from_date, to_date, frequency): |
| 268 | '''Return True if current date matches frequency''' |
| 269 | from_dt = get_datetime(from_date) |
| 270 | to_dt = get_datetime(to_date) |
| 271 | from dateutil import relativedelta |
| 272 | rd = relativedelta.relativedelta(to_dt, from_dt) |
| 273 | months = rd.months |
| 274 | if frequency == "Quarterly": |
| 275 | if not months % 3: |
| 276 | return True |
| 277 | elif frequency == "Yearly": |
| 278 | if not months % 12: |
| 279 | return True |
| 280 | return False |
Nabin Hait | 8c7af49 | 2018-06-04 11:23:36 +0530 | [diff] [blame] | 281 | |
Ranjith | 155ecc1 | 2018-05-30 13:37:15 +0530 | [diff] [blame] | 282 | def get_salary_assignment(employee, date): |
| 283 | assignment = frappe.db.sql(""" |
| 284 | select * from `tabSalary Structure Assignment` |
| 285 | where employee=%(employee)s |
| 286 | and docstatus = 1 |
| 287 | and ( |
| 288 | (%(on_date)s between from_date and ifnull(to_date, '2199-12-31')) |
| 289 | )""", { |
| 290 | 'employee': employee, |
| 291 | 'on_date': date, |
| 292 | }, as_dict=1) |
| 293 | return assignment[0] if assignment else None |
Ranjith | 793f8e8 | 2018-05-30 20:50:48 +0530 | [diff] [blame] | 294 | |
| 295 | def calculate_eligible_hra_exemption(company, employee, monthly_house_rent, rented_in_metro_city): |
| 296 | hra_component = frappe.db.get_value("Company", company, "hra_component") |
| 297 | annual_exemption, monthly_exemption, hra_amount = 0, 0, 0 |
| 298 | if hra_component: |
| 299 | assignment = get_salary_assignment(employee, getdate()) |
| 300 | if assignment and frappe.db.exists("Salary Detail", { |
| 301 | "parent": assignment.salary_structure, |
| 302 | "salary_component": hra_component, "parentfield": "earnings"}): |
| 303 | hra_amount = get_hra_from_salary_slip(employee, assignment.salary_structure, hra_component) |
| 304 | if hra_amount: |
| 305 | if monthly_house_rent: |
| 306 | annual_exemption = calculate_hra_exemption(assignment.salary_structure, |
| 307 | assignment.base, hra_amount, monthly_house_rent, |
| 308 | rented_in_metro_city) |
| 309 | if annual_exemption > 0: |
| 310 | monthly_exemption = annual_exemption / 12 |
| 311 | else: |
| 312 | annual_exemption = 0 |
| 313 | return {"hra_amount": hra_amount, "annual_exemption": annual_exemption, "monthly_exemption": monthly_exemption} |
| 314 | |
| 315 | def get_hra_from_salary_slip(employee, salary_structure, hra_component): |
| 316 | salary_slip = make_salary_slip(salary_structure, employee=employee) |
| 317 | for earning in salary_slip.earnings: |
| 318 | if earning.salary_component == hra_component: |
| 319 | return earning.amount |
| 320 | |
| 321 | def calculate_hra_exemption(salary_structure, base, monthly_hra, monthly_house_rent, rented_in_metro_city): |
| 322 | # TODO make this configurable |
| 323 | exemptions = [] |
| 324 | frequency = frappe.get_value("Salary Structure", salary_structure, "payroll_frequency") |
| 325 | # case 1: The actual amount allotted by the employer as the HRA. |
| 326 | exemptions.append(get_annual_component_pay(frequency, monthly_hra)) |
| 327 | actual_annual_rent = monthly_house_rent * 12 |
| 328 | annual_base = get_annual_component_pay(frequency, base) |
| 329 | # case 2: Actual rent paid less 10% of the basic salary. |
| 330 | exemptions.append(flt(actual_annual_rent) - flt(annual_base * 0.1)) |
| 331 | # case 3: 50% of the basic salary, if the employee is staying in a metro city (40% for a non-metro city). |
| 332 | exemptions.append(annual_base * 0.5 if rented_in_metro_city else annual_base * 0.4) |
| 333 | # return minimum of 3 cases |
| 334 | return min(exemptions) |
| 335 | |
| 336 | def get_annual_component_pay(frequency, amount): |
| 337 | if frequency == "Daily": |
| 338 | return amount * 365 |
| 339 | elif frequency == "Weekly": |
| 340 | return amount * 52 |
| 341 | elif frequency == "Fortnightly": |
| 342 | return amount * 26 |
| 343 | elif frequency == "Monthly": |
| 344 | return amount * 12 |
| 345 | elif frequency == "Bimonthly": |
Nabin Hait | 8c7af49 | 2018-06-04 11:23:36 +0530 | [diff] [blame] | 346 | return amount * 6 |