[IMP]: Remove xml_id prefix.
[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, context=None):
818     if not context:
819         context = {}
820     attach_ids = False    
821     attachment_obj = sugar_obj.pool.get('ir.attachment')
822     model_obj = sugar_obj.pool.get('ir.model.data')
823     mailgate_obj = sugar_obj.pool.get('mailgate.message')
824     attach_ids = attachment_obj.search(cr, uid, [('res_id','=', val.get('res_id'), ('res_model', '=', val.get('model')))])
825     if not attach_ids:
826         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)})
827         message_model_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
828         message_xml_id = model_obj.browse(cr, uid, message_model_ids)
829         if message_xml_id:
830           mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)]})                         
831     return True    
832     
833 def import_history(sugar_obj, cr, uid, context=None):
834     if not context:
835         context = {}
836     map_attachment = {'id' : 'id',
837                       'name':'name',
838                       'date': ['__datetime__', 'date_entered'],
839                       'user_id/id': 'assigned_user_id',
840                       'description': ['__prettyprint__','description', 'description_html'],
841                       'res_id': 'res_id',
842                       'model': 'model',
843                       'partner_id/.id' : 'partner_id/.id',
844     }
845     mailgate_obj = sugar_obj.pool.get('mailgate.message')
846     model_obj =  sugar_obj.pool.get('ir.model.data')
847     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
848     sugar_data = sugar.search(PortType, sessionid, 'Notes')
849     for val in sugar_data:
850         File, Filename = sugar.attachment_search(PortType, sessionid, 'Notes', val.get('id'))
851         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id')),('model','=', OPENERP_FIEDS_MAPS[val.get('parent_type')])])
852         if model_ids:
853             model = model_obj.browse(cr, uid, model_ids)[0]
854             if model.model == 'res.partner':
855                 val['partner_id/.id'] = model.res_id
856             else:    
857                 val['res_id'] = model.res_id
858                 val['model'] = model.model
859         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_attachment, context)   
860         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
861         get_attachment(sugar_obj, cr, uid, val, 'mailgate.message', File, Filename, context)
862     return True       
863     
864 def import_employees(sugar_obj, cr, uid, context=None):
865     if not context:
866         context = {}
867     map_employee = {'id' : 'user_hash',
868                     'resource_id/.id': 'resource_id/.id',
869                     'name': ['first_name', 'last_name'],
870                     'work_phone': 'phone_work',
871                     'mobile_phone':  'phone_mobile',
872                     'user_id/name': ['first_name', 'last_name'], 
873                     'address_home_id/.id': 'address_home_id/.id',
874                     'notes': 'description',
875                     #TODO: Creation of Employee create problem.
876                  #   'coach_id/id': 'reports_to_id',
877                     'job_id/.id': 'job_id/.id'
878     }
879     employee_obj = sugar_obj.pool.get('hr.employee')
880     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
881     sugar_data = sugar.search(PortType, sessionid, 'Employees')
882     for val in sugar_data:
883         address_id = get_user_address(sugar_obj, cr, uid, val, context)
884         val['address_home_id/.id'] = address_id
885         model_ids = find_mapped_id(sugar_obj, cr, uid, 'resource.resource', val.get('user_hash')+ '_resource_resource', context)
886         resource_id = sugar_obj.pool.get('ir.model.data').browse(cr, uid, model_ids)
887         if resource_id:
888             val['resource_id/.id'] = resource_id[0].res_id
889         val['job_id/.id'] = get_job_id(sugar_obj, cr, uid, val.get('title'), context)
890         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_employee, context)
891         employee_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
892     return True
893
894 def get_contact_title(sugar_obj, cr, uid, salutation, domain, context=None):
895     if not context:
896         context = {}
897     contact_title_obj = sugar_obj.pool.get('res.partner.title')
898     title_id = False            
899     title_ids = contact_title_obj.search(cr, uid, [('shortcut', '=', salutation), ('domain', '=', domain)])
900     if title_ids:
901          title_id = title_ids[0]
902     elif salutation:
903          title_id = contact_title_obj.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain})
904     return title_id
905     
906 def import_emails(sugar_obj, cr, uid, context=None):
907     if not context:
908         context= {}
909     map_emails = {'id': 'id',
910     'name':'name',
911     'date':['__datetime__', 'date_sent'],
912     'email_from': 'from_addr_name',
913     'email_to': 'reply_to_addr',
914     'email_cc': 'cc_addrs_names',
915     'email_bcc': 'bcc_addrs_names',
916     'message_id': 'message_id',
917     'user_id/id': 'assigned_user_id',
918     'description': ['__prettyprint__', 'description', 'description_html'],
919     'res_id': 'res_id',
920     'model': 'model',
921     'partner_id/.id': 'partner_id/.id'
922     }
923     mailgate_obj = sugar_obj.pool.get('mailgate.message')
924     model_obj = sugar_obj.pool.get('ir.model.data')
925     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
926     sugar_data = sugar.search(PortType, sessionid, 'Emails')
927     for val in sugar_data:
928         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id')),('model','=', OPENERP_FIEDS_MAPS[val.get('parent_type')])])
929         for model in model_obj.browse(cr, uid, model_ids):
930             if model.model == 'res.partner':
931                 val['partner_id/.id'] = model.res_id
932             else:    
933                 val['res_id'] = model.res_id
934                 val['model'] = model.model
935         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_emails, context)
936         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
937     return True    
938     
939 def get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context=None):
940     if not context:
941         context={}
942     partner_id = False
943     partner_invoice_id = False        
944     model_obj = sugar_obj.pool.get('ir.model.data')
945     partner_obj = sugar_obj.pool.get('res.partner')
946     partner_address_obj = sugar_obj.pool.get('res.partner.address')
947     sugar_project_account = sugar.relation_search(PortType, sessionid, 'Project', module_id=val.get('id'), related_module='Accounts', query=None, deleted=None)
948     for account_id in sugar_project_account:
949         model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner', account_id, context)
950         if model_ids:
951             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
952             partner_id = partner_obj.browse(cr, uid, model_id).id
953             address_ids = partner_address_obj.search(cr, uid, [('partner_id', '=', partner_id),('type', '=', 'invoice')])
954             partner_invoice_id = address_ids[0] 
955     return partner_id, partner_invoice_id      
956     
957 def import_projects(sugar_obj, cr, uid, context=None):
958     if not context:
959         context = {}
960     map_project = {'id': 'id',
961         'name': 'name',
962         'date_start': ['__datetime__', 'estimated_start_date'],
963         'date': ['__datetime__', 'estimated_end_date'],
964         'user_id/id': 'assigned_user_id',
965         'partner_id/.id': 'partner_id/.id',
966         'contact_id/.id': 'contact_id/.id', 
967          'state': 'state'   
968     }
969     project_obj = sugar_obj.pool.get('project.project')
970     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
971     sugar_data = sugar.search(PortType, sessionid, 'Project')
972     for val in sugar_data:
973         partner_id, partner_invoice_id = get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context) 
974         val['partner_id/.id'] = partner_id
975         val['contact_id/.id'] = partner_invoice_id 
976         val['state'] = get_project_state(sugar_obj, cr, uid, val.get('status'),context)
977         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project, context)
978         project_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
979     return True 
980
981
982 def import_project_tasks(sugar_obj, cr, uid, context=None):
983     if not context:
984         context = {}
985     map_project_task = {'id': 'id',
986         'name': 'name',
987         'date_start': ['__datetime__', 'date_start'],
988         'date_end': ['__datetime__', 'date_finish'],
989         'progress': 'progress',
990         'project_id/name': 'project_name',
991         'planned_hours': 'planned_hours',
992         'total_hours': 'total_hours',        
993         'priority': 'priority',
994         'description': 'description',
995         'user_id/id': 'assigned_user_id',
996          'state': 'state'   
997     }
998     task_obj = sugar_obj.pool.get('project.task')
999     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1000     sugar_data = sugar.search(PortType, sessionid, 'ProjectTask')
1001     for val in sugar_data:
1002         val['state'] = get_project_task_state(sugar_obj, cr, uid, val.get('status'),context)
1003         val['priority'] = get_project_task_priority(sugar_obj, cr, uid, val.get('priority'),context)
1004         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project_task, context)
1005         task_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1006     return True 
1007     
1008 def import_leads(sugar_obj, cr, uid, context=None):
1009     if not context:
1010         context = {}
1011     map_lead = {
1012             'id' : 'id',
1013             'name': ['first_name', 'last_name'],
1014             'contact_name': ['first_name', 'last_name'],
1015             'description': ['__prettyprint__', 'description', 'refered_by', 'lead_source', 'lead_source_description', 'website', 'email2', 'status_description', 'lead_source_description', 'do_not_call'],
1016             'partner_name': 'account_name',
1017             'email_from': 'email1',
1018             'phone': 'phone_work',
1019             'mobile': 'phone_mobile',
1020             'title.id': 'title.id',
1021             'function':'title',
1022             'street': 'primary_address_street',
1023             'street2': 'alt_address_street',
1024             'zip': 'primary_address_postalcode',
1025             'city':'primary_address_city',
1026             'user_id/id' : 'assigned_user_id',
1027             'stage_id.id' : 'stage_id.id',
1028             'type' : 'type',
1029             'state': 'state',
1030             'fax': 'phone_fax',
1031             'referred': 'refered_by',
1032             'optout': 'optout',
1033             'type_id/.id': 'type_id/.id'
1034             }
1035         
1036     lead_obj = sugar_obj.pool.get('crm.lead')
1037     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1038     sugar_data = sugar.search(PortType, sessionid, 'Leads')
1039     for val in sugar_data:
1040         if val.get('do_not_call') == '0':
1041             val['optout'] = '1'
1042         if val.get('opportunity_id'):
1043             continue
1044         title_id = get_contact_title(sugar_obj, cr, uid, val.get('salutation'), 'contact', context)
1045         val['title.id'] = title_id
1046         val['type'] = 'lead'
1047         val['type_id/.id'] = get_campaign_id(sugar_obj, cr, uid, val.get('lead_source'), context)
1048         stage_id = get_lead_status(sugar_obj, cr, uid, val, context)
1049         val['stage_id.id'] = stage_id
1050         val['state'] = get_lead_state(sugar_obj, cr, uid, val,context)
1051         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_lead, context)
1052         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1053     return True
1054
1055 def get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context=None):
1056     if not context:
1057         context={}
1058     partner_contact_name = False 
1059     partner_contact_email = False       
1060     model_obj = sugar_obj.pool.get('ir.model.data')
1061     partner_address_obj = sugar_obj.pool.get('res.partner.address')
1062     model_account_ids = model_obj.search(cr, uid, [('res_id', '=', partner_xml_id[0]), ('model', '=', 'res.partner'), ('module', '=', 'sugarcrm_import')])
1063     model_xml_id = model_obj.browse(cr, uid, model_account_ids)[0].name 
1064     sugar_account_contact = set(sugar.relation_search(PortType, sessionid, 'Accounts', module_id=model_xml_id, related_module='Contacts', query=None, deleted=None))
1065     sugar_opportunities_contact = set(sugar.relation_search(PortType, sessionid, 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
1066     sugar_contact = list(sugar_account_contact.intersection(sugar_opportunities_contact))
1067     if sugar_contact: 
1068         for contact in sugar_contact:
1069             model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', contact, context)
1070             if model_ids:
1071                 model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
1072                 address_id = partner_address_obj.browse(cr, uid, model_id)
1073                 partner_address_obj.write(cr, uid, [address_id.id], {'partner_id': partner_xml_id[0]})
1074                 partner_contact_name = address_id.name
1075                 partner_contact_email = address_id.email
1076             else:
1077                 partner_contact_name = val.get('account_name')    
1078     return partner_contact_name, partner_contact_email
1079
1080 def import_opportunities(sugar_obj, cr, uid, context=None):
1081     if not context:
1082         context = {}
1083     map_opportunity = {'id' : 'id',
1084         'name': 'name',
1085         'probability': 'probability',
1086         'partner_id/name': 'account_name',
1087         'title_action': 'next_step',
1088         'partner_address_id/name': 'partner_address_id/name',
1089         'planned_revenue': 'amount',
1090         'date_deadline': ['__datetime__', 'date_closed'],
1091         'user_id/id' : 'assigned_user_id',
1092         'stage_id.id' : 'stage_id.id',
1093         'type' : 'type',
1094         'categ_id.id': 'categ_id.id',
1095         'email_from': 'email_from'
1096     }
1097     lead_obj = sugar_obj.pool.get('crm.lead')
1098     partner_obj = sugar_obj.pool.get('res.partner')
1099     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1100     sugar_data = sugar.search(PortType, sessionid, 'Opportunities')
1101     for val in sugar_data:
1102         partner_xml_id = partner_obj.search(cr, uid, [('name', 'like', val.get('account_name'))])
1103         if not partner_xml_id:
1104             raise osv.except_osv(_('Warning !'), _('Reference Partner %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('account_name'))
1105         partner_contact_name, partner_contact_email = get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context)
1106         val['partner_address_id/name'] = partner_contact_name
1107         val['email_from'] = partner_contact_email
1108         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'crm.lead', val.get('opportunity_type'))                    
1109         val['type'] = 'opportunity'
1110         stage_id = get_opportunity_status(sugar_obj, cr, uid, val, context)
1111         val['stage_id.id'] = stage_id
1112         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_opportunity, context)
1113         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1114     return True
1115
1116 MAP_FIELDS = {'Opportunities':  #Object Mapping name
1117                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],  #Object to import before this table
1118                      'process' : import_opportunities,
1119                      },
1120               'Leads':
1121                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],  #Object to import before this table
1122                      'process' : import_leads,
1123                     },
1124               'Contacts':
1125                     {'dependencies' : ['Users', 'Accounts'],  #Object to import before this table
1126                      'process' : import_partner_address,
1127                     },
1128               'Accounts':
1129                     {'dependencies' : ['Users'],  #Object to import before this table
1130                      'process' : import_partners,
1131                     },
1132               'Users': 
1133                     {'dependencies' : [],
1134                      'process' : import_users,
1135                     },
1136               'Documents': 
1137                     {'dependencies' : ['Users'],
1138                      'process' : import_documents,
1139                     },
1140               'Meetings': 
1141                     {'dependencies' : ['Users', 'Tasks'],
1142                      'process' : import_meetings,
1143                     },        
1144               'Tasks': 
1145                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
1146                      'process' : import_tasks,
1147                     },  
1148               'Calls': 
1149                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],
1150                      'process' : import_calls,
1151                     }, 
1152               'Claims': 
1153                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],
1154                      'process' : import_claims,
1155                     },
1156               'Employees': 
1157                     {'dependencies' : ['Resources'],
1158                      'process' : import_employees,
1159                     },
1160               'Emails': 
1161                     {'dependencies' : ['Users', 'Projects', 'Project Tasks', 'Accounts', 'Contacts', 'Leads', 'Opportunities', 'Meetings', 'Calls'],
1162                      'process' : import_emails,
1163                     },    
1164               'Projects': 
1165                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
1166                      'process' : import_projects,
1167                     },                        
1168               'Project Tasks': 
1169                     {'dependencies' : ['Users', 'Projects'],
1170                      'process' : import_project_tasks,
1171                     },
1172               'Bugs': 
1173                     {'dependencies' : ['Users', 'Projects', 'Project Tasks'],
1174                      'process' : import_bug,
1175                     },   
1176               'Notes': 
1177                     {'dependencies' : ['Users', 'Projects', 'Project Tasks', 'Accounts', 'Contacts', 'Leads', 'Opportunities', 'Meetings', 'Calls'],
1178                      'process' : import_history,
1179                     },                    
1180               'Resources': 
1181                     {'dependencies' : ['Users'],
1182                      'process' : import_resources,
1183                     },                                      
1184           }
1185
1186 class import_sugarcrm(osv.osv):
1187     """Import SugarCRM DATA"""
1188     
1189     _name = "import.sugarcrm"
1190     _description = __doc__
1191     _columns = {
1192         'opportunity': fields.boolean('Leads and Opportunities', help="If Opportunities are checked, SugarCRM opportunities data imported in OpenERP crm-Opportunity form"),
1193         'user': fields.boolean('Users', help="If Users  are checked, SugarCRM Users data imported in OpenERP Users form"),
1194         'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
1195         'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
1196         'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
1197         'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings data imported in OpenERP meetings form"),
1198         'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
1199         'claim': fields.boolean('Claims', help="If Claims is checked, SugarCRM Claims data imported in OpenERP Claims form"),
1200         'email': fields.boolean('Emails', help="If Emails is checked, SugarCRM Emails data imported in OpenERP Emails form"),
1201         'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
1202         'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
1203         'task': fields.boolean('Tasks', help="If Tasks is checked, SugarCRM Tasks data imported in OpenERP Meetings form"),
1204         'bug': fields.boolean('Bugs', help="If Bugs is checked, SugarCRM Bugs data imported in OpenERP Project Issues form"),
1205         'attachment': fields.boolean('Attachments', help="If Attachments is checked, SugarCRM Notes data imported in OpenERP's Related module's History with attachment"),
1206          'document': fields.boolean('Documents', help="If Documents is checked, SugarCRM Documents data imported in OpenERP Document Form"),
1207         'username': fields.char('User Name', size=64),
1208         'password': fields.char('Password', size=24),
1209     }
1210     _defaults = {#to be set to true, but easier for debugging
1211        'opportunity': True,
1212        'user' : True,
1213        'contact' : True,
1214        'account' : True,
1215         'employee' : True,
1216         'meeting' : True,
1217         'task' : True,
1218         'call' : True,
1219         'claim' : True,    
1220         'email' : True, 
1221         'project' : True,   
1222         'project_task': True,     
1223         'bug': True,
1224         'document': True
1225     }
1226     
1227     def get_key(self, cr, uid, ids, context=None):
1228         """Select Key as For which Module data we want import data."""
1229         if not context:
1230             context = {}
1231         key_list = []
1232         for current in self.browse(cr, uid, ids, context):
1233             if current.opportunity:
1234                 key_list.append('Opportunities')
1235             if current.user:
1236                 key_list.append('Users')
1237             if current.contact:
1238                 key_list.append('Contacts')
1239             if current.account:
1240                 key_list.append('Accounts') 
1241             if current.employee:
1242                 key_list.append('Employees')  
1243             if current.meeting:
1244                 key_list.append('Meetings')
1245             if current.task:
1246                 key_list.append('Tasks')
1247             if current.call:
1248                 key_list.append('Calls')
1249             if current.claim:
1250                 key_list.append('Claims')                
1251             if current.email:
1252                 key_list.append('Emails') 
1253             if current.project:
1254                 key_list.append('Projects')
1255             if current.project_task:
1256                 key_list.append('Project Tasks')
1257             if current.bug:
1258                 key_list.append('Bugs')
1259             if current.attachment:
1260                 key_list.append('Notes')     
1261             if current.document:
1262                 key_list.append('Documents')                                                  
1263         return key_list
1264
1265     def import_all(self, cr, uid, ids, context=None):
1266         """Import all sugarcrm data into openerp module"""
1267         if not context:
1268             context = {}
1269         keys = self.get_key(cr, uid, ids, context)
1270         imported = set() #to invoid importing 2 times the sames modules
1271         for key in keys:
1272             if not key in imported:
1273                 self.resolve_dependencies(cr, uid, MAP_FIELDS, MAP_FIELDS[key]['dependencies'], imported, context=context)
1274                 MAP_FIELDS[key]['process'](self, cr, uid, context)
1275                 imported.add(key)
1276
1277         obj_model = self.pool.get('ir.model.data')
1278         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
1279         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
1280         return {
1281                 'view_type': 'form',
1282                 'view_mode': 'form',
1283                 'res_model': 'import.message',
1284                 'views': [(resource_id,'form')],
1285                 'type': 'ir.actions.act_window',
1286                 'target': 'new',
1287             }
1288
1289     def resolve_dependencies(self, cr, uid, dict, dep, imported, context=None):
1290         for dependency in dep:
1291             if not dependency in imported:
1292                 self.resolve_dependencies(cr, uid, dict, dict[dependency]['dependencies'], imported, context=context)
1293                 dict[dependency]['process'](self, cr, uid, context)
1294                 imported.add(dependency)
1295         return True        
1296
1297 import_sugarcrm()