[FIX] CRM: phone call ==> Set To TOdo from cancel state
[odoo/odoo.git] / addons / crm / crm_phonecall.py
index 49d1cef..4246fa4 100644 (file)
 #
 ##############################################################################
 
-from crm import crm_case
+from crm import crm_base
 from osv import fields, osv
 from tools.translate import _
 import crm
 import time
+from datetime import datetime
 
-class crm_phonecall(osv.osv, crm_case):
+class crm_phonecall(crm_base, osv.osv):
     """ Phonecall Cases """
 
     _name = "crm.phonecall"
     _description = "Phonecall"
     _order = "id desc"
-    _inherit = 'mailgate.thread'
-
     _columns = {
         # From crm.case
+        'id': fields.integer('ID', readonly=True),
+        'name': fields.char('Call Summary', size=64, required=True),
+        'active': fields.boolean('Active', required=False),
+        'date_action_last': fields.datetime('Last Action', readonly=1),
+        'date_action_next': fields.datetime('Next Action', readonly=1),
+        'create_date': fields.datetime('Creation Date' , readonly=True),
         '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.'), 
-        'user_id': fields.many2one('res.users', 'Responsible'), 
-        'partner_id': fields.many2one('res.partner', 'Partner'), 
+                        select=True, help='Sales team to which Case belongs to.'),
+        'user_id': fields.many2one('res.users', 'Responsible'),
+        'partner_id': fields.many2one('res.partner', 'Partner'),
         'partner_address_id': fields.many2one('res.partner.address', 'Partner Contact', \
-                                 domain="[('partner_id','=',partner_id)]"), 
-        'company_id': fields.many2one('res.company', 'Company'), 
-        'description': fields.text('Description'), 
+                                 domain="[('partner_id','=',partner_id)]"),
+        'company_id': fields.many2one('res.company', 'Company'),
+        'description': fields.text('Description'),
         'state': fields.selection([
                                     ('draft', 'Draft'), 
                                     ('open', 'Todo'), 
                                     ('cancel', 'Cancelled'), 
-                                    ('done', 'Closed'), 
-                                    ('pending', 'Pending'),
+                                    ('done', 'Held'), 
+                                    ('pending', 'Not Held'),
                                 ], 'State', size=16, readonly=True, 
-                                  help='The state is set to \'Draft\', when a case is created.\
+                                  help='The state is set to \'Todo\', 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\'.'), 
-        'email_from': fields.char('Email', size=128, help="These people will receive email."), 
-        'stage_id': fields.many2one('crm.case.stage', 'Stage', \
-                            domain="[('section_id','=',section_id),\
-                            ('object_id.model', '=', 'crm.phonecall')]"), 
+                                  \nWhen the call is over, the state is set to \'Held\'.\
+                                  \nIf the call needs to be done then the state is set to \'Not Held\'.'),
+        'email_from': fields.char('Email', size=128, help="These people will receive email."),
         'date_open': fields.datetime('Opened', readonly=True),
         # phonecall fields
-        'duration': fields.float('Duration'), 
+        'duration': fields.float('Duration', help="Duration in Minutes"),
         'categ_id': fields.many2one('crm.case.categ', 'Category', \
-                        domain="[('section_id','=',section_id),\
-                        ('object_id.model', '=', 'crm.phonecall')]"), 
-        'partner_phone': fields.char('Phone', size=32), 
+                        domain="['|',('section_id','=',section_id),('section_id','=',False),\
+                        ('object_id.model', '=', 'crm.phonecall')]"),
+        'partner_phone': fields.char('Phone', size=32),
         'partner_contact': fields.related('partner_address_id', 'name', \
-                                 type="char", string="Contact", size=128), 
-        'partner_mobile': fields.char('Mobile', size=32), 
-        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'), 
-        'canal_id': fields.many2one('res.partner.canal', 'Channel', \
-                        help="The channels represent the different communication\
-                         modes available with the customer." \
-                        " With each commercial opportunity, you can indicate\
-                         the canall which is this opportunity source."), 
+                                 type="char", string="Contact", size=128),
+        'partner_mobile': fields.char('Mobile', size=32),
+        'priority': fields.selection(crm.AVAILABLE_PRIORITIES, 'Priority'),
         'date_closed': fields.datetime('Closed', readonly=True), 
         'date': fields.datetime('Date'), 
