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