[MERGE] lp881356
[odoo/odoo.git] / addons / hr_evaluation / hr_evaluation.py
1 # -*- encoding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2009 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21
22 import time
23 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
25 from dateutil import parser
26 from osv import fields, osv
27 from tools.translate import _
28
29 class hr_evaluation_plan(osv.osv):
30     _name = "hr_evaluation.plan"
31     _description = "Appraisal Plan"
32     _columns = {
33         'name': fields.char("Appraisal Plan", size=64, required=True),
34         'company_id': fields.many2one('res.company', 'Company', required=True),
35         'phase_ids': fields.one2many('hr_evaluation.plan.phase', 'plan_id', 'Appraisal Phases'),
36         'month_first': fields.integer('First Appraisal in (months)', help="This number of months will be used to schedule the first evaluation date of the employee when selecting an evaluation plan. "),
37         'month_next': fields.integer('Periodicity of Appraisal (months)', help="The number of month that depicts the delay between each evaluation of this plan (after the first one)."),
38         'active': fields.boolean('Active')
39     }
40     _defaults = {
41         'active': True,
42         'month_first': 6,
43         'month_next': 12,
44         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=c),
45     }
46 hr_evaluation_plan()
47
48 class hr_evaluation_plan_phase(osv.osv):
49     _name = "hr_evaluation.plan.phase"
50     _description = "Appraisal Plan Phase"
51     _order = "sequence"
52     _columns = {
53         'name': fields.char("Phase", size=64, required=True),
54         'sequence': fields.integer("Sequence"),
55         'company_id': fields.related('plan_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
56         'plan_id': fields.many2one('hr_evaluation.plan','Appraisal Plan', ondelete='cascade'),
57         'action': fields.selection([
58             ('top-down','Top-Down Appraisal Requests'),
59             ('bottom-up','Bottom-Up Appraisal Requests'),
60             ('self','Self Appraisal Requests'),
61             ('final','Final Interview')], 'Action', required=True),
62         'survey_id': fields.many2one('survey','Appraisal Form',required=True),
63         'send_answer_manager': fields.boolean('All Answers',
64             help="Send all answers to the manager"),
65         'send_answer_employee': fields.boolean('All Answers',
66             help="Send all answers to the employee"),
67         'send_anonymous_manager': fields.boolean('Anonymous Summary',
68             help="Send an anonymous summary to the manager"),
69         'send_anonymous_employee': fields.boolean('Anonymous Summary',
70             help="Send an anonymous summary to the employee"),
71         'wait': fields.boolean('Wait Previous Phases',
72             help="Check this box if you want to wait that all preceding phases " +
73               "are finished before launching this phase."),
74         'mail_feature': fields.boolean('Send mail for this phase', help="Check this box if you want to send mail to employees"+
75                                        " coming under this phase"),
76         'mail_body': fields.text('Email'),
77         'email_subject':fields.text('char')
78     }
79     _defaults = {
80         'sequence': 1,
81         'email_subject': _('''Regarding '''),
82         'mail_body': lambda *a:_('''
83 Date: %(date)s
84
85 Dear %(employee_name)s,
86
87 I am doing an evaluation regarding %(eval_name)s.
88
89 Kindly submit your response.
90
91
92 Thanks,
93 --
94 %(user_signature)s
95
96         '''),
97     }
98 hr_evaluation_plan_phase()
99
100 class hr_employee(osv.osv):
101     _name = "hr.employee"
102     _inherit="hr.employee"
103     _columns = {
104         'evaluation_plan_id': fields.many2one('hr_evaluation.plan', 'Appraisal Plan'),
105         'evaluation_date': fields.date('Next Appraisal Date', help="The date of the next appraisal is computed by the appraisal plan's dates (first appraisal + periodicity)."),
106     }
107
108     def run_employee_evaluation(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
109         obj_evaluation = self.pool.get('hr_evaluation.evaluation')
110         for id in self.browse(cr, uid, self.search(cr, uid, [], context=context), context=context):
111             if id.evaluation_plan_id and id.evaluation_date:
112                 if (parser.parse(id.evaluation_date) + relativedelta(months = int(id.evaluation_plan_id.month_next))).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"):
113                     self.write(cr, uid, id.id, {'evaluation_date': (parser.parse(id.evaluation_date) + relativedelta(months =+ int(id.evaluation_plan_id.month_next))).strftime('%Y-%m-%d')}, context=context)
114                     obj_evaluation.create(cr, uid, {'employee_id': id.id, 'plan_id': id.evaluation_plan_id}, context=context)
115         return True
116
117     def onchange_evaluation_plan_id(self, cr, uid, ids, evaluation_plan_id, evaluation_date, context=None):
118         if evaluation_plan_id:
119             evaluation_plan_obj=self.pool.get('hr_evaluation.plan')
120             obj_evaluation = self.pool.get('hr_evaluation.evaluation')
121             flag = False
122             evaluation_plan =  evaluation_plan_obj.browse(cr, uid, [evaluation_plan_id], context=context)[0]
123             if not evaluation_date:
124                evaluation_date=(parser.parse(datetime.now().strftime('%Y-%m-%d'))+ relativedelta(months=+evaluation_plan.month_first)).strftime('%Y-%m-%d')
125                flag = True
126             else:
127                 if (parser.parse(evaluation_date) + relativedelta(months = int(evaluation_plan.month_next))).strftime('%Y-%m-%d') <= time.strftime("%Y-%m-%d"):
128                     evaluation_date=(parser.parse(evaluation_date)+ relativedelta(months=+evaluation_plan.month_next)).strftime('%Y-%m-%d')
129                     flag = True
130             if ids and flag:
131                 obj_evaluation.create(cr, uid, {'employee_id': ids[0], 'plan_id': evaluation_plan_id}, context=context)
132         return {'value': {'evaluation_date': evaluation_date}}
133
134     def create(self, cr, uid, vals, context=None):
135         id = super(hr_employee, self).create(cr, uid, vals, context=context)
136         if vals.get('evaluation_plan_id', False):
137             self.pool.get('hr_evaluation.evaluation').create(cr, uid, {'employee_id': id, 'plan_id': vals['evaluation_plan_id']}, context=context)
138         return id
139
140 hr_employee()
141
142 class hr_evaluation(osv.osv):
143     _name = "hr_evaluation.evaluation"
144     _description = "Employee Appraisal"
145     _rec_name = 'employee_id'
146     _columns = {
147         'date': fields.date("Appraisal Deadline", required=True, select=True),
148         'employee_id': fields.many2one('hr.employee', "Employee", required=True),
149         'note_summary': fields.text('Appraisal Summary'),
150         'note_action': fields.text('Action Plan',
151             help="If the evaluation does not meet the expectations, you can propose"+
152               "an action plan"),
153         'rating': fields.selection([
154             ('0','Significantly bellow expectations'),
155             ('1','Did not meet expectations'),
156             ('2','Meet expectations'),
157             ('3','Exceeds expectations'),
158             ('4','Significantly exceeds expectations'),
159         ], "Appreciation", help="This is the appreciation on that summarize the evaluation"),
160         'survey_request_ids': fields.one2many('hr.evaluation.interview','evaluation_id','Appraisal Forms'),
161         'plan_id': fields.many2one('hr_evaluation.plan', 'Plan', required=True),
162         'state': fields.selection([
163             ('draft','New'),
164             ('wait','Plan In Progress'),
165             ('progress','Waiting Appreciation'),
166             ('done','Done'),
167             ('cancel','Cancelled'),
168         ], 'State', required=True, readonly=True),
169         'date_close': fields.date('Ending Date', select=True),
170         'progress': fields.float("Progress"),
171     }
172     _defaults = {
173         'date': lambda *a: (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
174         'state': lambda *a: 'draft',
175     }
176
177     def name_get(self, cr, uid, ids, context=None):
178         if not ids:
179             return []
180         reads = self.browse(cr, uid, ids, context=context)
181         res = []
182         for record in reads:
183             name = record.plan_id.name
184             res.append((record['id'], name))
185         return res
186
187     def onchange_employee_id(self, cr, uid, ids, employee_id, context=None):
188         evaluation_plan_id=False
189         if employee_id:
190             employee_obj=self.pool.get('hr.employee')
191             for employee in employee_obj.browse(cr, uid, [employee_id], context=context):
192                 if employee and employee.evaluation_plan_id and employee.evaluation_plan_id.id:
193                     evaluation_plan_id=employee.evaluation_plan_id.id
194         return {'value': {'plan_id':evaluation_plan_id}}
195
196     def button_plan_in_progress(self, cr, uid, ids, context=None):
197         mail_message = self.pool.get('mail.message')
198         hr_eval_inter_obj = self.pool.get('hr.evaluation.interview')
199         if context is None:
200             context = {}
201         for evaluation in self.browse(cr, uid, ids, context=context):
202             wait = False
203             for phase in evaluation.plan_id.phase_ids:
204                 children = []
205                 if phase.action == "bottom-up":
206                     children = evaluation.employee_id.child_ids
207                 elif phase.action in ("top-down", "final"):
208                     if evaluation.employee_id.parent_id:
209                         children = [evaluation.employee_id.parent_id]
210                 elif phase.action == "self":
211                     children = [evaluation.employee_id]
212                 for child in children:
213 #                    if not child.user_id:
214 #                        continue
215
216                     int_id = hr_eval_inter_obj.create(cr, uid, {
217                         'evaluation_id': evaluation.id,
218                         'survey_id': phase.survey_id.id,
219                         'date_deadline': (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
220                         'user_id': child.user_id.id,
221                         'user_to_review_id': evaluation.employee_id.id
222                     }, context=context)
223                     if phase.wait:
224                         wait = True
225                     if not wait:
226                         hr_eval_inter_obj.survey_req_waiting_answer(cr, uid, [int_id], context=context)
227
228                     if (not wait) and phase.mail_feature:
229                         body = phase.mail_body % {'employee_name': child.name, 'user_signature': child.user_id.signature,
230                             'eval_name': phase.survey_id.title, 'date': time.strftime('%Y-%m-%d'), 'time': time }
231                         sub = phase.email_subject
232                         dest = [child.work_email]
233                         if dest:
234                            mail_message.schedule_with_attach(cr, uid, evaluation.employee_id.work_email, dest, sub, body, context=context)
235
236         self.write(cr, uid, ids, {'state':'wait'}, context=context)
237         return True
238
239     def button_final_validation(self, cr, uid, ids, context=None):
240         request_obj = self.pool.get('hr.evaluation.interview')
241         self.write(cr, uid, ids, {'state':'progress'}, context=context)
242         for id in self.browse(cr, uid, ids, context=context):
243             if len(id.survey_request_ids) != len(request_obj.search(cr, uid, [('evaluation_id', '=', id.id),('state', 'in', ['done','cancel'])], context=context)):
244                 raise osv.except_osv(_('Warning !'),_("You cannot change state, because some appraisal in waiting answer or draft state"))
245         return True
246
247     def button_done(self,cr, uid, ids, context=None):
248         self.write(cr, uid, ids,{'progress': 1 * 100}, context=context)
249         self.write(cr, uid, ids,{'state':'done', 'date_close': time.strftime('%Y-%m-%d')}, context=context)
250         return True
251
252     def button_cancel(self, cr, uid, ids, context=None):
253         interview_obj=self.pool.get('hr.evaluation.interview')
254         evaluation = self.browse(cr, uid, ids[0], context)
255         interview_obj.survey_req_cancel(cr, uid, [r.id for r in evaluation.survey_request_ids])
256         self.write(cr, uid, ids,{'state':'cancel'}, context=context)
257         return True
258
259     def button_draft(self, cr, uid, ids, context=None):
260         self.write(cr, uid, ids,{'state': 'draft'}, context=context)
261         return True
262
263     def write(self, cr, uid, ids, vals, context=None):
264         if 'date' in vals:
265             new_vals = {'date_deadline': vals.get('date')}
266             obj_hr_eval_iterview = self.pool.get('hr.evaluation.interview')
267             for evalutation in self.browse(cr, uid, ids, context=context):
268                 for survey_req in evalutation.survey_request_ids:
269                     obj_hr_eval_iterview.write(cr, uid, [survey_req.id], new_vals, context=context)
270         return super(hr_evaluation, self).write(cr, uid, ids, vals, context=context)
271
272 hr_evaluation()
273
274 class survey_request(osv.osv):
275     _inherit = "survey.request"
276     _columns = {
277         'is_evaluation': fields.boolean('Is Appraisal?'),
278     }
279
280 survey_request()
281
282 class hr_evaluation_interview(osv.osv):
283     _name = 'hr.evaluation.interview'
284     _inherits = {'survey.request': 'request_id'}
285     _rec_name = 'request_id'
286     _description = 'Appraisal Interview'
287     _columns = {
288         'request_id': fields.many2one('survey.request','Request_id', ondelete='cascade', required=True),
289         'user_to_review_id': fields.many2one('hr.employee', 'Employee to Interview'),
290         'evaluation_id': fields.many2one('hr_evaluation.evaluation', 'Appraisal Form'),
291     }
292     _defaults = {
293         'is_evaluation': True,
294     }
295
296     def name_get(self, cr, uid, ids, context=None):
297         if not ids:
298             return []
299         reads = self.browse(cr, uid, ids, context=context)
300         res = []
301         for record in reads:
302             name = record.request_id.survey_id.title
303             res.append((record['id'], name))
304         return res
305
306     def survey_req_waiting_answer(self, cr, uid, ids, context=None):
307         self.write(cr, uid, ids, { 'state': 'waiting_answer'}, context=context)
308         return True
309
310     def survey_req_done(self, cr, uid, ids, context=None):
311         hr_eval_obj = self.pool.get('hr_evaluation.evaluation')
312         for id in self.browse(cr, uid, ids, context=context):
313             flag = False
314             wating_id = 0
315             tot_done_req = 1
316             if not id.evaluation_id.id:
317                 raise osv.except_osv(_('Warning !'),_("You cannot start evaluation without Appraisal."))
318             records = hr_eval_obj.browse(cr, uid, [id.evaluation_id.id], context=context)[0].survey_request_ids
319             for child in records:
320                 if child.state == "draft":
321                     wating_id = child.id
322                     continue
323                 if child.state != "done":
324                     flag = True
325                 else:
326                     tot_done_req += 1
327             if not flag and wating_id:
328                 self.survey_req_waiting_answer(cr, uid, [wating_id], context=context)
329             hr_eval_obj.write(cr, uid, [id.evaluation_id.id], {'progress': tot_done_req * 100 / len(records)}, context=context)
330         self.write(cr, uid, ids, { 'state': 'done'}, context=context)
331         return True
332
333     def survey_req_draft(self, cr, uid, ids, context=None):
334         self.write(cr, uid, ids, { 'state': 'draft'}, context=context)
335         return True
336
337     def survey_req_cancel(self, cr, uid, ids, context=None):
338         self.write(cr, uid, ids, { 'state': 'cancel'}, context=context)
339         return True
340
341     def action_print_survey(self, cr, uid, ids, context=None):
342         """
343         If response is available then print this response otherwise print survey form(print template of the survey).
344
345         @param self: The object pointer
346         @param cr: the current row, from the database cursor,
347         @param uid: the current user’s ID for security checks,
348         @param ids: List of Survey IDs
349         @param context: A standard dictionary for contextual values
350         @return: Dictionary value for print survey form.
351         """
352         if context is None:
353             context = {}
354         record = self.browse(cr, uid, ids, context=context)
355         record = record and record[0]
356         context.update({'survey_id': record.survey_id.id, 'response_id': [record.response.id], 'response_no':0,})
357         value = self.pool.get("survey").action_print_survey(cr, uid, ids, context=context)
358         return value
359
360 hr_evaluation_interview()
361
362 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:1