[FIX]website_customer: group by country based on the result of the search, + do not...
[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 from datetime import datetime
23 from dateutil.relativedelta import relativedelta
24 from dateutil import parser
25 import time
26
27 from openerp.osv import fields, osv
28 from openerp.tools.translate import _
29
30 class hr_evaluation_plan(osv.osv):
31     _name = "hr_evaluation.plan"
32     _description = "Appraisal Plan"
33     _columns = {
34         'name': fields.char("Appraisal Plan", size=64, required=True),
35         'company_id': fields.many2one('res.company', 'Company', required=True),
36         'phase_ids': fields.one2many('hr_evaluation.plan.phase', 'plan_id', 'Appraisal Phases'),
37         '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. "),
38         '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)."),
39         'active': fields.boolean('Active')
40     }
41     _defaults = {
42         'active': True,
43         'month_first': 6,
44         'month_next': 12,
45         'company_id': lambda s,cr,uid,c: s.pool.get('res.company')._company_default_get(cr, uid, 'account.account', context=c),
46     }
47
48
49 class hr_evaluation_plan_phase(osv.osv):
50     _name = "hr_evaluation.plan.phase"
51     _description = "Appraisal Plan Phase"
52     _order = "sequence"
53     _columns = {
54         'name': fields.char("Phase", size=64, required=True),
55         'sequence': fields.integer("Sequence"),
56         'company_id': fields.related('plan_id', 'company_id', type='many2one', relation='res.company', string='Company', store=True, readonly=True),
57         'plan_id': fields.many2one('hr_evaluation.plan','Appraisal Plan', ondelete='cascade'),
58         'action': fields.selection([
59             ('top-down','Top-Down Appraisal Requests'),
60             ('bottom-up','Bottom-Up Appraisal Requests'),
61             ('self','Self Appraisal Requests'),
62             ('final','Final Interview')], 'Action', required=True),
63         'survey_id': fields.many2one('survey','Appraisal Form',required=True),
64         'send_answer_manager': fields.boolean('All Answers',
65             help="Send all answers to the manager"),
66         'send_answer_employee': fields.boolean('All Answers',
67             help="Send all answers to the employee"),
68         'send_anonymous_manager': fields.boolean('Anonymous Summary',
69             help="Send an anonymous summary to the manager"),
70         'send_anonymous_employee': fields.boolean('Anonymous Summary',
71             help="Send an anonymous summary to the employee"),
72         'wait': fields.boolean('Wait Previous Phases',
73             help="Check this box if you want to wait that all preceding phases " +
74               "are finished before launching this phase."),
75         'mail_feature': fields.boolean('Send mail for this phase', help="Check this box if you want to send mail to employees"+
76                                        " coming under this phase"),
77         'mail_body': fields.text('Email'),
78         'email_subject':fields.text('char')
79     }
80     _defaults = {
81         'sequence': 1,
82         'email_subject': _('''Regarding '''),
83         'mail_body': lambda *a:_('''
84 Date: %(date)s
85
86 Dear %(employee_name)s,
87
88 I am doing an evaluation regarding %(eval_name)s.
89
90 Kindly submit your response.
91
92
93 Thanks,
94 --
95 %(user_signature)s
96
97         '''),
98     }
99
100
101 class hr_employee(osv.osv):
102     _name = "hr.employee"
103     _inherit="hr.employee"
104     
105
106     _columns = {
107         'evaluation_plan_id': fields.many2one('hr_evaluation.plan', 'Appraisal Plan'),
108         '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)."),
109     }
110     def run_employee_evaluation(self, cr, uid, automatic=False, use_new_cursor=False, context=None):
111         now = parser.parse(datetime.now().strftime('%Y-%m-%d'))
112         obj_evaluation = self.pool.get('hr_evaluation.evaluation')
113         emp_ids =self.search(cr, uid, [ ('evaluation_plan_id','<>',False), ('evaluation_date','=', False)], context=context)
114         for emp in self.browse(cr, uid, emp_ids, context=context):
115             first_date = (now+ relativedelta(months=emp.evaluation_plan_id.month_first)).strftime('%Y-%m-%d')
116             self.write(cr, uid, [emp.id], {'evaluation_date': first_date}, context=context)
117
118         emp_ids =self.search(cr, uid, [
119             ('evaluation_plan_id','<>',False), ('evaluation_date','<=', time.strftime("%Y-%m-%d")),
120             ], context=context) 
121         for emp in self.browse(cr, uid, emp_ids, context=context):
122             next_date = (now + relativedelta(months=emp.evaluation_plan_id.month_next)).strftime('%Y-%m-%d')
123             self.write(cr, uid, [emp.id], {'evaluation_date': next_date}, context=context)
124             plan_id = obj_evaluation.create(cr, uid, {'employee_id': emp.id, 'plan_id': emp.evaluation_plan_id.id}, context=context)
125             obj_evaluation.button_plan_in_progress(cr, uid, [plan_id], context=context)
126         return True
127
128
129
130 class hr_evaluation(osv.osv):
131     _name = "hr_evaluation.evaluation"
132     _inherit = "mail.thread"
133     _description = "Employee Appraisal"
134     _rec_name = 'employee_id'
135     _columns = {
136         'date': fields.date("Appraisal Deadline", required=True, select=True),
137         'employee_id': fields.many2one('hr.employee', "Employee", required=True),
138         'note_summary': fields.text('Appraisal Summary'),
139         'note_action': fields.text('Action Plan',
140             help="If the evaluation does not meet the expectations, you can propose"+
141               "an action plan"),
142         'rating': fields.selection([
143             ('0','Significantly bellow expectations'),
144             ('1','Did not meet expectations'),
145             ('2','Meet expectations'),
146             ('3','Exceeds expectations'),
147             ('4','Significantly exceeds expectations'),
148         ], "Appreciation", help="This is the appreciation on which the evaluation is summarized."),
149         'survey_request_ids': fields.one2many('hr.evaluation.interview','evaluation_id','Appraisal Forms'),
150         'plan_id': fields.many2one('hr_evaluation.plan', 'Plan', required=True),
151         'state': fields.selection([
152             ('draft','New'),
153             ('cancel','Cancelled'),
154             ('wait','Plan In Progress'),
155             ('progress','Waiting Appreciation'),
156             ('done','Done'),
157         ], 'Status', required=True, readonly=True),
158         'date_close': fields.date('Ending Date', select=True),
159     }
160     _defaults = {
161         'date': lambda *a: (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
162         'state': lambda *a: 'draft',
163     }
164
165     def name_get(self, cr, uid, ids, context=None):
166         if not ids:
167             return []
168         reads = self.browse(cr, uid, ids, context=context)
169         res = []
170         for record in reads:
171             name = record.plan_id.name
172             res.append((record['id'], name))
173         return res
174
175     def onchange_employee_id(self, cr, uid, ids, employee_id, context=None):
176         vals = {}
177         vals['plan_id'] = False
178         if employee_id:
179             employee_obj = self.pool.get('hr.employee')
180             for employee in employee_obj.browse(cr, uid, [employee_id], context=context):
181                 if employee and employee.evaluation_plan_id and employee.evaluation_plan_id.id:
182                     vals.update({'plan_id': employee.evaluation_plan_id.id})
183         return {'value': vals}
184
185     def button_plan_in_progress(self, cr, uid, ids, context=None):
186         mail_message = self.pool.get('mail.message')
187         hr_eval_inter_obj = self.pool.get('hr.evaluation.interview')
188         if context is None:
189             context = {}
190         for evaluation in self.browse(cr, uid, ids, context=context):
191             wait = False
192             for phase in evaluation.plan_id.phase_ids:
193                 children = []
194                 if phase.action == "bottom-up":
195                     children = evaluation.employee_id.child_ids
196                 elif phase.action in ("top-down", "final"):
197                     if evaluation.employee_id.parent_id:
198                         children = [evaluation.employee_id.parent_id]
199                 elif phase.action == "self":
200                     children = [evaluation.employee_id]
201                 for child in children:
202
203                     int_id = hr_eval_inter_obj.create(cr, uid, {
204                         'evaluation_id': evaluation.id,
205                         'survey_id': phase.survey_id.id,
206                         'date_deadline': (parser.parse(datetime.now().strftime('%Y-%m-%d')) + relativedelta(months =+ 1)).strftime('%Y-%m-%d'),
207                         'user_id': child.user_id.id,
208                         'user_to_review_id': evaluation.employee_id.id
209                     }, context=context)
210                     if phase.wait:
211                         wait = True
212                     if not wait:
213                         hr_eval_inter_obj.survey_req_waiting_answer(cr, uid, [int_id], context=context)
214
215                     if (not wait) and phase.mail_feature:
216                         body = phase.mail_body % {'employee_name': child.name, 'user_signature': child.user_id.signature,
217                             'eval_name': phase.survey_id.title, 'date': time.strftime('%Y-%m-%d'), 'time': time }
218                         sub = phase.email_subject
219                         if child.work_email:
220                             vals = {'state': 'outgoing',
221                                     'subject': sub,
222                                     'body_html': '<pre>%s</pre>' % body,
223                                     'email_to': child.work_email,
224                                     'email_from': evaluation.employee_id.work_email}
225                             self.pool.get('mail.mail').create(cr, uid, vals, context=context)
226
227         self.write(cr, uid, ids, {'state':'wait'}, context=context)
228         return True
229
230     def button_final_validation(self, cr, uid, ids, context=None):
231         request_obj = self.pool.get('hr.evaluation.interview')
232         self.write(cr, uid, ids, {'state':'progress'}, context=context)
233         for evaluation in self.browse(cr, uid, ids, context=context):
234             if evaluation.employee_id and evaluation.employee_id.parent_id and evaluation.employee_id.parent_id.user_id:
235                 self.message_subscribe_users(cr, uid, [evaluation.id], user_ids=[evaluation.employee_id.parent_id.user_id.id], context=context)
236             if len(evaluation.survey_request_ids) != len(request_obj.search(cr, uid, [('evaluation_id', '=', evaluation.id),('state', 'in', ['done','cancel'])], context=context)):
237                 raise osv.except_osv(_('Warning!'),_("You cannot change state, because some appraisal(s) are in waiting answer or draft state."))
238         return True
239
240     def button_done(self, cr, uid, ids, context=None):
241         self.write(cr, uid, ids,{'state':'done', 'date_close': time.strftime('%Y-%m-%d')}, context=context)
242         return True
243
244     def button_cancel(self, cr, uid, ids, context=None):
245         interview_obj=self.pool.get('hr.evaluation.interview')
246         evaluation = self.browse(cr, uid, ids[0], context)
247         interview_obj.survey_req_cancel(cr, uid, [r.id for r in evaluation.survey_request_ids])
248         self.write(cr, uid, ids,{'state':'cancel'}, context=context)
249         return True
250
251     def button_draft(self, cr, uid, ids, context=None):
252         self.write(cr, uid, ids,{'state': 'draft'}, context=context)
253         return True
254
255     def copy(self, cr, uid, id, default=None, context=None):
256         if default is None:
257             default = {}
258         if context is None:
259             context = {}
260         default = default.copy()
261         default['survey_request_ids'] = []
262         return super(hr_evaluation, self).copy(cr, uid, id, default, context=context)
263     
264     def write(self, cr, uid, ids, vals, context=None):
265         if vals.get('employee_id'):
266             employee_id = self.pool.get('hr.employee').browse(cr, uid, vals.get('employee_id'), context=context)
267             if employee_id.parent_id and employee_id.parent_id.user_id:
268                 vals['message_follower_ids'] = [(4, employee_id.parent_id.user_id.partner_id.id)]
269         if 'date' in vals:
270             new_vals = {'date_deadline': vals.get('date')}
271             obj_hr_eval_iterview = self.pool.get('hr.evaluation.interview')
272             for evalutation in self.browse(cr, uid, ids, context=context):
273                 for survey_req in evalutation.survey_request_ids:
274                     obj_hr_eval_iterview.write(cr, uid, [survey_req.id], new_vals, context=context)
275         return super(hr_evaluation, self).write(cr, uid, ids, vals, context=context)
276
277
278 class survey_request(osv.osv):
279     _inherit = "survey.request"
280     _columns = {
281         'is_evaluation': fields.boolean('Is Appraisal?'),
282     }
283
284
285 class hr_evaluation_interview(osv.osv):
286     _name = 'hr.evaluation.interview'
287     _inherits = {'survey.request': 'request_id'}
288     _inherit =  'mail.thread'
289     _rec_name = 'request_id'
290     _description = 'Appraisal Interview'
291     _columns = {
292         'request_id': fields.many2one('survey.request','Request_id', ondelete='cascade', required=True),
293         'user_to_review_id': fields.many2one('hr.employee', 'Employee to Interview'),
294         'evaluation_id': fields.many2one('hr_evaluation.evaluation', 'Appraisal Form'),
295     }
296     _defaults = {
297         'is_evaluation': True,
298     }
299
300     def name_get(self, cr, uid, ids, context=None):
301         if not ids:
302             return []
303         reads = self.browse(cr, uid, ids, context=context)
304         res = []
305         for record in reads:
306             name = record.request_id.survey_id.title
307             res.append((record['id'], name))
308         return res
309
310     def survey_req_waiting_answer(self, cr, uid, ids, context=None):
311         self.write(cr, uid, ids, { 'state': 'waiting_answer'}, context=context)
312         return True
313
314     def survey_req_done(self, cr, uid, ids, context=None):
315         hr_eval_obj = self.pool.get('hr_evaluation.evaluation')
316         for id in self.browse(cr, uid, ids, context=context):
317             flag = False
318             wating_id = 0
319             if not id.evaluation_id.id:
320                 raise osv.except_osv(_('Warning!'),_("You cannot start evaluation without Appraisal."))
321             records = hr_eval_obj.browse(cr, uid, [id.evaluation_id.id], context=context)[0].survey_request_ids
322             for child in records:
323                 if child.state == "draft":
324                     wating_id = child.id
325                     continue
326                 if child.state != "done":
327                     flag = True
328             if not flag and wating_id:
329                 self.survey_req_waiting_answer(cr, uid, [wating_id], 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
361 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:1