[FIX] category of task + simple map field
[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         model_ids = sugar_obj.pool.get('ir.model').search(cr, uid, [('model', '=', model)], context=context)
310         model = model_ids and model_ids[0] or False
311         categ_id = categ_obj.create(cr, uid, {'name': name, 'object_id': model})
312     return categ_id     
313
314 def get_alarm_id(sugar_obj, cr, uid, val, context=None):
315     
316     alarm_dict = {'60': '1 minute before',
317                   '300': '5 minutes before',
318                   '600': '10 minutes before',
319                   '900': '15 minutes before',
320                   '1800':'30 minutes before',
321                   '3600': '1 hour before',
322      }
323     alarm_id = False
324     alarm_obj = sugar_obj.pool.get('res.alarm')
325     if alarm_dict.get(val):
326         alarm_ids = alarm_obj.search(cr, uid, [('name', 'like', alarm_dict.get(val))])
327         for alarm in alarm_obj.browse(cr, uid, alarm_ids, context):
328             alarm_id = alarm.id
329     return alarm_id 
330     
331 def get_meeting_state(sugar_obj, cr, uid, val,context=None):
332     if not context:
333         context = {}
334     state = False
335     state_dict = {'status': #field in the sugarcrm database
336         { #Mapping of sugarcrm stage : openerp meeting stage
337             'Planned' : 'draft',
338             'Held':'open',
339             'Not Held': 'draft',
340         },}
341     state = state_dict['status'].get(val, '')
342     return state    
343
344 def get_task_state(sugar_obj, cr, uid, val, context=None):
345     if not context:
346         context = {}
347     state = False
348     state_dict = {'status': #field in the sugarcrm database
349         { #Mapping of sugarcrm stage : openerp meeting stage
350             'Completed' : 'done',
351             'Not Started':'draft',
352             'In Progress': 'open',
353             'Pending Input': 'draft',
354             'deferred': 'cancel'
355         },}
356     state = state_dict['status'].get(val, '')
357     return state    
358
359 def get_project_state(sugar_obj, cr, uid, val,context=None):
360     if not context:
361         context = {}
362     state = False
363     state_dict = {'status': #field in the sugarcrm database
364         { #Mapping of sugarcrm staus : openerp Projects state
365             'Draft' : 'draft',
366             'In Review': 'open',
367             'Published': 'close',
368         },}
369     state = state_dict['status'].get(val, '')
370     return state    
371
372 def get_project_task_state(sugar_obj, cr, uid, val,context=None):
373     if not context:
374         context = {}
375     state = False
376     state_dict = {'status': #field in the sugarcrm database
377         { #Mapping of sugarcrm status : openerp Porject Tasks state
378              'Not Started': 'draft',
379              'In Progress': 'open',
380              'Completed': 'done',
381             'Pending Input': 'pending',
382             'Deferred': 'cancelled',
383         },}
384     state = state_dict['status'].get(val, '')
385     return state    
386
387 def get_project_task_priority(sugar_obj, cr, uid, val,context=None):
388     if not context:
389         context = {}
390     priority = False
391     priority_dict = {'priority': #field in the sugarcrm database
392         { #Mapping of sugarcrm status : openerp Porject Tasks state
393             'High': '0',
394             'Medium': '2',
395             'Low': '3'
396         },}
397     priority = priority_dict['priority'].get(val, '')
398     return priority    
399
400
401 def get_account(sugar_obj, cr, uid, val, context=None):
402     if not context:
403         context = {}
404     partner_id = False    
405     partner_address_id = False
406     model_obj = sugar_obj.pool.get('ir.model.data')
407     address_obj = sugar_obj.pool.get('res.partner.address')
408     if val.get('parent_type') == 'Accounts':
409         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner')])
410         if model_ids:
411             model = model_obj.browse(cr, uid, model_ids)[0]
412             partner_id = model.res_id
413             address_ids = address_obj.search(cr, uid, [('partner_id', '=', partner_id)])
414             partner_address_id = address_ids and address_ids[0]
415             
416     if val.get('parent_type') == 'Contacts':
417         model_ids = model_obj.search(cr, uid, [('name', '=', val.get('parent_id')), ('model', '=', 'res.partner.address')])
418         for model in model_obj.browse(cr, uid, model_ids):
419             partner_address_id = model.res_id
420             address_id = address_obj.browse(cr, uid, partner_address_id)
421             partner_id = address_id and address_id.partner_id or False
422     return partner_id, partner_address_id                             
423
424 def import_tasks(sugar_obj, cr, uid, context=None):
425     if not context:
426         context = {}
427     map_task = {'id' : 'id',
428                 'name': 'name',
429                 'date': 'date_start',
430                 'date_deadline' : 'date_due',
431                 'user_id/id': 'assigned_user_id',
432                 'categ_id/.id': 'categ_id/.id',
433                 'partner_id/.id': 'partner_id/.id',
434                 'partner_address_id/.id': 'partner_address_id/.id',
435                 'state': 'state'
436     }
437     meeting_obj = sugar_obj.pool.get('crm.meeting')
438     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
439     categ_id = get_category(sugar_obj, cr, uid, 'crm.meeting', 'Tasks')
440     sugar_data = sugar.search(PortType, sessionid, 'Tasks')
441     for val in sugar_data:
442         partner_xml_id = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', val.get('contact_id'), context)
443         if not partner_xml_id:
444             raise osv.except_osv(_('Warning !'), _('Reference Contact %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('contact_name'))
445         partner_id, partner_address_id = get_account(sugar_obj, cr, uid, val, context)
446         val['partner_id/.id'] = partner_id
447         val['partner_address_id/.id'] = partner_address_id
448         val['categ_id/.id'] = categ_id
449         val['state'] = get_task_state(sugar_obj, cr, uid, val.get('status'), context=None)
450         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_task)
451         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
452     return True    
453     
454 def get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, module_name, module_id, context=None):
455     if not context:
456         context = {}
457     model_obj = sugar_obj.pool.get('ir.model.data')
458     att_obj = sugar_obj.pool.get('calendar.attendee')
459     meeting_obj = sugar_obj.pool.get('crm.meeting')
460     user_dict = sugar.user_get_attendee_list(PortType, sessionid, module_name, module_id)
461     for user in user_dict: 
462         user_model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.users', user.get('id'), context)
463         user_resource_id = model_obj.browse(cr, uid, user_model_ids)        
464         if user_resource_id:
465             user_id = user_resource_id[0].res_id 
466             attend_ids = att_obj.search(cr, uid, [('user_id', '=', user_id)])
467             if attend_ids:
468                  attendees = attend_ids[0]
469             else:      
470                 attendees = att_obj.create(cr, uid, {'user_id': user_id, 'email': user.get('email1')})
471             meeting_model_ids = find_mapped_id(sugar_obj, cr, uid, 'crm.meeting', module_id, context)
472             meeting_xml_id = model_obj.browse(cr, uid, meeting_model_ids)
473             if meeting_xml_id:
474                 meeting_obj.write(cr, uid, [meeting_xml_id[0].res_id], {'attendee_ids': [(4, attendees)]})       
475     return True   
476     
477 def import_meetings(sugar_obj, cr, uid, context=None):
478     if not context:
479         context = {}
480     map_meeting = {'id' : 'id',
481                     'name': 'name',
482                     'date': 'date_start',
483                     'duration': ['duration_hours', 'duration_minutes'],
484                     'location': 'location',
485                     'alarm_id/.id': 'alarm_id/.id',
486                     'user_id/id': 'assigned_user_id',
487                     'partner_id/.id':'partner_id/.id',
488                     'partner_address_id/.id':'partner_address_id/.id',
489                     'state': 'state'
490     }
491     meeting_obj = sugar_obj.pool.get('crm.meeting')
492     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
493     sugar_data = sugar.search(PortType, sessionid, 'Meetings')
494     for val in sugar_data:
495         partner_id, partner_address_id = get_account(sugar_obj, cr, uid, val, context)
496         val['partner_id/.id'] = partner_id
497         val['partner_address_id/.id'] = partner_address_id
498         val['state'] = get_meeting_state(sugar_obj, cr, uid, val.get('status'),context)
499         val['alarm_id/.id'] = get_alarm_id(sugar_obj, cr, uid, val.get('reminder_time'), context)
500         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_meeting)
501         meeting_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
502         get_attendee_id(sugar_obj, cr, uid, PortType, sessionid, 'Meetings', val.get('id'), context)
503     return True    
504
505 def get_calls_state(sugar_obj, cr, uid, val,context=None):
506     if not context:
507         context = {}
508     state = False
509     state_dict = {'status': #field in the sugarcrm database
510         { #Mapping of sugarcrm stage : openerp calls stage
511             'Planned' : 'open',
512             'Held':'done',
513             'Not Held': 'pending',
514         },}
515     state = state_dict['status'].get(val, '')
516     return state   
517
518 def import_calls(sugar_obj, cr, uid, context=None):
519     if not context:
520         context = {}
521     map_calls = {'id' : 'id',
522                     'name': 'name',
523                     'date': 'date_start',
524                     'duration': ['duration_hours', 'duration_minutes'],
525                     'user_id/id': 'assigned_user_id',
526                     'partner_id/.id': 'partner_id/.id',
527                     'partner_address_id/.id': 'partner_address_id/.id',
528                     'categ_id/.id': 'categ_id/.id',
529                     'state': 'state',
530     }
531     phonecall_obj = sugar_obj.pool.get('crm.phonecall')
532     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
533     sugar_data = sugar.search(PortType, sessionid, 'Calls')
534     for val in sugar_data:
535         categ_id = get_category(sugar_obj, cr, uid, 'crm.phonecall', val.get('direction'))         
536         val['categ_id/.id'] = categ_id
537         partner_id, partner_address_id = get_account(sugar_obj, cr, uid, val, context)
538         val['partner_id/.id'] = partner_id
539         val['partner_address_id/.id'] = partner_address_id
540         val['state'] =  get_calls_state(sugar_obj, cr, uid, val.get('status'), context)  
541         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_calls)
542         phonecall_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
543     return True
544     
545 def import_resources(sugar_obj, cr, uid, context=None):
546     if not context:
547         context = {}
548     map_resource = {'id' : 'user_hash',
549                     'name': ['first_name', 'last_name'],
550     }
551     resource_obj = sugar_obj.pool.get('resource.resource')
552     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
553     sugar_data = sugar.search(PortType, sessionid, 'Employees')
554     for val in sugar_data:
555         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource)
556         resource_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
557     return True    
558
559 def get_bug_priority(sugar_obj, cr, uid, val,context=None):
560     if not context:
561         context = {}
562     priority = False
563     priority_dict = {'priority': #field in the sugarcrm database
564         { #Mapping of sugarcrm priority : openerp bugs priority
565             'Urgent': '1',
566             'High': '2',
567             'Medium': '3',
568             'Low': '4'
569         },}
570     priority = priority_dict['priority'].get(val, '')
571     return priority    
572
573 def get_bug_state(sugar_obj, cr, uid, val,context=None):
574     if not context:
575         context = {}
576     state = False
577     state_dict = {'status': #field in the sugarcrm database
578         { #Mapping of sugarcrm status : openerp Bugs state
579             'New' : 'draft',
580             'Assigned':'open',
581             'Closed': 'done',
582             'Pending': 'pending',
583             'Rejected': 'cancel',
584         },}
585     state = state_dict['status'].get(val, '')
586     return state
587     
588 def get_issue_related_project(sugar_obj,cr,uid, PortType, sessionid, val, context=None):
589     if not context:
590         context={}
591     project_id = False        
592     model_obj = sugar_obj.pool.get('ir.model.data')
593     project_obj = sugar_obj.pool.get('project.project')
594     sugar_bug_project = sugar.relation_search(PortType, sessionid, 'Bugs', module_id=val.get('id'), related_module='Project', query=None, deleted=None)
595     for project_id in sugar_bug_project:
596         model_ids = find_mapped_id(sugar_obj, cr, uid, 'project.project', project_id, context)
597         if model_ids:
598             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
599             project_id = project_obj.browse(cr, uid, model_id).id
600     return project_id     
601
602 def import_bug(sugar_obj, cr, uid, context=None):
603     if not context:
604         context = {}
605     map_resource = {'id' : 'id',
606                     'name': 'name',
607                     'project_id/.id':'project_id/.id',
608                     'categ_id.id': 'categ_id.id',
609                     'priority':'priority',
610                     'description': 'description',
611                     'state': 'state',
612     }
613     issue_obj = sugar_obj.pool.get('project.issue')
614     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
615     sugar_data = sugar.search(PortType, sessionid, 'Bugs')
616     for val in sugar_data:
617         val['project_id/.id'] = get_issue_related_project(sugar_obj,cr,uid, PortType, sessionid, val, context)
618         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'project.issue', val.get('type'))
619         val['priority'] = get_bug_priority(sugar_obj, cr, uid, val.get('priority'),context)
620         val['state'] = get_bug_state(sugar_obj, cr, uid, val.get('status'),context)
621         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_resource)
622         issue_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
623     return True    
624
625 def get_job_id(sugar_obj, cr, uid, val, context=None):
626     if not context:
627         context={}
628     job_id = False    
629     job_obj = sugar_obj.pool.get('hr.job')        
630     job_ids = job_obj.search(cr, uid, [('name', '=', val)])
631     if job_ids:
632         job_id = job_ids[0]
633     else:
634         job_id = job_obj.create(cr, uid, {'name': val})
635     return job_id
636     
637 def get_attachment(sugar_obj, cr, uid, val, model, File, context=None):
638     if not context:
639         context = {}
640     attachment_obj = sugar_obj.pool.get('ir.attachment')
641     model_obj = sugar_obj.pool.get('ir.model.data')
642     mailgate_obj = sugar_obj.pool.get('mailgate.message')
643     new_attachment_id = attachment_obj.create(cr, uid, {'name': val.get('name'), 'datas': File, 'res_id': val['res_id'],'res_model': val['model']})
644     message_model_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
645     message_xml_id = model_obj.browse(cr, uid, message_model_ids)
646     if message_xml_id:
647         mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)]})             
648     return True    
649     
650 def import_history(sugar_obj, cr, uid, context=None):
651     if not context:
652         context = {}
653     map_attachment = {'id' : 'id',
654                       'name':'name',
655                       'date':'date_entered',
656                       'user_id/id': 'assigned_user_id',
657                       'description': 'description_html',
658                       'res_id': 'res_id',
659                       'model': 'model',
660                       'partner_id.id' : 'partner_id.id',
661     }
662     mailgate_obj = sugar_obj.pool.get('mailgate.message')
663     model_obj =  sugar_obj.pool.get('ir.model.data')
664     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
665     sugar_data = sugar.search(PortType, sessionid, 'Notes')
666     for val in sugar_data:
667         File = sugar.attachment_search(PortType, sessionid, 'Notes', val.get('id'))
668         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id'))])
669         for model in model_obj.browse(cr, uid, model_ids):
670             val['res_id'] = model.res_id
671             val['model'] = model.model
672         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_attachment)   
673         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
674         get_attachment(sugar_obj, cr, uid, val, 'mailgate.message', File, context)
675     return True       
676     
677 def import_employees(sugar_obj, cr, uid, context=None):
678     if not context:
679         context = {}
680     map_employee = {'id' : 'user_hash',
681                     'resource_id/.id': 'resource_id/.id',
682                     'name': ['first_name', 'last_name'],
683                     'work_phone': 'phone_work',
684                     'mobile_phone':  'phone_mobile',
685                     'user_id/name': ['first_name', 'last_name'], 
686                     'address_home_id/.id': 'address_home_id/.id',
687                     'notes': 'description',
688                     #TODO: Creation of Employee create problem.
689                  #   'coach_id/id': 'reports_to_id',
690                     'job_id/.id': 'job_id/.id'
691     }
692     employee_obj = sugar_obj.pool.get('hr.employee')
693     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
694     sugar_data = sugar.search(PortType, sessionid, 'Employees')
695     for val in sugar_data:
696         address_id = get_user_address(sugar_obj, cr, uid, val, context)
697         val['address_home_id/.id'] = address_id
698         model_ids = find_mapped_id(sugar_obj, cr, uid, 'resource.resource', val.get('user_hash')+ '_resource_resource', context)
699         resource_id = sugar_obj.pool.get('ir.model.data').browse(cr, uid, model_ids)
700         if resource_id:
701             val['resource_id/.id'] = resource_id[0].res_id
702         val['job_id/.id'] = get_job_id(sugar_obj, cr, uid, val.get('title'), context)
703         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_employee)
704         employee_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
705     return True
706
707 def get_contact_title(sugar_obj, cr, uid, salutation, domain, context=None):
708     if not context:
709         context = {}
710     contact_title_obj = sugar_obj.pool.get('res.partner.title')
711     title_id = False            
712     title_ids = contact_title_obj.search(cr, uid, [('shortcut', '=', salutation), ('domain', '=', domain)])
713     if title_ids:
714          title_id = title_ids[0]
715     elif salutation:
716          title_id = contact_title_obj.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain})
717     return title_id
718     
719 def import_emails(sugar_obj, cr, uid, context=None):
720     if not context:
721         context= {}
722     map_emails = {'id': 'id',
723     'name':'name',
724     'date':'date_sent',
725     'email_from': 'from_addr_name',
726     'email_to': 'reply_to_addr',
727     'email_cc': 'cc_addrs_names',
728     'email_bcc': 'bcc_addrs_names',
729     'message_id': 'message_id',
730     'user_id/id': 'assigned_user_id',
731     'description': 'description_html',
732     'res_id': 'res_id',
733     'model': 'model',
734     }
735     mailgate_obj = sugar_obj.pool.get('mailgate.message')
736     model_obj = sugar_obj.pool.get('ir.model.data')
737     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
738     sugar_data = sugar.search(PortType, sessionid, 'Emails')
739     for val in sugar_data:
740         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id'))])
741         for model in model_obj.browse(cr, uid, model_ids):
742             val['res_id'] = model.res_id
743             val['model'] = model.model
744         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_emails)
745         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
746     return True    
747     
748 def get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context=None):
749     if not context:
750         context={}
751     partner_id = False
752     partner_invoice_id = False        
753     model_obj = sugar_obj.pool.get('ir.model.data')
754     partner_obj = sugar_obj.pool.get('res.partner')
755     partner_address_obj = sugar_obj.pool.get('res.partner.address')
756     sugar_project_account = sugar.relation_search(PortType, sessionid, 'Project', module_id=val.get('id'), related_module='Accounts', query=None, deleted=None)
757     for account_id in sugar_project_account:
758         model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner', account_id, context)
759         if model_ids:
760             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
761             partner_id = partner_obj.browse(cr, uid, model_id).id
762             address_ids = partner_address_obj.search(cr, uid, [('partner_id', '=', partner_id),('type', '=', 'invoice')])
763             partner_invoice_id = address_ids[0] 
764     return partner_id, partner_invoice_id      
765     
766 def import_projects(sugar_obj, cr, uid, context=None):
767     if not context:
768         context = {}
769     map_project = {'id': 'id',
770         'name': 'name',
771         'date_start': 'estimated_start_date',
772         'date': 'estimated_end_date',
773         'user_id/id': 'assigned_user_id',
774         'partner_id/.id': 'partner_id/.id',
775         'contact_id/.id': 'contact_id/.id', 
776          'state': 'state'   
777     }
778     project_obj = sugar_obj.pool.get('project.project')
779     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
780     sugar_data = sugar.search(PortType, sessionid, 'Project')
781     for val in sugar_data:
782         partner_id, partner_invoice_id = get_project_account(sugar_obj,cr,uid, PortType, sessionid, val, context) 
783         val['partner_id/.id'] = partner_id
784         val['contact_id/.id'] = partner_invoice_id 
785         val['state'] = get_project_state(sugar_obj, cr, uid, val.get('status'),context)
786         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project)
787         project_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
788     return True 
789
790
791 def import_project_tasks(sugar_obj, cr, uid, context=None):
792     if not context:
793         context = {}
794     map_project_task = {'id': 'id',
795         'name': 'name',
796         'date_start': 'date_start',
797         'date_end': 'date_finish',
798         'progress': 'progress',
799         'project_id/name': 'project_name',
800         'planned_hours': 'planned_hours',
801         'total_hours': 'total_hours',        
802         'priority': 'priority',
803         'description': 'description',
804         'user_id/id': 'assigned_user_id',
805          'state': 'state'   
806     }
807     task_obj = sugar_obj.pool.get('project.task')
808     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
809     sugar_data = sugar.search(PortType, sessionid, 'ProjectTask')
810     for val in sugar_data:
811         val['state'] = get_project_task_state(sugar_obj, cr, uid, val.get('status'),context)
812         val['priority'] = get_project_task_priority(sugar_obj, cr, uid, val.get('priority'),context)
813         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project_task)
814         task_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
815     return True 
816     
817 def import_leads(sugar_obj, cr, uid, context=None):
818     if not context:
819         context = {}
820     map_lead = {
821             'id' : 'id',
822             'name': ['first_name', 'last_name'],
823             'contact_name': ['first_name', 'last_name'],
824             'description': ['description', 'refered_by', 'lead_source', 'lead_source_description', 'website'],
825             'partner_name': 'account_name',
826             'email_from': 'email1',
827             'phone': 'phone_work',
828             'mobile': 'phone_mobile',
829             'title.id': 'title.id',
830             'function':'title',
831             'street': 'primary_address_street',
832             'street2': 'alt_address_street',
833             'zip': 'primary_address_postalcode',
834             'city':'primary_address_city',
835             'user_id/id' : 'assigned_user_id',
836             'stage_id.id' : 'stage_id.id',
837             'type' : 'type',
838             'state': 'state',
839             }
840         
841     lead_obj = sugar_obj.pool.get('crm.lead')
842     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
843     sugar_data = sugar.search(PortType, sessionid, 'Leads')
844     for val in sugar_data:
845         if val.get('opportunity_id'):
846             continue
847         title_id = get_contact_title(sugar_obj, cr, uid, val.get('salutation'), 'contact', context)
848         val['title.id'] = title_id
849         val['type'] = 'lead'
850         stage_id = get_lead_status(sugar_obj, cr, uid, val, context)
851         val['stage_id.id'] = stage_id
852         val['state'] = get_lead_state(sugar_obj, cr, uid, val,context)
853         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_lead)
854         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
855     return True
856
857 def get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context=None):
858     if not context:
859         context={}
860     partner_contact_name = False        
861     model_obj = sugar_obj.pool.get('ir.model.data')
862     partner_address_obj = sugar_obj.pool.get('res.partner.address')
863     model_account_ids = model_obj.search(cr, uid, [('res_id', '=', partner_xml_id[0]), ('model', '=', 'res.partner'), ('module', '=', 'sugarcrm_import')])
864     model_xml_id = model_obj.browse(cr, uid, model_account_ids)[0].name 
865     sugar_account_contact = set(sugar.relation_search(PortType, sessionid, 'Accounts', module_id=model_xml_id, related_module='Contacts', query=None, deleted=None))
866     sugar_opportunities_contact = set(sugar.relation_search(PortType, sessionid, 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
867     sugar_contact = list(sugar_account_contact.intersection(sugar_opportunities_contact))
868     if sugar_contact: 
869         for contact in sugar_contact:
870             model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', contact, context)
871             if model_ids:
872                 model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
873                 address_id = partner_address_obj.browse(cr, uid, model_id)
874                 partner_address_obj.write(cr, uid, [address_id.id], {'partner_id': partner_xml_id[0]})
875                 partner_contact_name = address_id.name
876             else:
877                 partner_contact_name = val.get('account_name')    
878     return partner_contact_name 
879
880 def import_opportunities(sugar_obj, cr, uid, context=None):
881     if not context:
882         context = {}
883     map_opportunity = {'id' : 'id',
884         'name': 'name',
885         'probability': 'probability',
886         'partner_id/name': 'account_name',
887         'title_action': 'next_step',
888         'partner_address_id/name': 'partner_address_id/name',
889         'planned_revenue': 'amount',
890         'date_deadline':'date_closed',
891         'user_id/id' : 'assigned_user_id',
892         'stage_id.id' : 'stage_id.id',
893         'type' : 'type',
894         'categ_id.id': 'categ_id.id'
895     }
896     lead_obj = sugar_obj.pool.get('crm.lead')
897     partner_obj = sugar_obj.pool.get('res.partner')
898     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
899     sugar_data = sugar.search(PortType, sessionid, 'Opportunities')
900     for val in sugar_data:
901         partner_xml_id = partner_obj.search(cr, uid, [('name', 'like', val.get('account_name'))])
902         if not partner_xml_id:
903             raise osv.except_osv(_('Warning !'), _('Reference Partner %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('account_name'))
904         partner_contact_name = get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context)
905         val['partner_address_id/name'] = partner_contact_name
906         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'crm.lead', val.get('opportunity_type'))                    
907         val['type'] = 'opportunity'
908         stage_id = get_opportunity_status(sugar_obj, cr, uid, val, context)
909         val['stage_id.id'] = stage_id
910         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_opportunity)
911         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
912     return True
913
914 MAP_FIELDS = {'Opportunities':  #Object Mapping name
915                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],  #Object to import before this table
916                      'process' : import_opportunities,
917                      },
918               'Leads':
919                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],  #Object to import before this table
920                      'process' : import_leads,
921                     },
922               'Contacts':
923                     {'dependencies' : ['Users'],  #Object to import before this table
924                      'process' : import_partner_address,
925                     },
926               'Accounts':
927                     {'dependencies' : ['Users', 'Contacts'],  #Object to import before this table
928                      'process' : import_partners,
929                     },
930               'Users': 
931                     {'dependencies' : [],
932                      'process' : import_users,
933                     },
934               'Meetings': 
935                     {'dependencies' : ['Users', 'Tasks'],
936                      'process' : import_meetings,
937                     },        
938               'Tasks': 
939                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
940                      'process' : import_tasks,
941                     },  
942               'Calls': 
943                     {'dependencies' : ['Users', 'Accounts', 'Contacts', 'Leads'],
944                      'process' : import_calls,
945                     },                        
946               'Employees': 
947                     {'dependencies' : ['Resources'],
948                      'process' : import_employees,
949                     },
950               'Emails': 
951                     {'dependencies' : ['Users'],
952                      'process' : import_emails,
953                     },    
954               'Projects': 
955                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
956                      'process' : import_projects,
957                     },                        
958               'Project Tasks': 
959                     {'dependencies' : ['Users', 'Projects'],
960                      'process' : import_project_tasks,
961                     },
962               'Bugs': 
963                     {'dependencies' : ['Users', 'Projects', 'Project Tasks'],
964                      'process' : import_bug,
965                     },   
966               'Notes': 
967                     {'dependencies' : ['Users', 'Projects', 'Project Tasks', 'Accounts', 'Contacts', 'Leads', 'Opportunities', 'Meetings', 'Calls'],
968                      'process' : import_history,
969                     },                    
970               'Resources': 
971                     {'dependencies' : ['Users'],
972                      'process' : import_resources,
973                     },                                      
974           }
975
976 class import_sugarcrm(osv.osv):
977     """Import SugarCRM DATA"""
978     
979     _name = "import.sugarcrm"
980     _description = __doc__
981     _columns = {
982         'lead': fields.boolean('Leads', help="If Leads are checked, SugarCRM Leads data imported in OpenERP crm-Lead form"),
983         'opportunity': fields.boolean('Opportunities', help="If Opportunities are checked, SugarCRM opportunities data imported in OpenERP crm-Opportunity form"),
984         'user': fields.boolean('User', help="If Users  are checked, SugarCRM Users data imported in OpenERP Users form"),
985         'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
986         'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
987         'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
988         'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings data imported in OpenERP meetings form"),
989         'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
990         'email': fields.boolean('Emails', help="If Emails is checked, SugarCRM Emails data imported in OpenERP Emails form"),
991         'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
992         'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
993         'bug': fields.boolean('Bugs', help="If Bugs is checked, SugarCRM Bugs data imported in OpenERP Project Issues form"),
994         'attachment': fields.boolean('Attachments', help="If Attachments is checked, SugarCRM Notes data imported in OpenERP's Related module's History with attachment"),
995         'username': fields.char('User Name', size=64),
996         'password': fields.char('Password', size=24),
997     }
998     _defaults = { #to be set to true, but easier for debugging
999        'lead': False,
1000        'opportunity': False,
1001        'user' : False,
1002        'contact' : False,
1003        'account' : False,
1004         'employee' : False,
1005         'meeting' : False,
1006         'call' : False,    
1007         'email' : False, 
1008         'project' : False,   
1009         'project_task': False,     
1010         'bug': False,
1011     }
1012     
1013     def get_key(self, cr, uid, ids, context=None):
1014         """Select Key as For which Module data we want import data."""
1015         if not context:
1016             context = {}
1017         key_list = []
1018         for current in self.browse(cr, uid, ids, context):
1019             if current.lead:
1020                 key_list.append('Leads')
1021             if current.opportunity:
1022                 key_list.append('Opportunities')
1023             if current.user:
1024                 key_list.append('Users')
1025             if current.contact:
1026                 key_list.append('Contacts')
1027             if current.account:
1028                 key_list.append('Accounts') 
1029             if current.employee:
1030                 key_list.append('Employees')  
1031             if current.meeting:
1032                 key_list.append('Meetings')
1033             if current.call:
1034                 key_list.append('Calls')
1035             if current.email:
1036                 key_list.append('Emails') 
1037             if current.project:
1038                 key_list.append('Projects')
1039             if current.project_task:
1040                 key_list.append('Project Tasks')
1041             if current.bug:
1042                 key_list.append('Bugs')
1043             if current.attachment:
1044                 key_list.append('Notes')                                    
1045         return key_list
1046
1047     def import_all(self, cr, uid, ids, context=None):
1048         """Import all sugarcrm data into openerp module"""
1049         if not context:
1050             context = {}
1051         keys = self.get_key(cr, uid, ids, context)
1052         imported = set() #to invoid importing 2 times the sames modules
1053         for key in keys:
1054             if not key in imported:
1055                 self.resolve_dependencies(cr, uid, MAP_FIELDS, MAP_FIELDS[key]['dependencies'], imported, context=context)
1056                 MAP_FIELDS[key]['process'](self, cr, uid, context)
1057                 imported.add(key)
1058
1059         obj_model = self.pool.get('ir.model.data')
1060         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
1061         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
1062         return {
1063                 'view_type': 'form',
1064                 'view_mode': 'form',
1065                 'res_model': 'import.message',
1066                 'views': [(resource_id,'form')],
1067                 'type': 'ir.actions.act_window',
1068                 'target': 'new',
1069             }
1070
1071     def resolve_dependencies(self, cr, uid, dict, dep, imported, context=None):
1072         for dependency in dep:
1073             if not dependency in imported:
1074                 self.resolve_dependencies(cr, uid, dict, dict[dependency]['dependencies'], imported, context=context)
1075                 dict[dependency]['process'](self, cr, uid, context)
1076                 imported.add(dependency)
1077         return True        
1078
1079 import_sugarcrm()