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