[IMP] safe_eval: do not log exceptions, when re-raising a new exception, make the...
[odoo/odoo.git] / addons / project_issue / project_issue.py
index f0d78f5..8eb7281 100644 (file)
 #
 ##############################################################################
 
-from crm import crm
+from openerp.addons.base_status.base_stage import base_stage
+from openerp.addons.crm import crm
 from datetime import datetime
-from osv import fields,osv
-from tools.translate import _
+from openerp.osv import fields,osv
+from openerp.tools.translate import _
 import binascii
 import time
-import tools
-from crm import wizard
-
-wizard.mail_compose_message.SUPPORTED_MODELS.append('project.issue')
+from openerp import tools
+from openerp.tools import html2plaintext
 
 class project_issue_version(osv.osv):
     _name = "project.issue.version"
@@ -42,49 +41,90 @@ class project_issue_version(osv.osv):
     }
 project_issue_version()
 
-class project_issue(crm.crm_case, osv.osv):
+_ISSUE_STATE = [('draft', 'New'), ('open', 'In Progress'), ('cancel', 'Cancelled'), ('done', 'Done'), ('pending', 'Pending')]
+
+
+class project_issue(base_stage, osv.osv):
     _name = "project.issue"
     _description = "Project Issue"
     _order = "priority, create_date desc"
-    _inherit = ['mail.thread']
-
-    def write(self, cr, uid, ids, vals, context=None):
-        #Update last action date everytime the user change the stage, the state or send a new email
-        logged_fields = ['type_id', 'state', 'message_ids']
-        if any([field in vals for field in logged_fields]):
-            vals['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
-        return super(project_issue, self).write(cr, uid, ids, vals, context)
-
-    def case_open(self, cr, uid, ids, *args):
-        """
-        @param self: The object pointer
-        @param cr: the current row, from the database cursor,
-        @param uid: the current user’s ID for security checks,
-        @param ids: List of case's Ids
-        @param *args: Give Tuple Value
-        """
-
-        res = super(project_issue, self).case_open(cr, uid, ids, *args)
-        self.write(cr, uid, ids, {'date_open': time.strftime('%Y-%m-%d %H:%M:%S'), 'user_id' : uid})
-        for (id, name) in self.name_get(cr, uid, ids):
-            message = _("Issue '%s' has been opened.") % name
-            self.log(cr, uid, id, message)
-        return res
+    _inherit = ['mail.thread', 'ir.needaction_mixin']
+
+    _track = {
+        'state': {
+            'project_issue.mt_issue_new': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'new',
+            'project_issue.mt_issue_closed': lambda self, cr, uid, obj, ctx=None:  obj['state'] == 'done',
+            'project_issue.mt_issue_started': lambda self, cr, uid, obj, ctx=None: obj['state'] == 'open',
+        },
+        'stage_id': {
+            'project_issue.mt_issue_stage': lambda self, cr, uid, obj, ctx=None: obj['state'] not in ['new', 'done', 'open'],
+        },
+        'kanban_state': {
+            'project_issue.mt_issue_blocked': lambda self, cr, uid, obj, ctx=None: obj['kanban_state'] == 'blocked',
+        },
+    }
 
-    def case_close(self, cr, uid, ids, *args):
-        """
-        @param self: The object pointer
-        @param cr: the current row, from the database cursor,
-        @param uid: the current user’s ID for security checks,
-        @param ids: List of case's Ids
-        @param *args: Give Tuple Value
+    def create(self, cr, uid, vals, context=None):
+        if context is None:
+            context = {}
+        if not vals.get('stage_id'):
+            ctx = context.copy()
+            if vals.get('project_id'):
+                ctx['default_project_id'] = vals['project_id']
+            vals['stage_id'] = self._get_default_stage_id(cr, uid, context=ctx)
+        return super(project_issue, self).create(cr, uid, vals, context=context)
+
+    def _get_default_project_id(self, cr, uid, context=None):
+        """ Gives default project by checking if present in the context """
+        return self._resolve_project_id_from_context(cr, uid, context=context)
+
+    def _get_default_stage_id(self, cr, uid, context=None):
+        """ Gives default stage_id """
+        project_id = self._get_default_project_id(cr, uid, context=context)
+        return self.stage_find(cr, uid, [], project_id, [('state', '=', 'draft')], context=context)
+
+    def _resolve_project_id_from_context(self, cr, uid, context=None):
+        """ Returns ID of project based on the value of 'default_project_id'
+            context key, or None if it cannot be resolved to a single
+            project.
         """
-
-        res = super(project_issue, self).case_close(cr, uid, ids, *args)
-        for (id, name) in self.name_get(cr, uid, ids):
-            message = _("Issue '%s' has been closed.") % name
-            self.log(cr, uid, id, message)
-        return res
+        if context is None:
+            context = {}
+        if type(context.get('default_project_id')) in (int, long):
+            return context.get('default_project_id')
+        if isinstance(context.get('default_project_id'), basestring):
+            project_name = context['default_project_id']
+            project_ids = self.pool.get('project.project').name_search(cr, uid, name=project_name, context=context)
+            if len(project_ids) == 1:
+                return int(project_ids[0][0])
+        return None
+
+    def _read_group_stage_ids(self, cr, uid, ids, domain, read_group_order=None, access_rights_uid=None, context=None):
+        access_rights_uid = access_rights_uid or uid
+        stage_obj = self.pool.get('project.task.type')
+        order = stage_obj._order
+        # lame hack to allow reverting search, should just work in the trivial case
+        if read_group_order == 'stage_id desc':
+            order = "%s desc" % order
+        # retrieve section_id from the context and write the domain
+        # - ('id', 'in', 'ids'): add columns that should be present
+        # - OR ('case_default', '=', True), ('fold', '=', False): add default columns that are not folded
+        # - OR ('project_ids', 'in', project_id), ('fold', '=', False) if project_id: add project columns that are not folded
+        search_domain = []
+        project_id = self._resolve_project_id_from_context(cr, uid, context=context)
+        if project_id:
+            search_domain += ['|', ('project_ids', '=', project_id)]
+        search_domain += [('id', 'in', ids)]
+        # perform search
+        stage_ids = stage_obj._search(cr, uid, search_domain, order=order, access_rights_uid=access_rights_uid, context=context)
+        result = stage_obj.name_get(cr, access_rights_uid, stage_ids, context=context)
+        # restore order of the search
+        result.sort(lambda x,y: cmp(stage_ids.index(x[0]), stage_ids.index(y[0])))
+
+        fold = {}
+        for stage in stage_obj.browse(cr, access_rights_uid, stage_ids, context=context):
+            fold[stage.id] = stage.fold or False
+        return result, fold
 
     def _compute_day(self, cr, uid, ids, fields, args, context=None):
         """
@@ -112,7 +152,8 @@ class project_issue(crm.crm_case, osv.osv):
                         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, issue.project_id.resource_calendar_id.id,
+                        if issue.project_id.resource_calendar_id:
+                            hours = cal_obj.interval_hours_get(cr, uid, issue.project_id.resource_calendar_id.id,
                                                            date_create,
                                                            date_open)
                 elif field in ['working_hours_close','day_close']:
@@ -121,7 +162,8 @@ class project_issue(crm.crm_case, osv.osv):
                         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, issue.project_id.resource_calendar_id.id,
+                        if issue.project_id.resource_calendar_id:
+                            hours = cal_obj.interval_hours_get(cr, uid, issue.project_id.resource_calendar_id.id,
                                date_create,
                                date_close)
                 elif field in ['days_since_creation']:
@@ -166,6 +208,19 @@ class project_issue(crm.crm_case, osv.osv):
 
         return res
 
+    def _hours_get(self, cr, uid, ids, field_names, args, context=None):
+        task_pool = self.pool.get('project.task')
+        res = {}
+        for issue in self.browse(cr, uid, ids, context=context):
+            progress = 0.0
+            if issue.task_id:
+                progress = task_pool._hours_get(cr, uid, [issue.task_id.id], field_names, args, context=context)[issue.task_id.id]['progress']
+            res[issue.id] = {'progress' : progress}
+        return res
+
+    def on_change_project(self, cr, uid, ids, project_id, context=None):
+        return {}
+
     def _get_issue_task(self, cr, uid, ids, context=None):
         issues = []
         issue_pool = self.pool.get('project.issue')
@@ -181,16 +236,6 @@ class project_issue(crm.crm_case, osv.osv):
                 issues += issue_pool.search(cr, uid, [('task_id','=',work.task_id.id)])
         return issues
 
-    def _hours_get(self, cr, uid, ids, field_names, args, context=None):
-        task_pool = self.pool.get('project.task')
-        res = {}
-        for issue in self.browse(cr, uid, ids, context=context):
-            progress = 0.0
-            if issue.task_id:
-                progress = task_pool._hours_get(cr, uid, [issue.task_id.id], field_names, args, context=context)[issue.task_id.id]['progress']
-            res[issue.id] = {'progress' : progress}
-        return res
-
     _columns = {
         'id': fields.integer('ID', readonly=True),
         'name': fields.char('Issue', size=128, required=True),
@@ -203,16 +248,23 @@ class project_issue(crm.crm_case, osv.osv):
         'section_id': fields.many2one('crm.case.section', 'Sales Team', \
                         select=True, help='Sales team to which Case belongs to.\
                              Define Responsible user and Email account for mail gateway.'),
-        'partner_id': fields.many2one('res.partner', 'Partner', select=1),
-        'partner_address_id': fields.many2one('res.partner.address', 'Partner Contact', \
-                                 domain="[('partner_id','=',partner_id)]"),
+        'partner_id': fields.many2one('res.partner', 'Contact', select=1),
         'company_id': fields.many2one('res.company', 'Company'),
-        'description': fields.text('Description'),
-        'state': fields.selection([('draft', 'New'), ('open', 'In Progress'), ('cancel', 'Cancelled'), ('done', 'Done'),('pending', 'Pending'), ], 'State', size=16, readonly=True,
-                                  help='The state is set to \'Draft\', when a case is created.\
-                                  \nIf the case is in progress the state is set to \'Open\'.\
-                                  \nWhen the case is over, the state is set to \'Done\'.\
-                                  \nIf the case needs to be reviewed then the state is set to \'Pending\'.'),
+        'description': fields.text('Private Note'),
+        'state': fields.related('stage_id', 'state', type="selection", store=True,
+                selection=_ISSUE_STATE, string="Status", readonly=True,
+                help='The status is set to \'Draft\', when a case is created.\
+                      If the case is in progress the status is set to \'Open\'.\
+                      When the case is over, the status is set to \'Done\'.\
+                      If the case needs to be reviewed then the status is \
+                      set to \'Pending\'.'),
+        'kanban_state': fields.selection([('normal', 'Normal'),('blocked', 'Blocked'),('done', 'Ready for next stage')], 'Kanban State',
+                                         track_visibility='onchange',
+                                         help="A Issue's kanban state indicates special situations affecting it:\n"
+                                              " * 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),
         '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),
@@ -220,18 +272,20 @@ class project_issue(crm.crm_case, osv.osv):
         'date_closed': fields.datetime('Closed', readonly=True,select=True),
         'date': fields.datetime('Date'),
         'channel_id': fields.many2one('crm.case.channel', 'Channel', help="Communication channel."),
-        'categ_id': fields.many2one('crm.case.categ', 'Category', domain="[('object_id.model', '=', 'crm.project.bug')]"),
+        'categ_ids': fields.many2many('project.category', string='Tags'),
         'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority', select=True),
         'version_id': fields.many2one('project.issue.version', 'Version'),
-        'type_id': fields.many2one ('project.task.type', 'Stages', domain="[('project_ids', '=', project_id)]"),
-        'project_id':fields.many2one('project.project', 'Project'),
+        'stage_id': fields.many2one ('project.task.type', 'Stage',
+                        track_visibility='onchange',
+                        domain="['&', ('fold', '=', False), ('project_ids', '=', project_id)]"),
+        'project_id':fields.many2one('project.project', 'Project', track_visibility='onchange'),
         '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),
-        'user_id': fields.many2one('res.users', 'Assigned to', required=False, select=1),
+        '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', \
@@ -239,8 +293,7 @@ class project_issue(crm.crm_case, osv.osv):
         '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', 'user_email', type='char', string='User Email', readonly=True),
-        'message_ids': fields.one2many('mail.message', 'res_id', 'Messages', domain=[('model','=',_name)]),
+        'user_email': fields.related('user_id', 'email', type='char', string='User Email', readonly=True),
         'date_action_last': fields.datetime('Last Action', readonly=1),
         'date_action_next': fields.datetime('Next Action', readonly=1),
         'progress': fields.function(_hours_get, string='Progress (%)', multi='hours', group_operator="avg", help="Computed as: Time Spent / Total Time.",
@@ -251,30 +304,22 @@ class project_issue(crm.crm_case, osv.osv):
             }),
     }
 
-    def _get_project(self, cr, uid, context=None):
-        user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
-        if user.context_project_id:
-            return user.context_project_id.id
-        return False
-
-    def on_change_project(self, cr, uid, ids, project_id, context=None):
-        return {}
-
-
     _defaults = {
         'active': 1,
-        'partner_id': crm.crm_case._get_default_partner,
-        'partner_address_id': crm.crm_case._get_default_partner_address,
-        'email_from': crm.crm_case._get_default_email,
-        'state': 'draft',
-        'section_id': crm.crm_case._get_section,
+        'partner_id': lambda s, cr, uid, c: s._get_default_partner(cr, uid, c),
+        'email_from': lambda s, cr, uid, c: s._get_default_email(cr, uid, c),
+        'stage_id': lambda s, cr, uid, c: s._get_default_stage_id(cr, uid, c),
+        'section_id': lambda s, cr, uid, c: s._get_default_section_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],
-        'project_id':_get_project,
-        'categ_id' : lambda *a: False,
-         }
+        'kanban_state': 'normal',
+    }
 
-    def set_priority(self, cr, uid, ids, priority):
+    _group_by_full = {
+        'stage_id': _read_group_stage_ids
+    }
+
+    def set_priority(self, cr, uid, ids, priority, *args):
         """Set lead priority
         """
         return self.write(cr, uid, ids, {'priority' : priority})
@@ -290,14 +335,13 @@ class project_issue(crm.crm_case, osv.osv):
         return self.set_priority(cr, uid, ids, '3')
 
     def convert_issue_task(self, cr, uid, ids, context=None):
+        if context is None:
+            context = {}
+
         case_obj = self.pool.get('project.issue')
         data_obj = self.pool.get('ir.model.data')
         task_obj = self.pool.get('project.task')
 
-
-        if context is None:
-            context = {}
-
         result = data_obj._get_id(cr, uid, 'project', 'view_task_search_form')
         res = data_obj.read(cr, uid, result, ['res_id'])
         id2 = data_obj._get_id(cr, uid, 'project', 'view_task_form2')
@@ -319,12 +363,13 @@ class project_issue(crm.crm_case, osv.osv):
                 'user_id': bug.user_id.id,
                 'planned_hours': 0.0,
             })
-
             vals = {
                 'task_id': new_task_id,
-                'state':'pending'
+                'stage_id': self.stage_find(cr, uid, [bug], bug.project_id.id, [('state', '=', 'pending')], context=context),
             }
-            case_obj.write(cr, uid, [bug.id], vals)
+            message = _("Project issue <b>converted</b> to task.")
+            self.message_post(cr, uid, [bug.id], body=message, context=context)
+            case_obj.write(cr, uid, [bug.id], vals, context=context)
 
         return  {
             'name': _('Tasks'),
@@ -339,63 +384,87 @@ class project_issue(crm.crm_case, osv.osv):
             'nodestroy': True
         }
 
