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