← Back to team overview

openerp-dev-web team mailing list archive

lp:~openerp-dev/openobject-addons/trunk-import_salesforce-backlog7-jam into lp:~openerp-dev/openobject-addons/trunk-import_salesforce

 

Jigar Amin - OpenERP has proposed merging lp:~openerp-dev/openobject-addons/trunk-import_salesforce-backlog7-jam into lp:~openerp-dev/openobject-addons/trunk-import_salesforce.

Requested reviews:
  Bhumika (OpenERP) (sbh-openerp)

For more details, see:
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-import_salesforce-backlog7-jam/+merge/61955

Changes : 
 + Backlog 7 : Integration with import_base
 + Cron import 
Kindly Review this.
Thank You.

-- 
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-import_salesforce-backlog7-jam/+merge/61955
Your team OpenERP R&D Team is subscribed to branch lp:~openerp-dev/openobject-addons/trunk-import_salesforce.
=== modified file 'import_base/import_framework.py'
--- import_base/import_framework.py	2011-05-16 09:32:16 +0000
+++ import_base/import_framework.py	2011-05-23 11:27:52 +0000
@@ -139,7 +139,7 @@
                 and each data_i have a external id => in data_id['id']
         """
         if not datas:
-            return
+            return 0, False
         mapping['id'] = 'id_new'
         res = []
         for data in datas:
@@ -151,7 +151,7 @@
                     field_name = mapping.pop(k)
                     data[k] = data.get(field_name) and self._generate_xml_id(data.get(field_name), table)
                     
-            data['id_new'] = self._generate_xml_id(data['id'], table)
+            data['id_new'] = self._generate_xml_id(data['Id'], table)
             fields, values = self._fields_mapp(data, mapping, table)
             res.append(values)
         
@@ -294,10 +294,10 @@
         domain_search = not domain_search and [('name', 'ilike', name)] or domain_search
         obj = self.obj.pool.get(model)
         xml_id = self._generate_xml_id(name, table)
-        
         xml_ref = self.mapped_id_if_exist(model, domain_search, table, name)
         fields.append('id')
         data.append(xml_id)
+
         obj.import_data(self.cr, self.uid, fields, [data], mode='update', current_module=self.module_name, noupdate=True, context=self.context)
         return xml_ref or xml_id
     
@@ -370,8 +370,8 @@
                 imported.add(dependency)
                 
     def _send_notification_email(self, result):
-		if not self.email:
-			return
+        if not self.email:
+	        return
         subject = "Openerp has finish to import your data at %s" % self.date_ended
         tools.email_send(
                 'import_sugarcrm@module.openerp',

=== modified file 'import_base/mapper.py'
--- import_base/mapper.py	2011-05-12 08:49:08 +0000
+++ import_base/mapper.py	2011-05-23 11:27:52 +0000
@@ -164,4 +164,4 @@
                 args.append(arg)
         return self.fun(external_values, *args)
     
-    
\ No newline at end of file
+    

=== modified file 'import_salesforce/__openerp__.py'
--- import_salesforce/__openerp__.py	2011-05-13 05:46:26 +0000
+++ import_salesforce/__openerp__.py	2011-05-23 11:27:52 +0000
@@ -30,7 +30,7 @@
 """,
     'author': 'OpenERP SA',
     'website': 'http://www.openerp.com',
-    'depends': ['base', 'crm_claim', 'document'],
+    'depends': ['import_base', 'crm_claim', 'document'],
     'init_xml': [],
     'update_xml': [
                 'wizard/import_salesforce_view.xml',

=== modified file 'import_salesforce/wizard/import_salesforce.py'
--- import_salesforce/wizard/import_salesforce.py	2011-05-13 10:22:48 +0000
+++ import_salesforce/wizard/import_salesforce.py	2011-05-23 11:27:52 +0000
@@ -20,188 +20,286 @@
 ##############################################################################
 
 from datetime import datetime
-import time
 from osv import osv
 from osv import fields
 from tools.translate import _
 import tools
 
-
 try:
     import beatbox
     from beatbox import SoapFaultError
 except ImportError:
     raise osv.except_osv(_('BeatBox Import Error!'), _('Please install beatbox api for SaleForce - beatbox-20.0.zip.\nhttp://pypi.python.org/pypi/beatbox'))
 
-import logging
-
-DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
-ACT_TYPE = ''
-INSTANCE = 'salesforce'
-MODEL_LIST = [('lead', 'Lead'), ('opportunity', 'Opportunity'),
-              ('user', 'User'), ('contact', 'Partner/Contacts'),
-              ('case', 'Cases/Claim'), ('event', 'Event/Meetings'),
-              ('task', 'Activity/Task'), ('attachment', 'Attachment'),
-              ('folder', 'Folder/Directory'), ('document', 'Documents')]
-
-
-def dataMapping(dictsf, dictoe):
-    '''
-    Helper Method to Map Field & Values in list
-    and return two list of Field and Values
-    '''
-    fields=[]
-    data = []
-    for key, val in dictoe.items():
-        if key not in fields and dictsf.get(isinstance(val, list) and val[0] or val):
-            fields.append(key)
-            if isinstance(val, list):
-                data.append(' '.join(map(lambda x: dictsf[x], val)))
-            else:
-                data.append(dictsf.get(val, ''))
-    return fields, data
-
-
-def getSFLogin(client, usr, pwd):
-    '''
-    Helper Methos for logining to the SaleFroce
-    @use : UserName
-    @pwd : Password + SecurityToken
-    '''
-    try:
-        sfi = client.login(usr, pwd)
-        return client, sfi
-    except SoapFaultError, sfe:
-        raise osv.except_osv(_('Error !'), _('%s.\n%s')%(sfe.faultCode, str(sfe.faultString)))
-    except:
-        raise osv.except_osv(_('Error !'), _('Unexpected end of message. Please check connectivity and permissions, and report a bug if problems persist.'))
-
-
-def prepareStatement(fieldMap, model):
-    '''
-    Helper Method to create SOQL for salesforce.
-    '''
-    field = []
-    for val in fieldMap.values():
-        if val not in field:
-            field.append(val)
-    sql = "SELECT " + ", ".join(field) + " FROM " + model
-    return sql
-
-
-def importAttachment(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-    attachment_pool = sf_obj.pool.get('ir.attachment')
-    data_pool = sf_obj.pool.get('ir.model.data')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('attachment').get('field_map'), 'Attachment')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('attachment').get('field_map')
-            model_data = data_pool.search(cr, uid, [('name', 'like', INSTANCE+rec.get('ParentId', False))])
-            rec.update({'ParentId': False})
-            if model_data:
-                res = data_pool.browse(cr, uid, model_data[0], context)
-                fields.update({'res_model': 'model'})
-                rec.update({'model': res.model})
-                rec.update({'ParentId': res.res_id})
-            fields.update({'datas_fname': 'datas_fname'})
-            rec.update({'datas_fname': rec.get('Name')})
-            rec.update({'Id': INSTANCE+"_attachment_"+rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            attachment_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            if model_data:
-                fields.pop('res_model')
-            fields.pop('datas_fname')
-
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importNote(sf_obj, cr, uid, sfc, context):
-    if context == None:
-        context = {}
-    message_pool = sf_obj.pool.get('mailgate.message')
-    data_pool = sf_obj.pool.get('ir.model.data')
-    try:
-        sqlStmt = prepareStatement(MODEL_MAP.get('note').get('field_map'), 'Note')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('note').get('field_map')
-            model_data = data_pool.search(cr, uid, [('name', 'like', INSTANCE+rec.get('ParentId', False))])
-            fields.update({'date': 'date'})
-            rec.update({'date': datetime.now().strftime(DATETIME_FORMAT)})
-            rec.update({'ParentId': False})
-            if model_data:
-                res = data_pool.browse(cr, uid, model_data[0], context)
-                fields.update({'model': 'model'})
-                rec.update({'model': res.model})
-                rec.update({'ParentId': res.res_id})
-            rec.update({'Id': INSTANCE + '_' + rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            message_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            if model_data:
-                fields.pop('model')
-            fields.pop('date')
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def titleMapping(sf_obj, cr, uid, salutation, domain, context):
-    '''
-    Helper Method to resolve title dependency
-    '''
-    if context == None:
-        context = {}
-
-    if salutation:
-        title_pool = sf_obj.pool.get('res.partner.title')
-        ids = title_pool.search(cr, uid, [('domain', '=', domain), '|', ('shortcut', '=', salutation), ('name', '=', salutation)])
-        if ids:
-            return ids[0]
-        else:
-            id = title_pool.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain}, context)
-            return id
-    return False
-
-
-def priorityMapping(sf_obj, cr, uid, rating, context):
-    '''
-    Helper Method to Priority of Lead/Opportunity
-    '''
-    if context == None:
-        context = {}
-    priMap = {
-        'Hot': '2',
-        'Warm': '3',
-        'Cold': '4',
-    }
-    return priMap.get(rating, '4')
-
-
-def leadStateMapping(sf_obj, cr, uid, state, context):
-    '''
-    Helper Method to resolve State dependency.
-    '''
-    if context == None:
-        context = {}
+from import_base.import_framework import *
+from import_base.mapper import *
+
+class salesforce_import(import_framework):
+
+    _SFCLIENT = False
+    
+    TABLE_USER = 'User'
+    TABLE_FOLDER = 'Folder'
+    TABLE_DOCUMENT = 'Document'
+    TABLE_LEAD  = 'Lead'
+    TABLE_CONTACT = 'Contact'
+    TABLE_OPPORTUNITY = 'Opportunity'
+    TABLE_CLAIM = 'Case'
+    TABLE_MEETING = 'Event'
+    TABLE_STAGE = 'crm_stage'
+    TABLE_ATTENDEE = 'EventAttendee'
+    TABLE_OPPOHISTORY = 'OpportunityHistory'
+    TABLE_ATTACHMENT = 'Attachment'
+    TABLE_TASK = 'Task'
+    DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S"
+
+    def initialize(self):
+        #login
+        self._SFCLIENT = beatbox.PythonClient()
+        self._SFCLIENT.login(self.context.get('username', False),
+                                        self.context.get('passtoken', False))
+
+    def prepareStatement(self):
+        return {
+            self.TABLE_USER: "SELECT Id, Name, Username, Email, TimeZoneSidKey, LanguageLocaleKey FROM %s"%(self.TABLE_USER),
+            self.TABLE_FOLDER: "SELECT Id, Name FROM %s WHERE Type = 'Document'"%(self.TABLE_FOLDER),
+            self.TABLE_DOCUMENT: "SELECT Id, Name, Type, AuthorId, FolderId, Description, Url FROM %s"%(self.TABLE_DOCUMENT),
+            self.TABLE_LEAD: "SELECT  Id, Name, Title, Phone, Email, MobilePhone, Company,  Description, PostalCode, Street, City, Rating, Country, Status, LeadSource, Salutation, State, Fax, CreatedById FROM %s"%(self.TABLE_LEAD),
+            self.TABLE_CONTACT: "SELECT Id, Name, Title FROM %s"%(self.TABLE_CONTACT),
+            self.TABLE_OPPORTUNITY : "SELECT CreatedById, AccountId, Id, Name , Probability, NextStep, Amount, Description, OwnerId, StageName, CloseDate, Account.Name FROM %s"%(self.TABLE_OPPORTUNITY),
+            self.TABLE_CLAIM : "SELECT Id, CaseNumber, Subject, OwnerId, Description, CreatedById, Priority, ContactId, ClosedDate, Status FROM %s"%(self.TABLE_CLAIM),
+            self.TABLE_MEETING : "SELECT Id, Subject, OwnerId, WhoId, Location, Description, StartDateTime, EndDateTime, IsRecurrence, IsAllDayEvent, DurationInMinutes, RecurrenceType, RecurrenceInterval, RecurrenceEndDateOnly, RecurrenceDayOfWeekMask, RecurrenceDayOfMonth, RecurrenceInstance FROM %s"%(self.TABLE_MEETING),
+            self.TABLE_ATTACHMENT: "SELECT Id, Name, Description, ParentId FROM Attachment",
+            self.TABLE_TASK: "SELECT Id, Subject, OwnerId, ActivityDate, CallDurationInSeconds, Description, WhoId FROM %s"%(self.TABLE_TASK),
+        }
+
+
+    def get_data(self, table):
+        sql = self.prepareStatement().get(table, False)
+        return self._SFCLIENT.query(sql)
+
+    def get_mapping(self):
+        return {
+            self.TABLE_USER: self.get_user_mapping(),
+            self.TABLE_FOLDER: self.get_folder_mapping(),
+            self.TABLE_DOCUMENT: self.get_document_mapping(),
+            self.TABLE_LEAD: self.get_lead_mapping(),
+            self.TABLE_CONTACT: self.get_contact_mapping(),
+            self.TABLE_OPPORTUNITY: self.get_opportunity_mapping(),
+            self.TABLE_CLAIM : self.get_claim_mapping(),
+            self.TABLE_MEETING : self.get_meeting_mapping(),
+            self.TABLE_ATTACHMENT : self.get_attachment_mapping(),
+            self.TABLE_TASK: self.get_task_mapping(),
+        }
+
+
+    def get_all_states(self, external_val, country_id):
+        """Get states or create new state unless country_id is False"""
+        state_code = external_val[0:3] #take the tree first char
+        fields = ['country_id/id', 'name', 'code']
+        data = [country_id, external_val, state_code]
+        if country_id:
+            return self.import_object(fields, data, 'res.country.state', 'country_state', external_val) 
+        return False
+
+    def get_all_countries(self, val):
+        """ Get Country, if no country match do not create anything, 
+            to avoid duplicate country code.
+        """
+        return self.mapped_id_if_exist('res.country', [('name', 'ilike', val)], 'res.country', val)
+
+
+    def get_title(self, vals, title , domain):
+        if title:
+            fields = ['name', 'shortcut', 'domain']
+            name = 'partner_title_' + title
+            data = [title, title, domain]
+            return self.import_object(fields, data, 'res.partner.title', self.TABLE_CONTACT, name, [('domain', '=', domain), ('name', 'ilike', title)])  
+
+
+    def import_user(self, val):
+        user_obj = self.obj.pool.get('res.users')
+        user_ids = user_obj.search(self.cr, self.uid, [('login', '=', val.get('user_name'))])
+        if user_ids: 
+            val['.id'] = str(user_ids[0])
+        else:
+            val['password'] = 'salesforce' #default password for all user #TODO needed in documentation
+        return val
+
+    def get_user_mapping(self):
+        return {
+            'model' : 'res.users',
+            'hook' : self.import_user,
+            'map' : { 
+                    'id': 'Id',
+                    'name': 'Name',
+                    'login': 'Username',
+                    'user_email': 'Email',
+                    'context_tz': 'TimeZoneSidKey',
+                    'context_lang': 'LanguageLocaleKey',
+                }
+        }
+
+    def get_folder_mapping(self):
+        return {
+            'model': 'document.directory',
+            'dependencies': [self.TABLE_USER],
+            'map': {
+                    'id': 'Id',
+                    'name': 'Name',
+                }
+        }
+
+    def get_document_type(self, val):
+        doc_type = 'binary'
+        if val.get('Url'):
+            doc_type = "url"
+        return doc_type
+        
+    def get_document_datas(self, dict):
+        if not dict.get('Type') == 'URL':
+            data = self._SFCLIENT.query("SELECT Body FROM Document WHERE id='%s'"%(dict.get('Id')))
+            if data:
+                data = data[0]
+                return data.get('Body', False)
+        return False        
+        
+    def get_document_mapping(self):
+        return {
+            'model': 'ir.attachment',
+            'dependencies': [self.TABLE_USER, self.TABLE_FOLDER],
+            'map': {
+                        'id': 'Id',
+                        'name': 'Name',
+                        'type': call(self.get_document_type),
+                        'user_id/id': ref(self.TABLE_USER, 'AuthorId'),
+                        'parent_id/id': ref(self.TABLE_FOLDER, 'FolderId'),
+                        'datas': call(self.get_document_datas),
+                        'datas_fname': 'Name',
+                        'description': 'Description',
+                        'url': 'Url'
+                    }
+        }
+        
+    # Import Contact
+    def get_address_vals(self, key, vals):
+        address = {
+            'contact': {
+                'contact_name': vals.get('Name', ''),
+                'type' : key,
+                'street': vals.get('MailingStreet',''),
+                'zip': vals.get('MailingPostalCode',''),
+                'city': vals.get('MailingCity',''),
+                'phone': vals.get('Phone',''),
+                'mobile': vals.get('MobilePhone',''),
+                'email':vals.get('Email',''),
+                'fax': vals.get('Fax',''),
+                'state_id/id': vals.get('MailingState',False),
+                'country_id/id': vals.get('MailingCountry',False),
+            },
+            'other': {
+                'contact_name': vals.get('Name', ''),
+                'type' : key,
+                'street': vals.get('OtherStreet',''),
+                'zip': vals.get('OtherPostalCode',''),
+                'city': vals.get('OtherCity',''),
+                'phone': vals.get('OtherPhone',''),
+                'mobile': vals.get('MobilePhone',''),
+                'email':vals.get('Email',''),
+                'fax': vals.get('Fax',''),
+                'country_id/id': vals.get('OtherCountry',False),
+                'state_id/id': vals.get('OtherState',False),
+            },
+        }
+        if vals.get('Account'):
+            address.update({
+                'invoice': {
+                    'contact_name': vals.get('Name', ''),
+                    'type' : key,
+                    'street': vals.get('Account',{}).get('BillingStreet',''),
+                    'zip': vals.get('Account',{}).get('BillingPostalCode',''),
+                    'city': vals.get('Account',{}).get('BillingCity',''),
+                    'phone':  vals.get('Account',{}).get('Phone',''),
+                    'mobile': False,
+                    'email':vals.get('Email',''),
+                    'fax': vals.get('Account',{}).get('Fax',''),
+                    'country_id/id': vals.get('Account',{}).get('BillingCountry',False),
+                    'state_id/id': vals.get('Account',{}).get('BillingState', False),
+                },
+                'delivery': {
+                    'contact_name': vals.get('Name', ''),
+                    'type' : key,
+                    'street': vals.get('Account',{}).get('ShippingStreet',''),
+                    'zip': vals.get('Account',{}).get('ShippingPostalCode',''),
+                    'city': vals.get('Account',{}).get('ShippingCity',''),
+                    'phone':  vals.get('Account',{}).get('Phone',''),
+                    'mobile': False,
+                    'email':vals.get('Email',''),
+                    'fax': vals.get('Account',{}).get('Fax',''),
+                    'country_id/id': vals.get('Account',{}).get('ShippingCountry',False),
+                    'state_id/id': vals.get('Account',{}).get('ShippingState',False),
+                },
+            })
+        return address.get(key, False)
+    
+    def get_address_type(self, add_type, vals):
+        val = self.get_address_vals(add_type, vals)
+        address = {
+            'name': 'contact_name',
+            'type' : 'type',
+            'street':'street',
+            'zip': 'zip',
+            'city': 'city',
+            'phone':  'phone',
+            'mobile': 'mobile',
+            'email': 'email',
+            'fax': 'fax',
+            'country_id/id': 'country_id/id', 
+            'state_id/id': 'state_id/id', 
+        }
+        if val:
+            country = state = False
+            if val.get('country_id/id'):
+                country = self.get_all_countries(val.get('country_id/id'))
+            if val.get('state_id/id'):
+                state = self.get_all_states(val.get('state_id/id'), country)
+            val.update({'country_id/id': country,
+                        'state_id/id': state,
+                        'id_new': vals['Id'] + '_address_' + add_type })
+            return self.import_object_mapping(address, val, 'res.partner.address', self.TABLE_CONTACT, val['id_new'], self.DO_NOT_FIND_DOMAIN)
+        else:
+            return False
+    
+    
+    def get_partner_address(self, vals):
+        address_types = ['contact', 'other', 'invoice', 'delivery']
+        address_vals = self._SFCLIENT.query("SELECT Id , Name, Email, MailingStreet, MailingCity, Phone, MobilePhone, MailingPostalCode, MailingState, MailingCountry, Fax, OtherStreet, OtherCity, OtherCountry, OtherState, OtherPostalCode, OtherPhone, Account.Website, Account.BillingStreet, Account.BillingCity, Account.BillingCountry, Account.BillingState, Account.BillingPostalCode, Account.ShippingStreet, Account.ShippingCity, Account.ShippingCountry, Account.ShippingState, Account.ShippingPostalCode, Account.Fax, Account.Phone FROM %s WHERE Id = '%s'"%(self.TABLE_CONTACT, vals.get('Id')))
+        address_ids = [] 
+        for add_type in address_types:
+            if add_type in ['invoice', 'delivery'] and not vals.get('Account'):
+                continue
+            address_ids.append(self.get_address_type(add_type, address_vals[0]))
+        return ','.join(address_ids)
+    
+    def get_contact_mapping(self):
+        return {
+            'model': 'res.partner',
+            'dependencies': [],
+            'map': {
+                'id': 'Id',
+                'name': 'Name',
+                'customer': const('1'),
+                'supplier': const('0'),
+                'title/id': call(self.get_title, value('Title'), const('partner')),                     
+                'address/id': self.get_partner_address,
+                }
+        }
+    
+    def get_status(self, val, status, status_type):
+        fields = ['name', 'type']
+        name = status_type + '_' + status
+        data = [status, status_type]
+        return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('type', '=', status_type), ('name', 'ilike', status)])
 
     stateMap = {
         'Open - Not Contacted': 'draft',
@@ -209,157 +307,83 @@
         'Closed - Converted': 'done',
         'Closed - Not Converted': 'cancel',
     }
-    return stateMap.get(state, False)
-
-
-def leadStatusMapping(sf_obj, cr, uid, status, context):
-    '''
-    Helper Method to resolve Status dependency.
-    '''
-    if context == None:
-        context = {}
-
-    stageMap = {
-        'Open - Not Contacted': 'New',
-        'Working - Contacted': 'Negotiation',
-        'Closed - Converted': 'Won',
-        'Closed - Not Converted': 'Lost',
+    priorityMap = {
+        'Hot' : '2',
+        'Warm' : '3',
+        'Cold' : '4',
     }
-    stage_pool = sf_obj.pool.get('crm.case.stage')
-    ids = stage_pool.search(cr, uid, [('type', '=', 'lead'), ('name', '=', stageMap.get(status, ''))])
-    if ids:
-        return ids[0]
-    return False
-
-
-def getUserId(sf_obj, cr, uid, user, context):
-    '''
-    Helper Method to to get SalesForce Owner id for User
-    '''
-    if context == None:
-        context = {}
-
-    return user.get('Id', False)
-
-
-def getLocalId(sf_obj, cr, uid, state, country, context):
-    if context == None:
-        context = {}
-
-    if state or country:
-        state_pool = sf_obj.pool.get('res.country.state')
-        country_pool = sf_obj.pool.get('res.country')
-        sid = state_pool.search(cr, uid, ['|', ('name', '=', state), ('code', '=', state[0:2])])
-        cid = country_pool.search(cr, uid, ['|', ('name', '=', country), ('code', '=', country[0:2])])
-        if sid:
-            st_id = state_pool.browse(cr, uid, sid[0])
-            return sid[0], st_id.country_id.id
-        elif not sid and cid:
-            sid = state_pool.create(cr, uid, {'name': state, 'code': state[0:2], 'country_id': cid[0]})
-            return sid, cid[0]
-    return False, False
-
-
-def getChannelId(sf_obj, cr, uid, channel, context):
-    '''
-    Helper Method to to get Lead Channel Id
-    '''
-    if context == None:
-        context = {}
-    channel_id = False
-    if channel:
-        partner_canal_pool = sf_obj.pool.get('res.partner.canal')
-        chnls = {
-            'Web': 'website',
-            'Phone Inquiry': 'phone',
-        }
-        if chnls.get(channel, False):
-            sid = partner_canal_pool.search(cr, uid, [('name', '=', chnls.get(channel))])
-            channel_id = sid and sid[0] or False
-        else:
-            sid = partner_canal_pool.search(cr, uid, [('name', '=', channel)])
-            if sid:
-                channel_id = sid and sid[0] or False
-            else:
-                channel_id = partner_canal_pool.create(cr, uid, {'name': channel, 'active': True}, context)
-    return channel_id
-
-
-def importLead(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    lead_pool = sf_obj.pool.get('crm.lead')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('lead').get('field_map'), 'Lead')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('lead').get('field_map')
-            rec.update({'Salutation': titleMapping(sf_obj, cr, uid, rec.get('Salutation', False), 'contact', context)})
-            rec.update({'Rating': priorityMapping(sf_obj, cr, uid, rec.get('Rating', False), context)})
-            fields.update({'state': 'state'})
-            rec.update({'state': leadStateMapping(sf_obj, cr, uid, rec.get('Status', False), context)})
-            rec.update({'Status': leadStatusMapping(sf_obj, cr, uid, rec.get('Status', False), context)})
-            state_id, conutry_id = getLocalId(sf_obj, cr, uid, rec.get('State', False), rec.get('Country', False), context)
-            rec.update({'State': state_id, 'Country': conutry_id})
-            user_id = getUserId(sf_obj, cr, uid, rec.get('CreatedBy', False), context)
-            if user_id:
-                rec.update({'CreatedBy.Id': INSTANCE +"_user_"+ user_id})
-            else:
-                rec.update({'CreatedBy.Id': False})
-            rec.update({'LeadSource': getChannelId(sf_obj, cr, uid, rec.get('LeadSource'), context)})
-
-            rec.update({'Id': INSTANCE+"_lead_"+rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            field.append('type')
-            data.append('lead')
-            lead_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            fields.pop('state')
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importUser(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-    user_pool = sf_obj.pool.get('res.users')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('user').get('field_map'), 'User')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            rec.update({'Id': INSTANCE+"_user_"+rec.get('Id')})
-            field, data = dataMapping(rec, MODEL_MAP.get('user').get('field_map'))
-            user_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def oppoStateMapping(sf_obj, cr, uid, state, context):
-    '''
-    Helper Method to resolve State dependency.
-    '''
-    if context == None:
-        context = {}
-
-    stateMap = {
+
+    def get_lead_country(self, val):
+        if val.get('Country'):
+            return self.get_all_countries(val.get('Country'))
+
+    def get_lead_fedstate(self, val):
+        country = False
+        if val.get('Country'):
+            country = self.get_all_countries(val.get('Country'))
+        return self.get_all_states(val.get('State'), country)
+    
+    def get_channel(self, val):
+        fields = ['name']
+        name = 'lead_' + val.get('LeadSource', '')
+        data = [val.get('LeadSource', '')]
+        return self.import_object(fields, data, 'res.partner.canal',self.TABLE_LEAD, name, [('name', 'ilike', val.get('LeadSource', ''))])
+    
+    def get_lead_mapping(self):
+        return{
+            'model': 'crm.lead',
+            'dependencies': [self.TABLE_USER, self.TABLE_CONTACT],
+            'map': {
+                        'id' : 'Id',
+                        'name': 'Company',
+                        'title/id': call(self.get_title, value('Salutation'), const('contact') ),
+                        'user_id/id': ref(self.TABLE_USER,'CreatedById'),
+                        'state': map_val('Status', self.stateMap),
+                        'priority': map_val('Rating', self.priorityMap, default='3'),
+                        'stage_id/id' : call(self.get_status, value('Status'), 'lead'),
+                        'partner_name': 'Company',
+                        'contact_name': 'Name',
+                        'function': 'Title',
+                        'street': 'Street',
+                        'city': 'City',
+                        'email_from': 'Email',
+                        'phone': 'Phone',
+                        'mobile': 'MobilePhone',
+                        'fax': 'Fax',
+                        'zip': 'PostalCode',
+                        'description': 'Description',
+                        'country_id/id': self.get_lead_country,
+                        'state_id/id': self.get_lead_fedstate,
+                        'channel_id/id': self.get_channel,
+                    }
+            }
+    
+
+    def get_leadtoppo_vals(self, val):
+        lead_data = self._SFCLIENT.query("SELECT Company, Title, Street, City, PostalCode, Country, State, Email, Fax, MobilePhone, Phone FROM Lead WHERE ConvertedOpportunityId = '%s'"%val.get('Id'))
+        for data in lead_data:
+            val.update({
+                'Company': data.get('Company', ''),
+                'Title': data.get('Title', ''),
+                'Street': data.get('Street', ''), 
+                'City': data.get('City', ''),
+                'Email': data.get('Email', ''),
+                'Phone': data.get('Phone', ''),
+                'MobilePhone': data.get('MobilePhone', ''),
+                'PostalCode': data.get('PostalCode', ''),
+                'Fax': data.get('Fax',''),
+                'Email': data.get('Email',''),
+            })   
+            country = state = False
+            if data.get('Country'):
+                country = self.get_all_countries(data.get('Country'))
+            if data.get('State'):
+                state = self.get_all_states(data.get('State'), country)
+            val.update({'Country': country, 'State': state})
+        return val
+
+
+    opportunity_state_map = {
             'Prospecting': 'draft',
             'Qualification': 'open',
             'Needs Analysis': 'open',
@@ -371,980 +395,341 @@
             'Closed Won': 'done',
             'Closed Lost': 'cancel',
     }
-    return stateMap.get(state, False)
-
-
-def oppoStatusMapping(sf_obj, cr, uid, status, context):
-    '''
-    Helper Method to resolve Status dependency.
-    '''
-    if context == None:
-        context = {}
-
-    stageMap = {
-            'Prospecting': 'New',
-            'Qualification': 'Qualification',
-            'Needs Analysis': 'Qualification',
-            'Value Proposition': 'Proposition',
-            'Id. Decision Makers': 'Proposition',
-            'Perception Analysis': 'Proposition',
-            'Proposal/Price Quote': 'Proposition',
-            'Negotiation/Review': 'Negotiation',
-            'Closed Won': 'Won',
-            'Closed Lost': 'Lost',
-    }
-    stage_pool = sf_obj.pool.get('crm.case.stage')
-    ids = stage_pool.search(cr, uid, [('type', '=', 'opportunity'), ('name', '=', stageMap.get(status, ''))])
-    if ids:
-        return ids[0]
-    return False
-
-
-def importOpportunityHistory(sf_obj, cr, uid, sfc, context):
-    if context == None:
-        context = {}
-
-    message_pool = sf_obj.pool.get('mailgate.message')
-    data_pool = sf_obj.pool.get('ir.model.data')
-    try:
-        sqlStmt = prepareStatement(MODEL_MAP.get('opportunityhistory').get('field_map'), 'OpportunityHistory')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('opportunityhistory').get('field_map')
-            sfopp_id = rec.pop('OpportunityId')
-            opp_id = data_pool.search(cr, uid, [('model', '=', 'crm.lead'), ('name', '=', INSTANCE+"_opportunity_"+ sfopp_id)])
-            if opp_id:
-                res = data_pool.browse(cr, uid, opp_id[0], context)
-                fields.update({'model': 'model'})
-                rec.update({'model': 'crm.lead'})
-                rec.update({'OpportunityId': res.res_id})
-                rec.update({'name': "Changed Stage to: " + rec.get('StageName', '')})
-                rec.update({'CloseDate': rec.get('CloseDate').strftime(DATETIME_FORMAT)})
-                fields.update({'description': 'description'})
-                rec.update({'description': "Changed Stage to: " + rec.get('StageName', '')})
-                rec.update({'Id': INSTANCE+"_opportunityhistory_"+rec.get('Id')})
-                field, data = dataMapping(rec, fields)
-                message_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-                fields.pop('model')
-                fields.pop('description')
-            else:
-                continue
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def getOpportunityPartner(sf_obj, cr, uid, sfc, account_id, context):
-    if context == None:
-        context = {}
-
-    if account_id:
-        account = sfc.query("SELECT Id, Name FROM Account WHERE Id = '%s'"%account_id)
-        partner_pool = sf_obj.pool.get('res.partner')
-        partner = partner_pool.search(cr, uid, [('name', '=', account[0].get('Name'))], context=context)
-        if partner:
-            return partner[0]
-    return False
-
-
-def importOpportunity(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    lead_pool = sf_obj.pool.get('crm.lead')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('opportunity').get('field_map'), 'Opportunity')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('opportunity').get('field_map')
-            rec.update({'type': 'opportunity'})
-            rec.update({'AccountId': getOpportunityPartner(sf_obj, cr, uid, sfc, rec.get('AccountId', False), context)})
-            lead = sfc.query("SELECT Id, Name, Status, Salutation, Title, Street, PostalCode, Country, State, Email, Fax, MobilePhone FROM Lead WHERE ConvertedOpportunityId = '%s'"%rec.get('Id'))
-            lead_fields= ['partner_name', 'title/.id', 'function', 'street',
-                        'city', 'email_from', 'mobile', 'zip',
-                        'state_id/.id', 'country_id/.id']
-            if lead:
-                lead = lead[0]
-                fields.update({'partner_name': 'LeadName',
-                                'title/.id': 'Salutation',
-                                'function': 'Title',
-                                'street': 'Street',
-                                'city': 'City',
-                                'state_id/.id': 'State',
-                                'country_id/.id': 'Country',
-                                'email_from': 'Email',
-                                'mobile': 'MobilePhone',
-                                'zip': 'PostalCode',
-                                })
-                state_id, conutry_id = getLocalId(sf_obj, cr, uid, lead.get('State', False), lead.get('Country', False), context)
-                rec.update({'LeadName': lead.get('Name', ''),
-                            'Salutation': titleMapping(sf_obj, cr, uid, lead.get('Salutation', False), 'contact', context),
-                            'Title': lead.get('Title', False),
-                            'Street': lead.get('Street', False),
-                            'City': lead.get('City', False),
-                            'State': state_id,
-                            'Country': conutry_id,
-                            'Email': lead.get('Email', False),
-                            'MobilePhone': lead.get('MobilePhone', False),
-                            'PostalCode': lead.get('PostalCode', False),
-                            })
-            fields.update({'state': 'state'})
-            rec.update({'state': oppoStateMapping(sf_obj, cr, uid, rec.get('StageName', False), context)})
-            rec.update({'StageName': oppoStatusMapping(sf_obj, cr, uid, rec.get('StageName', False), context)})
-            user_id = getUserId(sf_obj, cr, uid, rec.get('CreatedBy', False), context)
-            if user_id:
-                rec.update({'CreatedBy.Id': INSTANCE +"_user_"+ user_id})
-            else:
-                rec.update({'CreatedBy.Id': False})
-            rec.update({'LeadSource': getChannelId(sf_obj, cr, uid, rec.get('LeadSource'), context)})
-            rec.update({'Id': INSTANCE +"_opportunity_"+ rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            lead_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            if lead:
-                for fid in lead_fields:
-                    fields.pop(fid)
-            fields.pop('state')
-        MODEL_MAP['opportunityhistory']['function'](sf_obj, cr, uid, sfc, context)
-        MODEL_MAP['note']['function'](sf_obj, cr, uid, sfc, context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importAddress(sf_obj, cr, uid, address, context):
-    if context == None:
-        context = {}
-
-    address_pool = sf_obj.pool.get('res.partner.address')
-    aids = []
-    for key, val in address.items():
-        asids = address_pool.search(cr, uid, [('name', '=', val.get('name')), ('type', '=', val.get('type'))])
-        if asids:
-            aids.extend(asids)
-        else:
-            state, conutry = getLocalId(sf_obj, cr, uid, val.get('State', False), val.get('Country', False), context)
-            val.update({'state_id': state})
-            val.update({'country_id': conutry})
-            aids.append(address_pool.create(cr, uid, val, context))
-    return aids
-
-
-def importContact(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    partner_pool = sf_obj.pool.get('res.partner')
-    try:
-        addressDict = {
-            'contact': {
-                'cstreet': 'MailingStreet',
-                'ccity': 'MailingCity',
-                'cphone': 'Phone',
-                'cmobile': 'MobilePhone',
-                'czip': 'MailingPostalCode',
-                'cstate_id/.id': 'MailingState',
-                'ccountry_id/.id': 'MailingCountry',
-                'cfax': 'Fax',
-            },
-            'other': {
-                'ostreet': 'OtherStreet',
-                'ocity': 'OtherCity',
-                'ocountry_id': 'OtherCountry',
-                'ostate_id': 'OtherState',
-                'ozip': 'OtherPostalCode',
-                'ophone': 'OtherPhone',
-            },
-            'invoice': {
-                'bstreet': 'BillingStreet',
-                'bcity': 'BillingCity',
-                'bcountry_id': 'BillingCountry',
-                'bstate_id': 'BillingState',
-                'bzip': 'BillingPostalCode',
-            },
-            'delivery': {
-                'sstreet': 'ShippingStreet',
-                'scity': 'ShippingCity',
-                'scountry_id': 'ShippingCountry',
-                'sstate_id': 'ShippingState',
-                'szip': 'ShippingPostalCode',
-            },
+
+
+    
+    def get_oppo_partner(self, val):
+        if val.get('Account'):
+            name = val.get('Account').get('Name')
+            partner_xml_id = self.name_exist(self.TABLE_CONTACT, name, 'res.partner')
+            if partner_xml_id:
+                return partner_xml_id
+            if not partner_xml_id:
+                fields = ['name', 'customer', 'supplier']
+                name = 'Contact_' + name
+                data = [name,'1','0']
+                return self.import_object(fields, data, 'res.partner', self.TABLE_CONTACT, name, self.DO_NOT_FIND_DOMAIN)
+        return False
+
+
+    def get_oppo_history(self, val):
+        field_map = {
+                        'id': 'Id',
+                        'name': 'StageName',
+                        'description': 'StageName',
+                        'model': 'Model',
+                        'date': 'CloseDate',
+                    }
+
+        histories = self._SFCLIENT.query("SELECT Id, StageName ,CloseDate  From %s WHERE OpportunityId = '%s'"%(self.TABLE_OPPOHISTORY, val.get('Id')))
+        if histories:
+            ids = []
+            for history in histories:
+                history.update({'Model': 'crm.lead',
+                                'StageName': '	Changed Stage to: %s'%(history.get('StageName')),
+                                'CloseDate': val.get('CloseDate') and val.get('CloseDate').strftime(self.DATETIME_FORMAT) or False})
+                history.update({'id_new': history.get('Id')})
+                nid = self.import_object_mapping(field_map, history,  'mailgate.message', self.TABLE_OPPOHISTORY, history.get('id_new'), self.DO_NOT_FIND_DOMAIN)
+                ids.append(nid)
+            return ",".join(ids)
+        return False
+
+    def get_oppo_date_deadline(self, val):
+        if val.get('CloseDate'):
+            return val.get('CloseDate').strftime(self.DATETIME_FORMAT)
+        return False
+
+    def get_opportunity_mapping(self):
+        return {
+            'model' : 'crm.lead',
+            'dependencies': [self.TABLE_USER, self.TABLE_CONTACT],
+            'hook': self.get_leadtoppo_vals,
+            'map' : { 
+                    'id': 'Id',
+                    'name': 'Name',
+                    'probability': 'Probability',
+                    'user_id/id': ref(self.TABLE_USER,'OwnerId'),
+                    'title_action': 'NextStep',
+                    'planned_revenue': 'Amount',
+                    'date_deadline': self.get_oppo_date_deadline,
+                    'stage_id/id': call(self.get_status, value('StageName'), 'opportunity'),
+                    'type' : const('opportunity'),
+                    'partner_id/id': self.get_oppo_partner,
+                    'channel_id/id': self.get_channel,
+                    'description': 'Description',
+                    'state' : map_val('StageName', self.opportunity_state_map, 'open'),
+                    'partner_name': 'Company',
+                    'function': 'Title',
+                    'street': 'Street',
+                    'city': 'City',
+                    'email_from': 'Email',
+                    'phone': 'Phone',
+                    'fax': 'Fax',
+                    'email_from': 'Email',
+                    'mobile': 'MobilePhone',
+                    'zip': 'PostalCode',
+                    'country_id/id': 'Country',
+                    'state_id/id': 'State',
+                    'message_ids/id': self.get_oppo_history,
+                }
         }
-
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('contact').get('field_map'), 'Contact')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            add_dict = {}
-            for add in addressDict:
-                addr = {}
-                for key, vals in addressDict.get(add).items():
-                    if add in ['other', 'contact']:
-                        nkey = key[1:]
-                        val = rec.pop(vals)
-                        addr.update({nkey: val})
-                    if add in ['invoice', 'delivery']:
-                        account = rec.get('Account')
-                        nkey = key[1:]
-                        if account:
-                            val = account.pop(vals)
-                            addr.update({nkey: val})
-                    addr.update({'type': add})
-                    addr.update({'email': rec.get('Email')})
-                    addr.update({'name': rec.get('Name')})
-                add_dict.update({add: addr})
-            rec.pop('Account')
-            fields = MODEL_MAP.get('contact').get('field_map')
-            rec.pop('Email')
-            addIds = importAddress(sf_obj, cr, uid, add_dict, context)
-            rec.update({'Title': titleMapping(sf_obj, cr, uid, rec.get('Title', False), 'partner', context)})
-            rec.update({'Id': INSTANCE+"_contact_"+rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            partner_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            sid = partner_pool.search(cr, uid, [('name', '=', rec.get('Name'))])
-            for i in sid:
-                partner_pool.write(cr, uid, i, {'address': [(6, 0, addIds)]}, context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def claimPriorityMapping(sf_obj, cr, uid, rating, context):
-    '''
-    Helper M                    'partner_id/id': 'Contact.Id',
-                    'priority': 'Priority',
-                    'user_id/id': 'Owner.Id',ethod to Priority of Lead/Opportunity
-    '''
-    if context == None:
-        context = {}
-
-    priMap = {
-        'High': '2',
-        'Medium': '3',
-        'Low': '4',
+      
+      
+    Claimpriority = {
+        'High' : '2',
+        'Medium' : '1',
+        'Low' : '3',
     }
-    return priMap.get(rating, '4')
-
-
-def claimStateMapping(sf_obj, cr, uid, state, context):
-    '''
-    Helper Method to resolve State dependency.
-    '''
-    if context == None:
-        context = {}
-
-    stateMap = {
+    
+    claim_state_map = {
         'New': 'draft',
         'Working': 'open',
         'Escalated ': 'done',
         'Closed': 'cancel',
     }
-    return stateMap.get(state, False)
-
-
-def importCaseComment(sf_obj, cr, uid, sfc, context):
-    if context == None:
-        context = {}
-
-    message_pool = sf_obj.pool.get('mailgate.message')
-    data_pool = sf_obj.pool.get('ir.model.data')
-    try:
-        sqlStmt = prepareStatement(MODEL_MAP.get('casecomment').get('field_map'), 'CaseComment')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields = MODEL_MAP.get('casecomment').get('field_map')
-            claims = data_pool.search(cr, uid, [('model', '=', 'crm.claim'), ('name', '=', INSTANCE+"_case_"+rec.get('ParentId'))])
-            if claims:
-                res = data_pool.browse(cr, uid, claims[0], context)
-                fields.update({'model': 'model',
-                               'description': 'description'})
-                rec.update({'model': 'crm.claim',
-                            'ParentId': res.res_id,
-                            'description': rec.get('CommentBody', '')})
-                rec.update({'Id': INSTANCE+"_casecomment_"+rec.get('Id')})
-                field, data = dataMapping(rec, fields)
-                message_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-                fields.pop('model')
-                fields.pop('description')
-            else:
-                continue
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importCase(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    claim_pool = sf_obj.pool.get('crm.claim')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('case').get('field_map'), 'Case')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            rec.update({'Priority': claimPriorityMapping(sf_obj, cr, uid, rec.get('Priority', False), context)})
-            rec.update({'Status': claimStateMapping(sf_obj, cr, uid, rec.get('Status', False), context)})
-            user_id = getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)
-            if user_id:
-                rec.update({'Owner.Id': INSTANCE+"_user_"+user_id})
-            else:
-                rec.update({'Owner.Id': False})
-            contact_id = getUserId(sf_obj, cr, uid, rec.get('Contact', False), context)
-            if contact_id:
-                rec.update({'Contact.Id': INSTANCE+"_contact_"+contact_id})
-            else:
-                rec.update({'Contact.Id': False})
-            rec.update({'Id': INSTANCE+"_case_"+rec.get('Id')})
-            field, data = dataMapping(rec, MODEL_MAP.get('case').get('field_map'))
-            claim_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-        importCaseComment(sf_obj, cr, uid, sfc, context)
-
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def getRecurrancy(sf_obj, cr, uid, rec, fields, context):
-    if context == None:
-        context = {}
-
-    rrule_type = {
-        'RecursEveryWeekday': 'daily',
-        'RecursDaily': 'daily',
-        'RecursWeekly': 'weekly',
-        'RecursMonthlyNth': 'monthly',
-        'RecursMonthly': 'monthly',
-        'RecursYearlyNth': 'yearly',
-    }
-    week_list = {1: 'MO',
-                    2: 'TU',
-                    4: 'WE',
-                    8: 'TH',
-                    16: 'FR',
-                    32: 'SA',
-                    64: 'SU'}
-
-    byday = {'First': '1',
-            'Second': '2',
-            'Third': '3',
-            'Fourth': '4',
-            'Last': '-1', }
-    if rec.get('RecurrenceType') == 'RecursMonthlyNth':
-        fields.update({'select1': 'select1'})
-        rec.update({'select1': 'day'})
-        rec.update({'RecurrenceDayOfWeekMask': week_list.get(rec.get('RecurrenceDayOfWeekMask'))})
-        rec.update({'RecurrenceInstance': byday.get(rec.get('RecurrenceInstance'))})
-        rec.update({'RecurrenceDayOfMonth': False})
-
-    if rec.get('RecurrenceType') == 'RecursMonthly':
-        fields.update({'select1': 'select1'})
-        rec.update({'select1': 'date'})
-        rec.update({'RecurrenceDayOfMonth': rec.get('RecurrenceDayOfMonth')})
-        rec.update({'RecurrenceDayOfWeekMask': False})
-        rec.update({'RecurrenceInstance': False})
-
-    if rec.get('RecurrenceType') == 'RecursYearlyNth':
-        rec.update({'RecurrenceDayOfWeekMask': False})
-        rec.update({'RecurrenceInstance': False})
-    rec.update({'RecurrenceType': rrule_type.get(rec.get('RecurrenceType'))})
-    return rec, fields
-
-
-def getPartnerId(sf_obj, cr, uid, rec, context):
-    if context == None:
-        context = {}
-
-    if rec.get('WhoId', False):
-        model_pool = sf_obj.pool.get('ir.model.data')
-        model_data_ids = model_pool.search(cr, uid, [('model', '=', 'res.partner'), ('name', 'like', INSTANCE+"_contact_"+rec.get('WhoId'))])
-        if model_data_ids:
-            return INSTANCE+"_contact_"+rec.get('WhoId')
-    return False
-
-
-def getEventUser(sf_obj, cr, uid, rec, context):
-    if context == None:
-        context = {}
-
-    model_pool = sf_obj.pool.get('ir.model.data')
-    user = email = address = False
-    model_partner_id = model_pool.search(cr, uid, [('name', '=', INSTANCE+"_contact_"+rec.get('AttendeeId', False))])
-    if model_partner_id:
-        res = model_pool.browse(cr, uid, model_partner_id[0])
-        record = sf_obj.pool.get(res.model).browse(cr, uid, res.res_id)
-        if res.model == 'res.users':
-            email, user, address = record.user_email, record.id, record.address_id
-        if res.model == 'crm.lead':
-            email, user, address = record.email_from, record.user_id.id, record.user_id.address_id
-        if res.model == 'res.partner':
-            for add in record.address:
-                if add.type == 'contact':
-                    email, address = add.email, add.id
-    return user, email, address
-
-
-def getAttendee(sf_obj, cr, uid, sfc, context):
-    if context == None:
-        context = {}
-
-    attendee_pool = sf_obj.pool.get('calendar.attendee')
-    model_pool = sf_obj.pool.get('ir.model.data')
-    meeting_pool = sf_obj.pool.get('crm.meeting')
-    fields = {
-            'id': 'Id',
-            'state': 'Status',
-            'partner_id/id': 'AttendeeId',
-            'parent_ids/id': 'EventId',
-            }
-    stats = {
-        'New': 'needs-action',
-        'Declined': 'decliene',
-        'Accepted': 'accepted',
-        'Maybe': 'tentative',
-        'Deleted': 'delegated',
-    }
-
-    try:
-        sqlStmt = prepareStatement(fields, 'EventAttendee')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            user, email, address = getEventUser(sf_obj, cr, uid, rec, context)
-            fields.update({'user_id/.id': 'user_id', 'email': 'email', 'partner_address_id/.id': 'address_id'})
-            rec.update({'user_id': user, 'email': email, 'address_id': address})
-            parent_id = rec.pop('EventId')
-            rec.pop('AttendeeId')
-            rec.update({'Status': stats.get(rec.get('Status'))})
-            rec.update({'Id': INSTANCE +"_eventattendee_"+ rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            attendee_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            fields.pop('user_id/.id')
-            fields.pop('email')
-            fields.pop('partner_address_id/.id')
-            model_data_ids = model_pool.search(cr, uid, [('model', '=', 'crm.meeting'), ('name', '=', INSTANCE+"_event_"+parent_id)])
-            att_id = model_pool.search(cr, uid, [('model', '=', 'calendar.attendee'), ('name', '=', rec.get('Id'))])
-            if model_data_ids and att_id:
-                meeting = model_pool.browse(cr, uid, model_data_ids[0])
-                attendee = model_pool.browse(cr, uid, att_id[0])
-                meeting_pool.write(cr, uid, [meeting.res_id], {'attendee_ids': [(4, (attendee.res_id))]})
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importEvent(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    meeting_pool = sf_obj.pool.get('crm.meeting')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        sqlStmt = prepareStatement(MODEL_MAP.get('event').get('field_map'), 'Event')
-        sfVals = sfc.query(sqlStmt)
-        new_sfVals = []
-        for i in sfVals:
-            if not i.get("RecurrenceActivityId") or i.get('Id') == i.get("RecurrenceActivityId"):
-                new_sfVals.append(i)
-        for rec in new_sfVals:
-            fields= MODEL_MAP.get('event').get('field_map')
-            rec.pop('RecurrenceActivityId')
-            recurrence = '0'
-            if rec.get('IsRecurrence'):
-                recurrence = '1'
-                fields.update({'end_type': 'end_type'})
-                rec, fields = getRecurrancy(sf_obj, cr, uid, rec, fields, context)
-                rec.update({'end_type': 'end_date'})
-                rec.update({'RecurrenceEndDateOnly': rec.get('RecurrenceEndDateOnly').strftime(DATETIME_FORMAT)})
-            rec.update({'IsRecurrence': recurrence})
-            allday = '0'
-            if rec.get('IsAllDayEvent'):
-                allday = '1'
-            rec.update({'IsAllDayEvent': allday})
-            privacy = 'public'
-            if rec.get('IsPrivate'):
-                privacy = 'private'
-            rec.update({'class': privacy})
-            if rec.get('ShowAs'):
-                rec.update({'class': rec.get('ShowAs').lower()})
-            user_id = getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)
-            if user_id:
-                rec.update({'Owner.Id': INSTANCE+"_user_"+user_id})
-            else:
-                rec.update({'Owner.Id': False})
-            rec.update({'StartDateTime': rec.get('StartDateTime').strftime(DATETIME_FORMAT)})
-            rec.update({'EndDateTime': rec.get('EndDateTime').strftime(DATETIME_FORMAT)})
-            rec.update({'WhoId': getPartnerId(sf_obj, cr, uid, rec, context)})
-            rec.update({'Subject': rec.get('Subject')[0]})
-            rec.update({'Id': INSTANCE +"_event_"+ rec.get('Id')})
-            field, data = dataMapping(rec, fields)
-            meeting_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-            if 'end_type' in fields:
-                fields.pop('end_type')
-            if 'select1' in fields:
-                fields.pop('select1')
-        getAttendee(sf_obj, cr, uid, sfc, context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def createActivity(sf_obj, cr, uid, fields, rec, model, context):
-    if context == None:
-        context = {}
-
-    model_pool = sf_obj.pool.get(model)
-    try:
-        rec.update({'Subject': rec.get('Subject')[0]})
-        field, data = dataMapping(rec, fields)
-        model_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-        if 'categ_id/.id' in fields:
-            fields.pop('categ_id/.id')
-        if 'partner_id/.id' in fields:
-            fields.pop('partner_id/.id')
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importActivity(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-
-    cate_pool = sf_obj.pool.get('crm.case.categ')
-    modeldata_pool = sf_obj.pool.get('ir.model.data')
-    model_pool = sf_obj.pool.get('ir.model')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        fields = MODEL_MAP.get('task').get('field_map')
-        if ACT_TYPE == 'wtype':
-            fields.update({'Type': 'Type'})
-        sqlStmt = prepareStatement(fields, 'Task')
-        sfVals = sfc.query(sqlStmt)
-        modelDict = {
-            'Email': 'mailgate.message',
-            'Call': 'crm.phonecall',
-            'Meeting': 'crm.meeting',
-            'Other': 'crm.meeting',
-        }
-        meetmodel_id = model_pool.search(cr, uid, [('model', '=', 'crm.meeting')])
-        cate_ids = cate_pool.search(cr, uid, [('name', '=', 'Task')])
-        nid = cate_ids and cate_ids[0] or False
-        if not cate_ids:
-            nid = cate_pool.create(cr, uid, {'name': 'Task', 'object_id': meetmodel_id[0]})
-        for rec in sfVals:
-            model = 'crm.meeting'
-            if 'Type'in rec:
-                typ = rec.pop('Type')
-                if typ:
-                    model = modelDict.get(typ)
-                if typ == 'Call':
-                    ids = cate_pool.search(cr, uid, [('name', '=', 'Inbound')])
-                    if ids:
-                        fields.update({'categ_id/.id': 'category'})
-                        fields.update({'partner_id/id': 'partner'})
-                        rec.update({'category': ids[0]})
-                        rec.update({'partner': rec.get('WhoId')})
-                    if rec.get('WhatId'):
-                        fields.update({'opportunity_id/id': 'WhatId'})
-                if typ == 'Email':
-                    if rec.get('WhoId'):
-                        data_id = modeldata_pool.search(cr, uid, [('name', 'like', INSTANCE+rec.get('WhoId'))])
-                        if data_id:
-                            model_rec = modeldata_pool.browse(cr, uid, data_id[0])
-                            fields.update({'model': 'model'})
-                            fields.update({'res_id': 'res_id'})
-                            rec.update({'model': model_rec.model})
-                            rec.update({'res_id': model_rec.res_id})
-                    elif rec.get('WhatId'):
-                        data_id = modeldata_pool.search(cr, uid, [('name', 'like', INSTANCE+rec.get('WhatId'))])
-                        if data_id:
-                            model_rec = modeldata_pool.browse(cr, uid, data_id[0])
-                            fields.update({'model': 'model'})
-                            fields.update({'res_id': 'res_id'})
-                            rec.update({'model': model_rec.model})
-                            rec.update({'res_id': model_rec.res_id})
-                else:
-                    fields.update({'categ_id/.id': 'category'})
-                    rec.update({'category': nid})
-                rec.pop('WhatId')
-                rec.pop('WhoId')
-            else:
-                fields.update({'categ_id/.id': 'category_id'})
-                rec.update({'category_id': nid})
-                if rec.get('WhoId', False):
-                    data_id = modeldata_pool.search(cr, uid, [('name', '=', INSTANCE+"_contact_"+rec.get('WhoId')), ('model', '=', 'res.partner')])
-                    if data_id:
-                        model_rec = modeldata_pool.browse(cr, uid, data_id[0])
-                        fields.update({'partner_id/.id': 'partner'})
-                        rec.update({'partner': model_rec.res_id})
-            if 'WhatId' in rec:
-                rec.pop('WhatId')
-            if 'WhoId' in rec:
-                rec.pop('WhoId')
-            if rec.get('ActivityDate'):
-                rec.update({'ActivityDate': rec.get('ActivityDate').strftime(DATETIME_FORMAT)})
-            user_id = getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)
-            if user_id:
-                rec.update({'Owner.Id': INSTANCE+"_user_"+user_id})
-            else:
-                rec.update({'Owner.Id': False})
-            rec.update({'ActivityDate': datetime.now().strftime(DATETIME_FORMAT)})
-            createActivity(sf_obj, cr, uid, fields, rec, model, context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importFolder(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-    document_pool = sf_obj.pool.get('document.directory')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        fields = MODEL_MAP.get('folder').get('field_map')
-        sqlStmt = prepareStatement(fields, 'Folder')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            if rec.get('Type', False) == 'Document':
-                rec.update({'Type': 'directory'})
-                rec.update({'Id': INSTANCE +"_folder_"+ rec.get('Id')})
-                field, data = dataMapping(rec, fields)
-                document_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-def importDocument(sf_obj, cr, uid, context):
-    if context == None:
-        context = {}
-    attachment_pool = sf_obj.pool.get('ir.attachment')
-    try:
-        sfc = beatbox.PythonClient()
-        sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        fields = MODEL_MAP.get('document').get('field_map')
-        sqlStmt = prepareStatement(fields, 'Document')
-        sfVals = sfc.query(sqlStmt)
-        for rec in sfVals:
-            fields.update({'datas': 'Body'})
-            if rec.get('Type', False) == 'URL':
-                rec.update({'Type': 'url'})
-            else:
-                rec.update({'Type': 'binary'})
-                data = sfc.query("SELECT Body FROM Document WHERE id='%s'"%(rec.get('Id')))
-                if data:
-                    data = data[0]
-                    rec.update({'Body': data.get('Body')})
-            rec.update({'Id': INSTANCE +"_document_"+ rec.get('Id'),
-                        'AuthorId': INSTANCE +"_user_"+ rec.get('AuthorId'),
-                        })
-            field, data = dataMapping(rec, fields)
-            attachment_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
-
-    except SoapFaultError, sfe:
-        log = logging.getLogger('import.salesforce.SoapFaultError')
-        log.warning(str(sfe))
-        return False
-    except Exception, e:
-        log = logging.getLogger('import.salesforce')
-        log.warning(str(e))
-        return False
-    return True
-
-
-MODEL_MAP = {
-    'user': {
-        'dependencies': [],
-        'function': importUser,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Name',
-                        'login': 'Username',
-                        'user_email': 'Email',
-                        'context_tz': 'TimeZoneSidKey',
-                        'context_lang': 'LanguageLocaleKey',
-                 }
-    },
-    'attachment': {
-        'dependencies': ['user'],
-        'function': importAttachment,
-        'field_map': {
-                    'id': 'Id',
-                    'name': 'Name',
-                    'datas': 'Body',
-                    'description': 'Description',
-                    'res_id/.id': 'ParentId',
-            }
-    },
-    'note': {
-        'dependencies': [],
-        'function': importNote,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Title',
-                        'res_id/.id': 'ParentId',
-                        'description': 'Body',
-                    }
-    },
-    'opportunity': {
-        'dependencies': ['contact', 'user'],
-        'function': importOpportunity,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Name',
-                        'user_id/id': 'CreatedBy.Id',
-                        'planned_revenue': 'Amount',
-                        'probability': 'Probability',
-                        'title_action': 'NextStep',
-                        'type': 'type',
-                        'stage_id/.id': 'StageName',
-                        'partner_id/.id': 'AccountId',
-                        'channel_id/.id': 'LeadSource',
-                    }
-    },
-    'opportunityhistory': {
-        'dependencies': [],
-        'function': importOpportunityHistory,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'StageName',
-                        'date': 'CloseDate',
-                        'res_id/.id': 'OpportunityId',
-                    }
-    },
-    'lead': {
-        'dependencies': ['user'],
-        'function': importLead,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Company',
-                        'priority': 'Rating',
-                        'user_id/id': 'CreatedBy.Id',
-                        'stage_id/.id': 'Status',
-                        'partner_name': 'Company',
-                        'contact_name': 'Name',
-                        'title/.id': 'Salutation',
-                        'function': 'Title',
-                        'street': 'Street',
-                        'city': 'City',
-                        'email_from': 'Email',
-                        'phone': 'Phone',
-                        'mobile': 'MobilePhone',
-                        'zip': 'PostalCode',
-                        'description': 'Description',
-                        'state_id/.id': 'State',
-                        'country_id/.id': 'Country',
-                        'channel_id/.id': 'LeadSource',
-                }
-    },
-    'contact': {
-        'dependencies': [],
-        'function': importContact,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Name',
-                        'title/.id': 'Title',
-                        'email': 'Email',
-                        'cstreet': 'MailingStreet',
-                        'ccity': 'MailingCity',
-                        'cphone': 'Phone',
-                        'cmobile': 'MobilePhone',
-                        'czip': 'MailingPostalCode',
-                        'cstate_id': 'MailingState',
-                        'ccountry_id': 'MailingCountry',
-                        'cfax': 'Fax',
-                        'ostreet': 'OtherStreet',
-                        'ocity': 'OtherCity',
-                        'ocountry_id': 'OtherCountry',
-                        'ostate_id': 'OtherState',
-                        'ozip': 'OtherPostalCode',
-                        'ophone': 'OtherPhone',
-                        'bstreet': 'Account.BillingStreet',
-                        'bcity': 'Account.BillingCity',
-                        'bcountry_id': 'Account.BillingCountry',
-                        'bstate_id': 'Account.BillingState',
-                        'bzip': 'Account.BillingPostalCode',
-                        'sstreet': 'Account.ShippingStreet',
-                        'scity': 'Account.ShippingCity',
-                        'scountry_id': 'Account.ShippingCountry',
-                        'sstate_id': 'Account.ShippingState',
-                        'szip': 'Account.ShippingPostalCode',
-                }
-    },
-    'case': {
-        'dependencies': ['user', 'contact'],
-        'function': importCase,
-        'field_map': {
-                    'id': 'Id',
-                    'name': 'Subject',
-                    'partner_id/id': 'Contact.Id',
-                    'priority': 'Priority',
-                    'user_id/id': 'Owner.Id',
-                    'description': 'Description',
-                    'email_from': 'SuppliedEmail',
-                    'partner_phone': 'SuppliedPhone',
-                    'user_fault': 'SuppliedName',
-                    'state': 'Status',
-            }
-    },
-    'casecomment': {
-        'dependencies': [],
-        'function': importCaseComment,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'CommentBody',
-                        'res_id': 'ParentId',
-                    }
-    },
-    'event': {
-        'dependencies': ['user', 'contact'],
-        'function': importEvent,
-        'field_map': {
-                    'id': 'Id',
-                    'name': 'Subject',
-                    'user_id/id': 'Owner.Id',
-                    'allday': 'IsAllDayEvent',
-                    'date': 'StartDateTime',
-                    'date_deadline': 'EndDateTime',
-                    'location': 'Location',
-                    'duration': 'DurationInMinutes',
-                    'description': 'Description',
-                    'show_as': 'ShowAs',
-                    'class': 'IsPrivate',
-                    'recurrency': 'IsRecurrence',
-                    'rrule_type': 'RecurrenceType',
-                    'interval': 'RecurrenceInterval',
-                    'end_date': 'RecurrenceEndDateOnly',
-                    'week_list': 'RecurrenceDayOfWeekMask',
-                    'day': 'RecurrenceDayOfMonth',
-                    'byday': 'RecurrenceInstance',
-                    'repeat_id': 'RecurrenceActivityId',
-                    'partner_id/id': 'WhoId',
-            }
-    },
-    'task': {
-        'dependencies': ['lead', 'contact', 'opportunity'],
-        'function': importActivity,
-        'field_map': {
-                    'id': 'Id',
-                    'name': 'Subject',
-                    'user_id/id': 'Owner.Id',
-                    'date': 'ActivityDate',
-                    'duration': 'CallDurationInSeconds',
-                    'description': 'Description',
-                    'WhatId': 'WhatId',
-                    'WhoId': 'WhoId',
-            }
-    },
-    'folder': {
-        'dependencies': ['user'],
-        'function': importFolder,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Name',
-                        'type': 'Type',
-                    }
-    },
-    'document': {
-        'dependencies': ['folder', 'user'],
-        'function': importDocument,
-        'field_map': {
-                        'id': 'Id',
-                        'name': 'Name',
-                        'type': 'Type',
-                        'user_id/id': 'AuthorId',
+    def get_partner_detail(self, val):
+        partner_pool = self.obj.pool.get('res.partner')
+        address_pool = self.obj.pool.get('res.partner.address')
+        if val.get('ContactId'):
+            partner_id = self.get_mapped_id(self.TABLE_CONTACT, val.get('ContactId'))
+            if partner_id:
+                partner = partner_pool.browse(self.cr, self.uid, partner_id)
+                address = partner_pool.address_get(self.cr, self.uid, [partner_id],['contact'])
+                address_rec = address_pool.browse(self.cr, self.uid, address['contact'])
+                val.update({'partner_address_id': address['contact'],
+                            'email_from': address_rec.email,
+                            'partner_phone': address_rec.phone,})
+        return val
+
+    def get_claim_close_date(self, val):
+        if val.get('ClosedDate'):
+            return val.get('ClosedDate').strftime(self.DATETIME_FORMAT)
+        return False
+        
+    def get_claim_mapping(self):
+        return {
+                'model': 'crm.claim',
+                'dependencies': [self.TABLE_USER, self.TABLE_CONTACT],
+                'hook': self.get_partner_detail,
+                'map': {
+                    'id': 'Id',
+                    'name': concat('CaseNumber', 'Subject'),
+                    'user_id/id': ref(self.TABLE_USER,'OwnerId'),
+                    'description': 'Description',
+                    'date_closed' : self.get_claim_close_date,
+                    'partner_id/id': ref(self.TABLE_CONTACT , 'ContactId'),
+                    'partner_address_id/.id': 'partner_address_id',
+                    'partner_phone': 'partner_phone',
+                    'email_from': 'email_from',
+                    'priority' : map_val('Priority',self.Claimpriority),
+                    'stage_id/id' : call(self.get_status, value('Status'), 'claim'),
+                    'state': map_val('Status', self.claim_state_map, default='draft')
+                }
+        }
+        
+        
+    def get_duration(self,val):
+        return val.get('DurationInMinutes')/60
+
+    def get_date(self, val, field):
+        date = datetime.datetime.now().strftime(self.DATETIME_FORMAT)
+        if field:
+            date = field.strftime(self.DATETIME_FORMAT)
+        return date
+    
+    boolean_map = {
+        True: '1',
+        False: '0',
+    }
+    
+    def get_event(self, val):
+        if val.get('WhoId'):
+            partner_pool = self.obj.pool.get('res.partner')
+            address_pool = self.obj.pool.get('res.partner.address')
+            contact = self.xml_id_exist(self.TABLE_CONTACT, val.get('WhoId'))
+            if contact:
+                partner_id = self.get_mapped_id(self.TABLE_CONTACT, val.get('WhoId'))
+                address = partner_pool.address_get(self.cr, self.uid, [partner_id],['contact'])
+                address_rec = address_pool.browse(self.cr, self.uid, address['contact'])
+                val.update({'PartnerId': partner_id,
+                            'ContactId': address['contact'],
+                            'Email': address_rec.email,})
+        return val
+    
+    def get_subject(self, val):
+        return val.get('Subject')[0]
+
+    
+    def get_attendee_contact(self, val):
+        if val.get('AttendeeId'):
+            partner_pool = self.obj.pool.get('res.partner')
+            address_pool = self.obj.pool.get('res.partner.address')
+            users_pool = self.obj.pool.get('res.users')
+            contact = self.xml_id_exist(self.TABLE_CONTACT, val.get('AttendeeId'))
+            if contact:
+                partner_id = self.get_mapped_id(self.TABLE_CONTACT, val.get('AttendeeId'))
+                address = partner_pool.address_get(self.cr, self.uid, [partner_id],['contact'])
+                address_rec = address_pool.browse(self.cr, self.uid, address['contact'])
+                val.update({'ContactId': address['contact'],
+                            'Email': address_rec.email,})
+            else:
+                user = self.xml_id_exist(self.TABLE_USER, val.get('AttendeeId'))
+                if user:
+                    user_id = self.get_mapped_id(self.TABLE_USER, val.get('AttendeeId'))
+                    user_rec = users_pool.browse(self.cr, self.uid, user_id)
+                    val.update({'UserId': user_id,
+                                'ContactId': user_rec.address_id,
+                                'Email': user_rec.user_email,})
+        return val
+
+    
+    def get_attendee(self, vals):
+        attendee_vals = self._SFCLIENT.query("SELECT Id, Status, AttendeeId,EventId FROM %s WHERE EventId = '%s'"%(self.TABLE_ATTENDEE, vals.get('Id')))
+        attendee_ids = [] 
+        fields= {
+                'id': 'Id',
+                'state': 'Status',
+                'user_id/.id': 'UserId',
+                'partner_address_id/.id': 'ContactId',
+                'email': 'Email',
+                }
+        stats_attendee = {
+            'New': 'needs-action',
+            'Declined': 'decliene',
+            'Accepted': 'accepted',
+            'Maybe': 'tentative',
+            'Deleted': 'delegated',
+        }
+        for attendee in attendee_vals:
+            self.get_attendee_contact(attendee)
+            attendee.update({'Status': stats_attendee.get('Status', 'needs-action')})
+            attendee.update({'id_new': attendee['Id'] + '_EventAttendee_'})
+            p = self.import_object_mapping(fields, attendee,  'calendar.attendee', self.TABLE_ATTENDEE, attendee.get('id_new'), self.DO_NOT_FIND_DOMAIN)
+            attendee_ids.append(p)
+        return ','.join(attendee_ids)
+
+    def get_meeting_mapping(self):
+        return {
+            'model': 'crm.meeting',
+            'dependencies': [self.TABLE_CONTACT, self.TABLE_USER],
+            'hook': self.get_event,
+            'map': {
+                    'id': 'Id',
+                    'name': call(self.get_subject),
+                    'description' : 'Description',
+                    'user_id/id' : ref(self.TABLE_USER,'OwnerId'),
+                    'partner_id/.id' : 'PartnerId',
+                    'partner_address_id/.id': 'ContactId',
+                    'email_from': 'Email',
+                    'location' : 'Location',
+                    'date' : call(self.get_date, value('StartDateTime')),
+                    'date_deadline' : call(self.get_date, value('EndDateTime')),
+                    'duration' : call(self.get_duration),
+                    'allday': map_val('IsAllDayEvent', self.boolean_map),
+                    'recurrency': map_val('IsRecurrence', self.boolean_map),
+                    'attendee_ids/id': self.get_attendee, 
+#                    'rrule_type': 'RecurrenceType',
+#                    'interval': 'RecurrenceInterval',
+#                    'end_date': 'RecurrenceEndDateOnly',
+#                    'week_list': 'RecurrenceDayOfWeekMask',
+#                    'day': 'RecurrenceDayOfMonth',
+#                    'byday': 'RecurrenceInstance',
+                }
+        }
+        
+    def get_attachment_datas(self, val):
+        data = self._SFCLIENT.query("SELECT Body FROM Attachment WHERE id='%s'"%(val.get('Id')))
+        if data:
+            data = data[0]
+            return data.get('Body', False)
+    
+    def improt_attachment(self, val):
+        lookup = {self.TABLE_USER: 'res.users',
+                  self.TABLE_CONTACT: 'res.partner', 
+                  self.TABLE_LEAD: 'crm.lead', 
+                  self.TABLE_OPPORTUNITY: 'crm.lead',
+                  self.TABLE_CLAIM: 'crm.claim', 
+                  self.TABLE_MEETING: 'crm.meeting'}
+        for look in lookup:
+            xmlid = self.xml_id_exist(look, val.get('ParentId'))
+            if xmlid:
+                res_id = self.get_mapped_id(look, val.get('ParentId'))
+                val.update({'Model': lookup.get(look),
+                            'ResourceId':res_id})
+        return val
+    
+    def get_attachment_mapping(self):
+        return {
+            'model': 'ir.attachment',
+            'dependencies': [self.TABLE_USER, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_CLAIM, self.TABLE_MEETING],
+            'hook': self.improt_attachment,
+            'map': {
+                        'id': 'Id',
+                        'name': 'Name',
+                        'user_id/id': ref(self.TABLE_USER, 'OwnerId'),
+                        'datas': call(self.get_attachment_datas),
                         'datas_fname': 'Name',
+                        'res_model': 'Model',
+                        'res_id': 'ResourceId',
                         'description': 'Description',
-                        'url': 'Url',
                     }
-    },
-}
-
-LOGIN_DATA = {
-    'username': None,
-    'passToken': None,
-}
-
-
-class import_sf(osv.osv):
+        }
+
+    def get_duration(self, val):
+        if 'CallDurationInSeconds' in val and val.get('CallDurationInSeconds'):
+            return val.get('CallDurationInSeconds')/60
+        return False
+
+    def get_category(self, val, model, name):
+        fields = ['name', 'object_id']
+        data = [name, model]
+        return self.import_object(fields, data, 'crm.case.categ', self.TABLE_STAGE, name, [('object_id.model','=',model), ('name', '=', name)])
+
+    def import_tasks_partner(self, val):
+        if val.get('WhoId'):
+            partner_pool = self.obj.pool.get('res.partner')
+            address_pool = self.obj.pool.get('res.partner.address')
+            users_pool = self.obj.pool.get('res.users')
+            contact = self.xml_id_exist(self.TABLE_CONTACT, val.get('WhoId'))
+            if contact:
+                partner_id = self.get_mapped_id(self.TABLE_CONTACT, val.get('WhoId'))
+                address = partner_pool.address_get(self.cr, self.uid, [partner_id],['contact'])
+                address_rec = address_pool.browse(self.cr, self.uid, address['contact'])
+                val.update({'PartnerId': partner_id,
+                            'ContactId': address.get('contact', False), 
+                            'Email': address_rec.email})
+        return val
+        
+    def get_task_mapping(self):
+        return {
+            'model': 'crm.meeting',
+            'dependencies': [self.TABLE_CONTACT, self.TABLE_USER],
+            'hook': self.import_tasks_partner,
+            'map': {
+                    'id': 'Id',
+                    'name': self.get_subject,
+                    'user_id/id': ref(self.TABLE_USER, 'OwnerId'),
+#                    'catag_id/id': call(self.get_category, 'crm.meeting', const('Tasks')),
+                    'date': call(self.get_date, value('ActivityDate')),
+                    'duration': self.get_duration,
+                    'description': 'Description',
+                    'partner_id/.id' : 'PartnerId',
+                    'partner_address_id/.id': 'ContactId',
+                    'email_from': 'Email',
+            }
+        }
+
+class import_salesforce(osv.osv):
     '''
         Model to Select SalesForce Model to be imported
     '''
-    _name = 'import.sf'
+    _name = 'import.salesforce'
     _description = 'Import SalesForce Data'
 
     _columns = {
-        'file_path': fields.binary('Select CSV file', filters='*.csv,*.xls'),
-        'username': fields.char('Username/Email', size=255, help="Salesforce User name/login Name"),
+        'name': fields.char('Username/Email', size=255, help="Salesforce User name/login Name"),
         'password': fields.char('Password', size=255, help="Password for above User"),
         'token': fields.char('Security Token', size=255, help="Security Token generated by salesforce for user."),
-        'model_list': fields.selection(MODEL_LIST, 'Model'),
         'lead': fields.boolean('Leads', help="If Leads is checked, SalesFroce Leads data imported to OpenERP CRM Leads"),
         'opportunity': fields.boolean('Opportunities', help="If Opportunity is checked, SalesForce Leads data imported to OpenERP CRM Opportunity."),
         'users': fields.boolean('User', help="If Users is checked, SalesFroce Users data imported to OpenERP Users."),
@@ -1355,24 +740,11 @@
         'document': fields.boolean('Document', help="If Documents checked, SalesFroce Folder data imported to OpenERP Document."),
         'attachment': fields.boolean('Attachments', help="If Attachments is checked, SalesFroce attachments data  will imported to OpenERP Attachment, and if resource of the attachment is imported and it will linked to the respective documents."),
         'task': fields.boolean('Acivity', help="If Activity is checked, SalesFroce Activity data  will imported to OpenERP Meetings and if you want to import data according to the type in Task to repective model than select 'With Type' from below slection and Give Field level security of the Type Field in SalesForce.\nSalesForce Activity is comprised of Email, Call, Meeting."),
-        'task_type': fields.selection([('wttype', 'Without Type'), ('wtype', 'With Type')], 'Activity Type', invisible=True, help="In SalesForce Acivity > Task,  the Field Lavel Security of the field 'Type' is set for all user levels than select the 'Without Type' option else select 'With Type' option."),
-        'model': fields.char('Model', size=255, help="Name of model whose function will be called when this scheduler will run. e.g. 'res.partener'"),
-        'function': fields.char('Function', size=255, help="Name of the method to be called on the model when this scheduler is executed."),
-        'interval_number': fields.integer('Interval Number', help="Repeat every x interval."),
-        'interval_type': fields.selection([('minutes', 'Minutes'), ('hours', 'Hours'), ('work_days', 'Work Days'), ('days', 'Days'), ('weeks', 'Weeks'), ('months', 'Months')], 'Interval Unit'),
-        'numbercall': fields.integer('Number of Calls', help='Number of time the function is called,\na negative number indicates no limit'),
-        'nextcall': fields.datetime('Next Execution Date', required=True, help="Next planned execution date for this scheduler"),
         'email': fields.char('Email address to notify', size=128, help="On Successful import the Email is Send to the mention email address."),
         'instance_name': fields.char('Instance Name', required=True, size=128, help="Instance name will be used to separate import from multiple salesforce login instance."),
     }
 
     _defaults = {
-        'model': 'import.sf',
-        'function': '_do_import',
-        'interval_number': lambda *x: 6,
-        'interval_type': 'months',
-        'numbercall': lambda *x: 2,
-        'nextcall': lambda *x: time.strftime("%Y-%m-%d %H:%M:%S"),
         'instance_name': 'salesforce',
     }
 
@@ -1383,154 +755,77 @@
         nodes = []
         for current in self.browse(cr, uid, ids, context):
             if current.lead:
-                nodes.append('lead')
+                nodes.append('Lead')
             if current.opportunity:
-                nodes.append('opportunity')
+                nodes.append('Opportunity')
             if current.users:
-                nodes.append('user')
+                nodes.append('User')
             if current.contact:
-                nodes.append('contact')
+                nodes.append('Contact')
             if current.case:
-                nodes.append('case')
+                nodes.append('Case')
             if current.event:
-                nodes.append('event')
+                nodes.append('Event')
             if current.task:
-                nodes.append('task')
-                global ACT_TYPE
-                ACT_TYPE = current.task_type
+                nodes.append('Task')
             if current.attachment:
-                nodes.append('attachment')
+                nodes.append('Attachment')
             if current.folder:
-                nodes.append('folder')
+                nodes.append('Folder')
             if current.document:
-                nodes.append('document')
+                nodes.append('Document')
         return nodes
 
-    def resolve_dependencies(self, cr, uid, model_map, dep, visited, flag, context=None):
-        '''
-        Method to Reolve the Dependencies of the Model to be imported.
-        @uid        : Current UserID
-        @model_map  : Fieald Mapping Dict
-        @dep        : Dependencies List
-        @visited    : Set of Visited Nodes
-        @flag       : To Track Successfull Import
-        '''
-        if context == None:
-            context = {}
-        flag = flag
-        for dependency in dep:
-            if not dependency in visited:
-                self.resolve_dependencies(cr, uid, model_map, model_map[dependency]['dependencies'], visited, flag, context=context)
-                flag = model_map[dependency]['function'](self, cr, uid, context)
-                visited.add(dependency)
-        return flag
-
-    def _do_import(self, cr, uid, *args):
+
+    def import_all(self, cr, uid, ids, context=None):
+        """Import all salesforce data into openerp module"""
+        tables = self._get_nodes(cr, uid, ids, context)
+        if not tables:
+            raise osv.except_osv(_('Warning !'), _('Please check one or more model to begin import.'))
+        for current in self.browse(cr, uid, ids, context):
+            context.update({'username':current.name,
+                            'passtoken' : current.password+current.token})
+            instance = current.instance_name
+            mail = current.email
+        imp = salesforce_import(self, cr, uid, instance, "import_salesforce", [mail], context)
+        imp.set_table_list(tables)
+        imp.start()
+
+        context.update({'message': "Data Imported Successfully from Salesforce."})
+        model_pool = self.pool.get('ir.model.data')
+
+        model_data_ids = model_pool.search(cr,uid,[('model','=','ir.ui.view'),('name','=','sf.import.message.form')])
+        resource_id = model_pool.read(cr, uid, model_data_ids, fields=['res_id'])
+        return {
+                'view_type': 'form',
+                'view_mode': 'form',
+                'res_model': 'sf.import.message',
+                'views': [(resource_id,'form')],
+                'type': 'ir.actions.act_window',
+                'target': 'new',
+                'context': context
+            }
+
+    def _import_all(self, cr, uid, *args):
         ''''
         Method to be called by IrCron Job to initiate importing the data process
         @uid : Current Userid
         @args : it can have three parts
                 args[0] : list to model name to be imported
-                args[1] : Activty Type Field Detail
-                args[2] : SalesForce Login Deatil Id for the Schedular
+                args[1] : SalesForce Login Deatil Id for the Schedular
         '''
         context = {}
-        flag = False
         login_pool = self.pool.get('salesforce.login.services')
-        log = logging.getLogger('import.salesforce')
-        if args[2]:
-            try:
-                #Reloading new SF login configuration.
-                login = login_pool.browse(cr, uid, int(args[2]))
-                LOGIN_DATA.update({'username': login.name,
-                                   'passToken': login.password+login.token})
-                sf_model = args[0]
-                task_type = args[1]
-                if 'task' in sf_model:
-                    global ACT_TYPE
-                    ACT_TYPE = task_type and task_type[0] or 'wttype'
-                visited = set() #To avoid the Multiple call for resloving dependencies
-                flag = False
-                for model in sf_model:
-                    if not model in visited:
-                        flag = self.resolve_dependencies(cr, uid, MODEL_MAP, MODEL_MAP[model]['dependencies'], visited, flag, context=context)
-                        flag = MODEL_MAP[model]['function'](self, cr, uid, context)
-                        visited.add(model)
-            except Exception, e:
-                log.warning(str(e))
-
-        else:
-            log.warning("Invalid Login : Login information for the scheduler is missing.")
-        if flag:
-            log.info("Data Imported Successfully from SalesForce.")
-            if args[3]:
-                from_mail = tools.config.options['email_from'] or False
-                subject = "Data Imported Successfully from Salesforce,"
-                body = """Hello,\n\tFollowing Models has been imported Successfully " %s "\n on %s from salesforce with login %s.\n\nThank You for using OpenERP Import Salesforce module.\n---------\nOpenERP"""%(args[0], datetime.now().strftime(DATETIME_FORMAT), login.name)
-                tools.email_send(from_mail, [args[3]], subject, body)
-                log.info("Mail Send Successfully to %s ."%(args[0]))
-        else:
-            log.Warning("Unkown Error During Importing Data from SalesForce Check the server log for more.")
-        return flag
-
-    def sf_do_import(self, cr, uid, ids, context=None):
-        '''
-        Method to initiate data import from map dict
-        '''
-        if context == None:
-            context = {}
-        model_pool = self.pool.get('ir.model.data')
-
-        record = self.browse(cr, uid, ids, context=context)
-        choice = context.get('choice', False)
-        record = record[0]
-
-        LOGIN_DATA.update({'username': record.username,
-                           'passToken': record.password+record.token})
-
-        try:
-            sfc = beatbox.PythonClient()
-            sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        except SoapFaultError, sfe:
-            context.update({'message': '%s.\n%s'%(sfe.faultCode, str(sfe.faultString)), 'imported': False})
-        except:
-            context.update({'message': 'Unexpected end of message. Please check connectivity and permissions, and report a bug if problems persist.', 'imported': False})
-        sf_model = self._get_nodes(cr, uid, ids, context)
-        visited = set() #To avoid the Multiple call for resloving dependencies
-        flag = False
-        model_data_ids = model_pool.search(cr, uid, [('model', '=', 'ir.ui.view'), ('name', '=', 'sf.import.message.form')])
-        resource_id = model_pool.read(cr, uid, model_data_ids, fields=['res_id'])
-        #Import Via SalesForce WebServices
-        global INSTANCE
-        INSTANCE = record.instance_name
-        for model in sf_model:
-            if not model in visited:
-                flag = self.resolve_dependencies(cr, uid, MODEL_MAP, MODEL_MAP[model]['dependencies'], visited, flag, context=context)
-                flag = MODEL_MAP[model]['function'](self, cr, uid, context)
-                visited.add(model)
-        if flag:
-            message = "Data Imported Successfully from Salesforce."
-            to_mail = record.email
-            if to_mail:
-                from_mail = tools.config.options['email_from'] or False
-                subject = "Data Imported Successfully from Salesforce,"
-                body = """Hello,\n\tFollowing Models has been imported Successfully " %s "\n on %s from salesforce with login %s.\n\nThank You for using OpenERP Import Salesforce module.\n---------\nOpenERP"""%(', '.join(sf_model), datetime.now().strftime(DATETIME_FORMAT), record.username)
-                tools.email_send(from_mail, [to_mail], subject, body)
-                message += " Email Send Successfully to %s."%(to_mail)
-            else:
-                message += " No notification Email found so mail can not be send."
-            context.update({'message': message, 'imported': True})
-        else:
-            context.update({'message': 'Unexpected end of message. Please check connectivity and permissions, and report a bug if problems persist. For more check server log.', 'imported': False})
-        return {
-                'view_type': 'form',
-                'view_mode': 'form',
-                'res_model': 'sf.import.message',
-                'views': [(resource_id, 'form')],
-                'type': 'ir.actions.act_window',
-                'target': 'new',
-                'context': context,
-        }
+        if args[1]:
+            #Reloading new SF login configuration.
+            login = login_pool.browse(cr, uid, int(args[1]))
+            context.update({'username':login.name,
+                            'passtoken' : login.password+login.token})
+            imp = salesforce_import(self, cr, uid, login.instance, "import_salesforce", [login.email], context)
+            imp.set_table_list(args[0])
+            imp.start()
+
+
 
     def createCronJob(self, cr, uid, ids, context=None):
         if context == None:
@@ -1540,37 +835,32 @@
         model_pool = self.pool.get('ir.model.data')
         records = self.browse(cr, uid, ids, context=context)
         for record in records:
-            LOGIN_DATA.update({'username': record.username,
+            context.update({'username': record.name,
                            'passToken': record.password+record.token})
-
+        
         model_data_ids = model_pool.search(cr, uid, [('model', '=', 'ir.ui.view'), ('name', '=', 'ir.cron.form')])
         resource_id = model_pool.read(cr, uid, model_data_ids, fields=['res_id'])
 
         try:
             sfc = beatbox.PythonClient()
-            sfc, sflogin = getSFLogin(sfc, LOGIN_DATA.get('username'), LOGIN_DATA.get('passToken'))
-        except SoapFaultError, sfe:
-            raise osv.except_osv(_('Error !'), _('%s.\n%s')%(sfe.faultCode, str(sfe.faultString)))
+            sfc.login(context.get('username'), context.get('passToken'))
         except Exception, e:
-            raise osv.except_osv(_('Error !'), _('%s')%(e.value))
+            raise osv.except_osv(_('Error !'), _("Invalid Login"))
         vals = {}
         nodes = self._get_nodes(cr, uid, ids, context=None)
         if not nodes:
             raise osv.except_osv(_('Warning !'), _('No model is selected. select atleat one model.'))
-        task = []
-        if 'task' in nodes:
-            task=[record.task_type]
-        login_id = login_pool.create(cr, uid, {'name': record.username, 'password': record.password, 'token': record.token}, context=context)
+        login_id = login_pool.create(cr, uid, {'name': record.name, 'password': record.password, 'token': record.token, 'email': record.email, 'instance': record.instance_name}, context=context)
         if login_id:
-            args = (nodes, task, int(login_id), record.email)
+            args = (nodes, int(login_id))
             vals.update({'name': 'Import Salesforce Datas',
                          'interval_number': '6',
                          'interval_type': 'months',
                          'numbercall': '2',
                          'doall': False,
                          'active': False,
-                         'model': 'import.sf',
-                         'function': '_do_import',
+                         'model': 'import.salesforce',
+                         'function': '_import_all',
                          'args': args}),
             cron_id = cron_pool.create(cr, uid, vals, context=context)
         return {
@@ -1585,7 +875,7 @@
                 'nodestroy': False,
             }
 
-import_sf()
+import_salesforce()
 
 
 class salesforce_login_services(osv.osv):
@@ -1596,6 +886,8 @@
         'token': fields.char('Security Token', size=255),
         'name': fields.char('Username/Email', size=255),
         'password': fields.char('Password', size=255),
+        'email': fields.char('Notification Email', size=255),
+        'instance': fields.char('Instance Name', size=255),
     }
 salesforce_login_services()
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

=== modified file 'import_salesforce/wizard/import_salesforce_view.xml'
--- import_salesforce/wizard/import_salesforce_view.xml	2011-05-13 10:18:03 +0000
+++ import_salesforce/wizard/import_salesforce_view.xml	2011-05-23 11:27:52 +0000
@@ -6,52 +6,51 @@
 
         <!--Form View for the model import sf for webservices-->
         <record model="ir.ui.view" id="view_import_sf_webservice_form">
-            <field name="name">import.sf.webservice.form</field>
-            <field name="model">import.sf</field>
+            <field name="name">import.saleforce.webservice.form</field>
+            <field name="model">import.salesforce</field>
             <field name="type">form</field>
             <field name="arch" type="xml">
                 <form string="Import your data from Saleforce">
                     <group colspan="8" col="4">
                         <separator string="Login Information" colspan='4'/>
-                        <field name='username' colspan='4' required='True'/>
+                        <field name='name' colspan='4' required='True'/>
                         <field name='password' password='True' colspan='4' required='True'/>
                         <field name='token' password='True' colspan='4' required='True'/>
                     </group>
                     <group colspan="8" col="8">
                     <separator string="Choose The Data You Want To Import" colspan='8'/>
-                    <newline/>    
-                            <group colspan="4" col="4">
-                                <separator string="Base" colspan="2"/>
-                                <newline/> 
-                                <group colspan="2" col="2">
-                                    <field name="users"/>
-                                    <field name="contact"/>
-                                </group>
-                            </group>                
-                            <group colspan="4" col="4">
-                                <separator string="CRM" colspan="2"/>
-                                <newline/>
-                                <group colspan="2" col="4">
-                                    <field name='lead' />
-                                    <field name='opportunity'/>
-                                    <field name='event'/>
-                                    <field name='case'/>
-                                </group>
-                            </group>
-                            <group colspan="4" col="4">
-                                <separator string="Document" colspan="2"/>
-                                <newline/>
-                                <group colspan="2" col="4">
-                                    <field name='folder'/>
-                                    <field name='document'/>
-                                    <field name='attachment'/>
-                                </group>
-                            </group>
-                            <group colspan="4" col="4">
-                                <separator string="Others" colspan="4"/>
-                                <field name='task' colspan="4"/>
-                                <field name='task_type' attrs="{'invisible': [('task', '!=', True)], 'required':[('task', '=', True)]}" colspan="4"/>  
-                            </group>
+                    <newline/>
+                        <group colspan="4" col="4">
+                            <separator string="Base" colspan="2"/>
+                            <newline/>
+                            <group colspan="2" col="2">
+                                <field name="users"/>
+                                <field name="contact"/>
+                            </group>
+                        </group>
+                        <group colspan="4" col="4">
+                            <separator string="CRM" colspan="2"/>
+                            <newline/>
+                            <group colspan="2" col="4">
+                                <field name='lead' />
+                                <field name='opportunity'/>
+                                <field name='event'/>
+                                <field name='case'/>
+                            </group>
+                        </group>
+                        <group colspan="4" col="4">
+                            <separator string="Document" colspan="2"/>
+                            <newline/>
+                            <group colspan="2" col="4">
+                                <field name='folder'/>
+                                <field name='document'/>
+                                <field name='attachment'/>
+                            </group>
+                        </group>
+                        <group colspan="4" col="4">
+                            <separator string="Others" colspan="4"/>
+                            <field name='task' colspan="4"/>
+                        </group>
                     </group>
                     <group colspan="4" col="2">
                          <separator string="Email Notification When Import Finished" colspan="2"/>
@@ -64,16 +63,13 @@
                          <separator string="" colspan="4"/>
                     <group colspan="4" col="4">
                         <group colspan="2">
-                                <button string="Create _Recurrent Import" name="createCronJob" icon="gtk-new" type="object" />
-                                <label />        
+                            <button string="Create _Recurrent Import" name="createCronJob" icon="gtk-new" type="object" />
                         </group>
-                        
                         <group colspan="2" col="2">
                             <button icon="gtk-cancel" special="cancel" string="_Cancel"/>
-                            <button icon="gtk-go-forward" string="_Import Once" name="sf_do_import" type="object"/>
+                            <button icon="gtk-go-forward" string="_Import Once" name="import_all" type="object"/>
                         </group>
                     </group>
-
                 </form>
             </field>
         </record>
@@ -81,7 +77,7 @@
         <!--SalsForce Login Form Action-->
         <record model="ir.actions.act_window" id="action_view_import_sf_webservice_form">
             <field name="name">Import SalesForce</field>
-            <field name="res_model">import.sf</field>
+            <field name="res_model">import.salesforce</field>
             <field name="view_type">form</field>
             <field name="view_mode">tree,form</field>
             <field name="view_id" ref="view_import_sf_webservice_form"/>
@@ -101,8 +97,10 @@
             <field name="arch" type="xml">
                 <form string="SalesForce Login">
                     <field name='name' colspan='4' required='True'/>
-                    <field name='password' colspan='4' required='True'/>
-                    <field name='token' colspan='4' required='True'/>
+                    <field name='password' colspan='2' required='True' password="True"/>
+                    <field name='token' colspan='2' required='True'/>
+                    <field name='email' colspan='2' />
+                    <field name='instance' colspan='2' required='True'/>
                 </form>
             </field>
         </record>
@@ -113,8 +111,9 @@
             <field name="arch" type="xml">
                 <tree string="SalesForce Login">
                     <field name='name'/>
-                    <field name='password'/>
                     <field name='token'/>
+                    <field name='email'/>
+                    <field name='instance'/>
                 </tree>
             </field>
         </record>