Launchpad automatic translations update.
[odoo/odoo.git] / addons / import_sugarcrm / import_sugarcrm.py
index 3e39f34..3ff14bc 100644 (file)
@@ -26,10 +26,17 @@ from import_base.mapper import *
 from datetime import datetime
 import base64
 import pprint
-from papyon.service.SOAPService import url_split
 pp = pprint.PrettyPrinter(indent=4)
 #copy old import here
 
+import htmllib
+
+def unescape_htmlentities(s):
+    p = htmllib.HTMLParser(None)
+    p.save_bgn()
+    p.feed(s)
+    return p.save_end()
+
 class related_ref(dbmapper):
     def __init__(self, type):
         self.type = type
@@ -75,7 +82,6 @@ class sugar_import(import_framework):
         
     def get_data(self, table):
         offset = 0
-        
         res = []
         while True:
             r = sugar.search(self.context.get('port'), self.context.get('session_id'), table, offset, self.MAX_RESULT_PER_PAGE)
@@ -107,7 +113,7 @@ class sugar_import(import_framework):
             return False
         fields = ['name']
         data = [val]
-        return self.import_object(fields, data, 'res.partner.canal', 'crm_channel', val)
+        return self.import_object(fields, data, 'crm.case.channel', 'crm_channel', val)
     
     def get_all_states(self, external_val, country_id):
         """Get states or create new state unless country_id is False"""
@@ -157,7 +163,7 @@ class sugar_import(import_framework):
     
     def import_document(self, val):
         File,Filename = sugar.get_document_revision_search(self.context.get('port'), self.context.get('session_id'), val.get('document_revision_id'))
-        File = base64.encodestring(File)
+        #File = base64.encodestring(File)
         res_id, res_model  = self.import_related_document(val)
         val['res_id'] = res_id
         val['res_model'] = res_model
@@ -204,11 +210,12 @@ class sugar_import(import_framework):
         
     def get_email_mapping(self): 
         return { 
-                'model' : 'mailgate.message',
+                'model' : 'mail.message',
                 'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_MEETING, self.TABLE_CALL],
                 'hook' : self.import_email,
-                'map' : {'name':'name',
-                         'history' : const("1"),
+                'map' : {
+                        'subject':'name',
+                        'state' : const('received'),
                         'date':'date_sent',
                         'email_from': 'from_addr_name',
                         'email_to': 'to_addrs_names',
@@ -219,7 +226,9 @@ class sugar_import(import_framework):
                         'model': 'model',
                         'partner_id/.id': 'partner_id/.id',                         
                         'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
-                        'description': ppconcat('description', 'description_html'),
+                        'body_text': 'description',
+                        'body_html' : 'description_html',
+                        
                 }
             } 
     
@@ -247,7 +256,7 @@ class sugar_import(import_framework):
     def get_history_mapping(self): 
         return { 
                 'model' : 'ir.attachment',
-                'dependencies' : [self.TABLE_USER, self.TABLE_PROJECT, self.TABLE_PROJECT_TASK, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_MEETING, self.TABLE_CALL, self.TABLE_EMAIL],
+                'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_MEETING, self.TABLE_CALL, self.TABLE_EMAIL],
                 'hook' : self.import_history,
                 'map' : {
                       'name':'name',
@@ -443,8 +452,10 @@ class sugar_import(import_framework):
         }
 
     def import_task(self, val):
-        val['date'] = val.get('date_start') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
-        val['date_deadline'] = val.get('date_due') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+        date =  val.get('date_start') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+        val['date'] = ''.join(date)
+        date_deadline = val.get('date_due') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
+        val['date_deadline'] = ''.join(date_deadline)
         return val
 
     def get_task_mapping(self):
@@ -566,10 +577,10 @@ class sugar_import(import_framework):
         }
         
     def get_opportunity_status(self, sugar_val):
-        fields = ['name', 'type']
+        fields = ['name', 'case_default']
         name = 'Opportunity_' + sugar_val['sales_stage']
-        data = [sugar_val['sales_stage'], 'Opportunity']
-        return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('type', '=', 'opportunity'), ('name', 'ilike', sugar_val['sales_stage'])])
+        data = [sugar_val['sales_stage'], '1']
+        return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('name', 'ilike', sugar_val['sales_stage'])])
     
     def import_opportunity_contact(self, val):
         sugar_opportunities_contact = set(sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
@@ -617,7 +628,8 @@ class sugar_import(import_framework):
                 'type' : const('opportunity'),
                 'categ_id/id': call(self.get_category, 'crm.lead', value('opportunity_type')),
                 'email_from': 'email_from',
-                'state': map_val('status', self.opp_state)  , #TODO
+                'state': map_val('status', self.opp_state),
+                'description' : 'description',
             }
         }
         
@@ -637,11 +649,11 @@ class sugar_import(import_framework):
         import lead
     """
     def get_lead_status(self, sugar_val):
-        fields = ['name', 'type']
+        fields = ['name', 'case_default']
         name = 'lead_' + sugar_val.get('status', '')
-        data = [sugar_val.get('status', ''), 'lead']
-        return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('type', '=', 'lead'), ('name', 'ilike', sugar_val.get('status', ''))])
-
+        data = [sugar_val.get('status', ''), '1']
+        return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('name', 'ilike', sugar_val.get('status', ''))])
+    
     lead_state = {
         'New' : 'draft',
         'Assigned':'open',
@@ -685,11 +697,11 @@ class sugar_import(import_framework):
                 'state': map_val('status', self.lead_state) ,
                 'fax': 'phone_fax',
                 'referred': 'refered_by',
-                'optout': 'do_not_call',
+                'opt_out': 'do_not_call',
                 'channel_id/id': call(self.get_channel_id, value('lead_source')),
                 'type_id/id': ref(self.TABLE_COMPAIGN, 'campaign_id'),
                 'country_id/id': 'country_id/id',
-                'state_id/id': 'state_id/id'
+                'state_id/id': 'state_id/id',
                 } 
         }
     
@@ -882,7 +894,7 @@ class sugar_import(import_framework):
             'hook' : self.import_user,
             'map' : { 
                 'name': concat('first_name', 'last_name'),
-                'login': 'user_name',
+                'login': value('user_name', fallback='last_name'),
                 'context_lang' : 'context_lang',
                 'password' : 'password',
                 '.id' : '.id',
@@ -916,7 +928,9 @@ class sugar_import(import_framework):
     """
         Email notification
     """   
-    def get_email_subject(self, result):
+    def get_email_subject(self, result, error=False):
+        if error:
+            return "Sugarcrm data import failed at %s due to an unexpected error" % self.date_ended
         return "your sugarcrm data were successfully imported at %s" % self.date_ended 
     
     def get_body_header(self, result):
@@ -931,20 +945,21 @@ class import_sugarcrm(osv.osv):
     _columns = {
         'username': fields.char('User Name', size=64, required=True),
         'password': fields.char('Password', size=24,required=True),
-         'url' : fields.char('SugarSoap Api url:', size=264, required=True, help="Webservice's url where to get the data.\
+        'url' : fields.char('SugarSoap Api url:', size=264, required=True, help="Webservice's url where to get the data.\
                       example : 'http://example.com/sugarcrm/soap.php', or copy the address of your sugarcrm application http://trial.sugarcrm.com/qbquyj4802/index.php?module=Home&action=index"),
-        'opportunity': fields.boolean('Leads & Opp', help="IfLeads & Opp are checked, SugarCRM leads and opportunities data are imported in OpenERP crm-Opportunity form"),
-        'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
-        'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
-        'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
-        'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings and Meeting Tasks data imported in OpenERP meetings form"),
-        'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
-        'claim': fields.boolean('Cases', help="If Cases is checked, SugarCRM Cases data imported in OpenERP Claims form"),
-        'email_history': fields.boolean('Email and Note',help="If Email and History is checked, SugarCRM Notes, Attachment and Emails data imported in OpenERP's Related module's History with attachment"),
-        'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
-        'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
-        'bug': fields.boolean('Bugs', help="If Bugs is checked, SugarCRM Bugs data imported in OpenERP Project Issues form"),
-        'document': fields.boolean('Documents', help="If Documents is checked, SugarCRM Documents data imported in OpenERP Document Form"),
+        'user' : fields.boolean('User', help="Check this box to import sugarCRM Users into OpenERP users, warning if a user with the same login exist in OpenERP, user information will be erase by sugarCRM user information", readonly=True),
+        'opportunity': fields.boolean('Leads & Opp', help="Check this box to import sugarCRM Leads and Opportunities into OpenERP Leads and Opportunities"),
+        'contact': fields.boolean('Contacts', help="Check this box to import sugarCRM Contacts into OpenERP addresses"),
+        'account': fields.boolean('Accounts', help="Check this box to import sugarCRM Accounts into OpenERP partners"),
+        'employee': fields.boolean('Employee', help="Check this box to import sugarCRM Employees into OpenERP employees"),
+        'meeting': fields.boolean('Meetings', help="Check this box to import sugarCRM Meetings and Tasks into OpenERP meetings"),
+        'call': fields.boolean('Calls', help="Check this box to import sugarCRM Calls into OpenERP calls"),
+        'claim': fields.boolean('Cases', help="Check this box to import sugarCRM Cases into OpenERP claims"),
+        'email_history': fields.boolean('Email and Note',help="Check this box to import sugarCRM Emails, Notes and Attachments into OpenERP Messages and Attachments"),
+        'project': fields.boolean('Projects', help="Check this box to import sugarCRM Projects into OpenERP projects"),
+        'project_task': fields.boolean('Project Tasks', help="Check this box to import sugarCRM Project Tasks into OpenERP tasks"),
+        'bug': fields.boolean('Bugs', help="Check this box to import sugarCRM Bugs into OpenERP project issues"),
+        'document': fields.boolean('Documents', help="Check this box to import sugarCRM Documents into OpenERP documents"),
         'email_from': fields.char('Notify End Of Import To:', size=128),
         'instance_name': fields.char("Instance's Name", size=64, help="Prefix of SugarCRM id to differentiate xml_id of SugarCRM models datas come from different server."),
     }
@@ -952,45 +967,41 @@ class import_sugarcrm(osv.osv):
     def _get_email_id(self, cr, uid, context=None):
         return self.pool.get('res.users').browse(cr, uid, uid, context=context).user_email
     
-    def get_all(self, cr, uid,model, context=None):
-        obj_module = self.pool.get('ir.module.module')
-        module_id = obj_module.search(cr, uid, [('name', '=', model)])
-        if module_id:
-                for id in module_id:
-                    module_state = obj_module.browse(cr, uid, id).state
-                    if module_state == 'installed':
-                        return True
-                    else:
-                        return False
-        return True
+    def _module_installed(self, cr, uid, model, context=None):
+        module_id = self.pool.get('ir.module.module').search(cr, uid, [('name', '=', model), ('state', "=", "installed")], context=context)
+        return bool(module_id)
                 
-    def _get_project(self, cr, uid, context=None):
-        return self.get_all(cr,uid,'project',context=context)
+    def _project_installed(self, cr, uid, context=None):
+        return self._module_installed(cr,uid,'project',context=context)
                         
-    def _get_crm_claim(self, cr, uid, context=None):
-        return self.get_all(cr,uid,'crm_claim',context=context)
+    def _crm_claim_installed(self, cr, uid, context=None):
+        return self._module_installed(cr,uid,'crm_claim',context=context)
                     
-    def _get_project_issue(self, cr, uid, context=None):
-        return self.get_all(cr,uid,'project_issue',context=context)
+    def _project_issue_installed(self, cr, uid, context=None):
+        return self._module_installed(cr,uid,'project_issue',context=context)
+    
+    def _hr_installed(self, cr, uid, context=None):
+        return self._module_installed(cr,uid,'hr',context=context)
     
     _defaults = {#to be set to true, but easier for debugging
+       'user' : True,
        'opportunity': True,
        'contact' : True,
        'account' : True,
-        'employee' : True,
+        'employee' : _hr_installed,
         'meeting' : True,
         'call' : True,
-        'claim' : _get_crm_claim,    
+        'claim' : _crm_claim_installed,    
         'email_history' : True, 
-        'project' : _get_project,   
-        'project_task': _get_project,     
-        'bug': _get_project_issue,
+        'project' : _project_installed,   
+        'project_task': _project_installed,     
+        'bug': _project_issue_installed,
         'document': True,
         'instance_name': 'sugarcrm',
         'email_from': _get_email_id,
         'username' : 'admin',
         'password' : '',
-        'url':  "http://sugarcrm.example.com/soap.php"        
+        'url':  "http://sugarcrm.example.com/soap.php"
     }
     
     def check_url(self, url, context):
@@ -1032,9 +1043,11 @@ class import_sugarcrm(osv.osv):
         if not context:
             context = {}
         key_list = []
-        list = []
+        module = {}
         for current in self.browse(cr, uid, ids, context):
             context.update({'username': current.username, 'password': current.password, 'url': current.url, 'email_user': current.email_from or False, 'instance_name': current.instance_name or False})
+            if current.user:
+                key_list.append('Users')
             if current.contact:
                 key_list.append('Contacts')
             if current.account:
@@ -1043,30 +1056,30 @@ class import_sugarcrm(osv.osv):
                 key_list.append('Leads')
                 key_list.append('Opportunities')
             if current.employee:
-                key_list.append('Employees') 
+                key_list.append('Employees')
+                module.update({'Employees':'hr'}) 
             if current.meeting:
                 key_list.append('Meetings')
             if current.call:
                 key_list.append('Calls')
             if current.claim:
                 key_list.append('Cases')  
-                list.append('crm_claim')
+                module.update({'Cases':'crm_claim'})
             if current.email_history:
                 key_list.append('Emails') 
                 key_list.append('Notes') 
-                list.append('project')
             if current.project:
                 key_list.append('Project')
-                list.append('project')
+                module.update({'Project':'project'})
             if current.project_task:
                 key_list.append('ProjectTask')
-                list.append('project')
+                module.update({'ProjectTask':'project'})
             if current.bug:
                 key_list.append('Bugs')
-                list.append('project_issue')
+                module.update({'Bugs':'project_issue'})
             if current.document:
                 key_list.append('Documents')
-        return key_list,list
+        return key_list,module
 
 
     def do_import_all(self, cr, uid, *args):
@@ -1074,16 +1087,22 @@ class import_sugarcrm(osv.osv):
         scheduler Method
         """
         context = {'username': args[4], 'password': args[5], 'url': args[3], 'instance_name': args[3]}