-        'opportunity_id': fields.many2one ('crm.lead', 'Opportunity'), 
+        'opportunity_id': fields.many2one ('crm.lead', 'Lead/Opportunity'), 
+        'message_ids': fields.one2many('mail.message', 'res_id', 'Messages', domain=[('model','=',_name)]),
     }
 
+    def _get_default_state(self, cr, uid, context=None):
+        if context and context.get('default_state', False):
+            return context.get('default_state')
+        return 'open'
+
     _defaults = {
-        'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'), 
-        'priority': lambda *a: crm.AVAILABLE_PRIORITIES[2][0], 
-        'state': lambda *a: 'draft', 
-        'active': lambda *a: 1, 
+        'date': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
+        'priority': crm.AVAILABLE_PRIORITIES[2][0], 
+        'state':  _get_default_state, 
+        'user_id': lambda self,cr,uid,ctx: uid,
+        'active': 1,
     }
-    
-    # From crm.case
 
+    # From crm.case
     def onchange_partner_address_id(self, cr, uid, ids, add, email=False):
         res = super(crm_phonecall, self).onchange_partner_address_id(cr, uid, ids, add, email)
         res.setdefault('value', {})
@@ -100,41 +102,173 @@ class crm_phonecall(osv.osv, crm_case):
 
     def case_close(self, cr, uid, ids, *args):
         """Overrides close for crm_case for setting close date
-        @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
         """
-        res = super(crm_phonecall, self).case_close(cr, uid, ids, args)
-        self.write(cr, uid, ids, {'date_closed': time.strftime('%Y-%m-%d %H:%M:%S')})
+        res = True
+        for phone in self.browse(cr, uid, ids):
+            phone_id = phone.id
+            data = {'date_closed': time.strftime('%Y-%m-%d %H:%M:%S')}
+            if phone.duration <=0:
+                duration = datetime.now() - datetime.strptime(phone.date, '%Y-%m-%d %H:%M:%S')
+                data.update({'duration': duration.seconds/float(60)})
+            res = super(crm_phonecall, self).case_close(cr, uid, [phone_id], args)
+            self.write(cr, uid, [phone_id], data)
+        return res
+
+    def case_reset(self, cr, uid, ids, *args):
+        """Resets case as Todo
+        """
+        res = super(crm_phonecall, self).case_reset(cr, uid, ids, args, 'crm.phonecall')
+        self.write(cr, uid, ids, {'duration': 0.0, 'state':'open'})
         return res
 
+
     def case_open(self, cr, uid, ids, *args):
         """Overrides cancel for crm_case for setting Open Date
-        @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(crm_phonecall, self).case_open(cr, uid, ids, *args)
         self.write(cr, uid, ids, {'date_open': time.strftime('%Y-%m-%d %H:%M:%S')})
         return res
 
+    def schedule_another_phonecall(self, cr, uid, ids, schedule_time, call_summary, \
+                    user_id=False, section_id=False, categ_id=False, action='schedule', context=None):
+        """
+        action :('schedule','Schedule a call'), ('log','Log a call')
+        """
+        model_data = self.pool.get('ir.model.data')
+        phonecall_dict = {}
+        if not categ_id:
+            res_id = model_data._get_id(cr, uid, 'crm', 'categ_phone2')
+            if res_id:
+                categ_id = model_data.browse(cr, uid, res_id, context=context).res_id
+        for call in self.browse(cr, uid, ids, context=context):
+            if not section_id:
+                section_id = call.section_id and call.section_id.id or False
+            if not user_id:
+                user_id = call.user_id and call.user_id.id or False
+            vals = {
+                    'name' : call_summary,
+                    'user_id' : user_id or False,
+                    'categ_id' : categ_id or False,
+                    'description' : call.description or False,
+                    'date' : schedule_time,
+                    'section_id' : section_id or False,
+                    'partner_id': call.partner_id and call.partner_id.id or False,
+                    'partner_address_id': call.partner_address_id and call.partner_address_id.id or False,
+                    'partner_phone' : call.partner_phone,
+                    'partner_mobile' : call.partner_mobile,
+                    'priority': call.priority,
+            }
+            
+            new_id = self.create(cr, uid, vals, context=context)
+            self.case_open(cr, uid, [new_id])
+            if action == 'log':
+                self.case_close(cr, uid, [new_id])
+            phonecall_dict[call.id] = new_id
+        return phonecall_dict
+
+    def _call_create_partner(self, cr, uid, phonecall, context=None):
+        partner = self.pool.get('res.partner')
+        partner_id = partner.create(cr, uid, {
+                    'name': phonecall.name,
+                    'user_id': phonecall.user_id.id,
+                    'comment': phonecall.description,
+                    'address': []
+        })
+        return partner_id
+
+    def _call_set_partner(self, cr, uid, ids, partner_id, context=None):
+        return self.write(cr, uid, ids, {'partner_id' : partner_id}, context=context)
+
+    def _call_create_partner_address(self, cr, uid, phonecall, partner_id, context=None):
+        address = self.pool.get('res.partner.address')
+        return address.create(cr, uid, {
+                    'partner_id': partner_id,
+                    'name': phonecall.name,
+                    'phone': phonecall.partner_phone,
+        })
+
+    def convert_partner(self, cr, uid, ids, action='create', partner_id=False, context=None):
+        """
+        This function convert partner based on action.
+        if action is 'create', create new partner with contact and assign lead to new partner_id.
+        otherwise assign lead to specified partner_id
+        """
+        if context is None:
+            context = {}
+        partner_ids = {}
+        for call in self.browse(cr, uid, ids, context=context):
+            if action == 'create':
+               if not partner_id:
+                   partner_id = self._call_create_partner(cr, uid, call, context=context)
+               self._call_create_partner_address(cr, uid, call, partner_id, context=context)
+            self._call_set_partner(cr, uid, [call.id], partner_id, context=context)
+            partner_ids[call.id] = partner_id
+        return partner_ids
+
+
+    def redirect_phonecall_view(self, cr, uid, phonecall_id, context=None):
+        model_data = self.pool.get('ir.model.data')
+        # Select the view
+        tree_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_tree_view')
+        form_view = model_data.get_object_reference(cr, uid, 'crm', 'crm_case_phone_form_view')
+        search_view = model_data.get_object_reference(cr, uid, 'crm', 'view_crm_case_phonecalls_filter')
+        value = {
+                'name': _('Phone Call'),
+                'view_type': 'form',
+                'view_mode': 'tree,form',
+                'res_model': 'crm.phonecall',
+                'res_id' : int(phonecall_id),
+                'views': [(form_view and form_view[1] or False, 'form'), (tree_view and tree_view[1] or False, 'tree'), (False, 'calendar')],
+                'type': 'ir.actions.act_window',
+                'search_view_id': search_view and search_view[1] or False,
+        }
+        return value
+
+
+    def convert_opportunity(self, cr, uid, ids, opportunity_summary=False, partner_id=False, planned_revenue=0.0, probability=0.0, context=None):
+        partner = self.pool.get('res.partner')
+        address = self.pool.get('res.partner.address')
+        opportunity = self.pool.get('crm.lead')
+        opportunity_dict = {}
+        default_contact = False
+        for call in self.browse(cr, uid, ids, context=context):
+            if not partner_id:
+                partner_id = call.partner_id and call.partner_id.id or False
+            if partner_id:
+                address_id = partner.address_get(cr, uid, [partner_id])['default']
+                if address_id:
+                    default_contact = address.browse(cr, uid, address_id, context=context)
+            opportunity_id = opportunity.create(cr, uid, {
+                            'name': opportunity_summary or call.name,
+                            'planned_revenue': planned_revenue,
+                            'probability': probability,
+                            'partner_id': partner_id or False,
+                            'partner_address_id': default_contact and default_contact.id, 
+                            'phone': default_contact and default_contact.phone,
+                            'mobile': default_contact and default_contact.mobile,
+                            'section_id': call.section_id and call.section_id.id or False,
+                            'description': call.description or False,
+                            'priority': call.priority,
+                            'type': 'opportunity', 
+                            'phone': call.partner_phone or False,
+                        })
+            vals = {
+                    'partner_id': partner_id,
+                    'opportunity_id' : opportunity_id,
+            }
+            self.write(cr, uid, [call.id], vals)
+            self.case_close(cr, uid, [call.id])
+            opportunity.case_open(cr, uid, [opportunity_id])
+            opportunity_dict[call.id] = opportunity_id
+        return opportunity_dict   
+
     def action_make_meeting(self, cr, uid, ids, context=None):
         """
         This opens Meeting's calendar view to schedule meeting on current Phonecall
-        @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 Phonecall to Meeting IDs
-        @param context: A standard dictionary for contextual values
-
         @return : Dictionary value for created Meeting view
         """
         value = {}
-        for phonecall in self.browse(cr, uid, ids):
+        for phonecall in self.browse(cr, uid, ids, context=context):
             data_obj = self.pool.get('ir.model.data')
 
             # Get meeting views
@@ -151,23 +285,23 @@ class crm_phonecall(osv.osv, crm_case):
                 id3 = data_obj.browse(cr, uid, id3, context=context).res_id
 
             context = {
-                        'default_phonecall_id': phonecall.id, 
-                        'default_partner_id': phonecall.partner_id and phonecall.partner_id.id or False, 
-                        'default_email': phonecall.email_from , 
+                        'default_phonecall_id': phonecall.id,
+                        'default_partner_id': phonecall.partner_id and phonecall.partner_id.id or False,
+                        'default_email': phonecall.email_from ,
                         'default_name': phonecall.name
                     }
 
             value = {
-                'name': _('Meetings'), 
-                'domain' : "[('user_id','=',%s)]" % (uid), 
-                'context': context, 
-                'view_type': 'form', 
-                'view_mode': 'calendar,form,tree', 
-                'res_model': 'crm.meeting', 
-                'view_id': False, 
-                'views': [(id1, 'calendar'), (id2, 'form'), (id3, 'tree')], 
-                'type': 'ir.actions.act_window', 
-                'search_view_id': res['res_id'], 
+                'name': _('Meetings'),
+                'domain' : "[('user_id','=',%s)]" % (uid),
+                'context': context,
+                'view_type': 'form',
+                'view_mode': 'calendar,form,tree',
+                'res_model': 'crm.meeting',
+                'view_id': False,
+                'views': [(id1, 'calendar'), (id2, 'form'), (id3, 'tree')],
+                'type': 'ir.actions.act_window',
+                'search_view_id': res['res_id'],
                 'nodestroy': True
                 }
 
@@ -175,15 +309,5 @@ class crm_phonecall(osv.osv, crm_case):
 
 crm_phonecall()
 
-class res_partner(osv.osv):
-    """ Inherits partner and adds Phonecalls information in the partner form """
-    _inherit = 'res.partner'
-    
-    _columns = {
-                'phonecall_ids': fields.one2many('crm.phonecall', 'partner_id', 'Phonecalls'), 
-                }
-
-res_partner()
-
 
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: