[ADD]: Add History into Leads and Opportunity
[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_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
580     new_attachment_id = attachment_obj.create(cr, uid, {'name': val.get('name'), 'datas': File, 'res_id': val['res_id'],'res_model': val['model']})
581     message_model_ids = find_mapped_id(sugar_obj, cr, uid, model, val.get('id'), context)
582     message_xml_id = model_obj.browse(cr, uid, message_model_ids)
583     if message_xml_id:
584          mailgate_obj.write(cr, uid, [message_xml_id[0].res_id], {'attachment_ids': [(4, new_attachment_id)]})             
585     return True    
586     
587 def import_history(sugar_obj, cr, uid, xml_id, model, context=None):
588     if not context:
589         context = {}
590     map_attachment = {'id' : 'id',
591                       'name':'name',
592                       'date':'date_entered',
593                       'user_id/id': 'assigned_user_id',
594                       'description': 'description_html',
595                       'res_id': 'res_id',
596                       'model': 'model',
597     }
598     mailgate_obj = sugar_obj.pool.get('mailgate.message')
599     model_obj =  sugar_obj.pool.get('ir.model.data')
600    
601     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
602     sugar_data = sugar.search(PortType, sessionid, 'Notes')
603     for val in sugar_data:
604          File = sugar.attachment_search(PortType, sessionid, 'Notes', val.get('id'))
605          model_ids = model_obj.search(cr, uid, [('name', 'like', xml_id)])
606          for model in model_obj.browse(cr, uid, model_ids):
607             val['res_id'] = model.res_id
608             val['model'] = model.model
609          fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_attachment)            
610          mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
611          get_attachment(sugar_obj, cr, uid, val, 'mailgate.message', File, context)
612     return True       
613     
614 def import_employees(sugar_obj, cr, uid, context=None):
615     if not context:
616         context = {}
617     map_employee = {'id' : 'user_hash',
618                     'resource_id/.id': 'resource_id/.id',
619                     'name': ['first_name', 'last_name'],
620                     'work_phone': 'phone_work',
621                     'mobile_phone':  'phone_mobile',
622                     'user_id/name': ['first_name', 'last_name'], 
623                     'address_home_id/.id': 'address_home_id/.id',
624                     'notes': 'description',
625                     #TODO: Creation of Employee create problem.
626                  #   'coach_id/id': 'reports_to_id',
627                     'job_id/.id': 'job_id/.id'
628     }
629     employee_obj = sugar_obj.pool.get('hr.employee')
630     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
631     sugar_data = sugar.search(PortType, sessionid, 'Employees')
632     for val in sugar_data:
633         address_id = get_user_address(sugar_obj, cr, uid, val, context)
634         val['address_home_id/.id'] = address_id
635         model_ids = find_mapped_id(sugar_obj, cr, uid, 'resource.resource', val.get('user_hash')+ '_resource_resource', context)
636         resource_id = sugar_obj.pool.get('ir.model.data').browse(cr, uid, model_ids)
637         if resource_id:
638             val['resource_id/.id'] = resource_id[0].res_id
639         val['job_id/.id'] = get_job_id(sugar_obj, cr, uid, val.get('title'), context)
640         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_employee)
641         employee_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
642     return True
643
644 def get_contact_title(sugar_obj, cr, uid, salutation, domain, context=None):
645     if not context:
646         context = {}
647     contact_title_obj = sugar_obj.pool.get('res.partner.title')
648     title_id = False            
649     title_ids = contact_title_obj.search(cr, uid, [('shortcut', '=', salutation), ('domain', '=', domain)])
650     if title_ids:
651          title_id = title_ids[0]
652     elif salutation:
653          title_id = contact_title_obj.create(cr, uid, {'name': salutation, 'shortcut': salutation, 'domain': domain})
654     return title_id
655     
656 def import_emails(sugar_obj, cr, uid, context=None):
657     if not context:
658         context=None
659     map_emails = {'id': 'id',
660     'name':'name',
661     'date':'date_sent',
662     'email_from': 'from_addr_name',
663     'email_to': 'reply_to_addr',
664     'email_cc': 'cc_addrs_names',
665     'email_bcc': 'bcc_addrs_names',
666     'message_id': 'message_id',
667     'user_id/id': 'assigned_user_id',
668     'description': 'description_html',
669     'res_id': 'res_id',
670     'model': 'model',
671     }
672     mailgate_obj = sugar_obj.pool.get('mailgate.message')
673     model_obj = sugar_obj.pool.get('ir.model.data')
674     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
675     sugar_data = sugar.search(PortType, sessionid, 'Emails')
676     for val in sugar_data:
677         model_ids = model_obj.search(cr, uid, [('name', 'like', val.get('parent_id'))])
678         for model in model_obj.browse(cr, uid, model_ids):
679             val['res_id'] = model.res_id
680             val['model'] = model.model
681         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_emails)
682         mailgate_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
683     return True    
684     
685 def import_projects(sugar_obj, cr, uid, context=None):
686     if not context:
687         context = {}
688     map_project = {'id': 'id',
689         'name': 'name',
690         'date_start': 'estimated_start_date',
691         'date': 'estimated_end_date',
692         'user_id/id': 'assigned_user_id',
693          'state': 'state'   
694     }
695     project_obj = sugar_obj.pool.get('project.project')
696     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
697     sugar_data = sugar.search(PortType, sessionid, 'Project')
698     for val in sugar_data:
699         val['state'] = get_project_state(sugar_obj, cr, uid, val.get('status'),context)
700         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project)
701         project_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
702     return True 
703
704
705 def import_project_tasks(sugar_obj, cr, uid, context=None):
706     if not context:
707         context = {}
708     map_project_task = {'id': 'id',
709         'name': 'name',
710         'date_start': 'date_start',
711         'date_end': 'date_finish',
712         'progress': 'progress',
713         'project_id/name': 'project_name',
714         'planned_hours': 'planned_hours',
715         'total_hours': 'total_hours',        
716         'priority': 'priority',
717         'description': 'description',
718         'user_id/id': 'assigned_user_id',
719          'state': 'state'   
720     }
721     task_obj = sugar_obj.pool.get('project.task')
722     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
723     sugar_data = sugar.search(PortType, sessionid, 'ProjectTask')
724     for val in sugar_data:
725         val['state'] = get_project_task_state(sugar_obj, cr, uid, val.get('status'),context)
726         val['priority'] = get_project_task_priority(sugar_obj, cr, uid, val.get('priority'),context)
727         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_project_task)
728         task_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
729     return True 
730     
731 def import_leads(sugar_obj, cr, uid, context=None):
732     if not context:
733         context = {}
734     map_lead = {
735             'id' : 'id',
736             'name': ['first_name', 'last_name'],
737             'contact_name': ['first_name', 'last_name'],
738             'description': ['description', 'refered_by', 'lead_source', 'lead_source_description', 'website'],
739             'partner_name': 'account_name',
740             'email_from': 'email1',
741             'phone': 'phone_work',
742             'mobile': 'phone_mobile',
743             'title.id': 'title.id',
744             'function':'title',
745             'street': 'primary_address_street',
746             'street2': 'alt_address_street',
747             'zip': 'primary_address_postalcode',
748             'city':'primary_address_city',
749             'user_id/id' : 'assigned_user_id',
750             'stage_id.id' : 'stage_id.id',
751             'type' : 'type',
752             'state': 'state',
753             }
754         
755     lead_obj = sugar_obj.pool.get('crm.lead')
756     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
757     sugar_data = sugar.search(PortType, sessionid, 'Leads')
758     for val in sugar_data:
759         if val.get('opportunity_id'):
760             continue
761         title_id = get_contact_title(sugar_obj, cr, uid, val.get('salutation'), 'contact', context)
762         val['title.id'] = title_id
763         val['type'] = 'lead'
764         stage_id = get_lead_status(sugar_obj, cr, uid, val, context)
765         val['stage_id.id'] = stage_id
766         val['state'] = get_lead_state(sugar_obj, cr, uid, val,context)
767         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_lead)
768         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
769         import_history(sugar_obj, cr, uid, val.get('id'), 'crm.lead', context)
770     return True
771
772 def get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context=None):
773     if not context:
774         context={}
775     partner_contact_name = False        
776     model_obj = sugar_obj.pool.get('ir.model.data')
777     partner_address_obj = sugar_obj.pool.get('res.partner.address')
778     sugar_opportunity_contact = sugar.relation_search(PortType, sessionid, 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None)
779     for contact in sugar_opportunity_contact:
780         model_ids = find_mapped_id(sugar_obj, cr, uid, 'res.partner.address', contact, context)
781         if model_ids:
782             model_id = model_obj.browse(cr, uid, model_ids)[0].res_id
783             address_id = partner_address_obj.browse(cr, uid, model_id)
784             partner_address_obj.write(cr, uid, [address_id.id], {'partner_id': partner_xml_id[0]})
785             partner_contact_name = address_id.name
786         else:
787             partner_contact_name = val.get('account_name')    
788     return partner_contact_name 
789
790 def import_opportunities(sugar_obj, cr, uid, context=None):
791     if not context:
792         context = {}
793     map_opportunity = {'id' : 'id',
794         'name': 'name',
795         'probability': 'probability',
796         'partner_id/name': 'account_name',
797         'title_action': 'next_step',
798         'partner_address_id/name': 'partner_address_id/name',
799         'planned_revenue': 'amount',
800         'date_deadline':'date_closed',
801         'user_id/id' : 'assigned_user_id',
802         'stage_id.id' : 'stage_id.id',
803         'type' : 'type',
804         'categ_id.id': 'categ_id.id'
805     }
806     lead_obj = sugar_obj.pool.get('crm.lead')
807     partner_obj = sugar_obj.pool.get('res.partner')
808     PortType, sessionid = sugar.login(context.get('username', ''), context.get('password', ''), context.get('url',''))
809     sugar_data = sugar.search(PortType, sessionid, 'Opportunities')
810     for val in sugar_data:
811         partner_xml_id = partner_obj.search(cr, uid, [('name', 'like', val.get('account_name'))])
812         if not partner_xml_id:
813             raise osv.except_osv(_('Warning !'), _('Reference Partner %s cannot be created, due to Lower Record Limit in SugarCRM Configuration.') % val.get('account_name'))
814         partner_contact_name = get_opportunity_contact(sugar_obj,cr,uid, PortType, sessionid, val, partner_xml_id, context)
815         val['partner_address_id/name'] = partner_contact_name
816         val['categ_id.id'] = get_category(sugar_obj, cr, uid, 'crm.lead', val.get('opportunity_type'))                    
817         val['type'] = 'opportunity'
818         stage_id = get_opportunity_status(sugar_obj, cr, uid, val, context)
819         val['stage_id.id'] = stage_id
820         fields, datas = sugarcrm_fields_mapping.sugarcrm_fields_mapp(val, map_opportunity)
821         lead_obj.import_data(cr, uid, fields, [datas], mode='update', current_module='sugarcrm_import', noupdate=True, context=context)
822         import_history(sugar_obj, cr, uid, val.get('id'), 'crm.lead', context)
823     return True
824
825 MAP_FIELDS = {'Opportunities':  #Object Mapping name
826                     {'dependencies' : ['Users', 'Accounts'],  #Object to import before this table
827                      'process' : import_opportunities,
828                      },
829               'Leads':
830                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],  #Object to import before this table
831                      'process' : import_leads,
832                     },
833               'Contacts':
834                     {'dependencies' : ['Users'],  #Object to import before this table
835                      'process' : import_partner_address,
836                     },
837               'Accounts':
838                     {'dependencies' : ['Users'],  #Object to import before this table
839                      'process' : import_partners,
840                     },
841               'Users': 
842                     {'dependencies' : [],
843                      'process' : import_users,
844                     },
845               'Meetings': 
846                     {'dependencies' : ['Users', 'Tasks'],
847                      'process' : import_meetings,
848                     },        
849               'Tasks': 
850                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
851                      'process' : import_tasks,
852                     },  
853               'Calls': 
854                     {'dependencies' : ['Users', 'Accounts', 'Contacts'],
855                      'process' : import_calls,
856                     },                        
857               'Employees': 
858                     {'dependencies' : ['Resources'],
859                      'process' : import_employees,
860                     },
861               'Emails': 
862                     {'dependencies' : ['Users'],
863                      'process' : import_emails,
864                     },    
865               'Projects': 
866                     {'dependencies' : ['Users'],
867                      'process' : import_projects,
868                     },                        
869               'Project Tasks': 
870                     {'dependencies' : ['Users', 'Projects'],
871                      'process' : import_project_tasks,
872                     },                          
873               'Resources': 
874                     {'dependencies' : ['Users'],
875                      'process' : import_resources,
876                     },                                      
877           }
878
879 class import_sugarcrm(osv.osv):
880     """Import SugarCRM DATA"""
881     
882     _name = "import.sugarcrm"
883     _description = __doc__
884     _columns = {
885         'lead': fields.boolean('Leads', help="If Leads are checked, SugarCRM Leads data imported in OpenERP crm-Lead form"),
886         'opportunity': fields.boolean('Opportunities', help="If Opportunities are checked, SugarCRM opportunities data imported in OpenERP crm-Opportunity form"),
887         'user': fields.boolean('User', help="If Users  are checked, SugarCRM Users data imported in OpenERP Users form"),
888         'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
889         'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
890         'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
891         'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings data imported in OpenERP meetings form"),
892         'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
893         'email': fields.boolean('Emails', help="If Emails is checked, SugarCRM Emails data imported in OpenERP Emails form"),
894         'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
895         'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
896         'username': fields.char('User Name', size=64),
897         'password': fields.char('Password', size=24),
898     }
899     _defaults = {
900        'lead': True,
901        'opportunity': True,
902        'user' : True,
903        'contact' : True,
904        'account' : True,
905         'employee' : True,
906         'meeting' : True,
907         'call' : True,    
908         'email' : True, 
909         'project' : True,   
910         'project_task': True     
911     }
912     
913     def get_key(self, cr, uid, ids, context=None):
914         """Select Key as For which Module data we want import data."""
915         if not context:
916             context = {}
917         key_list = []
918         for current in self.browse(cr, uid, ids, context):
919             if current.lead:
920                 key_list.append('Leads')
921             if current.opportunity:
922                 key_list.append('Opportunities')
923             if current.user:
924                 key_list.append('Users')
925             if current.contact:
926                 key_list.append('Contacts')
927             if current.account:
928                 key_list.append('Accounts') 
929             if current.employee:
930                 key_list.append('Employees')  
931             if current.meeting:
932                 key_list.append('Meetings')
933             if current.call:
934                 key_list.append('Calls')
935             if current.email:
936                 key_list.append('Emails') 
937             if current.project:
938                 key_list.append('Projects')
939             if current.project_task:
940                 key_list.append('Project Tasks')
941         return key_list
942
943     def import_all(self, cr, uid, ids, context=None):
944         """Import all sugarcrm data into openerp module"""
945         if not context:
946             context = {}
947         keys = self.get_key(cr, uid, ids, context)
948         imported = set() #to invoid importing 2 times the sames modules
949         for key in keys:
950             if not key in imported:
951                 self.resolve_dependencies(cr, uid, MAP_FIELDS, MAP_FIELDS[key]['dependencies'], imported, context=context)
952                 MAP_FIELDS[key]['process'](self, cr, uid, context)
953                 imported.add(key)
954
955         obj_model = self.pool.get('ir.model.data')
956         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
957         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
958         return {
959                 'view_type': 'form',
960                 'view_mode': 'form',
961                 'res_model': 'import.message',
962                 'views': [(resource_id,'form')],
963                 'type': 'ir.actions.act_window',
964                 'target': 'new',
965             }
966
967     def resolve_dependencies(self, cr, uid, dict, dep, imported, context=None):
968         for dependency in dep:
969             if not dependency in imported:
970                 self.resolve_dependencies(cr, uid, dict, dict[dependency]['dependencies'], imported, context=context)
971                 dict[dependency]['process'](self, cr, uid, context)
972                 imported.add(dependency)
973         return True        
974
975 import_sugarcrm()