[IMP]: Improvement for attachment
[odoo/odoo.git] / addons / import_sugarcrm / import_sugarcrm.py
1 # -*- coding: utf-8 -*-
2 ##############################################################################
3 #
4 #    OpenERP, Open Source Management Solution
5 #    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
6 #
7 #    This program is free software: you can redistribute it and/or modify
8 #    it under the terms of the GNU Affero General Public License as
9 #    published by the Free Software Foundation, either version 3 of the
10 #    License, or (at your option) any later version.
11 #
12 #    This program is distributed in the hope that it will be useful,
13 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
14 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 #    GNU Affero General Public License for more details.
16 #
17 #    You should have received a copy of the GNU Affero General Public License
18 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
19 #
20 ##############################################################################
21 from osv import fields, osv
22 from operator import itemgetter
23 import sugar
24 import sugarcrm_fields_mapping
25 from tools.translate import _
26 import pprint
27 pp = pprint.PrettyPrinter(indent=4)
28
29 OPENERP_FIEDS_MAPS = {'Leads': 'crm.lead',
30                       'Opportunities': 'crm.lead',
31                       'Contacts': 'res.partner.address',
32                       'Accounts': 'res.partner',
33                       'Resources': 'resource.resource',
34                       'Users': 'res.users',
35                       'Meetings': 'crm.meeting',
36                       'Calls': 'crm.phonecall',
37                       'Claims': 'crm.claim',
38                       'Employee': 'hr.employee',
39                       'Project': 'project.project',
40                       'ProjectTask': 'project.task',
41                       'Bugs': 'project.issue',
42                       'Documents': 'ir.attachment',
43                       
44   }
45
46 def find_mapped_id(obj, cr, uid, res_model, sugar_id, context):
47     model_obj = obj.pool.get('ir.model.data')
48     return model_obj.search(cr, uid, [('model', '=', res_model), ('module', '=', 'sugarcrm_import'), ('name', '=', sugar_id)], context=context)
49
50 def get_all(sugar_obj, cr, uid, model, sugar_val, context=None):
51     models = sugar_obj.pool.get(model)
52     model_code = sugar_val[0:2]
53     all_model_ids = models.search(cr, uid, [('name', '=', sugar_val)]) or models.search(cr, uid, [('code', '=', model_code.upper())]) 
54     output = sorted([(o.id, o.name)
55                      for o in models.browse(cr, uid, all_model_ids, context=context)],
56                     key=itemgetter(1))
57     return output
58
59 def get_all_states(sugar_obj, cr, uid, sugar_val, country_id, context=None):
60     """Get states or create new state"""
61     state_id = False
62     res_country_state_obj = sugar_obj.pool.get('res.country.state')
63     
64     state = get_all(sugar_obj,
65         cr, uid, 'res.country.state', sugar_val, context=context)
66     if state:
67         state_id = state and state[0][0]
68     else:
69         state_id = res_country_state_obj.create(cr, uid, {'name': sugar_val, 'code': sugar_val, 'country_id': country_id})
70     return state_id   
71
72 def get_all_countries(sugar_obj, cr, uid, sugar_country_val, context=None):
73     """Get Country or Create new country"""
74     res_country_obj = sugar_obj.pool.get('res.country')
75     country_id = False
76     country_code = sugar_country_val[0:2]
77     country = get_all(sugar_obj,
78         cr, uid, 'res.country', sugar_country_val, context=context)
79     if country:
80         country_id = country and country[0][0] 
81     else:
82         country_id = res_country_obj.create(cr, uid, {'name': sugar_country_val, 'code': country_code})  
83     return country_id
84
85 def import_partner_address(sugar_obj, cr, uid, context=None):
86     if not context:
87         context = {}
88     map_partner_address = {
89              'id': 'id',              
90              'name': ['first_name', 'last_name'],
91              'partner_id/id': 'account_id',
92             'phone': 'phone_work',
93             'mobile': 'phone_mobile',
94             'fax': 'phone_fax',
95             'function': 'title',
96             'street': 'primary_address_street',
97             'zip': 'primary_address_postalcode',
98             'city': 'primary_address_city',
99             'country_id.id': 'country_id.id',
100             'state_id.id': 'state_id.id',
101             'email': 'email',
102             'type': 'type'
103             }
104     address_obj = sugar_obj.pool.get('res.partner.address')
105     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
106     sugar_data = sugar.search(PortType, sessionid, 'Contacts')
107     for val in sugar_data:
108         val['type'] = 'contact'
109         contact_emails = sugar.contact_emails_search(PortType, context.get('username', ''), context.get('password', ''), email_address=val.get('email1'))
110         val['email'] = (','.join(map(lambda x : x, contact_emails)))
111         if val.get('primary_address_country'):
112             country_id = get_all_countries(sugar_obj, cr, uid, val.get('primary_address_country'), context)
113             state = get_all_states(sugar_obj,cr, uid, val.get('primary_address_state'), country_id, context)
114             val['country_id.id'] =  country_id
115             val['state_id.id'] =  state        
116         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_partner_address, context)
117         address_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
118     return True
119     
120
121
122 def import_users(sugar_obj, cr, uid, context=None):
123     map_user = {
124         'id' : 'id', 
125         'name': ['first_name', 'last_name'],
126         'login': 'user_name',
127         'context_lang' : 'context_lang',
128         'password' : 'password',
129         '.id' : '.id',
130         'context_department_id.id': 'context_department_id.id',
131     } 
132     
133     def get_users_department(sugar_obj, cr, uid, val, context=None):
134         department_id = False       
135         department_obj = sugar_obj.pool.get('hr.department')
136         department_ids = department_obj.search(cr, uid, [('name', '=', val)])
137         if department_ids:
138             department_id = department_ids[0]
139         elif val:
140             department_id = department_obj.create(cr, uid, {'name': val})
141         return department_id 
142     
143     if not context:
144         context = {}
145     department_id = False        
146     
147     user_obj = sugar_obj.pool.get('res.users')
148     PortType,sessionid = sugar.login(context.get('username',''), context.get('password',''), context.get('url',''))
149     sugar_data = sugar.search(PortType,sessionid, 'Users')
150     for val in sugar_data:
151         user_ids = user_obj.search(cr, uid, [('login', '=', val.get('user_name'))])
152         if user_ids: 
153             val['.id'] = str(user_ids[0])
154         else:
155             val['password'] = 'sugarcrm' #default password for all user
156         department_id = get_users_department(sugar_obj, cr, uid, val.get('department'), context=context)
157         val['context_department_id.id'] = department_id     
158         val['context_lang'] = context.get('lang','en_US')
159         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_user, context)
160         #All data has to be imported separatly because they don't have the same field
161         user_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
162     return True
163
164 def get_lead_status(surgar_obj, cr, uid, sugar_val,context=None):
165     if not context:
166         context = {}
167     stage_id = False
168     stage_dict = {'status': #field in the sugarcrm database
169         { #Mapping of sugarcrm stage : openerp opportunity stage
170             'New' : 'New',
171             'Assigned':'Qualification',
172             'In Progress': 'Proposition',
173             'Recycled': 'Negotiation',
174             'Dead': 'Lost'
175         },}
176     stage = stage_dict['status'].get(sugar_val['status'], '')
177     stage_pool = surgar_obj.pool.get('crm.case.stage')
178     stage_ids = stage_pool.search(cr, uid, [('type', '=', 'lead'), ('name', '=', stage)])
179     for stage in stage_pool.browse(cr, uid, stage_ids, context):
180         stage_id = stage.id
181     return stage_id
182
183 def get_lead_state(surgar_obj, cr, uid, sugar_val,context=None):
184     if not context:
185         context = {}
186     state = False
187     state_dict = {'status': #field in the sugarcrm database
188         { #Mapping of sugarcrm stage : openerp opportunity stage
189             'New' : 'draft',
190             'Assigned':'open',
191             'In Progress': 'open',
192             'Recycled': 'cancel',
193             'Dead': 'done'
194         },}
195     state = state_dict['status'].get(sugar_val['status'], '')
196     return state
197
198 def get_opportunity_status(surgar_obj, cr, uid, sugar_val,context=None):
199     if not context:
200         context = {}
201     stage_id = False
202     stage_dict = { 'sales_stage':
203             {#Mapping of sugarcrm stage : openerp opportunity stage Mapping
204                'Need Analysis': 'New',
205                'Closed Lost': 'Lost',
206                'Closed Won': 'Won',
207                'Value Proposition': 'Proposition',
208                 'Negotiation/Review': 'Negotiation'
209             },
210     }
211     stage = stage_dict['sales_stage'].get(sugar_val['sales_stage'], '')
212     stage_pool = surgar_obj.pool.get('crm.case.stage')
213     stage_ids = stage_pool.search(cr, uid, [('type', '=', 'opportunity'), ('name', '=', stage)])
214     for stage in stage_pool.browse(cr, uid, stage_ids, context):
215         stage_id = stage.id
216     return stage_id
217
218 def get_user_address(sugar_obj, cr, uid, val, context=None):
219     address_obj = sugar_obj.pool.get('res.partner.address')
220     map_user_address = {
221     'name': ['first_name', 'last_name'],
222     'city': 'address_city',
223     'country_id': 'country_id',
224     'state_id': 'state_id',
225     'street': 'address_street',
226     'zip': 'address_postalcode',
227     }
228     address_ids = address_obj.search(cr, uid, [('name', 'like', val.get('first_name') +' '+ val.get('last_name'))])
229     if val.get('address_country'):
230         country_id = get_all_countries(sugar_obj, cr, uid, val.get('address_country'), context)
231         state_id = get_all_states(sugar_obj, cr, uid, val.get('address_state'), country_id, context)
232         val['country_id'] =  country_id
233         val['state_id'] =  state_id
234     fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_user_address, context)
235     dict_val = dict(zip(fields,datas))
236     if address_ids:
237         address_obj.write(cr, uid, address_ids, dict_val)
238     else:        
239         new_address_id = address_obj.create(cr,uid, dict_val)
240         return new_address_id
241     return True
242
243 def get_address_type(sugar_obj, cr, uid, val, map_partner_address, type, context=None):
244         address_obj = sugar_obj.pool.get('res.partner.address')
245         new_address_id = False
246         if type == 'invoice':
247             type_address = 'billing'
248         else:
249             type_address = 'shipping'     
250     
251         map_partner_address.update({
252             'street': type_address + '_address_street',
253             'zip': type_address +'_address_postalcode',
254             'city': type_address +'_address_city',
255              'country_id': 'country_id',
256              'type': 'type',
257             })
258         val['type'] = type
259         if val.get(type_address +'_address_country'):
260             country_id = get_all_countries(sugar_obj, cr, uid, val.get(type_address +'_address_country'), context)
261             state = get_all_states(sugar_obj, cr, uid, val.get(type_address +'_address_state'), country_id, context)
262             val['country_id'] =  country_id
263             val['state_id'] =  state
264         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_partner_address, context)
265         #Convert To list into Dictionary(Key, val). value pair.
266         dict_val = dict(zip(fields,datas))
267         new_address_id = address_obj.create(cr,uid, dict_val)
268         return new_address_id
269     
270 def get_address(sugar_obj, cr, uid, val, context=None):
271     map_partner_address={}
272     address_id=[]
273     address_obj = sugar_obj.pool.get('res.partner.address')
274     address_ids = address_obj.search(cr, uid, [('name', '=',val.get('name')), ('type', 'in', ('invoice', 'delivery')), ('street', '=', val.get('billing_address_street'))])
275     if address_ids:
276         return address_ids 
277     else:
278         map_partner_address = {
279             'id': 'id',                    
280             'name': 'name',
281             'partner_id/id': 'account_id',
282             'phone': 'phone_office',
283             'mobile': 'phone_mobile',
284             'fax': 'phone_fax',
285             'type': 'type',
286             }
287         if val.get('billing_address_street'):
288             address_id.append(get_address_type(sugar_obj, cr, uid, val, map_partner_address, 'invoice', context))
289             
290         if val.get('shipping_address_street'):
291             address_id.append(get_address_type(sugar_obj, cr, uid, val, map_partner_address, 'delivery', context))
292         return address_id
293     return True
294
295 def import_partners(sugar_obj, cr, uid, context=None):
296     if not context:
297         context = {}
298     map_partner = {
299                 'id': 'id',
300                 'name': 'name',
301                 'website': 'website',
302                 'user_id/id': 'assigned_user_id',
303                 'ref': 'sic_code',
304                 'comment': ['__prettyprint__', 'description', 'employees', 'ownership', 'annual_revenue', 'rating', 'industry', 'ticker_symbol'],
305                 'customer': 'customer',
306                 'supplier': 'supplier', 
307                 }
308     partner_obj = sugar_obj.pool.get('res.partner')
309     address_obj = sugar_obj.pool.get('res.partner.address')
310     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
311     sugar_data = sugar.search(PortType, sessionid, 'Accounts')
312     for val in sugar_data:
313         add_id = get_address(sugar_obj, cr, uid, val, context)
314         val['customer'] = '1'
315         val['supplier'] = '0'
316         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_partner, context)
317         partner_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
318         for address in  address_obj.browse(cr,uid,add_id):
319             data_id = partner_obj.search(cr,uid,[('name','like',address.name),('website','like',val.get('website'))])
320             if data_id:
321                 address_obj.write(cr,uid,address.id,{'partner_id':data_id[0]})                
322     return True
323
324 def get_category(sugar_obj, cr, uid, model, name, context=None):
325     categ_id = False
326     categ_obj = sugar_obj.pool.get('crm.case.categ')
327     categ_ids = categ_obj.search(cr, uid, [('object_id.model','=',model), ('name', 'like', name)] )
328     if categ_ids:
329         categ_id = categ_ids[0]
330     else:
331         model_ids = sugar_obj.pool.get('ir.model').search(cr, uid, [('model', '=', model)], context=context)
332         model = model_ids and model_ids[0] or False
333         categ_id = categ_obj.create(cr, uid, {'name': name, 'object_id': model})
334     return categ_id     
335
336 def get_alarm_id(sugar_obj, cr, uid, val, context=None):
337     
338     alarm_dict = {'60': '1 minute before',
339                   '300': '5 minutes before',
340                   '600': '10 minutes before',
341                   '900': '15 minutes before',
342                   '1800':'30 minutes before',
343                   '3600': '1 hour before',
344      }
345     alarm_id = False
346     alarm_obj = sugar_obj.pool.get('res.alarm')
347     if alarm_dict.get(val):
348         alarm_ids = alarm_obj.search(cr, uid, [('name', 'like', alarm_dict.get(val))])
349         for alarm in alarm_obj.browse(cr, uid, alarm_ids, context):
350             alarm_id = alarm.id
351     return alarm_id 
352     
353 def get_meeting_state(sugar_obj, cr, uid, val,context=None):
354     if not context:
355         context = {}
356     state = False
357     state_dict = {'status': #field in the sugarcrm database
358         { #Mapping of sugarcrm stage : openerp meeting stage
359             'Planned' : 'draft',
360             'Held':'open',
361             'Not Held': 'draft',
362         },}
363     state = state_dict['status'].get(val, '')
364     return state    
365
366 def get_task_state(sugar_obj, cr, uid, val, context=None):
367     if not context:
368         context = {}
369     state = False
370     state_dict = {'status': #field in the sugarcrm database
371         { #Mapping of sugarcrm stage : openerp meeting stage
372             'Completed' : 'done',
373             'Not Started':'draft',
374             'In Progress': 'open',
375             'Pending Input': 'draft',
376             'deferred': 'cancel'
377         },}
378     state = state_dict['status'].get(val, '')
379     return state    
380
381 def get_project_state(sugar_obj, cr, uid, val,context=None):
382     if not context:
383         context = {}
384     state = False
385     state_dict = {'status': #field in the sugarcrm database
386         { #Mapping of sugarcrm staus : openerp Projects state
387             'Draft' : 'draft',
388             'In Review': 'open',
389             'Published': 'close',
390         },}
391     state = state_dict['status'].get(val, '')
392     return state    
393
394 def get_project_task_state(sugar_obj, cr, uid, val,context=None):
395     if not context:
396         context = {}
397     state = False
398     state_dict = {'status': #field in the sugarcrm database
399         { #Mapping of sugarcrm status : openerp Porject Tasks state
400              'Not Started': 'draft',
401              'In Progress': 'open',
402              'Completed': 'done',
403             'Pending Input': 'pending',
404             'Deferred': 'cancelled',
405         },}
406     state = state_dict['status'].get(val, '')
407     return state    
408
409 def get_project_task_priority(sugar_obj, cr, uid, val,context=None):
410     if not context:
411         context = {}
412     priority = False
413     priority_dict = {'priority': #field in the sugarcrm database
414         { #Mapping of sugarcrm status : openerp Porject Tasks state
415             'High': '0',
416             'Medium': '2',
417             'Low': '3'
418         },}
419     priority = priority_dict['priority'].get(val, '')
420     return priority    
421
422
423 def get_account(sugar_obj, cr, uid, val, context=None):
424     if not context:
425         context = {}
426     partner_id = False    
427     partner_address_id = False
428     partner_phone = False
429     partner_mobile = False
430     model_obj = sugar_obj.pool.get('ir.model.data')
431     address_obj = sugar_obj.pool.get('res.partner.address')
432     crm_obj = sugar_obj.pool.get('crm.lead')
433     project_obj = sugar_obj.pool.get('project.project')
434     issue_obj = sugar_obj.pool.get('project.issue')
435     if val.get('parent_type') == 'Accounts':
436         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner')])
437         if model_ids:
438             model = model_obj.browse(cr, uid, model_ids)[0]
439             partner_id = model.res_id
440             address_ids = address_obj.search(cr, uid, [('partner_id', '=', partner_id)])
441             if address_ids:
442                 address_id = address_obj.browse(cr, uid, address_ids[0])
443                 partner_address_id = address_id.id
444                 partner_phone = address_id.phone
445                 partner_mobile = address_id.mobile
446             
447     if val.get('parent_type') == 'Contacts':
448         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner.address')])
449         for model in model_obj.browse(cr, uid, model_ids):
450             partner_address_id = model.res_id
451             address_id = address_obj.browse(cr, uid, partner_address_id)
452             partner_phone = address_id.phone
453             partner_mobile = address_id.mobile
454             partner_id = address_id and address_id.partner_id or False
455             
456     if val.get('parent_type') == 'Opportunities':
457         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'crm.lead')])
458         for model in model_obj.browse(cr, uid, model_ids):
459             opportunity_id = model.res_id
460             opportunity_id = crm_obj.browse(cr, uid, opportunity_id)
461             partner_id = opportunity_id.partner_id.id
462             partner_address_id =  opportunity_id.partner_address_id.id
463             partner_phone = opportunity_id.partner_address_id.phone
464             partner_mobile = opportunity_id.partner_address_id.mobile
465             
466     if val.get('parent_type') == 'Project':
467         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'project.project')])
468         for model in model_obj.browse(cr, uid, model_ids):
469             proj_ids = model.res_id
470             proj_id = project_obj.browse(cr, uid, proj_ids)
471             partner_id = proj_id.partner_id.id
472             partner_address_id =  proj_id.contact_id.id
473             partner_phone = proj_id.contact_id.phone
474             partner_mobile = proj_id.contact_id.mobile
475
476     if val.get('parent_type') == 'Bugs':
477         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'project.issue')])
478         for model in model_obj.browse(cr, uid, model_ids):
479             issue_ids = model.res_id
480             issue_id = issue_obj.browse(cr, uid, issue_ids)
481             partner_id = issue_id.partner_id.id
482             partner_address_id =  issue_id.partner_address_id.id
483             partner_phone = issue_id.partner_address_id.phone
484             partner_mobile = issue_id.partner_address_id.mobile                        
485                         
486     return partner_id, partner_address_id, partner_phone,partner_mobile                          
487
488 def import_documents(sugar_obj, cr, uid, context=None):
489     if not context:
490         context = {}
491     map_document = {'id' : 'id', 
492              'name': 'document_name',
493            'description': 'description',
494            'datas': 'datas',
495            'datas_fname': 'datas_fname',
496             } 
497     attach_obj = sugar_obj.pool.get('ir.attachment')
498     PortType,sessionid = sugar.login(context.get('username',''), context.get('password',''), context.get('url',''))
499     sugar_data = sugar.search(PortType,sessionid, 'Documents')
500     for val in sugar_data:
501         file, filename = sugar.attachment_search(PortType, sessionid, 'DocumentRevisions', val.get('document_revision_id'))
502         val['datas'] = file
503         val['datas_fname'] = filename
504         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_document, context)
505         attach_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
506     return True
507
508 def import_tasks(sugar_obj, cr, uid, context=None):
509     if not context:
510         context = {}
511     map_task = {'id' : 'id',
512                 'name': 'name',
513                 'date': ['__datetime__', 'date_start'],
514                 'date_deadline' : ['__datetime__', 'date_due'],
515                 'user_id/id': 'assigned_user_id',
516                 'categ_id/.id': 'categ_id/.id',
517                 'partner_id/.id': 'partner_id/.id',
518                 'partner_address_id/.id': 'partner_address_id/.id',
519                 'state': 'state'
520     }
521     meeting_obj = sugar_obj.pool.get('crm.meeting')
522     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
523     categ_id = get_category(sugar_obj, cr, uid, 'crm.meeting', 'Tasks')
524     sugar_data = sugar.search(PortType, sessionid, 'Tasks')
525     for val in sugar_data:
526         partner_xml_id = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', val.get('contact_id'), context)
527         if not partner_xml_id:
528             raise osv.except_osv(_('Warning !'), _('Reference Contact %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('contact_name'))
529         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
530         val['partner_id/.id'] = partner_id
531         val['partner_address_id/.id'] = partner_address_id
532         val['categ_id/.id'] = categ_id
533         val['state'] = get_task_state(sugar_obj, cr, uid, val.get('status'), context)
534         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_task, context)
535         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
536     return True    
537     
538 def get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, module_name, module_id, context=None):
539     if not context:
540         context = {}
541     model_obj = sugar_obj.pool.get('ir.model.data')
542     att_obj = sugar_obj.pool.get('calendar.attendee')
543     meeting_obj = sugar_obj.pool.get('crm.meeting')
544     user_dict = sugar.user_get_attendee_list(PortType, sessionid, module_name, module_id)
545     for user in user_dict: 
546         user_model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.users', user.get('id'), context)
547         user_resource_id = model_obj.browse(cr, uid, user_model_ids)        
548         if user_resource_id:
549             user_id = user_resource_id[0].res_id 
550             attend_ids = att_obj.search(cr, uid, [('user_id', '=', user_id)])
551             if attend_ids:
552                  attendees = attend_ids[0]
553             else:      
554                 attendees = att_obj.create(cr, uid, {'user_id': user_id, 'email': user.get('email1')})
555             meeting_model_ids = find_mapped_id(sugar_obj, cr, uid, 'crm.meeting', module_id, context)
556             meeting_xml_id = model_obj.browse(cr, uid, meeting_model_ids)
557             if meeting_xml_id:
558                 meeting_obj.write(cr, uid, [meeting_xml_id[0].res_id], {'attendee_ids': [(4, attendees)]})       
559     return True   
560     
561 def import_meetings(sugar_obj, cr, uid, context=None):
562     if not context:
563         context = {}
564     map_meeting = {'id' : 'id',
565                     'name': 'name',
566                     'date': ['__datetime__', 'date_start'],
567                     'duration': ['duration_hours', 'duration_minutes'],
568                     'location': 'location',
569                     'alarm_id/.id': 'alarm_id/.id',
570                     'user_id/id': 'assigned_user_id',
571                     'partner_id/.id':'partner_id/.id',
572                     'partner_address_id/.id':'partner_address_id/.id',
573                     'state': 'state'
574     }
575     meeting_obj = sugar_obj.pool.get('crm.meeting')
576     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
577     sugar_data = sugar.search(PortType, sessionid, 'Meetings')
578     for val in sugar_data:
579         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
580         val['partner_id/.id'] = partner_id
581         val['partner_address_id/.id'] = partner_address_id
582         val['state'] = get_meeting_state(sugar_obj, cr, uid, val.get('status'),context)
583         val['alarm_id/.id'] = get_alarm_id(sugar_obj, cr, uid, val.get('reminder_time'), context)
584         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_meeting, context)
585         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
586         get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, 'Meetings', val.get('id'), context)
587     return True    
588
589 def get_calls_state(sugar_obj, cr, uid, val,context=None):
590     if not context:
591         context = {}
592     state = False
593     state_dict = {'status': #field in the sugarcrm database
594         { #Mapping of sugarcrm stage : openerp calls stage
595             'Planned' : 'open',
596             'Held':'done',
597             'Not Held': 'pending',
598         },}
599     state = state_dict['status'].get(val, '')
600     return state   
601
602 def import_calls(sugar_obj, cr, uid, context=None):
603     if not context:
604         context = {}
605     map_calls = {'id' : 'id',
606                     'name': 'name',
607                     'date': ['__datetime__', 'date_start'],
608                     'duration': ['duration_hours', 'duration_minutes'],
609                     'user_id/id': 'assigned_user_id',
610                     'partner_id/.id': 'partner_id/.id',
611                     'partner_address_id/.id': 'partner_address_id/.id',
612                     'categ_id/.id': 'categ_id/.id',
613                    'state': 'state',
614                    'partner_phone': 'partner_phone',
615                    'partner_mobile': 'partner_mobile',
616                    'opportunity_id/id': 'opportunity_id/id',
617
618     }
619     phonecall_obj = sugar_obj.pool.get('crm.phonecall')
620     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
621     sugar_data = sugar.search(PortType, sessionid, 'Calls')
622     for val in sugar_data:
623         sugar_call_leads = sugar.relation_search(PortType, sessionid, 'Calls', module_id=val.get('id'), related_module='Leads', query=None, deleted=None)
624         if sugar_call_leads:
625             for call_opportunity in sugar_call_leads: 
626                 val['opportunity_id/id'] = call_opportunity 
627         categ_id = get_category(sugar_obj, cr, uid, 'crm.phonecall', val.get('direction'))         
628         val['categ_id/.id'] = categ_id
629         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
630         
631         val['partner_id/.id'] = partner_id
632         val['partner_address_id/.id'] = partner_address_id
633         val['partner_phone'] = partner_phone
634         val['partner_mobile'] = partner_mobile
635         val['state'] =  get_calls_state(sugar_obj, cr, uid, val.get('status'), context)  
636         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_calls, context)
637         phonecall_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
638     return True
639     
640 def import_resources(sugar_obj, cr, uid, context=None):
641     if not context:
642         context = {}
643     map_resource = {'id' : 'user_hash',
644                     'name': ['first_name', 'last_name'],
645     }
646     resource_obj = sugar_obj.pool.get('resource.resource')
647     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
648     sugar_data = sugar.search(PortType, sessionid, 'Employees')
649     for val in sugar_data:
650         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource, context)
651         resource_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
652     return True    
653
654 def get_bug_priority(sugar_obj, cr, uid, val,context=None):
655     if not context:
656         context = {}
657     priority = False
658     priority_dict = {'priority': #field in the sugarcrm database
659         { #Mapping of sugarcrm priority : openerp bugs priority
660             'Urgent': '1',
661             'High': '2',
662             'Medium': '3',
663             'Low': '4'
664         },}
665     priority = priority_dict['priority'].get(val, '')
666     return priority  
667
668 def get_claim_priority(sugar_obj, cr, uid, val,context=None):
669     if not context:
670         context = {}
671     priority = False
672     priority_dict = {'priority': #field in the sugarcrm database
673         { #Mapping of sugarcrm priority : openerp claims priority
674             'High': '2',
675             'Medium': '3',
676             'Low': '4'
677         },}
678     priority = priority_dict['priority'].get(val, '')
679     return priority   
680
681 def get_bug_state(sugar_obj, cr, uid, val,context=None):
682     if not context:
683         context = {}
684     state = False
685     state_dict = {'status': #field in the sugarcrm database
686         { #Mapping of sugarcrm status : openerp Bugs state
687             'New' : 'draft',
688             'Assigned':'open',
689             'Closed': 'done',
690             'Pending': 'pending',
691             'Rejected': 'cancel',
692         },}
693     state = state_dict['status'].get(val, '')
694     return state
695
696 def get_claim_state(sugar_obj, cr, uid, val,context=None):
697     if not context:
698         context = {}
699     state = False
700     state_dict = {'status': #field in the sugarcrm database
701         { #Mapping of sugarcrm status : openerp claim state
702             'New' : 'draft',
703             'Assigned':'open',
704             'Closed': 'done',
705             'Pending Input': 'pending',
706             'Rejected': 'cancel',
707             'Duplicate': 'draft',
708         },}
709     state = state_dict['status'].get(val, '')
710     return state
711     
712
713 def get_acc_contact_claim(sugar_obj, cr, uid, val, context=None):
714     if not context:
715         context = {}
716     partner_id = False    
717     partner_address_id = False
718     partner_phone = False
719     partner_email = False
720     model_obj = sugar_obj.pool.get('ir.model.data')
721     address_obj = sugar_obj.pool.get('res.partner.address')
722     model_ids = model_obj.search(cr, uid, [('name', '=', val.get('account_id')), ('model', '=', 'res.partner')])
723     if model_ids:
724         model = model_obj.browse(cr, uid, model_ids)[0]
725         partner_id = model.res_id
726         address_ids = address_obj.search(cr, uid, [('partner_id', '=', partner_id)])
727         if address_ids:
728             address_id = address_obj.browse(cr, uid, address_ids[0])
729             partner_address_id = address_id.id
730             partner_phone = address_id.phone
731             partner_mobile = address_id.email
732     return partner_id, partner_address_id, partner_phone,partner_email
733
734 def import_claims(sugar_obj, cr, uid, context=None):
735     if not context:
736         context = {}
737     map_claim = {'id' : 'id',
738                     'name': 'name',
739                     'date': ['__datetime__', 'date_entered'],
740                     'user_id/id': 'assigned_user_id',
741                     'priority':'priority',
742                     'partner_id/.id': 'partner_id/.id',
743                     'partner_address_id/.id': 'partner_address_id/.id',
744                     'partner_phone': 'partner_phone',
745                     'partner_mobile': 'partner_email',                    
746                     'description': 'description',
747                     'state': 'state',
748     }
749     claim_obj = sugar_obj.pool.get('crm.claim')
750     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
751     sugar_data = sugar.search(PortType, sessionid, 'Cases')
752     for val in sugar_data:
753         partner_id, partner_address_id, partner_phone,partner_email = get_acc_contact_claim(sugar_obj, cr, uid, val, context)
754         val['partner_id/.id'] = partner_id
755         val['partner_address_id/.id'] = partner_address_id
756         val['partner_phone'] = partner_phone
757         val['email_from'] = partner_email
758         val['priority'] = get_claim_priority(sugar_obj, cr, uid, val.get('priority'),context)
759         val['state'] = get_claim_state(sugar_obj, cr, uid, val.get('status'),context)
760         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_claim, context)
761         claim_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
762     return True    
763
764 def import_bug(sugar_obj, cr, uid, context=None):
765     if not context:
766         context = {}
767     map_resource = {'id' : 'id',
768                     'name': 'name',
769                     'project_id/.id':'project_id/.id',
770                     'categ_id.id': 'categ_id.id',
771                     'priority':'priority',
772                     'description': ['__prettyprint__','description', 'bug_number', 'fixed_in_release_name', 'source', 'fixed_in_release', 'work_log', 'found_in_release', 'release_name', 'resolution'],
773                     'state': 'state',
774     }
775     issue_obj = sugar_obj.pool.get('project.issue')
776     project_obj = sugar_obj.pool.get('project.project')
777     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
778     sugar_data = sugar.search(PortType, sessionid, 'Bugs')
779     for val in sugar_data:
780         project_ids = project_obj.search(cr, uid, [('name', 'like', 'sugarcrm_bugs')])
781         if project_ids:
782             project_id = project_ids[0]
783         else:
784              project_id = project_obj.create(cr, uid, {'name':'sugarcrm_bugs'})    
785         val['project_id/.id'] = project_id
786         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'project.issue', val.get('type'))
787         val['priority'] = get_bug_priority(sugar_obj, cr, uid, val.get('priority'),context)
788         val['state'] = get_bug_state(sugar_obj, cr, uid, val.get('status'),context)
789         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource, context)
790         issue_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
791     return True    
792
793 def get_job_id(sugar_obj, cr, uid, val, context=None):
794     if not context:
795         context={}
796     job_id = False    
797     job_obj = sugar_obj.pool.get('hr.job')        
798     job_ids = job_obj.search(cr, uid, [('name', '=', val)])
799     if job_ids:
800         job_id = job_ids[0]
801     else:
802         job_id = job_obj.create(cr, uid, {'name': val})
803     return job_id
804
805 def get_campaign_id(sugar_obj, cr, uid, val, context=None):
806     if not context:
807         context={}
808     cam_id = False    
809     cam_obj = sugar_obj.pool.get('crm.case.resource.type')        
810     cam_ids = cam_obj.search(cr, uid, [('name', '=', val)])
811     if cam_ids:
812         cam_id = cam_ids[0]
813     else:
814         cam_id = cam_obj.create(cr, uid, {'name': val})
815     return cam_id
816     
817 def get_attachment(sugar_obj, cr, uid, val, model, File, Filename, parent_type, context=None):
818     if not context:
819         context = {}
820     attach_ids = False    
821     attachment_obj = sugar_obj.pool.get('ir.attachment')
822     partner_obj = sugar_obj.pool.get('res.partner')
823     model_obj = sugar_obj.pool.get('ir.model.data')
824     mailgate_obj = sugar_obj.pool.get('mailgate.message')
825     attach_ids = attachment_obj.search(cr, uid, [('res_id','=', val.get('res_id'), ('res_model', '=', val.get('model')))])
826     if not attach_ids and Filename:
827         if parent_type == 'Accounts':
828             new_attachment_id = attachment_obj.create(cr, uid, {'name': Filename, 'datas_fname': Filename, 'datas': File, 'res_id': val.get('res_id', False),'res_model': val.get('model',False), 'partner_id': val.get('partner_id/.id')})
829         else:    
830             new_attachment_id = attachment_obj.create(cr, uid, {'name': Filename, 'datas_fname': Filename, 'datas': File, 'res_id': val.get('res_id', False),'res_model': val.get('model',False)})
831         message_model_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
832         message_xml_id = model_obj.browse(cr, uid, message_model_ids)
833         if message_xml_id:
834           if parent_type == 'Accounts':
835                  mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)], 'partner_id': val.get('partner_id/.id')})
836           else:
837                  mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)]})                                              
838     return True    
839     
840 def import_history(sugar_obj, cr, uid, context=None):
841     if not context:
842         context = {}
843     map_attachment = {'id' : 'id',
844                       'name':'name',
845                       'date': ['__datetime__', 'date_entered'],
846                       'user_id/id': 'assigned_user_id',
847                       'description': ['__prettyprint__','description', 'description_html'],
848                       'res_id': 'res_id',
849                       'model': 'model',
850                       'partner_id/.id' : 'partner_id/.id',
851     }
852     mailgate_obj = sugar_obj.pool.get('mailgate.message')
853     model_obj =  sugar_obj.pool.get('ir.model.data')
854     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
855     sugar_data = sugar.search(PortType, sessionid, 'Notes')
856     for val in sugar_data:
857         File, Filename = sugar.attachment_search(PortType, sessionid, 'Notes', val.get('id'))
858         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id')),('model','=', OPENERP_FIEDS_MAPS[val.get('parent_type')])])
859         if model_ids:
860             model = model_obj.browse(cr, uid, model_ids)[0]
861             if model.model == 'res.partner':
862                 val['partner_id/.id'] = model.res_id
863             else:    
864                 val['res_id'] = model.res_id
865                 val['model'] = model.model
866         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_attachment, context)   
867         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
868         get_attachment(sugar_obj, cr, uid, val, 'mailgate.message', File, Filename, val.get('parent_type'), context)
869     return True       
870     
871 def import_employees(sugar_obj, cr, uid, context=None):
872     if not context:
873         context = {}
874     map_employee = {'id' : 'user_hash',
875                     'resource_id/.id': 'resource_id/.id',
876                     'name': ['first_name', 'last_name'],
877                     'work_phone': 'phone_work',
878                     'mobile_phone':  'phone_mobile',
879                     'user_id/name': ['first_name', 'last_name'], 
880                     'address_home_id/.id': 'address_home_id/.id',
881                     'notes': 'description',
882                     #TODO: Creation of Employee create problem.
883                  #   'coach_id/id': 'reports_to_id',
884                     'job_id/.id': 'job_id/.id'
885     }
886     employee_obj = sugar_obj.pool.get('hr.employee')
887     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
888     sugar_data = sugar.search(PortType, sessionid, 'Employees')
889     for val in sugar_data:
890         address_id = get_user_address(sugar_obj, cr, uid, val, context)
891         val['address_home_id/.id'] = address_id
892         model_ids = find_mapped_id(sugar_obj, cr, uid, 'resource.resource', val.get('user_hash')+ '_resource_resource', context)
893         resource_id = sugar_obj.pool.get('ir.model.data').browse(cr, uid, model_ids)
894         if resource_id:
895             val['resource_id/.id'] = resource_id[0].res_id
896         val['job_id/.id'] = get_job_id(sugar_obj, cr, uid, val.get('title'), context)
897         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_employee, context)
898         employee_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
899     return True
900
901 def get_contact_title(sugar_obj, cr, uid, salutation, domain, context=None):
902     if not context:
903         context = {}
904     contact_title_obj = sugar_obj.pool.get('res.partner.title')
905     title_id = False            
906     title_ids = contact_title_obj.search(cr, uid, [('shortcut', '=', salutation), ('domain', '=', domain)])
907     if title_ids:
908          title_id = title_ids[0]
909     elif salutation:
910          title_id = contact_title_obj.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain})
911     return title_id
912     
913 def import_emails(sugar_obj, cr, uid, context=None):
914     if not context:
915         context= {}
916     map_emails = {'id': 'id',
917     'name':'name',
918     'date':['__datetime__', 'date_sent'],
919     'email_from': 'from_addr_name',
920     'email_to': 'reply_to_addr',
921     'email_cc': 'cc_addrs_names',
922     'email_bcc': 'bcc_addrs_names',
923     'message_id': 'message_id',
924     'user_id/id': 'assigned_user_id',
925     'description': ['__prettyprint__', 'description', 'description_html'],
926     'res_id': 'res_id',
927     'model': 'model',
928     'partner_id/.id': 'partner_id/.id'
929     }
930     mailgate_obj = sugar_obj.pool.get('mailgate.message')
931     model_obj = sugar_obj.pool.get('ir.model.data')
932     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
933     sugar_data = sugar.search(PortType, sessionid, 'Emails')
934     for val in sugar_data:
935         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id')),('model','=', OPENERP_FIEDS_MAPS[val.get('parent_type')])])
936         for model in model_obj.browse(cr, uid, model_ids):
937             if model.model == 'res.partner':
938                 val['partner_id/.id'] = model.res_id
939             else:    
940                 val['res_id'] = model.res_id
941                 val['model'] = model.model
942         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_emails, context)
943         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
944     return True    
945     
946 def get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context=None):
947     if not context:
948         context={}
949     partner_id = False
950     partner_invoice_id = False        
951     model_obj = sugar_obj.pool.get('ir.model.data')
952     partner_obj = sugar_obj.pool.get('res.partner')
953     partner_address_obj = sugar_obj.pool.get('res.partner.address')
954     sugar_project_account = sugar.relation_search(PortType, sessionid, 'Project', module_id=val.get('id'), related_module='Accounts', query=None, deleted=None)
955     for account_id in sugar_project_account:
956         model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner', account_id, context)
957         if model_ids:
958             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
959             partner_id = partner_obj.browse(cr, uid, model_id).id
960             address_ids = partner_address_obj.search(cr, uid, [('partner_id', '=', partner_id),('type', '=', 'invoice')])
961             partner_invoice_id = address_ids[0] 
962     return partner_id, partner_invoice_id      
963     
964 def import_projects(sugar_obj, cr, uid, context=None):
965     if not context:
966         context = {}
967     map_project = {'id': 'id',
968         'name': 'name',
969         'date_start': ['__datetime__', 'estimated_start_date'],
970         'date': ['__datetime__', 'estimated_end_date'],
971         'user_id/id': 'assigned_user_id',
972         'partner_id/.id': 'partner_id/.id',
973         'contact_id/.id': 'contact_id/.id', 
974          'state': 'state'   
975     }
976     project_obj = sugar_obj.pool.get('project.project')
977     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
978     sugar_data = sugar.search(PortType, sessionid, 'Project')
979     for val in sugar_data:
980         partner_id, partner_invoice_id = get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context) 
981         val['partner_id/.id'] = partner_id
982         val['contact_id/.id'] = partner_invoice_id 
983         val['state'] = get_project_state(sugar_obj, cr, uid, val.get('status'),context)
984         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project, context)
985         project_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
986     return True 
987
988
989 def import_project_tasks(sugar_obj, cr, uid, context=None):
990     if not context:
991         context = {}
992     map_project_task = {'id': 'id',
993         'name': 'name',
994         'date_start': ['__datetime__', 'date_start'],
995         'date_end': ['__datetime__', 'date_finish'],
996         'progress': 'progress',
997         'project_id/name': 'project_name',
998         'planned_hours': 'planned_hours',
999         'total_hours': 'total_hours',        
1000         'priority': 'priority',
1001         'description': 'description',
1002         'user_id/id': 'assigned_user_id',
1003          'state': 'state'   
1004     }
1005     task_obj = sugar_obj.pool.get('project.task')
1006     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1007     sugar_data = sugar.search(PortType, sessionid, 'ProjectTask')
1008     for val in sugar_data:
1009         val['state'] = get_project_task_state(sugar_obj, cr, uid, val.get('status'),context)
1010         val['priority'] = get_project_task_priority(sugar_obj, cr, uid, val.get('priority'),context)
1011         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project_task, context)
1012         task_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1013     return True 
1014     
1015 def import_leads(sugar_obj, cr, uid, context=None):
1016     if not context:
1017         context = {}
1018     map_lead = {
1019             'id' : 'id',
1020             'name': ['first_name', 'last_name'],
1021             'contact_name': ['first_name', 'last_name'],
1022             'description': ['__prettyprint__', 'description', 'refered_by', 'lead_source', 'lead_source_description', 'website', 'email2', 'status_description', 'lead_source_description', 'do_not_call'],
1023             'partner_name': 'account_name',
1024             'email_from': 'email1',
1025             'phone': 'phone_work',
1026             'mobile': 'phone_mobile',
1027             'title.id': 'title.id',
1028             'function':'title',
1029             'street': 'primary_address_street',
1030             'street2': 'alt_address_street',
1031             'zip': 'primary_address_postalcode',
1032             'city':'primary_address_city',
1033             'user_id/id' : 'assigned_user_id',
1034             'stage_id.id' : 'stage_id.id',
1035             'type' : 'type',
1036             'state': 'state',
1037             'fax': 'phone_fax',
1038             'referred': 'refered_by',
1039             'optout': 'optout',
1040             'type_id/.id': 'type_id/.id',
1041             'country_id.id': 'country_id.id',
1042             'state_id.id': 'state_id.id'
1043             
1044             }
1045         
1046     lead_obj = sugar_obj.pool.get('crm.lead')
1047     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1048     sugar_data = sugar.search(PortType, sessionid, 'Leads')
1049     for val in sugar_data:
1050         if val.get('do_not_call') == '0':
1051             val['optout'] = '1'
1052         if val.get('opportunity_id'):
1053             continue
1054         title_id = get_contact_title(sugar_obj, cr, uid, val.get('salutation'), 'contact', context)
1055         val['title.id'] = title_id
1056         val['type'] = 'lead'
1057         val['type_id/.id'] = get_campaign_id(sugar_obj, cr, uid, val.get('lead_source'), context)
1058         stage_id = get_lead_status(sugar_obj, cr, uid, val, context)
1059         val['stage_id.id'] = stage_id
1060         val['state'] = get_lead_state(sugar_obj, cr, uid, val,context)
1061         if val.get('primary_address_country'):
1062             country_id = get_all_countries(sugar_obj, cr, uid, val.get('primary_address_country'), context)
1063             state = get_all_states(sugar_obj,cr, uid, val.get('primary_address_state'), country_id, context)
1064             val['country_id.id'] =  country_id
1065             val['state_id.id'] =  state            
1066         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_lead, context)
1067         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1068     return True
1069
1070 def get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context=None):
1071     if not context:
1072         context={}
1073     partner_contact_name = False 
1074     partner_contact_email = False       
1075     model_obj = sugar_obj.pool.get('ir.model.data')
1076     partner_address_obj = sugar_obj.pool.get('res.partner.address')
1077     model_account_ids = model_obj.search(cr, uid, [('res_id', '=', partner_xml_id[0]), ('model', '=', 'res.partner'), ('module', '=', 'sugarcrm_import')])
1078     model_xml_id = model_obj.browse(cr, uid, model_account_ids)[0].name 
1079     sugar_account_contact = set(sugar.relation_search(PortType, sessionid, 'Accounts', module_id=model_xml_id, related_module='Contacts', query=None, deleted=None))
1080     sugar_opportunities_contact = set(sugar.relation_search(PortType, sessionid, 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
1081     sugar_contact = list(sugar_account_contact.intersection(sugar_opportunities_contact))
1082     if sugar_contact: 
1083         for contact in sugar_contact:
1084             model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', contact, context)
1085             if model_ids:
1086                 model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
1087                 address_id = partner_address_obj.browse(cr, uid, model_id)
1088                 partner_address_obj.write(cr, uid, [address_id.id], {'partner_id': partner_xml_id[0]})
1089                 partner_contact_name = address_id.name
1090                 partner_contact_email = address_id.email
1091             else:
1092                 partner_contact_name = val.get('account_name')
1093     return partner_contact_name, partner_contact_email
1094
1095 def import_opportunities(sugar_obj, cr, uid, context=None):
1096     if not context:
1097         context = {}
1098     map_opportunity = {'id' : 'id',
1099         'name': 'name',
1100         'probability': 'probability',
1101         'partner_id/name': 'account_name',
1102         'title_action': 'next_step',
1103         'partner_address_id/name': 'partner_address_id/name',
1104         'planned_revenue': 'amount',
1105         'date_deadline': ['__datetime__', 'date_closed'],
1106         'user_id/id' : 'assigned_user_id',
1107         'stage_id.id' : 'stage_id.id',
1108         'type' : 'type',
1109         'categ_id.id': 'categ_id.id',
1110         'email_from': 'email_from'
1111     }
1112     lead_obj = sugar_obj.pool.get('crm.lead')
1113     partner_obj = sugar_obj.pool.get('res.partner')
1114     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1115     sugar_data = sugar.search(PortType, sessionid, 'Opportunities')
1116     for val in sugar_data:
1117         partner_xml_id = partner_obj.search(cr, uid, [('name', 'like', val.get('account_name'))])
1118         if not partner_xml_id:
1119             raise osv.except_osv(_('Warning !'), _('Reference Partner %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('account_name'))
1120         partner_contact_name, partner_contact_email = get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context)
1121         val['partner_address_id/name'] = partner_contact_name
1122         val['email_from'] = partner_contact_email
1123         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'crm.lead', val.get('opportunity_type'))                    
1124         val['type'] = 'opportunity'
1125         stage_id = get_opportunity_status(sugar_obj, cr, uid, val, context)
1126         val['stage_id.id'] = stage_id
1127         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_opportunity, context)
1128         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1129     return True
1130
1131 MAP_FIELDS = {'Opportunities':  #Object Mapping name
1132                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],  #Object to import before this table
1133                      'process' : import_opportunities,
1134                      },
1135               'Leads':
1136                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],  #Object to import before this table
1137                      'process' : import_leads,
1138                     },
1139               'Contacts':
1140                     {'dependencies' : ['Users', 'Accounts'],  #Object to import before this table
1141                      'process' : import_partner_address,
1142                     },
1143               'Accounts':
1144                     {'dependencies' : ['Users'],  #Object to import before this table
1145                      'process' : import_partners,
1146                     },
1147               'Users': 
1148                     {'dependencies' : [],
1149                      'process' : import_users,
1150                     },
1151               'Documents': 
1152                     {'dependencies' : ['Users'],
1153                      'process' : import_documents,
1154                     },
1155               'Meetings': 
1156                     {'dependencies' : ['Users', 'Tasks'],
1157                      'process' : import_meetings,
1158                     },        
1159               'Tasks': 
1160                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
1161                      'process' : import_tasks,
1162                     },  
1163               'Calls': 
1164                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],
1165                      'process' : import_calls,
1166                     }, 
1167               'Claims': 
1168                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],
1169                      'process' : import_claims,
1170                     },
1171               'Employees': 
1172                     {'dependencies' : ['Resources'],
1173                      'process' : import_employees,
1174                     },
1175               'Emails': 
1176                     {'dependencies' : ['Users', 'Projects', 'Project Tasks', 'Accounts', 'Contacts', 'Leads', 'Opportunities', 'Meetings', 'Calls'],
1177                      'process' : import_emails,
1178                     },    
1179               'Projects': 
1180                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
1181                      'process' : import_projects,
1182                     },                        
1183               'Project Tasks': 
1184                     {'dependencies' : ['Users', 'Projects'],
1185                      'process' : import_project_tasks,
1186                     },
1187               'Bugs': 
1188                     {'dependencies' : ['Users', 'Projects', 'Project Tasks'],
1189                      'process' : import_bug,
1190                     },   
1191               'Notes': 
1192                     {'dependencies' : [],
1193                      'process' : import_history,
1194                     },                    
1195               'Resources': 
1196                     {'dependencies' : ['Users'],
1197                      'process' : import_resources,
1198                     },                                      
1199           }
1200
1201 class import_sugarcrm(osv.osv):
1202     """Import SugarCRM DATA"""
1203     
1204     _name = "import.sugarcrm"
1205     _description = __doc__
1206     _columns = {
1207         'opportunity': fields.boolean('Leads and Opportunities', help="If Opportunities are checked, SugarCRM opportunities data imported in OpenERP crm-Opportunity form"),
1208         'user': fields.boolean('Users', help="If Users  are checked, SugarCRM Users data imported in OpenERP Users form"),
1209         'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
1210         'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
1211         'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
1212         'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings data imported in OpenERP meetings form"),
1213         'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
1214         'claim': fields.boolean('Claims', help="If Claims is checked, SugarCRM Claims data imported in OpenERP Claims form"),
1215         'email': fields.boolean('Emails', help="If Emails is checked, SugarCRM Emails data imported in OpenERP Emails form"),
1216         'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
1217         'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
1218         'task': fields.boolean('Tasks', help="If Tasks is checked, SugarCRM Tasks data imported in OpenERP Meetings form"),
1219         'bug': fields.boolean('Bugs', help="If Bugs is checked, SugarCRM Bugs data imported in OpenERP Project Issues form"),
1220         'attachment': fields.boolean('Attachments', help="If Attachments is checked, SugarCRM Notes data imported in OpenERP's Related module's History with attachment"),
1221          'document': fields.boolean('Documents', help="If Documents is checked, SugarCRM Documents data imported in OpenERP Document Form"),
1222         'username': fields.char('User Name', size=64),
1223         'password': fields.char('Password', size=24),
1224     }
1225     _defaults = {#to be set to true, but easier for debugging
1226        'opportunity': True,
1227        'user' : True,
1228        'contact' : True,
1229        'account' : True,
1230         'employee' : True,
1231         'meeting' : True,
1232         'task' : True,
1233         'call' : True,
1234         'claim' : True,    
1235         'email' : True, 
1236         'project' : True,   
1237         'project_task': True,     
1238         'bug': True,
1239         'document': True
1240     }
1241     
1242     def get_key(self, cr, uid, ids, context=None):
1243         """Select Key as For which Module data we want import data."""
1244         if not context:
1245             context = {}
1246         key_list = []
1247         for current in self.browse(cr, uid, ids, context):
1248             if current.opportunity:
1249                 key_list.append('Opportunities')
1250             if current.user:
1251                 key_list.append('Users')
1252             if current.contact:
1253                 key_list.append('Contacts')
1254             if current.account:
1255                 key_list.append('Accounts') 
1256             if current.employee:
1257                 key_list.append('Employees')  
1258             if current.meeting:
1259                 key_list.append('Meetings')
1260             if current.task:
1261                 key_list.append('Tasks')
1262             if current.call:
1263                 key_list.append('Calls')
1264             if current.claim:
1265                 key_list.append('Claims')                
1266             if current.email:
1267                 key_list.append('Emails') 
1268             if current.project:
1269                 key_list.append('Projects')
1270             if current.project_task:
1271                 key_list.append('Project Tasks')
1272             if current.bug:
1273                 key_list.append('Bugs')
1274             if current.attachment:
1275                 key_list.append('Notes')     
1276             if current.document:
1277                 key_list.append('Documents')                                                  
1278         return key_list
1279
1280     def import_all(self, cr, uid, ids, context=None):
1281         """Import all sugarcrm data into openerp module"""
1282         if not context:
1283             context = {}
1284         keys = self.get_key(cr, uid, ids, context)
1285         imported = set() #to invoid importing 2 times the sames modules
1286         for key in keys:
1287             if not key in imported:
1288                 self.resolve_dependencies(cr, uid, MAP_FIELDS, MAP_FIELDS[key]['dependencies'], imported, context=context)
1289                 MAP_FIELDS[key]['process'](self, cr, uid, context)
1290                 imported.add(key)
1291
1292         obj_model = self.pool.get('ir.model.data')
1293         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
1294         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
1295         return {
1296                 'view_type': 'form',
1297                 'view_mode': 'form',
1298                 'res_model': 'import.message',
1299                 'views': [(resource_id,'form')],
1300                 'type': 'ir.actions.act_window',
1301                 'target': 'new',
1302             }
1303
1304     def resolve_dependencies(self, cr, uid, dict, dep, imported, context=None):
1305         for dependency in dep:
1306             if not dependency in imported:
1307                 self.resolve_dependencies(cr, uid, dict, dict[dependency]['dependencies'], imported, context=context)
1308                 dict[dependency]['process'](self, cr, uid, context)
1309                 imported.add(dependency)
1310         return True        
1311
1312 import_sugarcrm()