-        imp = sugar_import(self, cr, uid, args[2], "import_sugarcrm", [args[1]], context)
+        imp = sugar_import(self, cr, uid, args[2], "import_sugarcrm", args[1], context)
         imp.set_table_list(args[0])
         imp.start()
         return True 
 
     def import_from_scheduler_all(self, cr, uid, ids, context=None):
-        keys = self.get_key(cr, uid, ids, context)
-        
+        keys, module_list = self.get_key(cr, uid, ids, context)
         if not keys:
             raise osv.except_osv(_('Warning !'), _('Select Module to Import.'))
+        key_list = module_list.keys()
+        for module in key_list :
+            module = module_list[module]
+            state = self.get_all(cr,uid,module,context=context)
+            if state == False:
+                keys =  ', '.join(key_list)
+                raise osv.except_osv(_('Error !!'), _("%s data required %s Module to be installed, Please install %s module") %(keys,module,module))
         cron_obj = self.pool.get('ir.cron')
         url = self.parse_valid_url(context)
         args = (keys,context.get('email_user'), context.get('instance_name'), url, context.get('username'), context.get('password') )
@@ -1101,24 +1120,18 @@ class import_sugarcrm(osv.osv):
         
 #        """Import all sugarcrm data into openerp module"""
         keys, module_list = self.get_key(cr, uid, ids, context)
-        set_list = set(module_list)
-        model = list(set_list)
         if not keys:
             raise osv.except_osv(_('Warning !'), _('Select Module to Import.'))
-        obj_module = self.pool.get('ir.module.module')
-        module_id = obj_module.search(cr, uid, [('name', 'in', model)])
-        if module_id:
-                for id in module_id:
-                    k = obj_module.read(cr, uid, id)
-                    module_state = obj_module.browse(cr, uid, id).state
-                    if module_state == 'uninstalled':
-                        k = obj_module.read(cr, uid, id)
-                        keys =  ', '.join(keys)
-                        module = ', '.join(model)
-                        raise osv.except_osv(_('Error !!'), _("%s data required %s Module to be installed, please install %s module") %(keys,module,module))
+        key_list = module_list.keys()
+        for module in key_list :
+            module = module_list[module]
+            state = self._module_installed(cr,uid,module,context=context)
+            if state == False:
+                keys =  ', '.join(key_list)
+                raise osv.except_osv(_('Error !!'), _("%s data required %s Module to be installed, Please install %s module") %(keys,module,module))
         url = self.parse_valid_url(context)
         context.update({'url': url})
-        imp = sugar_import(self, cr, uid, context.get('instance_name'), "import_sugarcrm", [context.get('email_user')], context)
+        imp = sugar_import(self, cr, uid, context.get('instance_name'), "import_sugarcrm", context.get('email_user'), context)
         imp.set_table_list(keys)
         imp.start()
         obj_model = self.pool.get('ir.model.data')
@@ -1133,5 +1146,6 @@ class import_sugarcrm(osv.osv):
                 'target': 'new',
             }
         
-        
 import_sugarcrm()
+
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: