[FIX]: Fix model name for partner which cannot import document
[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 import sugar
23 from tools.translate import _
24 from import_base.import_framework import *
25 from import_base.mapper import *
26 from datetime import datetime
27 import base64
28 import pprint
29 from papyon.service.SOAPService import url_split
30 pp = pprint.PrettyPrinter(indent=4)
31 #copy old import here
32
33 class related_ref(dbmapper):
34     def __init__(self, type):
35         self.type = type
36         
37     def __call__(self, external_val):
38         if external_val.get('parent_type') in self.type and external_val.get('parent_id'):
39             return self.parent.xml_id_exist(external_val['parent_type'], external_val['parent_id'])
40         return ''
41
42 class sugar_import(import_framework):
43     URL = False   
44     TABLE_CONTACT = 'Contacts'
45     TABLE_ACCOUNT = 'Accounts'
46     TABLE_USER = 'Users'
47     TABLE_EMPLOYEE = 'Employees'
48     TABLE_RESSOURCE = "resource"
49     TABLE_OPPORTUNITY = 'Opportunities'
50     TABLE_LEAD = 'Leads'
51     TABLE_STAGE = 'crm_stage'
52     TABLE_ATTENDEE = 'calendar_attendee'
53     TABLE_CALL = 'Calls'
54     TABLE_MEETING = 'Meetings'
55     TABLE_TASK = 'Tasks'
56     TABLE_PROJECT = 'Project'
57     TABLE_PROJECT_TASK = 'ProjectTask'
58     TABLE_BUG = 'Bugs'
59     TABLE_CASE = 'Cases'
60     TABLE_NOTE = 'Notes'
61     TABLE_EMAIL = 'Emails'
62     TABLE_COMPAIGN = 'Campaigns'
63     TABLE_DOCUMENT = 'Documents'
64     TABLE_HISTORY_ATTACHMNET = 'history_attachment'
65     
66     MAX_RESULT_PER_PAGE = 200
67     
68     def initialize(self):
69         #login
70         PortType,sessionid = sugar.login(self.context.get('username',''), self.context.get('password',''), self.context.get('url',''))
71         if sessionid == '-1':
72             raise osv.except_osv(_('Error !'), _('Authentication error !\nBad Username or Password or bad SugarSoap Api url !'))
73         self.context['port'] = PortType
74         self.context['session_id'] = sessionid
75         
76     def get_data(self, table):
77         offset = 0
78         
79         res = []
80         while True:
81             r = sugar.search(self.context.get('port'), self.context.get('session_id'), table, offset, self.MAX_RESULT_PER_PAGE)
82             res.extend(r)
83             if len(r) < self.MAX_RESULT_PER_PAGE:
84                 break;
85             offset += self.MAX_RESULT_PER_PAGE
86         return res
87     
88     #def get_link(self, from_table, ids, to_table):
89         #return sugar.relation_search(self.context.get('port'), self.context.get('session_id'), from_table, module_id=ids, related_module=to_table)
90
91     """
92     Common import method
93     """
94     def get_category(self, val, model, name):
95         fields = ['name', 'object_id']
96         data = [name, model]
97         return self.import_object(fields, data, 'crm.case.categ', 'crm_categ', name, [('object_id.model','=',model), ('name', 'ilike', name)])
98
99     def get_job_title(self, dict, salutation):
100         fields = ['shortcut', 'name', 'domain']
101         if salutation:
102             data = [salutation, salutation, 'Contact']
103             return self.import_object(fields, data, 'res.partner.title', 'contact_title', salutation, [('shortcut', '=', salutation)])
104
105     def get_channel_id(self, dict, val):
106         if not val:
107             return False
108         fields = ['name']
109         data = [val]
110         return self.import_object(fields, data, 'res.partner.canal', 'crm_channel', val)
111     
112     def get_all_states(self, external_val, country_id):
113         """Get states or create new state unless country_id is False"""
114         state_code = external_val[0:3] #take the tree first char
115         fields = ['country_id/id', 'name', 'code']
116         data = [country_id, external_val, state_code]
117         if country_id:
118             return self.import_object(fields, data, 'res.country.state', 'country_state', external_val) 
119         return False
120
121     def get_all_countries(self, val):
122         """Get Country, if no country match do not create anything, to avoid duplicate country code"""
123         return self.mapped_id_if_exist('res.country', [('name', 'ilike', val)], 'country', val)
124     
125     def get_float_time(self, dict, hour, min):
126         min = int(min) * 100 / 60
127         return "%s.%i" % (hour, min)
128     
129     """
130     import Documents
131     """
132     
133     def import_related_document(self, val):
134         res_model = False
135         res_id = False
136         sugar_document_account = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Documents', module_id=val.get('id'), related_module='Accounts', query=None, deleted=None)
137         sugar_document_contact = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Documents', module_id=val.get('id'), related_module=self.TABLE_CONTACT, query=None, deleted=None)
138         sugar_document_opportunity = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Documents', module_id=val.get('id'), related_module=self.TABLE_OPPORTUNITY, query=None, deleted=None)
139         sugar_document_case = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Documents', module_id=val.get('id'), related_module=self.TABLE_CASE, query=None, deleted=None)
140         sugar_document_bug = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Documents', module_id=val.get('id'), related_module=self.TABLE_BUG, query=None, deleted=None)
141         for bug_id in sugar_document_bug:
142             res_id = self.get_mapped_id(self.TABLE_BUG, bug_id)
143             res_model = 'project.issue'
144         for case_id in sugar_document_case:
145             res_id = self.get_mapped_id(self.TABLE_CASE, case_id)
146             res_model = 'crm.claim'
147         for opportunity_id in sugar_document_opportunity:
148             res_id = self.get_mapped_id(self.TABLE_OPPORTUNITY, opportunity_id)
149             res_model = 'crm.lead' 
150         for contact_id in sugar_document_contact:
151             res_id = self.get_mapped_id(self.TABLE_CONTACT, contact_id)
152             res_model = 'res.partner.address'
153         for account_id in sugar_document_account:
154             res_id = self.get_mapped_id(self.TABLE_ACCOUNT, account_id)
155             res_model = 'res.partner'
156         return res_id,res_model
157     
158     def import_document(self, val):
159         File,Filename = sugar.get_document_revision_search(self.context.get('port'), self.context.get('session_id'), val.get('document_revision_id'))
160         res_id, res_model  = self.import_related_document(val)
161         val['res_id'] = res_id
162         val['res_model'] = res_model
163         if File:
164             val['datas'] = File
165             val['datas_fname'] = Filename
166         return val   
167         
168     def get_document_mapping(self): 
169         return { 
170                 'model' : 'ir.attachment',
171                 'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT,self.TABLE_CONTACT, self.TABLE_OPPORTUNITY, self.TABLE_CASE, self.TABLE_BUG],
172                 'hook' : self.import_document,
173                 'map' : {'name':'document_name',
174                          'description': ppconcat('description'),
175                          'datas': 'datas',
176                          'datas_fname': 'datas_fname',
177                          'res_model': 'res_model',
178                          'res_id': 'res_id',
179                 }
180             }     
181         
182     
183     """
184     import Emails
185     """
186
187       
188     def import_email(self, val):
189         vals = sugar.email_search(self.context.get('port'), self.context.get('session_id'), self.TABLE_EMAIL, val.get('id'))
190         model_obj =  self.obj.pool.get('ir.model.data')
191         for val in vals:
192             xml_id = self.xml_id_exist(val.get('parent_type'), val.get('parent_id'))
193             model_ids = model_obj.search(self.cr, self.uid, [('name', 'like', xml_id)])
194             if model_ids:
195                 model = model_obj.browse(self.cr, self.uid, model_ids)[0]
196                 if model.model == 'res.partner':
197                     val['partner_id/.id'] = model.res_id
198                 else:    
199                     val['res_id'] = model.res_id
200                     val['model'] = model.model
201         return val   
202         
203     def get_email_mapping(self): 
204         return { 
205                 'model' : 'mailgate.message',
206                 'dependencies' : [self.TABLE_USER, self.TABLE_PROJECT, self.TABLE_PROJECT_TASK, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_MEETING, self.TABLE_CALL],
207                 'hook' : self.import_email,
208                 'map' : {'name':'name',
209                          'history' : const("1"),
210                         'date':'date_sent',
211                         'email_from': 'from_addr_name',
212                         'email_to': 'to_addrs_names',
213                         'email_cc': 'cc_addrs_names',
214                         'email_bcc': 'bcc_addrs_names',
215                         'message_id': 'message_id',
216                         'res_id': 'res_id',
217                         'model': 'model',
218                         'partner_id/.id': 'partner_id/.id',                         
219                         'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
220                         'description': ppconcat('description', 'description_html'),
221                 }
222             } 
223     
224     """
225     import History(Notes)
226     """
227     
228
229     def import_history(self, val):
230         model_obj =  self.obj.pool.get('ir.model.data')
231         xml_id = self.xml_id_exist(val.get('parent_type'), val.get('parent_id'))
232         model_ids = model_obj.search(self.cr, self.uid, [('name', 'like', xml_id)])
233         if model_ids:
234             model = model_obj.browse(self.cr, self.uid, model_ids)[0]
235             if model.model == 'res.partner':
236                 val['partner_id/.id'] = model.res_id
237             val['res_id'] = model.res_id
238             val['model'] = model.model
239         File, Filename = sugar.attachment_search(self.context.get('port'), self.context.get('session_id'), self.TABLE_NOTE, val.get('id')) 
240         if File:
241             val['datas'] = File
242             val['datas_fname'] = Filename
243         return val    
244     
245     def get_history_mapping(self): 
246         return { 
247                 'model' : 'ir.attachment',
248                 'dependencies' : [self.TABLE_USER, self.TABLE_PROJECT, self.TABLE_PROJECT_TASK, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD, self.TABLE_OPPORTUNITY, self.TABLE_MEETING, self.TABLE_CALL, self.TABLE_EMAIL],
249                 'hook' : self.import_history,
250                 'map' : {
251                       'name':'name',
252                       'user_id/id': ref(self.TABLE_USER, 'created_by'),
253                       'description': ppconcat('description', 'description_html'),
254                       'res_id': 'res_id',
255                       'res_model': 'model',
256                       'partner_id/.id' : 'partner_id/.id',
257                       'datas' : 'datas',
258                       'datas_fname' : 'datas_fname'
259                 }
260             }     
261     
262     """
263     import Claims(Cases)
264     """
265     def get_claim_priority(self, val):
266         priority_dict = {            
267                 'P1': '2',
268                 'P2': '3',
269                 'P3': '4'
270         }
271         return priority_dict.get(val.get('priority'), '')
272         
273     def get_contact_info_from_account(self, val):
274         partner_id = self.get_mapped_id(self.TABLE_ACCOUNT, val.get('account_id'))
275         partner_address_id = False
276         partner_phone = False
277         partner_email = False
278         partner = self.obj.pool.get('res.partner').browse(self.cr, self.uid, [partner_id])[0]
279         if partner.address and partner.address[0]:
280             address = partner.address[0]
281             partner_address_id = address.id
282             partner_phone = address.phone
283             partner_email = address.email
284         return partner_address_id, partner_phone,partner_email
285     
286     def import_crm_claim(self, val):
287         partner_address_id, partner_phone,partner_email =  self.get_contact_info_from_account(val)
288         val['partner_address_id/.id'] = partner_address_id
289         val['partner_phone'] = partner_phone
290         val['email_from'] = partner_email
291         return val
292     
293     def get_crm_claim_mapping(self): 
294         return { 
295                 'model' : 'crm.claim',
296                 'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD],
297                 'hook' : self.import_crm_claim,
298                 'map' : {
299                     'name': concat('case_number','name', delimiter='-'),
300                     'date': 'date_entered',
301                     'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
302                     'description': ppconcat('description', 'resolution', 'work_log'),
303                     'partner_id/id': ref(self.TABLE_ACCOUNT, 'account_id'),
304                     'partner_address_id/.id': 'partner_address_id/.id',
305                     'categ_id/id': call(self.get_category, 'crm.claim', value('type')),
306                     'partner_phone': 'partner_phone',
307                     'email_from': 'email_from',                                        
308                     'priority': self.get_claim_priority,
309                     'state': map_val('status', self.project_issue_state)
310                 }
311             }    
312     """
313     Import Project Issue(Bugs)
314     """
315     project_issue_state = {
316             'New' : 'draft',
317             'Assigned':'open',
318             'Closed': 'done',
319             'Pending': 'pending',
320             'Rejected': 'cancel',
321     }
322      
323     def get_project_issue_priority(self, val):
324         priority_dict = {
325                 'Urgent': '1',
326                 'High': '2',
327                 'Medium': '3',
328                 'Low': '4'
329          }
330         return priority_dict.get(val.get('priority'), '')     
331       
332     def get_bug_project_id(self, dict, val):
333         fields = ['name']
334         data = [val]
335         return self.import_object(fields, data, 'project.project', 'project_issue', val)    
336     
337     def get_project_issue_mapping(self):
338         return { 
339                 'model' : 'project.issue',
340                 'dependencies' : [self.TABLE_USER],
341                 'map' : {
342                     'name': concat('bug_number', 'name', delimiter='-'),
343                     'project_id/id': call(self.get_bug_project_id, 'sugarcrm_bugs'),
344                     'categ_id/id': call(self.get_category, 'project.issue', value('type')),
345                     'description': ppconcat('description', 'source', 'resolution', 'work_log', 'found_in_release', 'release_name', 'fixed_in_release_name', 'fixed_in_release'),
346                     'priority': self.get_project_issue_priority,
347                     'state': map_val('status', self.project_issue_state),
348                     'assigned_to/id' : ref(self.TABLE_USER, 'assigned_user_id'),
349                 }
350             }
351     
352     """
353     import Project Tasks
354     """
355     project_task_state = {
356             'Not Started': 'draft',
357             'In Progress': 'open',
358             'Completed': 'done',
359             'Pending Input': 'pending',
360             'Deferred': 'cancelled',
361      }
362     
363     def get_project_task_priority(self, val):
364         priority_dict = {
365             'High': '0',
366             'Medium': '2',
367             'Low': '3'
368         }
369         return priority_dict.get(val.get('priority'), '')
370     
371     def get_project_task_mapping(self):
372         return { 
373                 'model' : 'project.task',
374                 'dependencies' : [self.TABLE_USER, self.TABLE_PROJECT],
375                 'map' : {
376                     'name': 'name',
377                     'date_start': 'date_start',
378                     'date_end': 'date_finish',
379                     'project_id/id': ref(self.TABLE_PROJECT, 'project_id'),
380                     'planned_hours': 'estimated_effort',
381                     'priority': self.get_project_task_priority,
382                     'description': ppconcat('description','milestone_flag', 'project_task_id', 'task_number', 'percent_complete'),
383                     'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
384                     'partner_id/id': 'partner_id/id',
385                     'contact_id/id': 'contact_id/id',
386                     'state': map_val('status', self.project_task_state)
387                 }
388             }
389
390     """
391     import Projects
392     """
393     project_state = {
394             'Draft' : 'draft',
395             'In Review': 'open',
396             'Published': 'close'
397      }
398     
399     def import_project_account(self, val):
400         partner_id = False
401         partner_invoice_id = False        
402         sugar_project_account = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Project', module_id=val.get('id'), related_module=self.TABLE_ACCOUNT, query=None, deleted=None)
403         sugar_project_contact = sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Project', module_id=val.get('id'), related_module=self.TABLE_CONTACT, query=None, deleted=None)
404         for contact_id in sugar_project_contact:
405             partner_invoice_id = self.get_mapped_id(self.TABLE_CONTACT, contact_id)
406         for account_id in sugar_project_account:
407             partner_id = self.get_mapped_id(self.TABLE_ACCOUNT, account_id)
408         return partner_id, partner_invoice_id      
409            
410     def import_project(self, val):
411         partner_id, partner_invoice_id  = self.import_project_account(val)    
412         val['partner_id/.id'] = partner_id
413         val['contact_id/.id'] = partner_invoice_id
414         return val
415     
416     def get_project_mapping(self):
417         return { 
418                 'model' : 'project.project',
419                 'dependencies' : [self.TABLE_CONTACT, self.TABLE_ACCOUNT, self.TABLE_USER],
420                 'hook' : self.import_project,
421                 'map' : {
422                     'name': 'name',
423                     'date_start': 'estimated_start_date',
424                     'date': 'estimated_end_date',
425                     'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
426                     'partner_id/.id': 'partner_id/.id',
427                     'contact_id/.id': 'contact_id/.id',
428                     'state': map_val('status', self.project_state)
429                 }
430             }
431     
432     """
433     import Tasks
434     """
435     task_state = {
436             'Completed' : 'done',
437             'Not Started':'draft',
438             'In Progress': 'open',
439             'Pending Input': 'draft',
440             'deferred': 'cancel'
441         }
442
443     def import_task(self, val):
444         val['date'] = val.get('date_start') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
445         val['date_deadline'] = val.get('date_due') or datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
446         return val
447
448     def get_task_mapping(self):
449         return { 
450                 'model' : 'crm.meeting',
451                 'dependencies' : [self.TABLE_CONTACT, self.TABLE_ACCOUNT, self.TABLE_USER],
452                 'hook' : self.import_task,
453                 'map' : {
454                     'name': 'name',
455                     'date': 'date',
456                     'date_deadline': 'date_deadline',
457                     'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
458                     'categ_id/id': call(self.get_category, 'crm.meeting', const('Tasks')),
459                     'partner_id/id': related_ref(self.TABLE_ACCOUNT),
460                     'partner_address_id/id': ref(self.TABLE_CONTACT,'contact_id'),
461                     'state': map_val('status', self.task_state)
462                 }
463             }
464        
465     """
466     import Calls
467     """  
468     #TODO adapt with project trunk-crm-imp   
469     call_state = {   
470             'Planned' : 'open',
471             'Held':'done',
472             'Not Held': 'pending',
473         }
474
475     def get_calls_mapping(self):
476         return { 
477                 'model' : 'crm.phonecall',
478                 'dependencies' : [self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_OPPORTUNITY, self.TABLE_LEAD],
479                 'map' : {
480                     'name': 'name',
481                     'date': 'date_start',
482                     'duration': call(self.get_float_time, value('duration_hours'), value('duration_minutes')),
483                     'user_id/id':  ref(self.TABLE_USER, 'assigned_user_id'),
484                     'partner_id/id': related_ref(self.TABLE_ACCOUNT),
485                     'partner_address_id/id': related_ref(self.TABLE_CONTACT),
486                     'categ_id/id': call(self.get_category, 'crm.phonecall', value('direction')),
487                     'opportunity_id/id': related_ref(self.TABLE_OPPORTUNITY),
488                     'description': ppconcat('description'),   
489                     'state': map_val('status', self.call_state)                      
490                 }
491             }       
492          
493     """
494         import meeting
495     """
496     meeting_state = {
497             'Planned' : 'draft',
498             'Held': 'open',
499             'Not Held': 'draft', 
500         }
501 #TODO    
502     def get_attendee_id(self, cr, uid, module_name, module_id):
503         contact_id = False
504         user_id = False
505         attendee_id= []
506         attendee_dict = sugar.user_get_attendee_list(self.context.get('port'), self.context.get('session_id'), module_name, module_id)
507         for attendee in attendee_dict:
508             user_id = self.xml_id_exist(self.TABLE_USER, attendee.get('id', False))
509             contact_id = False
510             if not user_id:
511                 contact_id = self.xml_id_exist(self.TABLE_CONTACT, attendee.get('id', False))
512             fields = ['user_id/id', 'email', 'partner_address_id/id']
513             data = [user_id, attendee.get('email1'), contact_id]
514             attendee_xml_id = self.import_object(fields, data, 'calendar.attendee', self.TABLE_ATTENDEE, user_id or contact_id or attendee.get('email1'), ['|',('user_id', '=', attendee.get('id')),('partner_address_id','=',attendee.get('id')),('email', '=', attendee.get('email1'))])
515             attendee_id.append(attendee_xml_id)
516         return ','.join(attendee_id) 
517     
518     def get_alarm_id(self, dict_val, val):
519         alarm_dict = {
520             '60': '1 minute before',
521             '300': '5 minutes before',
522             '600': '10 minutes before',
523             '900': '15 minutes before',
524             '1800':'30 minutes before',
525             '3600': '1 hour before',
526         }
527         return self.mapped_id_if_exist('res.alarm', [('name', 'like', alarm_dict.get(val))], 'alarm', val)
528     
529     #TODO attendees
530
531     def import_meeting(self, val):
532         attendee_id = self.get_attendee_id(self.cr, self.uid, 'Meetings', val.get('id')) #TODO
533         val['attendee_ids/id'] = attendee_id
534         return val
535
536     def get_meeting_mapping(self):
537         return { 
538                 'model' : 'crm.meeting',
539                 'dependencies' : [self.TABLE_CONTACT, self.TABLE_OPPORTUNITY, self.TABLE_LEAD, self.TABLE_TASK],
540                 'hook': self.import_meeting,
541                 'map' : {
542                     'name': 'name',
543                     'date': 'date_start',
544                     'duration': call(self.get_float_time, value('duration_hours'), value('duration_minutes')),
545                     'location': 'location',
546                     'attendee_ids/id':'attendee_ids/id',
547                     'alarm_id/id': call(self.get_alarm_id, value('reminder_time')),
548                     'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
549                     'partner_id/id': related_ref(self.TABLE_ACCOUNT),
550                     'partner_address_id/id': related_ref(self.TABLE_CONTACT),
551                     'state': map_val('status', self.meeting_state)
552                 }
553             }
554     
555     """
556         import Opportunity
557     """
558     opp_state = {
559             'Need Analysis' : 'New',
560             'Closed Lost': 'Lost',
561             'Closed Won': 'Won', 
562             'Value Proposition': 'Proposition',
563             'Negotiation/Review': 'Negotiation'
564         }
565         
566     def get_opportunity_status(self, sugar_val):
567         fields = ['name', 'type']
568         name = 'Opportunity_' + sugar_val['sales_stage']
569         data = [sugar_val['sales_stage'], 'Opportunity']
570         return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('type', '=', 'opportunity'), ('name', 'ilike', sugar_val['sales_stage'])])
571     
572     def import_opportunity_contact(self, val):
573         sugar_opportunities_contact = set(sugar.relation_search(self.context.get('port'), self.context.get('session_id'), 'Opportunities', module_id=val.get('id'), related_module='Contacts', query=None, deleted=None))
574             
575         partner_contact_id = False 
576         partner_contact_email = False       
577         partner_address_obj = self.obj.pool.get('res.partner.address')
578         partner_xml_id = self.name_exist(self.TABLE_ACCOUNT, val['account_name'], 'res.partner')
579         
580         for contact in sugar_opportunities_contact:
581             address_id = self.get_mapped_id(self.TABLE_CONTACT, contact)
582             if address_id:                    
583                 address = partner_address_obj.browse(self.cr, self.uid, address_id)
584                 partner_name = address.partner_id and address.partner_id.name or False
585                 if not partner_name: #link with partner id 
586                     fields = ['partner_id/id']
587                     data = [partner_xml_id]
588                     self.import_object(fields, data, 'res.partner.address', self.TABLE_CONTACT, contact, self.DO_NOT_FIND_DOMAIN)
589                 if not partner_name or partner_name == val.get('account_name'):
590                     partner_contact_id = self.xml_id_exist(self.TABLE_CONTACT, contact)
591                     partner_contact_email = address.email
592         return partner_contact_id, partner_contact_email
593
594     def import_opp(self, val):    
595         partner_contact_id, partner_contact_email = self.import_opportunity_contact(val)
596         val['partner_address_id/id'] = partner_contact_id
597         val['email_from'] = partner_contact_email
598         return val
599     
600     def get_opp_mapping(self):
601         return {
602             'model' : 'crm.lead',
603             'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT,self.TABLE_COMPAIGN],
604             'hook' : self.import_opp,
605             'map' :  {
606                 'name': 'name',
607                 'probability': 'probability',
608                 'partner_id/id': refbyname(self.TABLE_ACCOUNT, 'account_name', 'res.partner'),
609                 'title_action': 'next_step',
610                 'partner_address_id/id': 'partner_address_id/id',
611                 'planned_revenue': 'amount',
612                 'date_deadline': 'date_closed',
613                 'user_id/id' : ref(self.TABLE_USER, 'assigned_user_id'),
614                 'stage_id/id' : self.get_opportunity_status,
615                 'type' : const('opportunity'),
616                 'categ_id/id': call(self.get_category, 'crm.lead', value('opportunity_type')),
617                 'email_from': 'email_from',
618                 'state': map_val('status', self.opp_state)  , #TODO
619             }
620         }
621         
622     """
623     import campaign
624     """
625     
626     def get_compaign_mapping(self):
627         return {
628             'model' : 'crm.case.resource.type',
629             'map' : {
630                 'name': 'name',
631                 } 
632         }    
633         
634     """
635         import lead
636     """
637     def get_lead_status(self, sugar_val):
638         fields = ['name', 'type']
639         name = 'lead_' + sugar_val.get('status', '')
640         data = [sugar_val.get('status', ''), 'lead']
641         return self.import_object(fields, data, 'crm.case.stage', self.TABLE_STAGE, name, [('type', '=', 'lead'), ('name', 'ilike', sugar_val.get('status', ''))])
642
643     lead_state = {
644         'New' : 'draft',
645         'Assigned':'open',
646         'In Progress': 'open',
647         'Recycled': 'cancel',
648         'Dead': 'done',
649         'Converted': 'done',
650     }
651     
652     def import_lead(self, val):
653         if val.get('opportunity_id'): #if lead is converted into opp, don't import as lead
654             return False
655         if val.get('primary_address_country'):
656             country_id = self.get_all_countries(val.get('primary_address_country'))
657             val['country_id/id'] =  country_id
658             val['state_id/id'] =  self.get_all_states(val.get('primary_address_state'), country_id)
659         return val
660     
661     def get_lead_mapping(self):
662         return {
663             'model' : 'crm.lead',
664             'dependencies' : [self.TABLE_COMPAIGN, self.TABLE_USER],
665             'hook' : self.import_lead,
666             'map' : {
667                 'name': concat('first_name', 'last_name'),
668                 'contact_name': concat('first_name', 'last_name'),
669                 'description': ppconcat('description', 'refered_by', 'lead_source', 'lead_source_description', 'website', 'email2', 'status_description', 'lead_source_description', 'do_not_call'),
670                 'partner_name': 'account_name',
671                 'email_from': 'email1',
672                 'phone': 'phone_work',
673                 'mobile': 'phone_mobile',
674                 'title/id': call(self.get_job_title, value('salutation')),
675                 'function':'title',
676                 'street': 'primary_address_street',
677                 'street2': 'alt_address_street',
678                 'zip': 'primary_address_postalcode',
679                 'city':'primary_address_city',
680                 'user_id/id' : ref(self.TABLE_USER, 'assigned_user_id'),
681                 'stage_id/id' : self.get_lead_status,
682                 'type' : const('lead'),
683                 'state': map_val('status', self.lead_state) ,
684                 'fax': 'phone_fax',
685                 'referred': 'refered_by',
686                 'optout': 'do_not_call',
687                 'channel_id/id': call(self.get_channel_id, value('lead_source')),
688                 'type_id/id': ref(self.TABLE_COMPAIGN, 'campaign_id'),
689                 'country_id/id': 'country_id/id',
690                 'state_id/id': 'state_id/id'
691                 } 
692         }
693     
694     """
695         import contact
696     """
697     
698     def get_email(self, val):
699         email_address = sugar.get_contact_by_email(self.context.get('port'), self.context.get('username'), self.context.get('password'), val.get('email1'))
700         if email_address:
701             return ','.join(email_address)     
702     
703     def import_contact(self, val):
704         if val.get('primary_address_country'):
705             country_id = self.get_all_countries(val.get('primary_address_country'))
706             state = self.get_all_states(val.get('primary_address_state'), country_id)
707             val['country_id/id'] =  country_id
708             val['state_id/id'] =  state
709         return val    
710         
711     def get_contact_mapping(self):
712         return { 
713             'model' : 'res.partner.address',
714             'dependencies' : [self.TABLE_ACCOUNT],
715             'hook' : self.import_contact,
716             'map' :  {
717                 'name': concat('first_name', 'last_name'),
718                 'partner_id/id': ref(self.TABLE_ACCOUNT,'account_id'),
719                 'phone': 'phone_work',
720                 'mobile': 'phone_mobile',
721                 'fax': 'phone_fax',
722                 'function': 'title',
723                 'street': 'primary_address_street',
724                 'zip': 'primary_address_postalcode',
725                 'city': 'primary_address_city',
726                 'country_id/id': 'country_id/id',
727                 'state_id/id': 'state_id/id',
728                 'email': self.get_email,
729                 'type': const('contact')
730             }
731         }
732     
733     """ 
734         import Account
735     """
736     
737     def get_address_type(self, val, type):
738         if type == 'invoice':
739             type_address = 'billing'
740         else:
741             type_address = 'shipping' 
742             
743         if type == 'default':
744             map_partner_address = {
745                 'name': 'name',
746                 'type': const('default'),
747                 'email': 'email1' 
748             }
749         else:        
750             map_partner_address = {
751                 'name': 'name',
752                 'phone': 'phone_office',
753                 'mobile': 'phone_mobile',
754                 'fax': 'phone_fax',
755                 'type': 'type',
756                 'street': type_address + '_address_street',
757                 'zip': type_address +'_address_postalcode',
758                 'city': type_address +'_address_city',
759                  'country_id/id': 'country_id/id',
760                  'type': 'type',
761                 }
762             
763         if val.get(type_address +'_address_country'):
764             country_id = self.get_all_countries(val.get(type_address +'_address_country'))
765             state = self.get_all_states(val.get(type_address +'_address_state'), country_id)
766             val['country_id/id'] =  country_id
767             val['state_id/id'] =  state
768             
769         val['type'] = type
770         val['id_new'] = val['id'] + '_address_' + type
771         return self.import_object_mapping(map_partner_address, val, 'res.partner.address', self.TABLE_CONTACT, val['id_new'], self.DO_NOT_FIND_DOMAIN) 
772         
773     def get_partner_address(self, val):
774         address_id=[]
775         type_dict = {'billing_address_street' : 'invoice', 'shipping_address_street' : 'delivery', 'type': 'default'}
776         for key, type_value in type_dict.items():
777             if val.get(key):
778                 id = self.get_address_type(val, type_value)
779                 address_id.append(id)
780           
781         return ','.join(address_id)
782     
783     def get_partner_mapping(self):
784         return {
785                 'model' : 'res.partner',
786                 'dependencies' : [self.TABLE_USER],
787                 'map' : {
788                     'name': 'name',
789                     'website': 'website',
790                     'user_id/id': ref(self.TABLE_USER,'assigned_user_id'),
791                     'ref': 'sic_code',
792                     'comment': ppconcat('description', 'employees', 'ownership', 'annual_revenue', 'rating', 'industry', 'ticker_symbol'),
793                     'customer': const('1'),
794                     'supplier': const('0'),
795                     'address/id':'address/id', 
796                     'parent_id/id_parent' : 'parent_id',
797                     'address/id' : self.get_partner_address,
798                 }
799         }
800
801     """
802         import Employee
803     """
804     def get_ressource(self, val):
805         map_resource = { 
806             'name': concat('first_name', 'last_name'),
807         }        
808         return self.import_object_mapping(map_resource, val, 'resource.resource', self.TABLE_RESSOURCE, val['id'], self.DO_NOT_FIND_DOMAIN)
809     
810     def get_job_id(self, val):
811         fields = ['name']
812         data = [val.get('title')]
813         return self.import_object(fields, data, 'hr.job', 'hr_job', val.get('title'))
814
815     def get_user_address(self, val):
816         map_user_address = {
817             'name': concat('first_name', 'last_name'),
818             'city': 'address_city',
819             'country_id/id': 'country_id/id',
820             'state_id/id': 'state_id/id',
821             'street': 'address_street',
822             'zip': 'address_postalcode',
823             'fax': 'phone_fax',
824             'phone': 'phone_work',
825             'mobile':'phone_mobile',
826             'email': 'email1'
827         }
828         
829         if val.get('address_country'):
830             country_id = self.get_all_countries(val.get('address_country'))
831             state_id = self.get_all_states(val.get('address_state'), country_id)
832             val['country_id/id'] =  country_id
833             val['state_id/id'] =  state_id
834             
835         return self.import_object_mapping(map_user_address, val, 'res.partner.address', self.TABLE_CONTACT, val['id'], self.DO_NOT_FIND_DOMAIN)
836
837     def get_employee_mapping(self):
838         return {
839             'model' : 'hr.employee',
840             'dependencies' : [self.TABLE_USER],
841             'map' : {
842                 'resource_id/id': self.get_ressource, 
843                 'name': concat('first_name', 'last_name'),
844                 'work_phone': 'phone_work',
845                 'mobile_phone':  'phone_mobile',
846                 'user_id/id': ref(self.TABLE_USER, 'id'), 
847                 'address_home_id/id': self.get_user_address,
848                 'notes': ppconcat('messenger_type', 'messenger_id', 'description'),
849                 'job_id/id': self.get_job_id,
850                 'work_email' : 'email1',
851                 'coach_id/id_parent' : 'reports_to_id',
852             }
853      }
854     
855     """
856         import user
857     """  
858     def import_user(self, val):
859         user_obj = self.obj.pool.get('res.users')
860         user_ids = user_obj.search(self.cr, self.uid, [('login', '=', val.get('user_name'))])
861         if user_ids: 
862             val['.id'] = str(user_ids[0])
863         else:
864             val['password'] = 'sugarcrm' #default password for all user #TODO needed in documentation
865             
866         val['context_lang'] = self.context.get('lang','en_US')
867         return val
868     
869     def get_users_department(self, val):
870         dep = val.get('department')
871         fields = ['name']
872         data = [dep]
873         if not dep:
874             return False
875         return self.import_object(fields, data, 'hr.department', 'hr_department_user', dep)
876
877     def get_user_mapping(self):
878         return {
879             'model' : 'res.users',
880             'hook' : self.import_user,
881             'map' : { 
882                 'name': concat('first_name', 'last_name'),
883                 'login': 'user_name',
884                 'context_lang' : 'context_lang',
885                 'password' : 'password',
886                 '.id' : '.id',
887                 'context_department_id/id': self.get_users_department,
888                 'user_email' : 'email1',
889             }
890         }
891
892
893     def get_mapping(self):
894         return {
895             self.TABLE_USER : self.get_user_mapping(),
896             self.TABLE_EMPLOYEE : self.get_employee_mapping(),
897             self.TABLE_ACCOUNT : self.get_partner_mapping(),
898             self.TABLE_CONTACT : self.get_contact_mapping(),
899             self.TABLE_LEAD : self.get_lead_mapping(),
900             self.TABLE_OPPORTUNITY : self.get_opp_mapping(),
901             self.TABLE_MEETING : self.get_meeting_mapping(),
902             self.TABLE_CALL : self.get_calls_mapping(),
903             self.TABLE_TASK : self.get_task_mapping(),
904             self.TABLE_PROJECT : self.get_project_mapping(),
905             self.TABLE_PROJECT_TASK: self.get_project_task_mapping(),
906             self.TABLE_BUG: self.get_project_issue_mapping(),
907             self.TABLE_CASE: self.get_crm_claim_mapping(),
908             self.TABLE_NOTE: self.get_history_mapping(),
909             self.TABLE_EMAIL: self.get_email_mapping(),
910             self.TABLE_DOCUMENT: self.get_document_mapping(),
911             self.TABLE_COMPAIGN: self.get_compaign_mapping()
912         }
913         
914     """
915         Email notification
916     """   
917     def get_email_subject(self, result):
918         return "your sugarcrm data were successfully imported at %s" % self.date_ended 
919     
920     def get_body_header(self, result):
921         return "Sugarcrm import : report of last import" 
922
923
924 class import_sugarcrm(osv.osv):
925     """Import SugarCRM DATA"""
926     
927     _name = "import.sugarcrm"
928     _description = __doc__
929     _columns = {
930         'username': fields.char('User Name', size=64, required=True),
931         'password': fields.char('Password', size=24,required=True),
932          'url' : fields.char('SugarSoap Api url:', size=264, required=True, help="Webservice's url where to get the data.\
933                       example : 'http://example.com/sugarcrm/soap.php', or copy the address of your sugarcrm application http://trial.sugarcrm.com/qbquyj4802/index.php?module=Home&action=index"),
934         'opportunity': fields.boolean('Leads and Opportunities', help="If Opportunities are checked, SugarCRM opportunities data imported in OpenERP crm-Opportunity form"),
935         'contact': fields.boolean('Contacts', help="If Contacts are checked, SugarCRM Contacts data imported in OpenERP partner address form"),
936         'account': fields.boolean('Accounts', help="If Accounts are checked, SugarCRM  Accounts data imported in OpenERP partners form"),
937         'employee': fields.boolean('Employee', help="If Employees is checked, SugarCRM Employees data imported in OpenERP employees form"),
938         'meeting': fields.boolean('Meetings', help="If Meetings is checked, SugarCRM Meetings and Meeting Tasks data imported in OpenERP meetings form"),
939         'call': fields.boolean('Calls', help="If Calls is checked, SugarCRM Calls data imported in OpenERP phonecalls form"),
940         'claim': fields.boolean('Cases', help="If Cases is checked, SugarCRM Cases data imported in OpenERP Claims form"),
941         'email_history': fields.boolean('Email and History',help="If Email and History is checked, SugarCRM Notes and Emails data imported in OpenERP's Related module's History with attachment"),
942         'project': fields.boolean('Projects', help="If Projects is checked, SugarCRM Projects data imported in OpenERP Projects form"),
943         'project_task': fields.boolean('Project Tasks', help="If Project Tasks is checked, SugarCRM Project Tasks data imported in OpenERP Project Tasks form"),
944         'bug': fields.boolean('Bugs', help="If Bugs is checked, SugarCRM Bugs data imported in OpenERP Project Issues form"),
945         'document': fields.boolean('Documents', help="If Documents is checked, SugarCRM Documents data imported in OpenERP Document Form"),
946         'email_from': fields.char('Notify End Of Import To:', size=128),
947         'instance_name': fields.char("Instance's Name", size=64, help="Prefix of SugarCRM id to differentiate xml_id of SugarCRM models datas come from different server."),
948     }
949     
950     def _get_email_id(self, cr, uid, context=None):
951         return self.pool.get('res.users').browse(cr, uid, uid, context=context).user_email    
952     
953     _defaults = {#to be set to true, but easier for debugging
954        'opportunity': False,
955        'contact' : False,
956        'account' : False,
957         'employee' : False,
958         'meeting' : False,
959         'call' : False,
960         'claim' : False,    
961         'email_history' : False, 
962         'project' : False,   
963         'project_task': False,     
964         'bug': False,
965         'document': False,
966         'instance_name': 'sugarcrm',
967         'email_from': _get_email_id,
968         'username' : 'tfr',
969         'password' : 'a',
970         'url':  "http://localhost/sugarcrm/soap.php"        
971     }
972     
973     def check_url(self, url, context):
974         if not context:
975             context = {}
976         user = context.get('username')
977         password = context.get('password')
978         
979         try :
980             sugar.login(user, password, url)
981             return True
982         except Exception:
983             return False
984                 
985         
986     def parse_valid_url(self, context=None):
987         if not context:
988             context = {}
989         url = context.get('url')
990         
991         
992         url_split = str(url).split('/')
993         while len(url_split) >= 3:
994             #3 case, soap.php is already at the end of url should be valid
995             #url end by / or not
996             if url_split[-1] == 'soap.php':
997                 url = "/".join(url_split)
998             elif url_split[-1] == '':
999                 url = "/".join(url_split) + "soap.php"
1000             else:
1001                 url = "/".join(url_split) + "/soap.php"
1002             
1003             if self.check_url(url, context):
1004                 return url
1005             else: 
1006                 url_split = url_split[:-1] #take parent folder
1007         return url
1008             
1009     def get_key(self, cr, uid, ids, context=None):
1010         """Select Key as For which Module data we want import data."""
1011         if not context:
1012             context = {}
1013         key_list = []
1014         for current in self.browse(cr, uid, ids, context):
1015             context.update({'username': current.username, 'password': current.password, 'url': current.url, 'email_user': current.email_from or False, 'instance_name': current.instance_name or False})
1016             if current.opportunity:
1017                 key_list.append('Leads')
1018                 key_list.append('Opportunities')
1019             if current.contact:
1020                 key_list.append('Contacts')
1021             if current.account:
1022                 key_list.append('Accounts') 
1023             if current.employee:
1024                 key_list.append('Employees')  
1025             if current.meeting:
1026                 key_list.append('Meetings')
1027             if current.call:
1028                 key_list.append('Calls')
1029             if current.claim:
1030                 key_list.append('Cases')                
1031             if current.email_history:
1032                 key_list.append('Emails') 
1033                 key_list.append('Notes') 
1034             if current.project:
1035                 key_list.append('Project')
1036             if current.project_task:
1037                 key_list.append('ProjectTask')
1038             if current.bug:
1039                 key_list.append('Bugs')
1040             if current.document:
1041                 key_list.append('Documents')
1042         return key_list
1043
1044
1045     def do_import_all(self, cr, uid, *args):
1046         """
1047         scheduler Method
1048         """
1049         context = {'username': args[4], 'password': args[5], 'url': args[3], 'instance_name': args[3]}
1050         imp = sugar_import(self, cr, uid, args[2], "import_sugarcrm", [args[1]], context)
1051         imp.set_table_list(args[0])
1052         imp.start()
1053         return True 
1054
1055     def import_from_scheduler_all(self, cr, uid, ids, context=None):
1056         keys = self.get_key(cr, uid, ids, context)
1057         if not keys:
1058             raise osv.except_osv(_('Warning !'), _('Select Module to Import.'))
1059         cron_obj = self.pool.get('ir.cron')
1060         url = self.parse_valid_url(context)
1061         args = (keys,context.get('email_user'), context.get('instance_name'), url, context.get('username'), context.get('password') )
1062         new_create_id = cron_obj.create(cr, uid, {'name': 'Import SugarCRM datas','interval_type': 'hours','interval_number': 1, 'numbercall': -1,'model': 'import.sugarcrm','function': 'do_import_all', 'args': args, 'active': False})
1063         return {
1064             'name': 'SugarCRM Scheduler',
1065             'view_type': 'form',
1066             'view_mode': 'form,tree',
1067             'res_model': 'ir.cron',
1068             'res_id': new_create_id,
1069             'type': 'ir.actions.act_window',
1070         }
1071     
1072     
1073     def import_all(self, cr, uid, ids, context=None):
1074         
1075 #        """Import all sugarcrm data into openerp module"""
1076         keys = self.get_key(cr, uid, ids, context)
1077         url = self.parse_valid_url(context)
1078         context.update({'url': url})
1079         imp = sugar_import(self, cr, uid, context.get('instance_name'), "import_sugarcrm", [context.get('email_user')], context)
1080         imp.set_table_list(keys)
1081         imp.start()
1082         
1083         obj_model = self.pool.get('ir.model.data')
1084         model_data_ids = obj_model.search(cr,uid,[('model','=','ir.ui.view'),('name','=','import.message.form')])
1085         resource_id = obj_model.read(cr, uid, model_data_ids, fields=['res_id'])
1086         return {
1087                 'view_type': 'form',
1088                 'view_mode': 'form',
1089                 'res_model': 'import.message',
1090                 'views': [(resource_id,'form')],
1091                 'type': 'ir.actions.act_window',
1092                 'target': 'new',
1093             }
1094         
1095 import_sugarcrm()