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