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