2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
22 from datetime import datetime
24 from openerp import SUPERUSER_ID
25 from openerp import tools
26 from openerp.addons.crm import crm
27 from openerp.osv import fields, osv, orm
28 from openerp.tools import html2plaintext
29 from openerp.tools.translate import _
31 class project_issue_version(osv.Model):
32 _name = "project.issue.version"
35 'name': fields.char('Version Number', size=32, required=True),
36 'active': fields.boolean('Active', required=False),
42 class project_issue(osv.Model):
43 _name = "project.issue"
44 _description = "Project Issue"
45 _order = "priority, create_date desc"
46 _inherit = ['mail.thread', 'ir.needaction_mixin']
48 _mail_post_access = 'read'
51 # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages
52 'project_issue.mt_issue_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1,
53 'project_issue.mt_issue_stage': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1,
56 'project_issue.mt_issue_assigned': lambda self, cr, uid, obj, ctx=None: obj.user_id and obj.user_id.id,
59 'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked',
63 def _get_default_partner(self, cr, uid, context=None):
64 project_id = self._get_default_project_id(cr, uid, context)
66 project = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
67 if project and project.partner_id:
68 return project.partner_id.id
71 def _get_default_project_id(self, cr, uid, context=None):
72 """ Gives default project by checking if present in the context """
73 return self._resolve_project_id_from_context(cr, uid, context=context)
75 def _get_default_stage_id(self, cr, uid, context=None):
76 """ Gives default stage_id """
77 project_id = self._get_default_project_id(cr, uid, context=context)
78 return self.stage_find(cr, uid, [], project_id, [('fold', '=', False)], context=context)
80 def _resolve_project_id_from_context(self, cr, uid, context=None):
81 """ Returns ID of project based on the value of 'default_project_id'
82 context key, or None if it cannot be resolved to a single
87 if type(context.get('default_project_id')) in (int, long):
88 return context.get('default_project_id')
89 if isinstance(context.get('default_project_id'), basestring):
90 project_name = context['default_project_id']
91 project_ids = self.pool.get('project.project').name_search(cr, uid, name=project_name, context=context)
92 if len(project_ids) == 1:
93 return int(project_ids[0][0])
96 def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
97 access_rights_uid = access_rights_uid or uid
98 stage_obj = self.pool.get('project.task.type')
99 order = stage_obj._order
100 # lame hack to allow reverting search, should just work in the trivial case
101 if read_group_order == 'stage_id desc':
102 order = "%s desc" % order
103 # retrieve section_id from the context and write the domain
104 # - ('id', 'in', 'ids'): add columns that should be present
105 # - OR ('case_default', '=', True), ('fold', '=', False): add default columns that are not folded
106 # - OR ('project_ids', 'in', project_id), ('fold', '=', False) if project_id: add project columns that are not folded
108 project_id = self._resolve_project_id_from_context(cr, uid, context=context)
110 search_domain += ['|', ('project_ids', '=', project_id)]
111 search_domain += [('id', 'in', ids)]
113 stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
114 result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
115 # restore order of the search
116 result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
119 for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
120 fold[stage.id] = stage.fold or False
123 def _compute_day(self, cr, uid, ids, fields, args, context=None):
125 @param cr: the current row, from the database cursor,
126 @param uid: the current user’s ID for security checks,
127 @param ids: List of Openday’s IDs
128 @return: difference between current date and log date
129 @param context: A standard dictionary for contextual values
131 cal_obj = self.pool.get('resource.calendar')
132 res_obj = self.pool.get('resource.resource')
135 for issue in self.browse(cr, uid, ids, context=context):
137 # if the working hours on the project are not defined, use default ones (8 -> 12 and 13 -> 17 * 5), represented by None
138 if not issue.project_id or not issue.project_id.resource_calendar_id:
141 working_hours = issue.project_id.resource_calendar_id.id
149 date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
150 if field in ['working_hours_open','day_open']:
152 date_open = datetime.strptime(issue.date_open, "%Y-%m-%d %H:%M:%S")
153 ans = date_open - date_create
154 date_until = issue.date_open
155 #Calculating no. of working hours to open the issue
156 hours = cal_obj._interval_hours_get(cr, uid, working_hours,
159 timezone_from_uid=issue.user_id.id or uid,
160 exclude_leaves=False,
162 elif field in ['working_hours_close','day_close']:
163 if issue.date_closed:
164 date_close = datetime.strptime(issue.date_closed, "%Y-%m-%d %H:%M:%S")
165 date_until = issue.date_closed
166 ans = date_close - date_create
167 #Calculating no. of working hours to close the issue
168 hours = cal_obj._interval_hours_get(cr, uid, working_hours,
171 timezone_from_uid=issue.user_id.id or uid,
172 exclude_leaves=False,
174 elif field in ['days_since_creation']:
175 if issue.create_date:
176 days_since_creation = datetime.today() - datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
177 res[issue.id][field] = days_since_creation.days
180 elif field in ['inactivity_days']:
181 res[issue.id][field] = 0
182 if issue.date_action_last:
183 inactive_days = datetime.today() - datetime.strptime(issue.date_action_last, '%Y-%m-%d %H:%M:%S')
184 res[issue.id][field] = inactive_days.days
189 resource_ids = res_obj.search(cr, uid, [('user_id','=',issue.user_id.id)])
190 if resource_ids and len(resource_ids):
191 resource_id = resource_ids[0]
192 duration = float(ans.days) + float(ans.seconds)/(24*3600)
194 if field in ['working_hours_open','working_hours_close']:
195 res[issue.id][field] = hours
196 elif field in ['day_open','day_close']:
197 res[issue.id][field] = duration
201 def _hours_get(self, cr, uid, ids, field_names, args, context=None):
202 task_pool = self.pool.get('project.task')
204 for issue in self.browse(cr, uid, ids, context=context):
207 progress = task_pool._hours_get(cr, uid, [issue.task_id.id], field_names, args, context=context)[issue.task_id.id]['progress']
208 res[issue.id] = {'progress' : progress}
211 def on_change_project(self, cr, uid, ids, project_id, context=None):
213 project = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
214 if project and project.partner_id:
215 return {'value': {'partner_id': project.partner_id.id}}
218 def _get_issue_task(self, cr, uid, ids, context=None):
220 issue_pool = self.pool.get('project.issue')
221 for task in self.pool.get('project.task').browse(cr, uid, ids, context=context):
222 issues += issue_pool.search(cr, uid, [('task_id','=',task.id)])
225 def _get_issue_work(self, cr, uid, ids, context=None):
227 issue_pool = self.pool.get('project.issue')
228 for work in self.pool.get('project.task.work').browse(cr, uid, ids, context=context):
230 issues += issue_pool.search(cr, uid, [('task_id','=',work.task_id.id)])
234 'id': fields.integer('ID', readonly=True),
235 'name': fields.char('Issue', size=128, required=True),
236 'active': fields.boolean('Active', required=False),
237 'create_date': fields.datetime('Creation Date', readonly=True,select=True),
238 'write_date': fields.datetime('Update Date', readonly=True),
239 'days_since_creation': fields.function(_compute_day, string='Days since creation date', \
240 multi='compute_day', type="integer", help="Difference in days between creation date and current date"),
241 'date_deadline': fields.date('Deadline'),
242 'section_id': fields.many2one('crm.case.section', 'Sales Team', \
243 select=True, help='Sales team to which Case belongs to.\
244 Define Responsible user and Email account for mail gateway.'),
245 'partner_id': fields.many2one('res.partner', 'Contact', select=1),
246 'company_id': fields.many2one('res.company', 'Company'),
247 'description': fields.text('Private Note'),
248 'kanban_state': fields.selection([('normal', 'Normal'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State',
249 track_visibility='onchange',
250 help="A Issue's kanban state indicates special situations affecting it:\n"
251 " * Normal is the default situation\n"
252 " * Blocked indicates something is preventing the progress of this issue\n"
253 " * Ready for next stage indicates the issue is ready to be pulled to the next stage",
254 readonly=True, required=False),
255 'email_from': fields.char('Email', size=128, help="These people will receive email.", select=1),
256 'email_cc': fields.char('Watchers Emails', size=256, help="These email addresses will be added to the CC field of all inbound and outbound emails for this record before being sent. Separate multiple email addresses with a comma"),
257 'date_open': fields.datetime('Opened', readonly=True,select=True),
258 # Project Issue fields
259 'date_closed': fields.datetime('Closed', readonly=True,select=True),
260 'date': fields.datetime('Date'),
261 'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
262 'channel_id': fields.many2one('crm.case.channel', 'Channel', help="Communication channel."),
263 'categ_ids': fields.many2many('project.category', string='Tags'),
264 'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority', select=True),
265 'version_id': fields.many2one('project.issue.version', 'Version'),
266 'stage_id': fields.many2one ('project.task.type', 'Stage',
267 track_visibility='onchange',
268 domain="[('project_ids', '=', project_id)]"),
269 'project_id':fields.many2one('project.project', 'Project', track_visibility='onchange'),
270 'duration': fields.float('Duration'),
271 'task_id': fields.many2one('project.task', 'Task', domain="[('project_id','=',project_id)]"),
272 'day_open': fields.function(_compute_day, string='Days to Open', \
273 multi='compute_day', type="float", store=True),
274 'day_close': fields.function(_compute_day, string='Days to Close', \
275 multi='compute_day', type="float", store=True),
276 'user_id': fields.many2one('res.users', 'Assigned to', required=False, select=1, track_visibility='onchange'),
277 'working_hours_open': fields.function(_compute_day, string='Working Hours to Open the Issue', \
278 multi='compute_day', type="float", store=True),
279 'working_hours_close': fields.function(_compute_day, string='Working Hours to Close the Issue', \
280 multi='compute_day', type="float", store=True),
281 'inactivity_days': fields.function(_compute_day, string='Days since last action', \
282 multi='compute_day', type="integer", help="Difference in days between last action and current date"),
283 'color': fields.integer('Color Index'),
284 'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
285 'date_action_last': fields.datetime('Last Action', readonly=1),
286 'date_action_next': fields.datetime('Next Action', readonly=1),
287 'progress': fields.function(_hours_get, string='Progress (%)', multi='hours', group_operator="avg", help="Computed as: Time Spent / Total Time.",
289 'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['task_id'], 10),
290 'project.task': (_get_issue_task, ['progress'], 10),
291 'project.task.work': (_get_issue_work, ['hours'], 10),
297 'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
298 'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c),
299 'priority': crm.AVAILABLE_PRIORITIES[2][0],
300 'kanban_state': 'normal',
301 'date_last_stage_update': fields.datetime.now,
302 'user_id': lambda obj, cr, uid, context: uid,
306 'stage_id': _read_group_stage_ids
309 def set_priority(self, cr, uid, ids, priority, *args):
310 return self.write(cr, uid, ids, {'priority' : priority})
312 def set_high_priority(self, cr, uid, ids, *args):
313 """Set lead priority to high
315 return self.set_priority(cr, uid, ids, '1')
317 def set_normal_priority(self, cr, uid, ids, *args):
318 """Set lead priority to normal
320 return self.set_priority(cr, uid, ids, '3')
322 def copy(self, cr, uid, id, default=None, context=None):
323 issue = self.read(cr, uid, id, ['name'], context=context)
326 default = default.copy()
327 default.update(name=_('%s (copy)') % (issue['name']))
328 return super(project_issue, self).copy(cr, uid, id, default=default,
331 def create(self, cr, uid, vals, context=None):
334 if vals.get('project_id') and not context.get('default_project_id'):
335 context['default_project_id'] = vals.get('project_id')
337 # context: no_log, because subtype already handle this
338 create_context = dict(context, mail_create_nolog=True)
339 return super(project_issue, self).create(cr, uid, vals, context=create_context)
341 def write(self, cr, uid, ids, vals, context=None):
342 # stage change: update date_last_stage_update
343 if 'stage_id' in vals:
344 vals['date_last_stage_update'] = fields.datetime.now()
345 if 'kanban_state' not in vals:
346 vals['kanban_state'] = 'normal'
347 # user_id change: update date_start
348 if vals.get('user_id'):
349 vals['date_start'] = fields.datetime.now()
351 return super(project_issue, self).write(cr, uid, ids, vals, context)
353 def onchange_task_id(self, cr, uid, ids, task_id, context=None):
356 task = self.pool.get('project.task').browse(cr, uid, task_id, context=context)
357 return {'value': {'user_id': task.user_id.id, }}
359 def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
360 """ This function returns value of partner email address based on partner
361 :param part: Partner's id
365 partner = self.pool['res.partner'].browse(cr, uid, partner_id, context)
366 result['email_from'] = partner.email
367 return {'value': result}
369 def get_empty_list_help(self, cr, uid, help, context=None):
370 context['empty_list_help_model'] = 'project.project'
371 context['empty_list_help_id'] = context.get('default_project_id')
372 context['empty_list_help_document_name'] = _("issues")
373 return super(project_issue, self).get_empty_list_help(cr, uid, help, context=context)
375 # -------------------------------------------------------
377 # -------------------------------------------------------
379 def set_kanban_state_blocked(self, cr, uid, ids, context=None):
380 return self.write(cr, uid, ids, {'kanban_state': 'blocked'}, context=context)
382 def set_kanban_state_normal(self, cr, uid, ids, context=None):
383 return self.write(cr, uid, ids, {'kanban_state': 'normal'}, context=context)
385 def set_kanban_state_done(self, cr, uid, ids, context=None):
386 return self.write(cr, uid, ids, {'kanban_state': 'done'}, context=context)
388 def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
389 """ Override of the base.stage method
390 Parameter of the stage search taken from the issue:
391 - type: stage type must be the same or 'both'
392 - section_id: if set, stages must belong to this section or
395 if isinstance(cases, (int, long)):
396 cases = self.browse(cr, uid, cases, context=context)
397 # collect all section_ids
400 section_ids.append(section_id)
403 section_ids.append(task.project_id.id)
404 # OR all section_ids and OR with case_default
407 search_domain += [('|')] * (len(section_ids)-1)
408 for section_id in section_ids:
409 search_domain.append(('project_ids', '=', section_id))
410 search_domain += list(domain)
411 # perform search, return the first found
412 stage_ids = self.pool.get('project.task.type').search(cr, uid, search_domain, order=order, context=context)
417 def case_escalate(self, cr, uid, ids, context=None): # FIXME rename this method to issue_escalate
418 for issue in self.browse(cr, uid, ids, context=context):
420 esc_proj = issue.project_id.project_escalation_id
422 raise osv.except_osv(_('Warning!'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!'))
424 data['project_id'] = esc_proj.id
426 data['user_id'] = esc_proj.user_id.id
430 issue.task_id.write({'project_id': esc_proj.id, 'user_id': False})
433 # -------------------------------------------------------
435 # -------------------------------------------------------
437 def message_get_reply_to(self, cr, uid, ids, context=None):
438 """ Override to get the reply_to of the parent project. """
439 return [issue.project_id.message_get_reply_to()[0] if issue.project_id else False
440 for issue in self.browse(cr, uid, ids, context=context)]
442 def message_get_suggested_recipients(self, cr, uid, ids, context=None):
443 recipients = super(project_issue, self).message_get_suggested_recipients(cr, uid, ids, context=context)
445 for issue in self.browse(cr, uid, ids, context=context):
447 self._message_add_suggested_recipient(cr, uid, recipients, issue, partner=issue.partner_id, reason=_('Customer'))
448 elif issue.email_from:
449 self._message_add_suggested_recipient(cr, uid, recipients, issue, email=issue.email_from, reason=_('Customer Email'))
450 except (osv.except_osv, orm.except_orm): # no read access rights -> just ignore suggested recipients because this imply modifying followers
454 def message_new(self, cr, uid, msg, custom_values=None, context=None):
455 """ Overrides mail_thread message_new that is called by the mailgateway
456 through message_process.
457 This override updates the document according to the email.
459 if custom_values is None:
463 context['state_to'] = 'draft'
465 'name': msg.get('subject') or _("No Subject"),
466 'email_from': msg.get('from'),
467 'email_cc': msg.get('cc'),
468 'partner_id': msg.get('author_id', False),
471 defaults.update(custom_values)
472 res_id = super(project_issue, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
475 def message_post(self, cr, uid, thread_id, body='', subject=None, type='notification', subtype=None, parent_id=False, attachments=None, context=None, content_subtype='html', **kwargs):
476 """ Overrides mail_thread message_post so that we can set the date of last action field when
477 a new message is posted on the issue.
481 res = super(project_issue, self).message_post(cr, uid, thread_id, body=body, subject=subject, type=type, subtype=subtype, parent_id=parent_id, attachments=attachments, context=context, content_subtype=content_subtype, **kwargs)
482 if thread_id and subtype:
483 self.write(cr, SUPERUSER_ID, thread_id, {'date_action_last': fields.datetime.now()}, context=context)
487 class project(osv.Model):
488 _inherit = "project.project"
490 def _get_alias_models(self, cr, uid, context=None):
491 return [('project.task', "Tasks"), ("project.issue", "Issues")]
493 def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
494 """ :deprecated: this method will be removed with OpenERP v8. Use issue_ids
496 res = dict.fromkeys(ids, 0)
497 issue_ids = self.pool.get('project.issue').search(cr, uid, [('project_id', 'in', ids)])
498 for issue in self.pool.get('project.issue').browse(cr, uid, issue_ids, context):
499 if issue.stage_id and not issue.stage_id.fold:
500 res[issue.project_id.id] += 1
504 'project_escalation_id': fields.many2one('project.project', 'Project Escalation',
505 help='If any issue is escalated from the current Project, it will be listed under the project selected here.',
506 states={'close': [('readonly', True)], 'cancelled': [('readonly', True)]}),
507 'issue_count': fields.function(_issue_count, type='integer', string="Unclosed Issues",
508 deprecated="This field will be removed in OpenERP v8. Use issue_ids one2many field instead."),
509 'issue_ids': fields.one2many('project.issue', 'project_id',
510 domain=[('stage_id.fold', '=', False)])
513 def _check_escalation(self, cr, uid, ids, context=None):
514 project_obj = self.browse(cr, uid, ids[0], context=context)
515 if project_obj.project_escalation_id:
516 if project_obj.project_escalation_id.id == project_obj.id:
521 (_check_escalation, 'Error! You cannot assign escalation to the same project!', ['project_escalation_id'])
525 class account_analytic_account(osv.Model):
526 _inherit = 'account.analytic.account'
527 _description = 'Analytic Account'
530 'use_issues': fields.boolean('Issues', help="Check this field if this project manages issues"),
533 def on_change_template(self, cr, uid, ids, template_id, context=None):
534 res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, context=context)
535 if template_id and 'value' in res:
536 template = self.browse(cr, uid, template_id, context=context)
537 res['value']['use_issues'] = template.use_issues
540 def _trigger_project_creation(self, cr, uid, vals, context=None):
543 res = super(account_analytic_account, self)._trigger_project_creation(cr, uid, vals, context=context)
544 return res or (vals.get('use_issues') and not 'project_creation_in_progress' in context)
547 class project_project(osv.Model):
548 _inherit = 'project.project'
554 def _check_create_write_values(self, cr, uid, vals, context=None):
555 """ Perform some check on values given to create or write. """
556 # Handle use_tasks / use_issues: if only one is checked, alias should take the same model
557 if vals.get('use_tasks') and not vals.get('use_issues'):
558 vals['alias_model'] = 'project.task'
559 elif vals.get('use_issues') and not vals.get('use_tasks'):
560 vals['alias_model'] = 'project.issue'
562 def on_change_use_tasks_or_issues(self, cr, uid, ids, use_tasks, use_issues, context=None):
564 if use_tasks and not use_issues:
565 values['alias_model'] = 'project.task'
566 elif not use_tasks and use_issues:
567 values['alias_model'] = 'project.issues'
568 return {'value': values}
570 def create(self, cr, uid, vals, context=None):
571 self._check_create_write_values(cr, uid, vals, context=context)
572 return super(project_project, self).create(cr, uid, vals, context=context)
574 def write(self, cr, uid, ids, vals, context=None):
575 self._check_create_write_values(cr, uid, vals, context=context)
576 return super(project_project, self).write(cr, uid, ids, vals, context=context)
579 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: