68157e8ef6a6f8f8586912914ec7bb19776daa7b
[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         val['id'] = 'sugarcrm_'+'user_'+ val.get('id')
153         if user_ids: 
154             val['.id'] = str(user_ids[0])
155         else:
156             val['password'] = 'sugarcrm' #default password for all user
157         department_id = get_users_department(sugar_obj, cr, uid, val.get('department'), context=context)
158         val['context_department_id.id'] = department_id     
159         val['context_lang'] = context.get('lang','en_US')
160         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_user, context)
161         #All data has to be imported separatly because they don't have the same field
162         user_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
163     return True
164
165 def get_lead_status(surgar_obj, cr, uid, sugar_val,context=None):
166     if not context:
167         context = {}
168     stage_id = False
169     stage_dict = {'status': #field in the sugarcrm database
170         { #Mapping of sugarcrm stage : openerp opportunity stage
171             'New' : 'New',
172             'Assigned':'Qualification',
173             'In Progress': 'Proposition',
174             'Recycled': 'Negotiation',
175             'Dead': 'Lost'
176         },}
177     stage = stage_dict['status'].get(sugar_val['status'], '')
178     stage_pool = surgar_obj.pool.get('crm.case.stage')
179     stage_ids = stage_pool.search(cr, uid, [('type', '=', 'lead'), ('name', '=', stage)])
180     for stage in stage_pool.browse(cr, uid, stage_ids, context):
181         stage_id = stage.id
182     return stage_id
183
184 def get_lead_state(surgar_obj, cr, uid, sugar_val,context=None):
185     if not context:
186         context = {}
187     state = False
188     state_dict = {'status': #field in the sugarcrm database
189         { #Mapping of sugarcrm stage : openerp opportunity stage
190             'New' : 'draft',
191             'Assigned':'open',
192             'In Progress': 'open',
193             'Recycled': 'cancel',
194             'Dead': 'done'
195         },}
196     state = state_dict['status'].get(sugar_val['status'], '')
197     return state
198
199 def get_opportunity_status(surgar_obj, cr, uid, sugar_val,context=None):
200     if not context:
201         context = {}
202     stage_id = False
203     stage_dict = { 'sales_stage':
204             {#Mapping of sugarcrm stage : openerp opportunity stage Mapping
205                'Need Analysis': 'New',
206                'Closed Lost': 'Lost',
207                'Closed Won': 'Won',
208                'Value Proposition': 'Proposition',
209                 'Negotiation/Review': 'Negotiation'
210             },
211     }
212     stage = stage_dict['sales_stage'].get(sugar_val['sales_stage'], '')
213     stage_pool = surgar_obj.pool.get('crm.case.stage')
214     stage_ids = stage_pool.search(cr, uid, [('type', '=', 'opportunity'), ('name', '=', stage)])
215     for stage in stage_pool.browse(cr, uid, stage_ids, context):
216         stage_id = stage.id
217     return stage_id
218
219 def get_user_address(sugar_obj, cr, uid, val, context=None):
220     address_obj = sugar_obj.pool.get('res.partner.address')
221     map_user_address = {
222     'name': ['first_name', 'last_name'],
223     'city': 'address_city',
224     'country_id': 'country_id',
225     'state_id': 'state_id',
226     'street': 'address_street',
227     'zip': 'address_postalcode',
228     }
229     address_ids = address_obj.search(cr, uid, [('name', 'like', val.get('first_name') +' '+ val.get('last_name'))])
230     if val.get('address_country'):
231         country_id = get_all_countries(sugar_obj, cr, uid, val.get('address_country'), context)
232         state_id = get_all_states(sugar_obj, cr, uid, val.get('address_state'), country_id, context)
233         val['country_id'] =  country_id
234         val['state_id'] =  state_id
235     fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_user_address, context)
236     dict_val = dict(zip(fields,datas))
237     if address_ids:
238         address_obj.write(cr, uid, address_ids, dict_val)
239     else:        
240         new_address_id = address_obj.create(cr,uid, dict_val)
241         return new_address_id
242     return True
243
244 def get_address_type(sugar_obj, cr, uid, val, map_partner_address, type, context=None):
245         address_obj = sugar_obj.pool.get('res.partner.address')
246         new_address_id = False
247         if type == 'invoice':
248             type_address = 'billing'
249         else:
250             type_address = 'shipping'     
251     
252         map_partner_address.update({
253             'street': type_address + '_address_street',
254             'zip': type_address +'_address_postalcode',
255             'city': type_address +'_address_city',
256              'country_id': 'country_id',
257              'type': 'type',
258             })
259         val['type'] = type
260         if val.get(type_address +'_address_country'):
261             country_id = get_all_countries(sugar_obj, cr, uid, val.get(type_address +'_address_country'), context)
262             state = get_all_states(sugar_obj, cr, uid, val.get(type_address +'_address_state'), country_id, context)
263             val['country_id'] =  country_id
264             val['state_id'] =  state
265         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_partner_address, context)
266         #Convert To list into Dictionary(Key, val). value pair.
267         dict_val = dict(zip(fields,datas))
268         new_address_id = address_obj.create(cr,uid, dict_val)
269         return new_address_id
270     
271 def get_address(sugar_obj, cr, uid, val, context=None):
272     map_partner_address={}
273     address_id=[]
274     address_obj = sugar_obj.pool.get('res.partner.address')
275     address_ids = address_obj.search(cr, uid, [('name', '=',val.get('name')), ('type', 'in', ('invoice', 'delivery')), ('street', '=', val.get('billing_address_street'))])
276     if address_ids:
277         return address_ids 
278     else:
279         map_partner_address = {
280             'id': 'id',                    
281             'name': 'name',
282             'partner_id/id': 'account_id',
283             'phone': 'phone_office',
284             'mobile': 'phone_mobile',
285             'fax': 'phone_fax',
286             'type': 'type',
287             }
288         if val.get('billing_address_street'):
289             address_id.append(get_address_type(sugar_obj, cr, uid, val, map_partner_address, 'invoice', context))
290             
291         if val.get('shipping_address_street'):
292             address_id.append(get_address_type(sugar_obj, cr, uid, val, map_partner_address, 'delivery', context))
293         return address_id
294     return True
295
296 def import_partners(sugar_obj, cr, uid, context=None):
297     if not context:
298         context = {}
299     map_partner = {
300                 'id': 'id',
301                 'name': 'name',
302                 'website': 'website',
303                 'user_id/id': 'assigned_user_id',
304                 'ref': 'sic_code',
305                 'comment': ['__prettyprint__', 'description', 'employees', 'ownership', 'annual_revenue', 'rating', 'industry', 'ticker_symbol'],
306                 'customer': 'customer',
307                 'supplier': 'supplier', 
308                 }
309     partner_obj = sugar_obj.pool.get('res.partner')
310     address_obj = sugar_obj.pool.get('res.partner.address')
311     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
312     sugar_data = sugar.search(PortType, sessionid, 'Accounts')
313     for val in sugar_data:
314         val['id'] = 'sugarcrm_'+'account_'+ val.get('id')
315         add_id = get_address(sugar_obj, cr, uid, val, context)
316         val['customer'] = '1'
317         val['supplier'] = '0'
318         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_partner, context)
319         partner_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
320         for address in  address_obj.browse(cr,uid,add_id):
321             data_id = partner_obj.search(cr,uid,[('name','like',address.name),('website','like',val.get('website'))])
322             if data_id:
323                 address_obj.write(cr,uid,address.id,{'partner_id':data_id[0]})                
324     return True
325
326 def get_category(sugar_obj, cr, uid, model, name, context=None):
327     categ_id = False
328     categ_obj = sugar_obj.pool.get('crm.case.categ')
329     categ_ids = categ_obj.search(cr, uid, [('object_id.model','=',model), ('name', 'like', name)] )
330     if categ_ids:
331         categ_id = categ_ids[0]
332     else:
333         model_ids = sugar_obj.pool.get('ir.model').search(cr, uid, [('model', '=', model)], context=context)
334         model = model_ids and model_ids[0] or False
335         categ_id = categ_obj.create(cr, uid, {'name': name, 'object_id': model})
336     return categ_id     
337
338 def get_alarm_id(sugar_obj, cr, uid, val, context=None):
339     
340     alarm_dict = {'60': '1 minute before',
341                   '300': '5 minutes before',
342                   '600': '10 minutes before',
343                   '900': '15 minutes before',
344                   '1800':'30 minutes before',
345                   '3600': '1 hour before',
346      }
347     alarm_id = False
348     alarm_obj = sugar_obj.pool.get('res.alarm')
349     if alarm_dict.get(val):
350         alarm_ids = alarm_obj.search(cr, uid, [('name', 'like', alarm_dict.get(val))])
351         for alarm in alarm_obj.browse(cr, uid, alarm_ids, context):
352             alarm_id = alarm.id
353     return alarm_id 
354     
355 def get_meeting_state(sugar_obj, cr, uid, val,context=None):
356     if not context:
357         context = {}
358     state = False
359     state_dict = {'status': #field in the sugarcrm database
360         { #Mapping of sugarcrm stage : openerp meeting stage
361             'Planned' : 'draft',
362             'Held':'open',
363             'Not Held': 'draft',
364         },}
365     state = state_dict['status'].get(val, '')
366     return state    
367
368 def get_task_state(sugar_obj, cr, uid, val, context=None):
369     if not context:
370         context = {}
371     state = False
372     state_dict = {'status': #field in the sugarcrm database
373         { #Mapping of sugarcrm stage : openerp meeting stage
374             'Completed' : 'done',
375             'Not Started':'draft',
376             'In Progress': 'open',
377             'Pending Input': 'draft',
378             'deferred': 'cancel'
379         },}
380     state = state_dict['status'].get(val, '')
381     return state    
382
383 def get_project_state(sugar_obj, cr, uid, val,context=None):
384     if not context:
385         context = {}
386     state = False
387     state_dict = {'status': #field in the sugarcrm database
388         { #Mapping of sugarcrm staus : openerp Projects state
389             'Draft' : 'draft',
390             'In Review': 'open',
391             'Published': 'close',
392         },}
393     state = state_dict['status'].get(val, '')
394     return state    
395
396 def get_project_task_state(sugar_obj, cr, uid, val,context=None):
397     if not context:
398         context = {}
399     state = False
400     state_dict = {'status': #field in the sugarcrm database
401         { #Mapping of sugarcrm status : openerp Porject Tasks state
402              'Not Started': 'draft',
403              'In Progress': 'open',
404              'Completed': 'done',
405             'Pending Input': 'pending',
406             'Deferred': 'cancelled',
407         },}
408     state = state_dict['status'].get(val, '')
409     return state    
410
411 def get_project_task_priority(sugar_obj, cr, uid, val,context=None):
412     if not context:
413         context = {}
414     priority = False
415     priority_dict = {'priority': #field in the sugarcrm database
416         { #Mapping of sugarcrm status : openerp Porject Tasks state
417             'High': '0',
418             'Medium': '2',
419             'Low': '3'
420         },}
421     priority = priority_dict['priority'].get(val, '')
422     return priority    
423
424
425 def get_account(sugar_obj, cr, uid, val, context=None):
426     if not context:
427         context = {}
428     partner_id = False    
429     partner_address_id = False
430     partner_phone = False
431     partner_mobile = False
432     model_obj = sugar_obj.pool.get('ir.model.data')
433     address_obj = sugar_obj.pool.get('res.partner.address')
434     crm_obj = sugar_obj.pool.get('crm.lead')
435     project_obj = sugar_obj.pool.get('project.project')
436     issue_obj = sugar_obj.pool.get('project.issue')
437     if val.get('parent_type') == 'Accounts':
438         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner')])
439         if model_ids:
440             model = model_obj.browse(cr, uid, model_ids)[0]
441             partner_id = model.res_id
442             address_ids = address_obj.search(cr, uid, [('partner_id', '=', partner_id)])
443             if address_ids:
444                 address_id = address_obj.browse(cr, uid, address_ids[0])
445                 partner_address_id = address_id.id
446                 partner_phone = address_id.phone
447                 partner_mobile = address_id.mobile
448             
449     if val.get('parent_type') == 'Contacts':
450         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner.address')])
451         for model in model_obj.browse(cr, uid, model_ids):
452             partner_address_id = model.res_id
453             address_id = address_obj.browse(cr, uid, partner_address_id)
454             partner_phone = address_id.phone
455             partner_mobile = address_id.mobile
456             partner_id = address_id and address_id.partner_id or False
457             
458     if val.get('parent_type') == 'Opportunities':
459         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'crm.lead')])
460         for model in model_obj.browse(cr, uid, model_ids):
461             opportunity_id = model.res_id
462             opportunity_id = crm_obj.browse(cr, uid, opportunity_id)
463             partner_id = opportunity_id.partner_id.id
464             partner_address_id =  opportunity_id.partner_address_id.id
465             partner_phone = opportunity_id.partner_address_id.phone
466             partner_mobile = opportunity_id.partner_address_id.mobile
467             
468     if val.get('parent_type') == 'Project':
469         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'project.project')])
470         for model in model_obj.browse(cr, uid, model_ids):
471             proj_ids = model.res_id
472             proj_id = project_obj.browse(cr, uid, proj_ids)
473             partner_id = proj_id.partner_id.id
474             partner_address_id =  proj_id.contact_id.id
475             partner_phone = proj_id.contact_id.phone
476             partner_mobile = proj_id.contact_id.mobile
477
478     if val.get('parent_type') == 'Bugs':
479         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'project.issue')])
480         for model in model_obj.browse(cr, uid, model_ids):
481             issue_ids = model.res_id
482             issue_id = issue_obj.browse(cr, uid, issue_ids)
483             partner_id = issue_id.partner_id.id
484             partner_address_id =  issue_id.partner_address_id.id
485             partner_phone = issue_id.partner_address_id.phone
486             partner_mobile = issue_id.partner_address_id.mobile                        
487                         
488     return partner_id, partner_address_id, partner_phone,partner_mobile                          
489
490 def import_documents(sugar_obj, cr, uid, context=None):
491     if not context:
492         context = {}
493     map_document = {'id' : 'id', 
494              'name': 'document_name',
495            'description': 'description',
496            'datas': 'datas',
497            'datas_fname': 'datas_fname',
498             } 
499     attach_obj = sugar_obj.pool.get('ir.attachment')
500     PortType,sessionid = sugar.login(context.get('username',''), context.get('password',''), context.get('url',''))
501     sugar_data = sugar.search(PortType,sessionid, 'Documents')
502     for val in sugar_data:
503         val['id'] = 'sugarcrm_'+'document_'+ val.get('id')
504         file, filename = sugar.attachment_search(PortType, sessionid, 'DocumentRevisions', val.get('document_revision_id'))
505         val['datas'] = file
506         val['datas_fname'] = filename
507         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_document, context)
508         attach_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
509     return True
510
511 def import_tasks(sugar_obj, cr, uid, context=None):
512     if not context:
513         context = {}
514     map_task = {'id' : 'id',
515                 'name': 'name',
516                 'date': ['__datetime__', 'date_start'],
517                 'date_deadline' : ['__datetime__', 'date_due'],
518                 'user_id/id': 'assigned_user_id',
519                 'categ_id/.id': 'categ_id/.id',
520                 'partner_id/.id': 'partner_id/.id',
521                 'partner_address_id/.id': 'partner_address_id/.id',
522                 'state': 'state'
523     }
524     meeting_obj = sugar_obj.pool.get('crm.meeting')
525     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
526     categ_id = get_category(sugar_obj, cr, uid, 'crm.meeting', 'Tasks')
527     sugar_data = sugar.search(PortType, sessionid, 'Tasks')
528     for val in sugar_data:
529         val['id'] = 'sugarcrm_'+'task_'+ val.get('id')
530         partner_xml_id = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', val.get('contact_id'), context)
531         if not partner_xml_id:
532             raise osv.except_osv(_('Warning !'), _('Reference Contact %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('contact_name'))
533         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
534         val['partner_id/.id'] = partner_id
535         val['partner_address_id/.id'] = partner_address_id
536         val['categ_id/.id'] = categ_id
537         val['state'] = get_task_state(sugar_obj, cr, uid, val.get('status'), context)
538         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_task, context)
539         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
540     return True    
541     
542 def get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, module_name, module_id, context=None):
543     if not context:
544         context = {}
545     model_obj = sugar_obj.pool.get('ir.model.data')
546     att_obj = sugar_obj.pool.get('calendar.attendee')
547     meeting_obj = sugar_obj.pool.get('crm.meeting')
548     user_dict = sugar.user_get_attendee_list(PortType, sessionid, module_name, module_id)
549     for user in user_dict: 
550         user_model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.users', user.get('id'), context)
551         user_resource_id = model_obj.browse(cr, uid, user_model_ids)        
552         if user_resource_id:
553             user_id = user_resource_id[0].res_id 
554             attend_ids = att_obj.search(cr, uid, [('user_id', '=', user_id)])
555             if attend_ids:
556                  attendees = attend_ids[0]
557             else:      
558                 attendees = att_obj.create(cr, uid, {'user_id': user_id, 'email': user.get('email1')})
559             meeting_model_ids = find_mapped_id(sugar_obj, cr, uid, 'crm.meeting', module_id, context)
560             meeting_xml_id = model_obj.browse(cr, uid, meeting_model_ids)
561             if meeting_xml_id:
562                 meeting_obj.write(cr, uid, [meeting_xml_id[0].res_id], {'attendee_ids': [(4, attendees)]})       
563     return True   
564     
565 def import_meetings(sugar_obj, cr, uid, context=None):
566     if not context:
567         context = {}
568     map_meeting = {'id' : 'id',
569                     'name': 'name',
570                     'date': ['__datetime__', 'date_start'],
571                     'duration': ['duration_hours', 'duration_minutes'],
572                     'location': 'location',
573                     'alarm_id/.id': 'alarm_id/.id',
574                     'user_id/id': 'assigned_user_id',
575                     'partner_id/.id':'partner_id/.id',
576                     'partner_address_id/.id':'partner_address_id/.id',
577                     'state': 'state'
578     }
579     meeting_obj = sugar_obj.pool.get('crm.meeting')
580     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
581     sugar_data = sugar.search(PortType, sessionid, 'Meetings')
582     for val in sugar_data:
583         val['id'] = 'sugarcrm_'+'meeting_'+ val.get('id')
584         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
585         val['partner_id/.id'] = partner_id
586         val['partner_address_id/.id'] = partner_address_id
587         val['state'] = get_meeting_state(sugar_obj, cr, uid, val.get('status'),context)
588         val['alarm_id/.id'] = get_alarm_id(sugar_obj, cr, uid, val.get('reminder_time'), context)
589         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_meeting, context)
590         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
591         get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, 'Meetings', val.get('id'), context)
592     return True    
593
594 def get_calls_state(sugar_obj, cr, uid, val,context=None):
595     if not context:
596         context = {}
597     state = False
598     state_dict = {'status': #field in the sugarcrm database
599         { #Mapping of sugarcrm stage : openerp calls stage
600             'Planned' : 'open',
601             'Held':'done',
602             'Not Held': 'pending',
603         },}
604     state = state_dict['status'].get(val, '')
605     return state   
606
607 def import_calls(sugar_obj, cr, uid, context=None):
608     if not context:
609         context = {}
610     map_calls = {'id' : 'id',
611                     'name': 'name',
612                     'date': ['__datetime__', 'date_start'],
613                     'duration': ['duration_hours', 'duration_minutes'],
614                     'user_id/id': 'assigned_user_id',
615                     'partner_id/.id': 'partner_id/.id',
616                     'partner_address_id/.id': 'partner_address_id/.id',
617                     'categ_id/.id': 'categ_id/.id',
618                    'state': 'state',
619                    'partner_phone': 'partner_phone',
620                    'partner_mobile': 'partner_mobile',
621                    'opportunity_id/id': 'opportunity_id/id',
622
623     }
624     phonecall_obj = sugar_obj.pool.get('crm.phonecall')
625     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
626     sugar_data = sugar.search(PortType, sessionid, 'Calls')
627     for val in sugar_data:
628         val['id'] = 'sugarcrm_'+'call_'+ val.get('id')
629         sugar_call_leads = sugar.relation_search(PortType, sessionid, 'Calls', module_id=val.get('id'), related_module='Leads', query=None, deleted=None)
630         if sugar_call_leads:
631             for call_opportunity in sugar_call_leads: 
632                 val['opportunity_id/id'] = call_opportunity 
633         categ_id = get_category(sugar_obj, cr, uid, 'crm.phonecall', val.get('direction'))         
634         val['categ_id/.id'] = categ_id
635         partner_id, partner_address_id, partner_phone, partner_mobile = get_account(sugar_obj, cr, uid, val, context)
636         
637         val['partner_id/.id'] = partner_id
638         val['partner_address_id/.id'] = partner_address_id
639         val['partner_phone'] = partner_phone
640         val['partner_mobile'] = partner_mobile
641         val['state'] =  get_calls_state(sugar_obj, cr, uid, val.get('status'), context)  
642         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_calls, context)
643         phonecall_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
644     return True
645     
646 def import_resources(sugar_obj, cr, uid, context=None):
647     if not context:
648         context = {}
649     map_resource = {'id' : 'user_hash',
650                     'name': ['first_name', 'last_name'],
651     }
652     resource_obj = sugar_obj.pool.get('resource.resource')
653     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
654     sugar_data = sugar.search(PortType, sessionid, 'Employees')
655     for val in sugar_data:
656         val['id'] = 'sugarcrm_'+'resource_'+ val.get('id')
657         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource, context)
658         resource_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
659     return True    
660
661 def get_bug_priority(sugar_obj, cr, uid, val,context=None):
662     if not context:
663         context = {}
664     priority = False
665     priority_dict = {'priority': #field in the sugarcrm database
666         { #Mapping of sugarcrm priority : openerp bugs priority
667             'Urgent': '1',
668             'High': '2',
669             'Medium': '3',
670             'Low': '4'
671         },}
672     priority = priority_dict['priority'].get(val, '')
673     return priority  
674
675 def get_claim_priority(sugar_obj, cr, uid, val,context=None):
676     if not context:
677         context = {}
678     priority = False
679     priority_dict = {'priority': #field in the sugarcrm database
680         { #Mapping of sugarcrm priority : openerp claims priority
681             'High': '2',
682             'Medium': '3',
683             'Low': '4'
684         },}
685     priority = priority_dict['priority'].get(val, '')
686     return priority   
687
688 def get_bug_state(sugar_obj, cr, uid, val,context=None):
689     if not context:
690         context = {}
691     state = False
692     state_dict = {'status': #field in the sugarcrm database
693         { #Mapping of sugarcrm status : openerp Bugs state
694             'New' : 'draft',
695             'Assigned':'open',
696             'Closed': 'done',
697             'Pending': 'pending',
698             'Rejected': 'cancel',
699         },}
700     state = state_dict['status'].get(val, '')
701     return state
702
703 def get_claim_state(sugar_obj, cr, uid, val,context=None):
704     if not context:
705         context = {}
706     state = False
707     state_dict = {'status': #field in the sugarcrm database
708         { #Mapping of sugarcrm status : openerp claim state
709             'New' : 'draft',
710             'Assigned':'open',
711             'Closed': 'done',
712             'Pending Input': 'pending',
713             'Rejected': 'cancel',
714             'Duplicate': 'draft',
715         },}
716     state = state_dict['status'].get(val, '')
717     return state
718     
719
720 def get_acc_contact_claim(sugar_obj, cr, uid, val, context=None):
721     if not context:
722         context = {}
723     partner_id = False    
724     partner_address_id = False
725     partner_phone = False
726     partner_email = False
727     model_obj = sugar_obj.pool.get('ir.model.data')
728     address_obj = sugar_obj.pool.get('res.partner.address')
729     model_ids = model_obj.search(cr, uid, [('name', '=', val.get('account_id')), ('model', '=', 'res.partner')])
730     if model_ids:
731         model = model_obj.browse(cr, uid, model_ids)[0]
732         partner_id = model.res_id
733         address_ids = address_obj.search(cr, uid, [('partner_id', '=', partner_id)])
734         if address_ids:
735             address_id = address_obj.browse(cr, uid, address_ids[0])
736             partner_address_id = address_id.id
737             partner_phone = address_id.phone
738             partner_mobile = address_id.email
739     return partner_id, partner_address_id, partner_phone,partner_email
740
741 def import_claims(sugar_obj, cr, uid, context=None):
742     if not context:
743         context = {}
744     map_claim = {'id' : 'id',
745                     'name': 'name',
746                     'date': ['__datetime__', 'date_entered'],
747                     'user_id/id': 'assigned_user_id',
748                     'priority':'priority',
749                     'partner_id/.id': 'partner_id/.id',
750                     'partner_address_id/.id': 'partner_address_id/.id',
751                     'partner_phone': 'partner_phone',
752                     'partner_mobile': 'partner_email',                    
753                     'description': 'description',
754                     'state': 'state',
755     }
756     claim_obj = sugar_obj.pool.get('crm.claim')
757     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
758     sugar_data = sugar.search(PortType, sessionid, 'Cases')
759     for val in sugar_data:
760         val['id'] = 'sugarcrm_'+'case_'+ val.get('id')
761         partner_id, partner_address_id, partner_phone,partner_email = get_acc_contact_claim(sugar_obj, cr, uid, val, context)
762         val['id'] = 'Cases_' + val.get('id')
763         val['partner_id/.id'] = partner_id
764         val['partner_address_id/.id'] = partner_address_id
765         val['partner_phone'] = partner_phone
766         val['email_from'] = partner_email
767         val['priority'] = get_claim_priority(sugar_obj, cr, uid, val.get('priority'),context)
768         val['state'] = get_claim_state(sugar_obj, cr, uid, val.get('status'),context)
769         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_claim, context)
770         claim_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
771     return True    
772
773 def import_bug(sugar_obj, cr, uid, context=None):
774     if not context:
775         context = {}
776     map_resource = {'id' : 'id',
777                     'name': 'name',
778                     'project_id/.id':'project_id/.id',
779                     'categ_id.id': 'categ_id.id',
780                     'priority':'priority',
781                     'description': ['__prettyprint__','description', 'bug_number', 'fixed_in_release_name', 'source', 'fixed_in_release', 'work_log', 'found_in_release', 'release_name', 'resolution'],
782                     'state': 'state',
783     }
784     issue_obj = sugar_obj.pool.get('project.issue')
785     project_obj = sugar_obj.pool.get('project.project')
786     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
787     sugar_data = sugar.search(PortType, sessionid, 'Bugs')
788     for val in sugar_data:
789         val['id'] = 'sugarcrm_'+'bug_'+ val.get('id')
790         project_ids = project_obj.search(cr, uid, [('name', 'like', 'sugarcrm_bugs')])
791         if project_ids:
792             project_id = project_ids[0]
793         else:
794              project_id = project_obj.create(cr, uid, {'name':'sugarcrm_bugs'})    
795         val['id'] = 'Bugs_' + val.get('id')     
796         val['project_id/.id'] = project_id
797         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'project.issue', val.get('type'))
798         val['priority'] = get_bug_priority(sugar_obj, cr, uid, val.get('priority'),context)
799         val['state'] = get_bug_state(sugar_obj, cr, uid, val.get('status'),context)
800         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource, context)
801         issue_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
802     return True    
803
804 def get_job_id(sugar_obj, cr, uid, val, context=None):
805     if not context:
806         context={}
807     job_id = False    
808     job_obj = sugar_obj.pool.get('hr.job')        
809     job_ids = job_obj.search(cr, uid, [('name', '=', val)])
810     if job_ids:
811         job_id = job_ids[0]
812     else:
813         job_id = job_obj.create(cr, uid, {'name': val})
814     return job_id
815
816 def get_campaign_id(sugar_obj, cr, uid, val, context=None):
817     if not context:
818         context={}
819     cam_id = False    
820     cam_obj = sugar_obj.pool.get('crm.case.resource.type')        
821     cam_ids = cam_obj.search(cr, uid, [('name', '=', val)])
822     if cam_ids:
823         cam_id = cam_ids[0]
824     else:
825         cam_id = cam_obj.create(cr, uid, {'name': val})
826     return cam_id
827     
828 def get_attachment(sugar_obj, cr, uid, val, model, File, context=None):
829     if not context:
830         context = {}
831     attachment_obj = sugar_obj.pool.get('ir.attachment')
832     model_obj = sugar_obj.pool.get('ir.model.data')
833     mailgate_obj = sugar_obj.pool.get('mailgate.message')
834     new_attachment_id = attachment_obj.create(cr, uid, {'name': val.get('name'), 'datas_fname': val.get('name'), 'datas': File, 'res_id': val.get('res_id', False),'res_model': val.get('model',False)})
835     message_model_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
836     message_xml_id = model_obj.browse(cr, uid, message_model_ids)
837     if message_xml_id:
838         if val.get('model') == 'res.partner':
839             mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)], 'partner_id': val.get('res_id', False)})
840         else:    
841             mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)]})                         
842     return True    
843     
844 def import_history(sugar_obj, cr, uid, context=None):
845     if not context:
846         context = {}
847     map_attachment = {'id' : 'id',
848                       'name':'name',
849                       'date': ['__datetime__', 'date_entered'],
850                       'user_id/id': 'assigned_user_id',
851                       'description': ['__prettyprint__','description', 'description_html'],
852                       'res_id': 'res_id',
853                       'model': 'model',
854                       'partner_id/.id' : 'partner_id/.id',
855     }
856     mailgate_obj = sugar_obj.pool.get('mailgate.message')
857     model_obj =  sugar_obj.pool.get('ir.model.data')
858     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
859     sugar_data = sugar.search(PortType, sessionid, 'Notes')
860     for val in sugar_data:
861         val['id'] = 'sugarcrm_'+'note_'+ val.get('id')
862         File, Filename = sugar.attachment_search(PortType, sessionid, 'Notes', val.get('id'))
863         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id')),('model','=', OPENERP_FIEDS_MAPS[val.get('parent_type')])])
864         if model_ids:
865             model = model_obj.browse(cr, uid, model_ids)[0]
866             val['res_id'] = model.res_id
867             val['model'] = model.model
868         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_attachment, context)   
869         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
870         get_attachment(sugar_obj, cr, uid, val, 'mailgate.message', File, context)
871     return True       
872     
873 def import_employees(sugar_obj, cr, uid, context=None):
874     if not context:
875         context = {}
876     map_employee = {'id' : 'user_hash',
877                     'resource_id/.id': 'resource_id/.id',
878                     'name': ['first_name', 'last_name'],
879                     'work_phone': 'phone_work',
880                     'mobile_phone':  'phone_mobile',
881                     'user_id/name': ['first_name', 'last_name'], 
882                     'address_home_id/.id': 'address_home_id/.id',
883                     'notes': 'description',
884                     #TODO: Creation of Employee create problem.
885                  #   'coach_id/id': 'reports_to_id',
886                     'job_id/.id': 'job_id/.id'
887     }
888     employee_obj = sugar_obj.pool.get('hr.employee')
889     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
890     sugar_data = sugar.search(PortType, sessionid, 'Employees')
891     for val in sugar_data:
892         val['id'] = 'sugarcrm_'+'employee_'+ val.get('id')
893         address_id = get_user_address(sugar_obj, cr, uid, val, context)
894         val['address_home_id/.id'] = address_id
895         model_ids = find_mapped_id(sugar_obj, cr, uid, 'resource.resource', val.get('user_hash')+ '_resource_resource', context)
896         resource_id = sugar_obj.pool.get('ir.model.data').browse(cr, uid, model_ids)
897         if resource_id:
898             val['resource_id/.id'] = resource_id[0].res_id
899         val['job_id/.id'] = get_job_id(sugar_obj, cr, uid, val.get('title'), context)
900         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_employee, context)
901         employee_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
902     return True
903
904 def get_contact_title(sugar_obj, cr, uid, salutation, domain, context=None):
905     if not context:
906         context = {}
907     contact_title_obj = sugar_obj.pool.get('res.partner.title')
908     title_id = False            
909     title_ids = contact_title_obj.search(cr, uid, [('shortcut', '=', salutation), ('domain', '=', domain)])
910     if title_ids:
911          title_id = title_ids[0]
912     elif salutation:
913          title_id = contact_title_obj.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain})
914     return title_id
915     
916 def import_emails(sugar_obj, cr, uid, context=None):
917     if not context:
918         context= {}
919     map_emails = {'id': 'id',
920     'name':'name',
921     'date':['__datetime__', 'date_sent'],
922     'email_from': 'from_addr_name',
923     'email_to': 'reply_to_addr',
924     'email_cc': 'cc_addrs_names',
925     'email_bcc': 'bcc_addrs_names',
926     'message_id': 'message_id',
927     'user_id/id': 'assigned_user_id',
928     'description': ['__prettyprint__', 'description', 'description_html'],
929     'res_id': 'res_id',
930     'model': 'model',
931     'partner_id/.id': 'partner_id/.id'
932     }
933     mailgate_obj = sugar_obj.pool.get('mailgate.message')
934     model_obj = sugar_obj.pool.get('ir.model.data')
935     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
936     sugar_data = sugar.search(PortType, sessionid, 'Emails')
937     for val in sugar_data:
938         val['id'] = 'sugarcrm_'+'email_'+ val.get('id')
939         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id'))])
940         for model in model_obj.browse(cr, uid, model_ids):
941             if model.model == 'res.partner':
942                 val['partner_id/.id'] = model.res_id
943             val['res_id'] = model.res_id
944             val['model'] = model.model
945             
946         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_emails, context)
947         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
948     return True    
949     
950 def get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context=None):
951     if not context:
952         context={}
953     partner_id = False
954     partner_invoice_id = False        
955     model_obj = sugar_obj.pool.get('ir.model.data')
956     partner_obj = sugar_obj.pool.get('res.partner')
957     partner_address_obj = sugar_obj.pool.get('res.partner.address')
958     sugar_project_account = sugar.relation_search(PortType, sessionid, 'Project', module_id=val.get('id'), related_module='Accounts', query=None, deleted=None)
959     for account_id in sugar_project_account:
960         model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner', account_id, context)
961         if model_ids:
962             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
963             partner_id = partner_obj.browse(cr, uid, model_id).id
964             address_ids = partner_address_obj.search(cr, uid, [('partner_id', '=', partner_id),('type', '=', 'invoice')])
965             partner_invoice_id = address_ids[0] 
966     return partner_id, partner_invoice_id      
967     
968 def import_projects(sugar_obj, cr, uid, context=None):
969     if not context:
970         context = {}
971     map_project = {'id': 'id',
972         'name': 'name',
973         'date_start': ['__datetime__', 'estimated_start_date'],
974         'date': ['__datetime__', 'estimated_end_date'],
975         'user_id/id': 'assigned_user_id',
976         'partner_id/.id': 'partner_id/.id',
977         'contact_id/.id': 'contact_id/.id', 
978          'state': 'state'   
979     }
980     project_obj = sugar_obj.pool.get('project.project')
981     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
982     sugar_data = sugar.search(PortType, sessionid, 'Project')
983     for val in sugar_data:
984         val['id'] = 'sugarcrm_'+'project_'+ val.get('id') 
985         partner_id, partner_invoice_id = get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context) 
986         val['partner_id/.id'] = partner_id
987         val['contact_id/.id'] = partner_invoice_id 
988         val['state'] = get_project_state(sugar_obj, cr, uid, val.get('status'),context)
989         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project, context)
990         project_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
991     return True 
992
993
994 def import_project_tasks(sugar_obj, cr, uid, context=None):
995     if not context:
996         context = {}
997     map_project_task = {'id': 'id',
998         'name': 'name',
999         'date_start': ['__datetime__', 'date_start'],
1000         'date_end': ['__datetime__', 'date_finish'],
1001         'progress': 'progress',
1002         'project_id/name': 'project_name',
1003         'planned_hours': 'planned_hours',
1004         'total_hours': 'total_hours',        
1005         'priority': 'priority',
1006         'description': 'description',
1007         'user_id/id': 'assigned_user_id',
1008          'state': 'state'   
1009     }
1010     task_obj = sugar_obj.pool.get('project.task')
1011     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1012     sugar_data = sugar.search(PortType, sessionid, 'ProjectTask')
1013     for val in sugar_data:
1014         val['id'] = 'sugarcrm_'+'projecttask_'+ val.get('id')
1015         val['state'] = get_project_task_state(sugar_obj, cr, uid, val.get('status'),context)
1016         val['priority'] = get_project_task_priority(sugar_obj, cr, uid, val.get('priority'),context)
1017         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project_task, context)
1018         task_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1019     return True 
1020     
1021 def import_leads(sugar_obj, cr, uid, context=None):
1022     if not context:
1023         context = {}
1024     map_lead = {
1025             'id' : 'id',
1026             'name': ['first_name', 'last_name'],
1027             'contact_name': ['first_name', 'last_name'],
1028             'description': ['__prettyprint__', 'description', 'refered_by', 'lead_source', 'lead_source_description', 'website', 'email2', 'status_description', 'lead_source_description', 'do_not_call'],
1029             'partner_name': 'account_name',
1030             'email_from': 'email1',
1031             'phone': 'phone_work',
1032             'mobile': 'phone_mobile',
1033             'title.id': 'title.id',
1034             'function':'title',
1035             'street': 'primary_address_street',
1036             'street2': 'alt_address_street',
1037             'zip': 'primary_address_postalcode',
1038             'city':'primary_address_city',
1039             'user_id/id' : 'assigned_user_id',
1040             'stage_id.id' : 'stage_id.id',
1041             'type' : 'type',
1042             'state': 'state',
1043             'fax': 'phone_fax',
1044             'referred': 'refered_by',
1045             'optout': 'optout',
1046             'type_id/.id': 'type_id/.id'
1047             }
1048         
1049     lead_obj = sugar_obj.pool.get('crm.lead')
1050     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1051     sugar_data = sugar.search(PortType, sessionid, 'Leads')
1052     for val in sugar_data:
1053         val['id'] = 'sugarcrm_'+'lead_'+ val.get('id')
1054         if val.get('do_not_call') == '0':
1055             val['optout'] = '1'
1056         if val.get('opportunity_id'):
1057             continue
1058         title_id = get_contact_title(sugar_obj, cr, uid, val.get('salutation'), 'contact', context)
1059         val['title.id'] = title_id
1060         val['type'] = 'lead'
1061         val['type_id/.id'] = get_campaign_id(sugar_obj, cr, uid, val.get('lead_source'), context)
1062         stage_id = get_lead_status(sugar_obj, cr, uid, val, context)
1063         val['stage_id.id'] = stage_id
1064         val['state'] = get_lead_state(sugar_obj, cr, uid, val,context)
1065         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_lead, context)
1066         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
1067     return True
1068
1069 def get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context=None):
1070     if not context:
1071         context={}
1072     partner_contact_name = False 
1073     partner_contact_email = False       
1074     model_obj = sugar_obj.pool.get('ir.model.data')
1075     partner_address_obj = sugar_obj.pool.get('res.partner.address')
1076     model_account_ids = model_obj.search(cr, uid, [('res_id', '=', partner_xml_id[0]), ('model', '=', 'res.partner'), ('module', '=', 'sugarcrm_import')])
1077     model_xml_id = model_obj.browse(cr, uid, model_account_ids)[0].name 
1078     sugar_account_contact = set(sugar.relation_search(PortType, sessionid, 'Accounts', module_id=model_xml_id, related_module='Contacts', query=None, deleted=None))
1079     sugar_opportunities_contact = set(sugar.relation_search(PortType, sessionid, 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
1080     sugar_contact = list(sugar_account_contact.intersection(sugar_opportunities_contact))
1081     if sugar_contact: 
1082         for contact in sugar_contact:
1083             model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', contact, context)
1084             if model_ids:
1085                 model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
1086                 address_id = partner_address_obj.browse(cr, uid, model_id)
1087                 partner_address_obj.write(cr, uid, [address_id.id], {'partner_id': partner_xml_id[0]})
1088                 partner_contact_name = address_id.name
1089                 partner_contact_email = address_id.email
1090             else:
1091                 partner_contact_name = val.get('account_name')    
1092     return partner_contact_name, partner_contact_email
1093
1094 def import_opportunities(sugar_obj, cr, uid, context=None):
1095     if not context:
1096         context = {}
1097     map_opportunity = {'id' : 'id',
1098         'name': 'name',
1099         'probability': 'probability',
1100         'partner_id/name': 'account_name',
1101         'title_action': 'next_step',
1102         'partner_address_id/name': 'partner_address_id/name',
1103         'planned_revenue': 'amount',
1104         'date_deadline': ['__datetime__', 'date_closed'],
1105         'user_id/id' : 'assigned_user_id',
1106         'stage_id.id' : 'stage_id.id',
1107         'type' : 'type',
1108         'categ_id.id': 'categ_id.id',
1109         'email_from': 'email_from'
1110     }
1111     lead_obj = sugar_obj.pool.get('crm.lead')
1112     partner_obj = sugar_obj.pool.get('res.partner')
1113     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
1114     sugar_data = sugar.search(PortType, sessionid, 'Opportunities')
1115     for val in sugar_data:
1116         val['id'] = 'sugarcrm_'+'opportunity_'+ val.get('id')
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'],
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' : ['Users', 'Projects', 'Project Tasks', 'Accounts', 'Contacts', 'Leads', 'Opportunities', 'Meetings', 'Calls'],
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()