+    def copy(self, cr, uid, id, default=None, context=None):
+        issue = self.read(cr, uid, id, ['name'], context=context)
+        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)
 
-    def _convert(self, cr, uid, ids, xml_id, context=None):
-        data_obj = self.pool.get('ir.model.data')
-        id2 = data_obj._get_id(cr, uid, 'project_issue', xml_id)
-        categ_id = False
-        if id2:
-            categ_id = data_obj.browse(cr, uid, id2, context=context).res_id
-        if categ_id:
-            self.write(cr, uid, ids, {'categ_id': categ_id})
-        return True
-
-    def convert_to_feature(self, cr, uid, ids, context=None):
-        return self._convert(cr, uid, ids, 'feature_request_categ', context=context)
-
-    def convert_to_bug(self, cr, uid, ids, context=None):
-        return self._convert(cr, uid, ids, 'bug_categ', context=context)
-
-    def next_type(self, cr, uid, ids, *args):
-        for task in self.browse(cr, uid, ids):
-            typeid = task.type_id.id
-            types = map(lambda x:x.id, task.project_id.type_ids or [])
-            if types:
-                if not typeid:
-                    self.write(cr, uid, task.id, {'type_id': types[0]})
-                elif typeid and typeid in types and types.index(typeid) != len(types)-1 :
-                    index = types.index(typeid)
-                    self.write(cr, uid, task.id, {'type_id': types[index+1]})
-        return True
+    def write(self, cr, uid, ids, vals, context=None):
+        #Update last action date every time the user change the stage, the state or send a new email
+        logged_fields = ['stage_id', 'state', 'message_ids']
+        if any([field in vals for field in logged_fields]):
+            vals['date_action_last'] = time.strftime('%Y-%m-%d %H:%M:%S')
 
-    def prev_type(self, cr, uid, ids, *args):
-        for task in self.browse(cr, uid, ids):
-            typeid = task.type_id.id
-            types = map(lambda x:x.id, task.project_id and task.project_id.type_ids or [])
-            if types:
-                if typeid and typeid in types:
-                    index = types.index(typeid)
-                    self.write(cr, uid, task.id, {'type_id': index and types[index-1] or False})
-        return True
+        return super(project_issue, self).write(cr, uid, ids, vals, context)
 
     def onchange_task_id(self, cr, uid, ids, task_id, context=None):
-        result = {}
         if not task_id:
-            return {'value':{}}
+            return {'value': {}}
         task = self.pool.get('project.task').browse(cr, uid, task_id, context=context)
-        return {'value':{'user_id': task.user_id.id,}}
+        return {'value': {'user_id': task.user_id.id, }}
 
