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