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