← Back to team overview

openerp-dev-web team mailing list archive

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

 

Jigar Amin - OpenERP has proposed merging lp:~openerp-dev/openobject-addons/trunk-import_salesforce-import_data-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-import_data-jam/+merge/56874

Hello, 
   
   + Import Lead from SalesFroce Leads
   + Import Opportunity from SalesFroce Opprotunity.
   + Import Meetings from SalesFroce Events
   + Import Claim from SalesForce Cases
   + Import User from SalesFroce User
   + Import Partners from SalesForce Contacts, with account address linked with Contact
   + Import Activity if Type field level security is on than Calls, Email, Meeting will be imported separately else they will be imported to Meeting under Category of the Task
   
Kindly Review This,
Think You
-- 
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-import_salesforce-import_data-jam/+merge/56874
Your team OpenERP R&D Team is subscribed to branch lp:~openerp-dev/openobject-addons/trunk-import_salesforce.
=== added directory 'import_salesforce'
=== added file 'import_salesforce/__init__.py'
--- import_salesforce/__init__.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/__init__.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+import import_sf
+import wizard

=== added file 'import_salesforce/__openerp__.py'
--- import_salesforce/__openerp__.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/__openerp__.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,41 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+{
+    'name': 'SaleForce Data Synchronization.',
+    'version': '1.0',
+    'category': 'Generic Modules',
+    'description': """This Module Import SaleForce 'Leads', 'Opportunity', and 'contacts' Data into OpenERP Module.""",
+    'author': 'OpenERP SA',
+    'website': 'http://www.openerp.com',
+    'depends': [ 'base','crm_claim'],
+    'init_xml': [],
+    'update_xml': [
+                'import_sf_view.xml',
+                'wizard/import_salesforce_view.xml', 
+                'wizard/sf_import_message_view.xml',   
+            ],
+    'demo_xml': [],
+    'test': [],
+    'installable': True,
+    'active': False,
+}
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

=== added file 'import_salesforce/import_sf.py'
--- import_salesforce/import_sf.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/import_sf.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,734 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+from datetime import datetime
+from osv import osv
+from osv import fields
+from tools.translate import _ 
+try:
+    import beatbox
+except ImportError:
+    raise osv.except_osv(_('BeaobtBox 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 = ''
+
+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 Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+
+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 titleMapping(sf_obj, cr, uid, salutation, domain, context):
+    '''
+    Helper Method to resolve title dependency
+    '''
+    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
+    '''
+    priMap = {
+        'Hot' : '2',
+        'Warm' : '3',
+        'Cold' : '4'
+    } 
+    return priMap.get(rating, '4')
+
+def statusMapping(sf_obj, cr, uid, status, ctype ,context):
+    '''
+    Helper Method to resolve Status dependency of Lead/Opportunity
+    '''
+    stageMap = {
+        'Open - Not Contacted':'New', 
+        'Working - Contacted' :'Negotiation',
+        'Closed - Converted' :'Won', 
+        'Closed - Not Converted':'Lost',
+    } 
+    stage_pool = sf_obj.pool.get('crm.case.stage')
+    ids = stage_pool.search(cr, uid, [('type','=' , ctype), ('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
+    '''
+    return user.get('Id',False)
+
+def getLocalId(sf_obj, cr, uid, state, country, 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 importAddress(sf_obj, cr, uid, address, 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 importLead(sf_obj, cr, uid, 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:
+            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)})
+            rec.update({'Status' : statusMapping(sf_obj, cr, uid, rec.get('Status', False), 'lead', context)})
+            state, conutry = getLocalId(sf_obj, cr, uid, rec.get('State', False), rec.get('Country', False) , context)
+            rec.update({'State':state, 'Country' : conutry })
+            rec.update({'CreatedBy.Id' : getUserId(sf_obj, cr, uid, rec.get('CreatedBy', False), context)})
+            field, data = dataMapping(rec, MODEL_MAP.get('Lead').get('field_map'))
+            field.append('type')
+            data.append('lead')
+            lead_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
+    except Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+    return True
+
+def importUser(sf_obj, cr, uid, 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:
+            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 Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+    return True
+
+
+def importOpportunity(sf_obj, cr, uid, 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:
+            rec.update({'type':'opportunity'})
+            rec.update({'CreatedBy.Id' : getUserId(sf_obj, cr, uid, rec.get('CreatedBy', False), context)})
+            field, data = dataMapping(rec, MODEL_MAP.get('Opportunity').get('field_map'))
+            lead_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
+    except Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+    return True
+    
+def importContact(sf_obj, cr, uid, context):
+    partner_pool = sf_obj.pool.get('res.partner')
+    try:
+        addressDict = {
+            'contact' : {
+                'street' : 'MailingStreet',
+                'city' :'MailingCity',
+                'phone' : 'Phone',
+                'mobile' : 'MobilePhone',
+                'zip' : 'MailingPostalCode',
+                'state_id/.id' : 'MailingState',
+                'country_id/.id' : 'MailingCountry',
+                'fax' : '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', 
+            },
+        }
+            
+        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:]
+                        val = account.pop(vals)
+                        addr.update({nkey: val})
+                    addr.update({'type' : add})
+                    addr.update({'name' : rec.get('Name')})
+                add_dict.update({add : addr})
+            rec.pop('Account')
+            addIds = importAddress(sf_obj, cr, uid, add_dict, context)
+            rec.update({'Title' : titleMapping(sf_obj, cr, uid, rec.get('Title', False), 'partner' , context)})
+            field, data = dataMapping(rec, MODEL_MAP.get('Contact').get('field_map'))
+            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 Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+    return True
+
+def claimPriorityMapping(sf_obj, cr, uid, rating, context):
+    '''
+    Helper Method to Priority of Lead/Opportunity
+    '''
+    priMap = {
+        'High' : '2',
+        'Medium' : '3',
+        'Low' : '4'
+    } 
+    return priMap.get(rating, '4')
+
+
+def importCase(sf_obj, cr, uid, 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({'Owner.Id' : getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)})
+            rec.update({'Contact.Id' : getUserId(sf_obj, cr, uid, rec.get('Contact', False), context)})
+            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)
+    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):
+    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 importEvent(sf_obj, cr, uid, 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')
+            fields.update({'end_type' : 'end_type'})
+            rec.pop('RecurrenceActivityId')
+            recurrence = '0'
+            if rec.get('IsRecurrence'):
+                recurrence = '1'
+                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() })
+            rec.update({'Owner.Id' : getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)})
+            rec.update({'StartDateTime' : rec.get('StartDateTime').strftime(DATETIME_FORMAT )})
+            rec.update({'EndDateTime' : rec.get('EndDateTime').strftime(DATETIME_FORMAT )})
+            field, data = dataMapping(rec, fields)
+            meeting_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
+            fields.pop('end_type')
+            if fields.has_key('select1'):
+                fields.pop('select1')
+    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):
+    model_pool = sf_obj.pool.get(model)
+    try:
+        field, data = dataMapping(rec, fields)
+        model_pool.import_data(cr, uid, field, [data], mode='update', current_module='import_salesforce', noupdate=True, context=context)
+        fields.pop( 'categ_id/.id')
+    except Exception, e:
+        log = logging.getLogger('import.salesforce')
+        log.warning(str(e))
+        return False
+    return True
+
+def importActivity(sf_obj, cr, uid, 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')])
+        for rec in sfVals:
+            model = 'crm.meeting'
+            if rec.has_key('Type'):
+                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', '=', 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', '=', 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:
+                    nid = cate_ids[0]
+                    if not cate_ids:
+                        nid = cate_pool.create(cr, uid, { 'name':'Task','object_id':meetmodel_id[0]})
+                    fields.update({'categ_id/.id' : 'category'})
+                    rec.update({'category' : nid})
+                rec.pop('WhatId')
+                rec.pop('WhoId')
+            else:              
+                nid = cate_ids[0]
+                if not cate_ids:
+                    nid = cate_pool.create(cr, uid, { 'name':'Task','object_id':meetmodel_id[0]})
+                fields.update({'categ_id/.id' : 'category_id'})
+                rec.update({'category_id' : nid})  
+                    
+            rec.pop('WhatId')
+            rec.pop('WhoId')
+            if rec.get('ActivityDate'):
+                rec.update({'ActivityDate' : rec.get('ActivityDate').strftime(DATETIME_FORMAT )})
+            rec.update({'Owner.Id' : getUserId(sf_obj, cr, uid, rec.get('Owner', False), context)})
+            rec.update({'ActivityDate' : datetime.now().strftime(DATETIME_FORMAT)})
+            createActivity(sf_obj, cr , uid, fields, rec, model, context)
+    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',
+                 }        
+    },
+    'Opportunity' : {
+        'dependencies' : [ 'User' ],
+        'function' : importOpportunity,
+        'field_map' : {
+                        'id' : 'Id',
+                        'name' : 'Name',
+                        'user_id/id' : 'CreatedBy.Id',
+                        'planned_revenue' : 'Amount',
+                        'probability' : 'Probability',
+                        'title_action' : 'NextStep',
+                        'type' : 'type',
+                    }
+    },
+    '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'
+                }
+    },
+    'Contact' : {
+        'dependencies' : [],
+        'function' : importContact,
+        'field_map' : {
+                        'id' : 'Id',
+                        'name': 'Name',
+                        'title/.id' : 'Title',
+                        'street' : 'MailingStreet',
+                        'city' :'MailingCity',
+                        'phone' : 'Phone',
+                        'mobile' : 'MobilePhone',
+                        'zip' : 'MailingPostalCode',
+                        'state_id' : 'MailingState',
+                        'country_id' : 'MailingCountry',
+                        'fax' : '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',
+        }
+    },
+    'Event' : {
+        'dependencies' : [ 'User' ],
+        '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',
+        }
+    },
+}   
+
+LOGIN_DATA = {
+    'username' : None,
+    'passToken' : None
+}
+
+class import_sf(osv.osv):
+    '''
+        Model to Select SalesForce Model to be imported
+    '''
+    _name = 'import.sf'
+    _description = 'Import SalesForce Data'
+    
+    _columns = {
+        '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, SalesFroce Leads data imported to OpenERP CRM Opportunity."),
+        'users': fields.boolean('User', help="If Users is checked, SalesFroce Users data imported to OpenERP Users."),
+        'contact': fields.boolean('Partner/Contacts', help="If Partner/Contacts is checked, SalesFroce Contact data imported to OpenERP Partner and Partner Address."),
+        'case': fields.boolean('Cases/Claim', help="If Cases/Claim is checked, SalesFroce Cases data imported to OpenERP CRM Claim."),
+        'event': fields.boolean('Event/Meetings', help="If Event/Meetings is checked, SalesFroce Cases data imported to OpenERP Meetings."),
+        'task': fields.boolean('Acivity', help="If Activity is checked, SalesFroce Activity data  will imported to OpenERP Meetings and if you want ot import data in separate than selectd 'With Type' from below slection else  select 'Without Type'.\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 'With Type' option else select 'With Type' option."),
+    } 
+    
+    _defaults = {
+       'lead': True,
+       'opportunity': True,
+       'users': True,
+       'contact': True,
+       'event': True,
+       'task': True,
+       'case':True,
+       'task_type' : 'wttype',
+    }
+     
+    def _get_nodes(self, cr, uid, ids, context=None):
+        """Retun the List of the Select Model to be imported"""
+        if not context:
+            context = {}
+        nodes = []
+        for current in self.browse(cr, uid, ids, context):
+            if current.lead:
+                nodes.append('Lead')
+            if current.opportunity:
+                nodes.append('Opportunity')
+            if current.users:
+                nodes.append('User')
+            if current.contact:
+                nodes.append('Contact')
+            if current.case:
+                nodes.append('Case')
+            if current.event:
+                nodes.append('Event')
+            if current.task:
+                nodes.append('Task')
+                global ACT_TYPE
+                ACT_TYPE = current.task_type
+        return nodes
+        
+    def sf_do_import(self, cr, uid, ids, context=None):
+        '''
+        Method to initiate data import from map dict
+        '''
+        if context == None:
+            context = {}
+        LOGIN_DATA.update({'username' : context.get('username',None),
+                           'passToken' : context.get('passToken',None)})
+        sf_model = self._get_nodes(cr, uid, ids, context)
+        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)
+        if flag:
+            obj_model = self.pool.get('ir.model.data')
+            model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','sf.import.message.form')])
+            resource_id = obj_model.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',
+                }
+        raise osv.except_osv(_('Error !'), _('Error during importing data from salesforce.\nFor more check server log.'))
+
+    def resolve_dependencies(self, cr, uid, model_map, dep, visited, flag, context=None):
+        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
+                
+import_sf()
+# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:getRecurrancy(sf_obj, cr, uid, rec, context):

=== added file 'import_salesforce/import_sf_view.xml'
--- import_salesforce/import_sf_view.xml	1970-01-01 00:00:00 +0000
+++ import_salesforce/import_sf_view.xml	2011-04-08 04:53:25 +0000
@@ -0,0 +1,37 @@
+<?xml version="1.0"?>
+<openerp>
+    <data>
+        <!--Form View for the model import sf-->
+        <record model="ir.ui.view" id="view_import_sf_form">
+            <field name="name">import.sf.form</field>
+            <field name="model">import.sf</field>
+            <field name="type">form</field>
+            <field name="arch" type="xml">
+                <form string="Import SalesForce">
+                    <separator string="Check Model to Import" colspan='4' />
+                    <group  colspan="4" width="400" height="150">
+                        <field name='users' />
+                        <field name='contact'/>
+                        <field name='lead' />
+                        <field name='opportunity'/>
+                        <field name='case'/>
+                        <field name='event'/>
+                        <field name='task'/>
+                        <newline/>
+                        <field name='task_type' attrs="{'invisible': [('task', '!=', True)], 'required':[('task', '=', True)]}" colspan="4"/>
+                    </group>
+                    <group colspan="4" width="400">
+                        <separator colspan='4' />
+                        <group colspan="2"/>
+                        <group colspan="2">
+                            <button icon="gtk-cancel" special="cancel" string="_Cancel"/>
+                            <button icon="gtk-execute" string="_Import" name="sf_do_import" type="object"/>
+                        </group>
+                    </group>
+                </form> 
+            </field>
+        </record>
+    </data>
+</openerp>
+
+

=== added directory 'import_salesforce/wizard'
=== added file 'import_salesforce/wizard/__init__.py'
--- import_salesforce/wizard/__init__.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/wizard/__init__.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,23 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+import import_salesforce
+import sf_import_message

=== added file 'import_salesforce/wizard/import_salesforce.py'
--- import_salesforce/wizard/import_salesforce.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/wizard/import_salesforce.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,79 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+
+try:
+	import beatbox
+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
+from osv import osv
+from osv import fields
+from tools.translate import _ 
+	
+class salesforce_login(osv.osv):
+	'''
+		SalesForce Login Form
+		@name : Userlogin Name
+		@password : User Password for login name
+		@token : Security Token Provided bthe salesforce
+	'''
+	_name = 'salesforce.login'
+	_description = 'SalesForce Login'
+	_columns = {
+		'name' : fields.char('Username', size=255, required=True, help='Enter SalesForce login ussername.'), 
+		'password' : fields.char('Password', size=255, required=True, help='Enter valid password for the supplied username.'),
+		'token' : fields.char('Scurity Token', size=255, required=True, help='Enter Security Token generated by salesforce for the above user.'),
+	}
+
+	def sf_do_login(self, cr, uid, ids, context=None):
+		'''
+			Method Will validated the login of user. 
+		'''
+		record = self.browse(cr, uid, ids, context=context)
+		for rec in record:
+			uname = rec.name
+			passkey = rec.password + rec.token
+			log = logging.getLogger('salesforce.login')
+			try:
+				sfc = beatbox.PythonClient() 
+				sflogin = sfc.login(uname, passkey)
+				log.info(_("SuccessAttributeError: WindowConfigurator instance has no attribute 'containers'ful login to SalesForce Services with user - %s")%(uname))
+			except Exception, e:
+				log.warning(str(e))
+				raise osv.except_osv(_('Error !'),_('Invalid login detail'))
+	
+		model_pool = self.pool.get('ir.model.data')
+		view_ids = model_pool.search(cr,uid,[('model','=','ir.ui.view'),('name','=','salesforce.login.form')])
+		view_res_id = model_pool.read(cr, uid, view_ids, fields=['res_id'])
+		context.update({'username' : uname, 'passToken' : passkey})
+		return {
+			'name' : 'Import SalesForce',
+			'view_type': 'form',
+			'view_mode': 'form',
+			'res_model': 'import.sf',
+			'views': [(view_res_id,'form')],
+			'type': 'ir.actions.act_window',
+			'target': 'new',
+			'context': context
+		}
+		
+salesforce_login()

=== added file 'import_salesforce/wizard/import_salesforce_view.xml'
--- import_salesforce/wizard/import_salesforce_view.xml	1970-01-01 00:00:00 +0000
+++ import_salesforce/wizard/import_salesforce_view.xml	2011-04-08 04:53:25 +0000
@@ -0,0 +1,49 @@
+<?xml version="1.0"?>
+<openerp>
+    <data>
+        <!-- Menu for SalesForce Import Wizard-->
+        <menuitem id="menu_sf" name="Sales Force" parent="base.menu_base_partner" />
+        
+        <!--form view for the SalesForce Login -->
+        <record model="ir.ui.view" id="view_salesforce_login_form">
+            <field name="name">salesforce.login.form</field>
+            <field name="model">salesforce.login</field>
+            <field name="type">form</field>
+            <field name="arch" type="xml">
+                <form string="SalesForce Login">
+                    <separator string="Login Detail" colspan='4' />
+                    <group colspan="4" width="400">
+                        <field name='name' colspan='4'/>
+                        <field name='password' password='True' colspan='4'/>
+                        <field name='token' password='True' colspan='4'/>
+                    </group>
+                    <label string="       Enter Username, password and Security Token generated by SalesForce."/>
+                    <group colspan="4" width="400">
+                        <separator colspan='4' />
+                        <group colspan="2"/>
+                        <group colspan="2">
+                            <button icon="gtk-cancel" special="cancel" string="_Cancel"/>
+                            <button icon="terp-camera_test" string="_Login" name="sf_do_login" type="object"/>
+                        </group>
+                    </group>
+                </form> 
+            </field>
+        </record>
+
+        <!--SalsForce Login Form Action-->
+        <record model="ir.actions.act_window" id="action_view_salesforce_login">
+            <field name="name">SalesForce Login</field>
+            <field name="res_model">salesforce.login</field>
+            <field name="view_type">form</field>
+            <field name="view_mode">tree,form</field>
+            <field name="view_id" ref="view_salesforce_login_form"/>
+            <field name="target">new</field>
+        </record>
+
+        <!--wizard under importsalesforce menu-->
+        <menuitem id="menu_sf_login" name="Import SalesForce" parent="menu_sf" action="action_view_salesforce_login" icon="STOCK_EXECUTE"/>
+
+    </data>
+</openerp>
+
+

=== added file 'import_salesforce/wizard/sf_import_message.py'
--- import_salesforce/wizard/sf_import_message.py	1970-01-01 00:00:00 +0000
+++ import_salesforce/wizard/sf_import_message.py	2011-04-08 04:53:25 +0000
@@ -0,0 +1,29 @@
+# -*- coding: utf-8 -*-
+##############################################################################
+#
+#    OpenERP, Open Source Management Solution
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
+#
+#    This program is free software: you can redistribute it and/or modify
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
+#
+#    This program is distributed in the hope that it will be useful,
+#    but WITHOUT ANY WARRANTY; without even the implied warranty of
+#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
+#    GNU Affero General Public License for more details.
+#
+#    You should have received a copy of the GNU Affero General Public License
+#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
+#
+##############################################################################
+from osv import osv
+
+class sf_import_message(osv.osv):
+     """Import Message"""
+
+     _name = "sf.import.message"
+     _description = __doc__
+     
+sf_import_message()

=== added file 'import_salesforce/wizard/sf_import_message_view.xml'
--- import_salesforce/wizard/sf_import_message_view.xml	1970-01-01 00:00:00 +0000
+++ import_salesforce/wizard/sf_import_message_view.xml	2011-04-08 04:53:25 +0000
@@ -0,0 +1,19 @@
+<?xml version="1.0"?>
+<openerp>
+    <data>
+        <!-- Import Message Form View -->
+        <record model="ir.ui.view" id="view_sf_import_message_form">
+            <field name="name">sf.import.message.form</field>
+            <field name="model">sf.import.message</field>
+            <field name="type">form</field>
+            <field name="arch" type="xml">
+                <form string="Import SalesFroce">
+                   <label string="Data Imported Successfully" colspan="4"/>  
+                   <separator string="" colspan="4" />
+                   <label string="" colspan="2"/>
+                   <button  icon="gtk-ok" special="cancel" string="_Ok"/>
+                </form>
+            </field>
+        </record>
+    </data>
+</openerp>