[MERGE] forward port of branch saas-3 up to 8c4a7cb
[odoo/odoo.git] / addons / project_issue / project_issue.py
index 691a9fd..1503991 100644 (file)
 
 from datetime import datetime
 
+from openerp import api
 from openerp import SUPERUSER_ID
 from openerp import tools
-from openerp.addons.crm import crm
 from openerp.osv import fields, osv, orm
+from openerp.tools import DEFAULT_SERVER_DATETIME_FORMAT
 from openerp.tools import html2plaintext
 from openerp.tools.translate import _
 
+
 class project_issue_version(osv.Model):
     _name = "project.issue.version"
     _order = "name desc"
     _columns = {
-        'name': fields.char('Version Number', size=32, required=True),
+        'name': fields.char('Version Number', required=True),
         'active': fields.boolean('Active', required=False),
     }
     _defaults = {
@@ -42,7 +44,7 @@ class project_issue_version(osv.Model):
 class project_issue(osv.Model):
     _name = "project.issue"
     _description = "Project Issue"
-    _order = "priority, create_date desc"
+    _order = "priority desc, create_date desc"
     _inherit = ['mail.thread', 'ir.needaction_mixin']
 
     _mail_post_access = 'read'
@@ -57,6 +59,7 @@ class project_issue(osv.Model):
         },
         'kanban_state': {
             'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'blocked',
+            'project_issue.mt_issue_ready': lambda self, cr, uid, obj, ctx=None: obj.kanban_state == 'done',
         },
     }
 
@@ -128,73 +131,51 @@ class project_issue(osv.Model):
         @return: difference between current date and log date
         @param context: A standard dictionary for contextual values
         """
-        cal_obj = self.pool.get('resource.calendar')
-        res_obj = self.pool.get('resource.resource')
+        Calendar = self.pool['resource.calendar']
 
-        res = {}
+        res = dict((res_id, {}) for res_id in ids)
         for issue in self.browse(cr, uid, ids, context=context):
-
+            values = {
+                'day_open': 0.0, 'day_close': 0.0,
+                'working_hours_open': 0.0, 'working_hours_close': 0.0,
+                'days_since_creation': 0.0, 'inactivity_days': 0.0,
+            }
             # if the working hours on the project are not defined, use default ones (8 -> 12 and 13 -> 17 * 5), represented by None
-            if not issue.project_id or not issue.project_id.resource_calendar_id:
-                working_hours = None
+            calendar_id = None
+            if issue.project_id and issue.project_id.resource_calendar_id:
+                calendar_id = issue.project_id.resource_calendar_id.id
+
+            dt_create_date = datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT)
+
+            if issue.date_open:
+                dt_date_open = datetime.strptime(issue.date_open, DEFAULT_SERVER_DATETIME_FORMAT)
+                values['day_open'] = (dt_date_open - dt_create_date).total_seconds() / (24.0 * 3600)
+                values['working_hours_open'] = Calendar._interval_hours_get(
+                    cr, uid, calendar_id, dt_create_date, dt_date_open,
+                    timezone_from_uid=issue.user_id.id or uid,
+                    exclude_leaves=False, context=context)
+
+            if issue.date_closed:
+                dt_date_closed = datetime.strptime(issue.date_closed, DEFAULT_SERVER_DATETIME_FORMAT)
+                values['day_close'] = (dt_date_closed - dt_create_date).total_seconds() / (24.0 * 3600)
+                values['working_hours_close'] = Calendar._interval_hours_get(
+                    cr, uid, calendar_id, dt_create_date, dt_date_closed,
+                    timezone_from_uid=issue.user_id.id or uid,
+                    exclude_leaves=False, context=context)
+
+            days_since_creation = datetime.today() - dt_create_date
+            values['days_since_creation'] = days_since_creation.days
+            if issue.date_action_last:
+                inactive_days = datetime.today() - datetime.strptime(issue.date_action_last, DEFAULT_SERVER_DATETIME_FORMAT)
+            elif issue.date_last_stage_update:
+                inactive_days = datetime.today() - datetime.strptime(issue.date_last_stage_update, DEFAULT_SERVER_DATETIME_FORMAT)
             else:
-                working_hours = issue.project_id.resource_calendar_id.id
+                inactive_days = datetime.today() - datetime.strptime(issue.create_date, DEFAULT_SERVER_DATETIME_FORMAT)
+            values['inactivity_days'] = inactive_days.days
 
-            res[issue.id] = {}
+            # filter only required values
             for field in fields:
-                duration = 0
-                ans = False
-                hours = 0
-
-                date_create = datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
-                if field in ['working_hours_open','day_open']:
-                    if issue.date_open:
-                        date_open = datetime.strptime(issue.date_open, "%Y-%m-%d %H:%M:%S")
-                        ans = date_open - date_create
-                        date_until = issue.date_open
-                        #Calculating no. of working hours to open the issue
-                        hours = cal_obj._interval_hours_get(cr, uid, working_hours,
-                                                           date_create,
-                                                           date_open,
-                                                           timezone_from_uid=issue.user_id.id or uid,
-                                                           exclude_leaves=False,
-                                                           context=context)
-                elif field in ['working_hours_close','day_close']:
-                    if issue.date_closed:
-                        date_close = datetime.strptime(issue.date_closed, "%Y-%m-%d %H:%M:%S")
-                        date_until = issue.date_closed
-                        ans = date_close - date_create
-                        #Calculating no. of working hours to close the issue
-                        hours = cal_obj._interval_hours_get(cr, uid, working_hours,
-                                                           date_create,
-                                                           date_close,
-                                                           timezone_from_uid=issue.user_id.id or uid,
-                                                           exclude_leaves=False,
-                                                           context=context)
-                elif field in ['days_since_creation']:
-                    if issue.create_date:
-                        days_since_creation = datetime.today() - datetime.strptime(issue.create_date, "%Y-%m-%d %H:%M:%S")
-                        res[issue.id][field] = days_since_creation.days
-                    continue
-
-                elif field in ['inactivity_days']:
-                    res[issue.id][field] = 0
-                    if issue.date_action_last:
-                        inactive_days = datetime.today() - datetime.strptime(issue.date_action_last, '%Y-%m-%d %H:%M:%S')
-                        res[issue.id][field] = inactive_days.days
-                    continue
-                if ans:
-                    resource_id = False
-                    if issue.user_id:
-                        resource_ids = res_obj.search(cr, uid, [('user_id','=',issue.user_id.id)])
-                        if resource_ids and len(resource_ids):
-                            resource_id = resource_ids[0]
-                    duration = float(ans.days) + float(ans.seconds)/(24*3600)
-
-                if field in ['working_hours_open','working_hours_close']:
-                    res[issue.id][field] = hours
-                elif field in ['day_open','day_close']:
-                    res[issue.id][field] = duration
+                res[issue.id][field] = values[field]
 
         return res
 
@@ -232,9 +213,9 @@ class project_issue(osv.Model):
 
     _columns = {
         'id': fields.integer('ID', readonly=True),
-        'name': fields.char('Issue', size=128, required=True),
+        'name': fields.char('Issue', required=True),
         'active': fields.boolean('Active', required=False),
-        'create_date': fields.datetime('Creation Date', readonly=True,select=True),
+        'create_date': fields.datetime('Creation Date', readonly=True, select=True),
         'write_date': fields.datetime('Update Date', readonly=True),
         'days_since_creation': fields.function(_compute_day, string='Days since creation date', \
                                                multi='compute_day', type="integer", help="Difference in days between creation date and current date"),
@@ -251,35 +232,39 @@ class project_issue(osv.Model):
                                               " * Normal is the default situation\n"
                                               " * Blocked indicates something is preventing the progress of this issue\n"
                                               " * Ready for next stage indicates the issue is ready to be pulled to the next stage",
-                                         readonly=True, required=False),
+                                         required=False),
         'email_from': fields.char('Email', size=128, help="These people will receive email.", select=1),
         '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"),
-        'date_open': fields.datetime('Opened', readonly=True,select=True),
+        'date_open': fields.datetime('Assigned', readonly=True, select=True),
         # Project Issue fields
-        'date_closed': fields.datetime('Closed', readonly=True,select=True),
+        'date_closed': fields.datetime('Closed', readonly=True, select=True),
         'date': fields.datetime('Date'),
         'date_last_stage_update': fields.datetime('Last Stage Update', select=True),
-        'channel_id': fields.many2one('crm.case.channel', 'Channel', help="Communication channel."),
+        'channel': fields.char('Channel', help="Communication channel."),
         'categ_ids': fields.many2many('project.category', string='Tags'),
-        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority', select=True),
+        'priority': fields.selection([('0','Low'), ('1','Normal'), ('2','High')], 'Priority', select=True),
         'version_id': fields.many2one('project.issue.version', 'Version'),
         'stage_id': fields.many2one ('project.task.type', 'Stage',
                         track_visibility='onchange', select=True,
-                        domain="[('project_ids', '=', project_id)]"),
+                        domain="[('project_ids', '=', project_id)]", copy=False),
         'project_id': fields.many2one('project.project', 'Project', track_visibility='onchange', select=True),
         'duration': fields.float('Duration'),
         'task_id': fields.many2one('project.task', 'Task', domain="[('project_id','=',project_id)]"),
-        'day_open': fields.function(_compute_day, string='Days to Open', \
-                                multi='compute_day', type="float", store=True),
-        'day_close': fields.function(_compute_day, string='Days to Close', \
-                                multi='compute_day', type="float", store=True),
+        'day_open': fields.function(_compute_day, string='Days to Assign',
+                                    multi='compute_day', type="float",
+                                    store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}),
+        'day_close': fields.function(_compute_day, string='Days to Close',
+                                     multi='compute_day', type="float",
+                                     store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}),
         'user_id': fields.many2one('res.users', 'Assigned to', required=False, select=1, track_visibility='onchange'),
-        'working_hours_open': fields.function(_compute_day, string='Working Hours to Open the Issue', \
-                                multi='compute_day', type="float", store=True),
-        'working_hours_close': fields.function(_compute_day, string='Working Hours to Close the Issue', \
-                                multi='compute_day', type="float", store=True),
-        'inactivity_days': fields.function(_compute_day, string='Days since last action', \
-                                multi='compute_day', type="integer", help="Difference in days between last action and current date"),
+        'working_hours_open': fields.function(_compute_day, string='Working Hours to assign the Issue',
+                                              multi='compute_day', type="float",
+                                              store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_open'], 10)}),
+        'working_hours_close': fields.function(_compute_day, string='Working Hours to close the Issue',
+                                               multi='compute_day', type="float",
+                                               store={'project.issue': (lambda self, cr, uid, ids, c={}: ids, ['date_closed'], 10)}),
+        'inactivity_days': fields.function(_compute_day, string='Days since last action',
+                                           multi='compute_day', type="integer", help="Difference in days between last action and current date"),
         'color': fields.integer('Color Index'),
         'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
         'date_action_last': fields.datetime('Last Action', readonly=1),
@@ -296,7 +281,7 @@ class project_issue(osv.Model):
         'active': 1,
         'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
         'company_id': lambda s, cr, uid, c: s.pool.get('res.company')._company_default_get(cr, uid, 'crm.helpdesk', context=c),
-        'priority': crm.AVAILABLE_PRIORITIES[2][0],
+        'priority': '0',
         'kanban_state': 'normal',
         'date_last_stage_update': fields.datetime.now,
         'user_id': lambda obj, cr, uid, context: uid,
@@ -306,33 +291,22 @@ class project_issue(osv.Model):
         'stage_id': _read_group_stage_ids
     }
 
-    def set_priority(self, cr, uid, ids, priority, *args):
-        return self.write(cr, uid, ids, {'priority' : priority})
-
-    def set_high_priority(self, cr, uid, ids, *args):
-        """Set lead priority to high
-        """
-        return self.set_priority(cr, uid, ids, '1')
-
-    def set_normal_priority(self, cr, uid, ids, *args):
-        """Set lead priority to normal
-        """
-        return self.set_priority(cr, uid, ids, '3')
-
     def copy(self, cr, uid, id, default=None, context=None):
-        issue = self.read(cr, uid, id, ['name'], context=context)
+        issue = self.read(cr, uid, [id], ['name'], context=context)[0]
         if not default:
             default = {}
         default = default.copy()
         default.update(name=_('%s (copy)') % (issue['name']))
-        return super(project_issue, self).copy(cr, uid, id, default=default,
-                context=context)
+        return super(project_issue, self).copy(cr, uid, id, default=default, context=context)
 
     def create(self, cr, uid, vals, context=None):
-        if context is None:
-            context = {}
+        context = dict(context or {})
         if vals.get('project_id') and not context.get('default_project_id'):
             context['default_project_id'] = vals.get('project_id')
+        if vals.get('user_id'):
+            vals['date_open'] = fields.datetime.now()
+        if 'stage_id' in vals:
+            vals.update(self.onchange_stage_id(cr, uid, None, vals.get('stage_id'), context=context)['value'])
 
         # context: no_log, because subtype already handle this
         create_context = dict(context, mail_create_nolog=True)
@@ -341,12 +315,13 @@ class project_issue(osv.Model):
     def write(self, cr, uid, ids, vals, context=None):
         # stage change: update date_last_stage_update
         if 'stage_id' in vals:
+            vals.update(self.onchange_stage_id(cr, uid, ids, vals.get('stage_id'), context=context)['value'])
             vals['date_last_stage_update'] = fields.datetime.now()
             if 'kanban_state' not in vals:
                 vals['kanban_state'] = 'normal'
         # user_id change: update date_start
         if vals.get('user_id'):
-            vals['date_start'] = fields.datetime.now()
+            vals['date_open'] = fields.datetime.now()
 
         return super(project_issue, self).write(cr, uid, ids, vals, context)
 
@@ -367,6 +342,7 @@ class project_issue(osv.Model):
         return {'value': result}
 
     def get_empty_list_help(self, cr, uid, help, context=None):
+        context = dict(context or {})
         context['empty_list_help_model'] = 'project.project'
         context['empty_list_help_id'] = context.get('default_project_id')
         context['empty_list_help_document_name'] = _("issues")
@@ -376,14 +352,13 @@ class project_issue(osv.Model):
     # Stage management
     # -------------------------------------------------------
 
-    def set_kanban_state_blocked(self, cr, uid, ids, context=None):
-        return self.write(cr, uid, ids, {'kanban_state': 'blocked'}, context=context)
-
-    def set_kanban_state_normal(self, cr, uid, ids, context=None):
-        return self.write(cr, uid, ids, {'kanban_state': 'normal'}, context=context)
-
-    def set_kanban_state_done(self, cr, uid, ids, context=None):
-        return self.write(cr, uid, ids, {'kanban_state': 'done'}, context=context)
+    def onchange_stage_id(self, cr, uid, ids, stage_id, context=None):
+        if not stage_id:
+            return {'value': {}}
+        stage = self.pool['project.task.type'].browse(cr, uid, stage_id, context=context)
+        if stage.fold:
+            return {'value': {'date_closed': fields.datetime.now()}}
+        return {'value': {'date_closed': False}}
 
     def stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
         """ Override of the base.stage method
@@ -436,8 +411,10 @@ class project_issue(osv.Model):
 
     def message_get_reply_to(self, cr, uid, ids, context=None):
         """ Override to get the reply_to of the parent project. """
-        return [issue.project_id.message_get_reply_to()[0] if issue.project_id else False
-                    for issue in self.browse(cr, uid, ids, context=context)]
+        issues = self.browse(cr, SUPERUSER_ID, ids, context=context)
+        project_ids = set([issue.project_id.id for issue in issues if issue.project_id])
+        aliases = self.pool['project.project'].message_get_reply_to(cr, uid, list(project_ids), context=context)
+        return dict((issue.id, aliases.get(issue.project_id and issue.project_id.id or 0, False)) for issue in issues)
 
     def message_get_suggested_recipients(self, cr, uid, ids, context=None):
         recipients = super(project_issue, self).message_get_suggested_recipients(cr, uid, ids, context=context)
@@ -458,9 +435,7 @@ class project_issue(osv.Model):
         """
         if custom_values is None:
             custom_values = {}
-        if context is None:
-            context = {}
-        context['state_to'] = 'draft'
+        context = dict(context or {}, state_to='draft')
         defaults = {
             'name':  msg.get('subject') or _("No Subject"),
             'email_from': msg.get('from'),
@@ -472,6 +447,7 @@ class project_issue(osv.Model):
         res_id = super(project_issue, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
         return res_id
 
+    @api.cr_uid_ids_context
     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):
         """ Overrides mail_thread message_post so that we can set the date of last action field when
             a new message is posted on the issue.
@@ -491,21 +467,16 @@ class project(osv.Model):
         return [('project.task', "Tasks"), ("project.issue", "Issues")]
 
     def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
-        """ :deprecated: this method will be removed with OpenERP v8. Use issue_ids
-                         fields instead. """
-        res = dict.fromkeys(ids, 0)
-        issue_ids = self.pool.get('project.issue').search(cr, uid, [('project_id', 'in', ids)])
-        for issue in self.pool.get('project.issue').browse(cr, uid, issue_ids, context):
-            if issue.stage_id and not issue.stage_id.fold:
-                res[issue.project_id.id] += 1
-        return res
-
+        Issue = self.pool['project.issue']
+        return {
+            project_id: Issue.search_count(cr,uid, [('project_id', '=', project_id), ('stage_id.fold', '=', False)], context=context)
+            for project_id in ids
+        }
     _columns = {
         'project_escalation_id': fields.many2one('project.project', 'Project Escalation',
             help='If any issue is escalated from the current Project, it will be listed under the project selected here.',
             states={'close': [('readonly', True)], 'cancelled': [('readonly', True)]}),
-        'issue_count': fields.function(_issue_count, type='integer', string="Unclosed Issues",
-                                       deprecated="This field will be removed in OpenERP v8. Use issue_ids one2many field instead."),
+        'issue_count': fields.function(_issue_count, type='integer', string="Issues",),
         'issue_ids': fields.one2many('project.issue', 'project_id',
                                      domain=[('stage_id.fold', '=', False)])
     }
@@ -530,8 +501,8 @@ class account_analytic_account(osv.Model):
         'use_issues': fields.boolean('Issues', help="Check this field if this project manages issues"),
     }
 
-    def on_change_template(self, cr, uid, ids, template_id, context=None):
-        res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, context=context)
+    def on_change_template(self, cr, uid, ids, template_id, date_start=False, context=None):
+        res = super(account_analytic_account, self).on_change_template(cr, uid, ids, template_id, date_start=date_start, context=context)
         if template_id and 'value' in res:
             template = self.browse(cr, uid, template_id, context=context)
             res['value']['use_issues'] = template.use_issues
@@ -575,5 +546,17 @@ class project_project(osv.Model):
         self._check_create_write_values(cr, uid, vals, context=context)
         return super(project_project, self).write(cr, uid, ids, vals, context=context)
 
-
+class res_partner(osv.osv):
+    def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
+        Issue = self.pool['project.issue']
+        return {
+            partner_id: Issue.search_count(cr,uid, [('partner_id', '=', partner_id)])
+            for partner_id in ids
+        }
+    
+    """ Inherits partner and adds Issue information in the partner form """
+    _inherit = 'res.partner'
+    _columns = {
+        'issue_count': fields.function(_issue_count, string='# Issues', type='integer'),
+    }
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: