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