-    def case_escalate(self, cr, uid, ids, *args):
-        """Escalates case to top level
-        @param self: The object pointer
-        @param cr: the current row, from the database cursor,
-        @param uid: the current user’s ID for security checks,
-        @param ids: List of case Ids
-        @param *args: Tuple Value for additional Params
+    def case_reset(self, cr, uid, ids, context=None):
+        """Resets case as draft
+        """
+        res = super(project_issue, self).case_reset(cr, uid, ids, context)
+        self.write(cr, uid, ids, {'date_open': False, 'date_closed': False})
+        return res
+
+    # -------------------------------------------------------
+    # 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 stage_find(self, cr, uid, cases, section_id, domain=[], order='sequence', context=None):
+        """ Override of the base.stage method
+            Parameter of the stage search taken from the issue:
+            - type: stage type must be the same or 'both'
+            - section_id: if set, stages must belong to this section or
+              be a default case
         """
+        if isinstance(cases, (int, long)):
+            cases = self.browse(cr, uid, cases, context=context)
+        # collect all section_ids
+        section_ids = []
+        if section_id:
+            section_ids.append(section_id)
+        for task in cases:
+            if task.project_id:
+                section_ids.append(task.project_id.id)
+        # OR all section_ids and OR with case_default
+        search_domain = []
+        if section_ids:
+            search_domain += [('|')] * (len(section_ids)-1)
+            for section_id in section_ids:
+                search_domain.append(('project_ids', '=', section_id))
+        search_domain += list(domain)
+        # perform search, return the first found
+        stage_ids = self.pool.get('project.task.type').search(cr, uid, search_domain, order=order, context=context)
+        if stage_ids:
+            return stage_ids[0]
+        return False
+
+    def case_cancel(self, cr, uid, ids, context=None):
+        """ Cancels case """
+        self.case_set(cr, uid, ids, 'cancelled', {'active': True}, context=context)
+        return True
+
+    def case_escalate(self, cr, uid, ids, context=None):
         cases = self.browse(cr, uid, ids)
         for case in cases:
-            data = {'state' : 'draft'}
+            data = {}
             if case.project_id.project_escalation_id:
                 data['project_id'] = case.project_id.project_escalation_id.id
                 if case.project_id.project_escalation_id.user_id:
@@ -403,106 +472,130 @@ class project_issue(crm.crm_case, osv.osv):
                 if case.task_id:
                     self.pool.get('project.task').write(cr, uid, [case.task_id.id], {'project_id': data['project_id'], 'user_id': False})
             else:
-                raise osv.except_osv(_('Warning !'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!'))
-            self.write(cr, uid, [case.id], data)
-        self.message_append(cr, uid, cases, _('Escalate'))
+                raise osv.except_osv(_('Warning!'), _('You cannot escalate this issue.\nThe relevant Project has not configured the Escalation Project!'))
+            self.case_set(cr, uid, ids, 'draft', data, context=context)
         return True
 
+    # -------------------------------------------------------
+    # Mail gateway
+    # -------------------------------------------------------
+
+    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)]
+
     def message_new(self, cr, uid, msg, custom_values=None, context=None):
-        """Automatically called when new email message arrives"""
-        if context is None:
-            context = {}
-        subject = msg.get('subject') or _('No Title')
-        body = msg.get('body_text')
-        msg_from = msg.get('from')
-        priority = msg.get('priority')
-        vals = {
-            'name': subject,
-            'email_from': msg_from,
+        """ Overrides mail_thread message_new that is called by the mailgateway
+            through message_process.
+            This override updates the document according to the email.
+        """
+        if custom_values is None: custom_values = {}
+        if context is None: context = {}
+        context['state_to'] = 'draft'
+
+        desc = html2plaintext(msg.get('body')) if msg.get('body') else ''
+
+        defaults = {
+            'name':  msg.get('subject') or _("No Subject"),
+            'description': desc,
+            'email_from': msg.get('from'),
             'email_cc': msg.get('cc'),
-            'description': body,
+            'partner_id': msg.get('author_id', False),
             'user_id': False,
         }
-        if priority:
-            vals['priority'] = priority
-        vals.update(self.message_partner_by_email(cr, uid, msg_from))
-        context.update({'state_to' : 'draft'})
-
-        if custom_values and isinstance(custom_values, dict):
-            vals.update(custom_values)
-
-        res_id = self.create(cr, uid, vals, context)
-        self.message_append_dict(cr, uid, [res_id], msg, context=context)
-        if 'categ_id' not in vals:
-            self.convert_to_bug(cr, uid, [res_id], context=context)
-        return res_id
-
-    def message_update(self, cr, uid, ids, msg, vals=None, default_act='pending', context=None):
+        if  msg.get('priority'):
+            defaults['priority'] = msg.get('priority')
 
-        if vals is None:
-            vals = {}
+        defaults.update(custom_values)
+        res_id = super(project_issue, self).message_new(cr, uid, msg, custom_values=defaults, context=context)
+        return res_id
 
+    def message_update(self, cr, uid, ids, msg, update_vals=None, context=None):
+        """ Overrides mail_thread message_update that is called by the mailgateway
+            through message_process.
+            This method updates the document according to the email.
+        """
         if isinstance(ids, (str, int, long)):
             ids = [ids]
+        if update_vals is None: update_vals = {}
 
-        vals.update({
-            'description': msg['body_text']
-        })
-        if msg.get('priority', False):
-            vals['priority'] = msg.get('priority')
-
+        # Update doc values according to the message
+        if msg.get('priority'):
+            update_vals['priority'] = msg.get('priority')
+        # Parse 'body' to find values to update
         maps = {
             'cost': 'planned_cost',
             'revenue': 'planned_revenue',
-            'probability': 'probability'
+            'probability': 'probability',
         }
-
-        # Reassign the 'open' state to the case if this one is in pending or done
-        for record in self.browse(cr, uid, ids, context=context):
-            if record.state in ('pending', 'done'):
-                record.write({'state' : 'open'})
-
-        vls = { }
-        for line in msg['body_text'].split('\n'):
+        for line in msg.get('body', '').split('\n'):
             line = line.strip()
-            res = tools.misc.command_re.match(line)
+            res = tools.command_re.match(line)
             if res and maps.get(res.group(1).lower(), False):
                 key = maps.get(res.group(1).lower())
-                vls[key] = res.group(2).lower()
+                update_vals[key] = res.group(2).lower()
 
-        vals.update(vls)
-        res = self.write(cr, uid, ids, vals)
-        self.message_append_dict(cr, uid, ids, msg, context=context)
-        return res
+        return super(project_issue, self).message_update(cr, uid, ids, msg, update_vals=update_vals, context=context)
 
-    def copy(self, cr, uid, id, default=None, context=None):
-        issue = self.read(cr, uid, id, ['name'], context=context)
-        if not default:
-            default = {}
-        default = default.copy()
-        default['name'] = issue['name'] + _(' (copy)')
-        return super(project_issue, self).copy(cr, uid, id, default=default,
-                context=context)
-
-project_issue()
 
 class project(osv.osv):
     _inherit = "project.project"
+
+    def _get_alias_models(self, cr, uid, context=None):
+        return [('project.task', "Tasks"), ("project.issue", "Issues")]
+
+    def _issue_count(self, cr, uid, ids, field_name, arg, context=None):
+        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):
+            res[issue.project_id.id] += 1
+        return res
+
     _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)]}),
-        'reply_to' : fields.char('Reply-To Email Address', size=256)
+        'issue_count': fields.function(_issue_count, type='integer'),
     }
 
     def _check_escalation(self, cr, uid, ids, context=None):
-         project_obj = self.browse(cr, uid, ids[0], context=context)
-         if project_obj.project_escalation_id:
-             if project_obj.project_escalation_id.id == project_obj.id:
-                 return False
-         return True
+        project_obj = self.browse(cr, uid, ids[0], context=context)
+        if project_obj.project_escalation_id:
+            if project_obj.project_escalation_id.id == project_obj.id:
+                return False
+        return True
 
     _constraints = [
         (_check_escalation, 'Error! You cannot assign escalation to the same project!', ['project_escalation_id'])
     ]
+
 project()
 
+class account_analytic_account(osv.osv):
+    _inherit = 'account.analytic.account'
+    _description = 'Analytic Account'
+
+    _columns = {
+        '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)
+        if template_id and 'value' in res:
+            template = self.browse(cr, uid, template_id, context=context)
+            res['value']['use_issues'] = template.use_issues
+        return res
+
+    def _trigger_project_creation(self, cr, uid, vals, context=None):
+        if context is None: context = {}
+        res = super(account_analytic_account, self)._trigger_project_creation(cr, uid, vals, context=context)
+        return res or (vals.get('use_issues') and not 'project_creation_in_progress' in context)
+
+account_analytic_account()
+
+class project_project(osv.osv):
+    _inherit = 'project.project'
+    _defaults = {
+        'use_issues': True
+    }
+
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: