[MERGE] forward port of branch 8.0 up to 491372e
[odoo/odoo.git] / addons / project_issue / project_issue.py
1  #-*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 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 calendar
23 from datetime import datetime,date
24 from dateutil import relativedelta
25 import json
26 import time
27 from openerp import api
28 from openerp import SUPERUSER_ID
29 from openerp import tools
30 from openerp.osv import fields, osv, orm
31 from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
32 from openerp.tools import html2plaintext
33 from openerp.tools.translate import _
34
35
36 class project_issue_version(osv.Model):
37     _name = "project.issue.version"
38     _order = "name desc"
39     _columns = {
40         'name': fields.char('Version Number', required=True),
41         'active': fields.boolean('Active', required=False),
42     }
43     _defaults = {
44         'active': 1,
45     }
46
47 class project_issue(osv.Model):
48     _name = "project.issue"
49     _description = "Project Issue"
50     _order = "priority desc, create_date desc"
51     _inherit = ['mail.thread', 'ir.needaction_mixin']
52
53     _mail_post_access = 'read'
54     _track = {
55         'stage_id': {
56             # this is only an heuristics; depending on your particular stage configuration it may not match all 'new' stages
57             'project_issue.mt_issue_new': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence <= 1,
58             'project_issue.mt_issue_stage': lambda self, cr, uid, obj, ctx=None: obj.stage_id and obj.stage_id.sequence > 1,
59         },
60         'user_id': {
61             'project_issue.mt_issue_assigned': lambda self, cr, uid, obj, ctx=None: obj.user_id and obj.user_id.id,
62         },
63         'kanban_state': {
64             'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked',
65             'project_issue.mt_issue_ready': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'done',
66         },
67     }
68
69     def _get_default_partner(self, cr, uid, context=None):
70         project_id = self._get_default_project_id(cr, uid, context)
71         if project_id:
72             project = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
73             if project and project.partner_id:
74                 return project.partner_id.id
75         return False
76
77     def _get_default_project_id(self, cr, uid, context=None):
78         """ Gives default project by checking if present in the context """
79         return self._resolve_project_id_from_context(cr, uid, context=context)
80
81     def _get_default_stage_id(self, cr, uid, context=None):
82         """ Gives default stage_id """
83         project_id = self._get_default_project_id(cr, uid, context=context)
84         return self.stage_find(cr, uid, [], project_id, [('fold', '=', False)], context=context)
85
86     def _resolve_project_id_from_context(self, cr, uid, context=None):
87         """ Returns ID of project based on the value of 'default_project_id'
88             context key, or None if it cannot be resolved to a single
89             project.
90         """
91         if context is None:
92             context = {}
93         if type(context.get('default_project_id')) in (int, long):
94             return context.get('default_project_id')
95         if isinstance(context.get('default_project_id'), basestring):
96             project_name = context['default_project_id']
97             project_ids = self.pool.get('project.project').name_search(cr, uid, name=project_name, context=context)
98             if len(project_ids) == 1:
99                 return int(project_ids[0][0])
100         return None
101
102     def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
103         access_rights_uid = access_rights_uid or uid
104         stage_obj = self.pool.get('project.task.type')
105         order = stage_obj._order
106         # lame hack to allow reverting search, should just work in the trivial case
107         if read_group_order == 'stage_id desc':
108             order = "%s desc" % order
109         # retrieve team_id from the context and write the domain
110         # - ('id', 'in', 'ids'): add columns that should be present
111         # - OR ('case_default', '=', True), ('fold', '=', False): add default columns that are not folded
112         # - OR ('project_ids', 'in', project_id), ('fold', '=', False) if project_id: add project columns that are not folded
113         search_domain = []
114         project_id = self._resolve_project_id_from_context(cr, uid, context=context)
115         if project_id:
116             search_domain += ['|', ('project_ids', '=', project_id)]
117         search_domain += [('id', 'in', ids)]
118         # perform search
119         stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
120         result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
121         # restore order of the search
122         result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
123
124         fold = {}
125         for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
126             fold[stage.id] = stage.fold or False
127         return result, fold
128
129     def _compute_day(self, cr, uid, ids, fields, args, context=None):
130         """
131         @param cr: the current row, from the database cursor,
132         @param uid: the current user’s ID for security checks,
133         @param ids: List of Openday’s IDs
134         @return: difference between current date and log date
135         @param context: A standard dictionary for contextual values
136         """
137         Calendar = self.pool['resource.calendar']
138
139         res = dict((res_id, {}) for res_id in ids)
140         for issue in self.browse(cr, uid, ids, context=context):
141             values = {
142                 'day_open': 0.0, 'day_close': 0.0,
143                 'working_hours_open': 0.0, 'working_hours_close': 0.0,
144                 'days_since_creation': 0.0, 'inactivity_days': 0.0,
145             }
146             # if the working hours on the project are not defined, use default ones (8 -> 12 and 13 -> 17 * 5), represented by None
147             calendar_id = None
148             if issue.project_id and issue.project_id.resource_calendar_id:
149                 calendar_id = issue.project_id.resource_calendar_id.id
150
151             dt_create_date = datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT)
152
153             if issue.date_open:
154                 dt_date_open = datetime.strptime(issue.date_open, DEFAULT_SERVER_DATETIME_FORMAT)
155                 values['day_open'] = (dt_date_open - dt_create_date).total_seconds() / (24.0 * 3600)
156                 values['working_hours_open'] = Calendar._interval_hours_get(
157                     cr, uid, calendar_id, dt_create_date, dt_date_open,
158                     timezone_from_uid=issue.user_id.id or uid,
159                     exclude_leaves=False, context=context)
160
161             if issue.date_closed:
162                 dt_date_closed = datetime.strptime(issue.date_closed, DEFAULT_SERVER_DATETIME_FORMAT)
163                 values['day_close'] = (dt_date_closed - dt_create_date).total_seconds() / (24.0 * 3600)
164                 values['working_hours_close'] = Calendar._interval_hours_get(
165                     cr, uid, calendar_id, dt_create_date, dt_date_closed,
166                     timezone_from_uid=issue.user_id.id or uid,
167                     exclude_leaves=False, context=context)
168
169             days_since_creation = datetime.today() - dt_create_date
170             values['days_since_creation'] = days_since_creation.days
171             if issue.date_action_last:
172                 inactive_days = datetime.today() - datetime.strptime(issue.date_action_last, DEFAULT_SERVER_DATETIME_FORMAT)
173             elif issue.date_last_stage_update:
174                 inactive_days = datetime.today() - datetime.strptime(issue.date_last_stage_update, DEFAULT_SERVER_DATETIME_FORMAT)
175             else:
176                 inactive_days = datetime.today() - datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT)
177             values['inactivity_days'] = inactive_days.days
178
179             # filter only required values
180             for field in fields:
181                 res[issue.id][field] = values[field]
182
183         return res
184
185     def _hours_get(self, cr, uid, ids, field_names, args, context=None):
186         task_pool = self.pool.get('project.task')
187         res = {}
188         for issue in self.browse(cr, uid, ids, context=context):
189             progress = 0.0
190             if issue.task_id:
191                 progress = task_pool._hours_get(cr, uid, [issue.task_id.id], field_names, args, context=context)[issue.task_id.id]['progress']
192             res[issue.id] = {'progress' : progress}
193         return res
194
195     def _can_escalate(self, cr, uid, ids, field_name, arg, context=None):
196         res = {}
197         for issue in self.browse(cr, uid, ids, context=context):
198             if issue.project_id.parent_id.type == 'contract':
199                 res[issue.id] = True
200         return res
201
202     def on_change_project(self, cr, uid, ids, project_id, context=None):
203         if project_id:
204             project = self.pool.get('project.project').browse(cr, uid, project_id, context=context)
205             if project and project.partner_id:
206                 return {'value': {'partner_id': project.partner_id.id}}
207         return {}
208
209     def _get_issue_task(self, cr, uid, ids, context=None):
210         issues = []
211         issue_pool = self.pool.get('project.issue')
212         for task in self.pool.get('project.task').browse(cr, uid, ids, context=context):
213             issues += issue_pool.search(cr, uid, [('task_id','=',task.id)])
214         return issues
215
216     def _get_issue_work(self, cr, uid, ids, context=None):
217         issues = []
218         issue_pool = self.pool.get('project.issue')
219         for work in self.pool.get('project.task.work').browse(cr, uid, ids, context=context):
220             if work.task_id:
221                 issues += issue_pool.search(cr, uid, [('task_id','=',work.task_id.id)])
222         return issues
223
224     _columns = {
225         'id': fields.integer('ID', readonly=True),
226         'name': fields.char('Issue', required=True),
227         'active': fields.boolean('Active', required=False),
228         'create_date': fields.datetime('Creation Date', readonly=True, select=True),
229         'write_date': fields.datetime('Update Date', readonly=True),
230         'days_since_creation': fields.function(_compute_day, string='Days since creation date', \
231                                                multi='compute_day', type="integer", help="Difference in days between creation date and current date"),
232         'date_deadline': fields.date('Deadline'),
233         'team_id': fields.many2one('crm.team', 'Sales Team', oldname='section_id',\
234                         select=True, help='Sales team to which Case belongs to.\
235                              Define Responsible user and Email account for mail gateway.'),
236         'partner_id': fields.many2one('res.partner', 'Contact', select=1),
237         'company_id': fields.many2one('res.company', 'Company'),
238         'description': fields.text('Private Note'),
239         'kanban_state': fields.selection([('normal', 'Normal'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State',
240                                          track_visibility='onchange',
241                                          help="A Issue's kanban state indicates special situations affecting it:\n"
242                                               " * Normal is the default situation\n"
243                                               " * Blocked indicates something is preventing the progress of this issue\n"
244                                               " * Ready for next stage indicates the issue is ready to be pulled to the next stage",
245                                          required=False),
246         'email_from': fields.char('Email', size=128, help="These people will receive email.", select=1),
247         '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"),
248         'date_open': fields.datetime('Assigned', readonly=True, select=True),
249         # Project Issue fields
250         'date_closed': fields.datetime('Closed', readonly=True, select=True),
251         'date': fields.datetime('Date'),
252         'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
253         'channel': fields.char('Channel', help="Communication channel."),
254         'categ_ids': fields.many2many('project.category', string='Tags'),
255         'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority', select=True),
256         'version_id': fields.many2one('project.issue.version', 'Version'),
257         'stage_id': fields.many2one ('project.task.type', 'Stage',
258                         track_visibility='onchange', select=True,
259                         domain="[('project_ids', '=', project_id)]", copy=False),
260         'project_id': fields.many2one('project.project', 'Project', track_visibility='onchange', select=True),
261         'duration': fields.float('Duration'),
262         'task_id': fields.many2one('project.task', 'Task', domain="[('project_id','=',project_id)]"),
263         'day_open': fields.function(_compute_day, string='Days to Assign',
264                                     multi='compute_day', type="float",
265                                     store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}),
266         'day_close': fields.function(_compute_day, string='Days to Close',
267                                      multi='compute_day', type="float",
268                                      store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}),
269         'user_id': fields.many2one('res.users', 'Assigned to', required=False, select=1, track_visibility='onchange'),
270         'working_hours_open': fields.function(_compute_day, string='Working Hours to assign the Issue',
271                                               multi='compute_day', type="float",
272                                               store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}),
273         'working_hours_close': fields.function(_compute_day, string='Working Hours to close the Issue',
274                                                multi='compute_day', type="float",
275                                                store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}),
276         'inactivity_days': fields.function(_compute_day, string='Days since last action',
277                                            multi='compute_day', type="integer", help="Difference in days between last action and current date"),
278         'color': fields.integer('Color Index'),
279         'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
280         'date_action_last': fields.datetime('Last Action', readonly=1),
281         'date_action_next': fields.datetime('Next Action', readonly=1),
282         'can_escalate': fields.function(_can_escalate, type='boolean', string='Can Escalate'),
283         'progress': fields.function(_hours_get, string='Progress (%)', multi='hours', group_operator="avg", help="Computed as: Time Spent / Total Time.",
284             store = {
285                 'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['task_id'], 10),
286                 'project.task': (_get_issue_task, ['work_ids', 'remaining_hours', 'planned_hours', 'state', 'stage_id'], 10),
287                 'project.task.work': (_get_issue_work, ['hours'], 10),
288             }),
289     }
290
291     _defaults = {
292         'active': 1,
293         'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
294         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c),
295         'priority': '0',
296         'kanban_state': 'normal',
297         'date_last_stage_update': fields.datetime.now,
298         'user_id': lambda obj, cr, uid, context: uid,
299     }
300
301     _group_by_full = {
302         'stage_id': _read_group_stage_ids
303     }
304
305     def copy(self, cr, uid, id, default=None, context=None):
306         issue = self.read(cr, uid, [id], ['name'], context=context)[0]
307         if not default:
308             default = {}
309         default = default.copy()
310         default.update(name=_('%s (copy)') % (issue['name']))
311         return super(project_issue, self).copy(cr, uid, id, default=default, context=context)
312
313     def create(self, cr, uid, vals, context=None):
314         context = dict(context or {})
315         if vals.get('project_id') and not context.get('default_project_id'):
316             context['default_project_id'] = vals.get('project_id')
317         if vals.get('user_id'):
318             vals['date_open'] = fields.datetime.now()
319         if 'stage_id' in vals:
320             vals.update(self.onchange_stage_id(cr, uid, None, vals.get('stage_id'), context=context)['value'])
321
322         # context: no_log, because subtype already handle this
323         create_context = dict(context, mail_create_nolog=True)
324         return super(project_issue, self).create(cr, uid, vals, context=create_context)
325
326     def write(self, cr, uid, ids, vals, context=None):
327         # stage change: update date_last_stage_update
328         if 'stage_id' in vals:
329             vals.update(self.onchange_stage_id(cr, uid, ids, vals.get('stage_id'), context=context)['value'])
330             vals['date_last_stage_update'] = fields.datetime.now()
331             if 'kanban_state' not in vals:
332                 vals['kanban_state'] = 'normal'
333         # user_id change: update date_start
334         if vals.get('user_id'):
335             vals['date_open'] = fields.datetime.now()
336
337         return super(project_issue, self).write(cr, uid, ids, vals, context)
338
339     def onchange_task_id(self, cr, uid, ids, task_id, context=None):
340         if not task_id:
341             return {'value': {}}
342         task = self.pool.get('project.task').browse(cr, uid, task_id, context=context)
343         return {'value': {'user_id': task.user_id.id, }}
344
345     def onchange_partner_id(self, cr, uid, ids, partner_id, context=None):
346         """ This function returns value of partner email address based on partner
347             :param part: Partner's id
348         """
349         result = {}
350         if partner_id:
351             partner = self.pool['res.partner'].browse(cr, uid, partner_id, context)
352             result['email_from'] = partner.email
353         return {'value': result}
354
355     def get_empty_list_help(self, cr, uid, help, context=None):
356         context = dict(context or {})
357         context['empty_list_help_model'] = 'project.project'
358         context['empty_list_help_id'] = context.get('default_project_id')
359         context['empty_list_help_document_name'] = _("issues")
360         return super(project_issue, self).get_empty_list_help(cr, uid, help, context=context)
361
362     # -------------------------------------------------------
363     # Stage management
364     # -------------------------------------------------------
365
366     def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):
367         if not stage_id:
368             return {'value': {}}
369         stage = self.pool['project.task.type'].browse(cr, uid, stage_id, context=context)
370         if stage.fold:
371             return {'value': {'date_closed': fields.datetime.now()}}
372         return {'value': {'date_closed': False}}
373
374     def stage_find(self, cr, uid, cases, team_id, domain=[], order='sequence', context=None):
375         """ Override of the base.stage method
376             Parameter of the stage search taken from the issue:
377             - type: stage type must be the same or 'both'
378             - team_id: if set, stages must belong to this team or
379               be a default case
380         """
381         if isinstance(cases, (int, long)):
382             cases = self.browse(cr, uid, cases, context=context)
383         # collect all team_ids
384         team_ids = []
385         if team_id:
386             team_ids.append(team_id)
387         for task in cases:
388             if task.project_id:
389                 team_ids.append(task.project_id.id)
390         # OR all team_ids and OR with case_default
391         search_domain = []
392         if team_ids:
393             search_domain += [('|')] * (len(team_ids)-1)
394             for team_id in team_ids:
395                 search_domain.append(('project_ids', '=', team_id))
396         search_domain += list(domain)
397         # perform search, return the first found
398         stage_ids = self.pool.get('project.task.type').search(cr, uid, search_domain, order=order, context=context)
399         if stage_ids:
400             return stage_ids[0]
401         return False
402
403     def case_escalate(self, cr, uid, ids, context=None):        # FIXME rename this method to issue_escalate
404         for issue in self.browse(cr, uid, ids, context=context):
405             data = {}
406             esc_proj = issue.project_id.project_escalation_id
407             if not esc_proj:
408                 raise osv.except_osv(_('Warning!'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!'))
409
410             data['project_id'] = esc_proj.id
411             if esc_proj.user_id:
412                 data['user_id'] = esc_proj.user_id.id
413             issue.write(data)
414
415             if issue.task_id:
416                 issue.task_id.write({'project_id': esc_proj.id, 'user_id': False})
417         return True
418
419     # -------------------------------------------------------
420     # Mail gateway
421     # -------------------------------------------------------
422
423     def message_get_reply_to(self, cr, uid, ids, context=None):
424         """ Override to get the reply_to of the parent project. """
425         issues = self.browse(cr, SUPERUSER_ID, ids, context=context)
426         project_ids = set([issue.project_id.id for issue in issues if issue.project_id])
427         aliases = self.pool['project.project'].message_get_reply_to(cr, uid, list(project_ids), context=context)
428         return dict((issue.id, aliases.get(issue.project_id and issue.project_id.id or 0, False)) for issue in issues)
429
430     def message_get_suggested_recipients(self, cr, uid, ids, context=None):
431         recipients = super(project_issue, self).message_get_suggested_recipients(cr, uid, ids, context=context)
432         try:
433             for issue in self.browse(cr, uid, ids, context=context):
434                 if issue.partner_id:
435                     self._message_add_suggested_recipient(cr, uid, recipients, issue, partner=issue.partner_id, reason=_('Customer'))
436                 elif issue.email_from:
437                     self._message_add_suggested_recipient(cr, uid, recipients, issue, email=issue.email_from, reason=_('Customer Email'))
438         except (osv.except_osv, orm.except_orm):  # no read access rights -> just ignore suggested recipients because this imply modifying followers
439             pass
440         return recipients
441
442     def message_new(self, cr, uid, msg, custom_values=None, context=None):
443         """ Overrides mail_thread message_new that is called by the mailgateway
444             through message_process.
445             This override updates the document according to the email.
446         """
447         if custom_values is None:
448             custom_values = {}
449         context = dict(context or {}, state_to='draft')
450         defaults = {
451             'name':  msg.get('subject') or _("No Subject"),
452             'email_from': msg.get('from'),
453             'email_cc': msg.get('cc'),
454             'partner_id': msg.get('author_id', False),
455             'user_id': False,
456         }
457         defaults.update(custom_values)
458         res_id = super(project_issue, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
459         return res_id
460
461     @api.cr_uid_ids_context
462     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):
463         """ Overrides mail_thread message_post so that we can set the date of last action field when
464             a new message is posted on the issue.
465         """
466         if context is None:
467             context = {}
468         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)
469         if thread_id and subtype:
470             self.write(cr, SUPERUSER_ID, thread_id, {'date_action_last': fields.datetime.now()}, context=context)
471         return res
472
473
474 class project(osv.Model):
475     _inherit = "project.project"
476
477     def _get_alias_models(self, cr, uid, context=None):
478         return [('project.task', "Tasks"), ("project.issue", "Issues")]
479
480     def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
481         Issue = self.pool['project.issue']
482         return {
483             project_id: Issue.search_count(cr,uid, [('project_id', '=', project_id), ('stage_id.fold', '=', False)], context=context)
484             for project_id in ids
485         }
486     def _get_project_issue_data(self, cr, uid, ids, field_name, arg, context=None):
487         obj = self.pool['project.issue']
488         month_begin = date.today().replace(day=1)
489         date_begin = (month_begin - relativedelta.relativedelta(months=self._period_number - 1)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
490         date_end = month_begin.replace(day=calendar.monthrange(month_begin.year, month_begin.month)[1]).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
491         res = {}
492         for id in ids:
493             created_domain = [('project_id', '=', id), ('date_closed', '>=', date_begin ), ('date_closed', '<=', date_end )]
494             res[id] = json.dumps(self.__get_bar_values(cr, uid, obj, created_domain, [ 'date_closed'], 'date_closed_count', 'date_closed', context=context))
495         return res
496     _columns = {
497         'project_escalation_id': fields.many2one('project.project', 'Project Escalation',
498             help='If any issue is escalated from the current Project, it will be listed under the project selected here.',
499             states={'close': [('readonly', True)], 'cancelled': [('readonly', True)]}),
500         'issue_count': fields.function(_issue_count, type='integer', string="Issues",),
501         'issue_ids': fields.one2many('project.issue', 'project_id', string="Issues",
502                                      domain=[('date_closed', '!=', False)]),
503         'monthly_issues': fields.function(_get_project_issue_data, type='char', readonly=True,
504                                              string='Project Issue By Month')
505     }
506
507     def _check_escalation(self, cr, uid, ids, context=None):
508         project_obj = self.browse(cr, uid, ids[0], context=context)
509         if project_obj.project_escalation_id:
510             if project_obj.project_escalation_id.id == project_obj.id:
511                 return False
512         return True
513
514     _constraints = [
515         (_check_escalation, 'Error! You cannot assign escalation to the same project!', ['project_escalation_id'])
516     ]
517
518
519 class account_analytic_account(osv.Model):
520     _inherit = 'account.analytic.account'
521     _description = 'Analytic Account'
522
523     _columns = {
524         'use_issues': fields.boolean('Issues', help="Check this field if this project manages issues"),
525     }
526
527     def on_change_template(self, cr, uid, ids, template_id, date_start=False, context=None):
528         res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, date_start=date_start, context=context)
529         if template_id and 'value' in res:
530             template = self.browse(cr, uid, template_id, context=context)
531             res['value']['use_issues'] = template.use_issues
532         return res
533
534     def _trigger_project_creation(self, cr, uid, vals, context=None):
535         if context is None:
536             context = {}
537         res = super(account_analytic_account, self)._trigger_project_creation(cr, uid, vals, context=context)
538         return res or (vals.get('use_issues') and not 'project_creation_in_progress' in context)
539
540     def unlink(self, cr, uid, ids, context=None):
541         proj_ids = self.pool['project.project'].search(cr, uid, [('analytic_account_id', 'in', ids)])
542         has_issues = self.pool['project.issue'].search(cr, uid, [('project_id', 'in', proj_ids)], count=True, context=context)
543         if has_issues:
544             raise osv.except_osv(_('Warning!'), _('Please remove existing issues in the project linked to the accounts you want to delete.'))
545         return super(account_analytic_account, self).unlink(cr, uid, ids, context=context)
546
547
548 class project_project(osv.Model):
549     _inherit = 'project.project'
550
551     _defaults = {
552         'use_issues': True
553     }
554
555     def _check_create_write_values(self, cr, uid, vals, context=None):
556         """ Perform some check on values given to create or write. """
557         # Handle use_tasks / use_issues: if only one is checked, alias should take the same model
558         if vals.get('use_tasks') and not vals.get('use_issues'):
559             vals['alias_model'] = 'project.task'
560         elif vals.get('use_issues') and not vals.get('use_tasks'):
561             vals['alias_model'] = 'project.issue'
562
563     def on_change_use_tasks_or_issues(self, cr, uid, ids, use_tasks, use_issues, context=None):
564         values = {}
565         if use_tasks and not use_issues:
566             values['alias_model'] = 'project.task'
567         elif not use_tasks and use_issues:
568             values['alias_model'] = 'project.issue'
569         return {'value': values}
570
571     def create(self, cr, uid, vals, context=None):
572         self._check_create_write_values(cr, uid, vals, context=context)
573         return super(project_project, self).create(cr, uid, vals, context=context)
574
575     def write(self, cr, uid, ids, vals, context=None):
576         self._check_create_write_values(cr, uid, vals, context=context)
577         return super(project_project, self).write(cr, uid, ids, vals, context=context)
578
579 class res_partner(osv.osv):
580     def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
581         Issue = self.pool['project.issue']
582         return {
583             partner_id: Issue.search_count(cr,uid, [('partner_id', '=', partner_id)])
584             for partner_id in ids
585         }
586     
587     """ Inherits partner and adds Issue information in the partner form """
588     _inherit = 'res.partner'
589     _columns = {
590         'issue_count': fields.function(_issue_count, string='# Issues', type='integer'),
591     }
592 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: