1 # -*- coding: utf-8 -*-
2 ##############################################################################
4 # OpenERP, Open Source Management Solution
5 # Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
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.
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.
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/>.
20 ##############################################################################
21 from osv import fields, osv
23 from tools.translate import _
24 from import_base.import_framework import *
25 from import_base.mapper import *
26 from datetime import datetime
29 from papyon.service.SOAPService import url_split
30 pp = pprint.PrettyPrinter(indent=4)
33 class related_ref(dbmapper):
34 def __init__(self, type):
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'])
42 class sugar_import(import_framework):
44 TABLE_CONTACT = 'Contacts'
45 TABLE_ACCOUNT = 'Accounts'
47 TABLE_EMPLOYEE = 'Employees'
48 TABLE_RESSOURCE = "resource"
49 TABLE_OPPORTUNITY = 'Opportunities'
51 TABLE_STAGE = 'crm_stage'
52 TABLE_ATTENDEE = 'calendar_attendee'
54 TABLE_MEETING = 'Meetings'
56 TABLE_PROJECT = 'Project'
57 TABLE_PROJECT_TASK = 'ProjectTask'
61 TABLE_EMAIL = 'Emails'
62 TABLE_COMPAIGN = 'Campaigns'
63 TABLE_DOCUMENT = 'Documents'
64 TABLE_HISTORY_ATTACHMNET = 'history_attachment'
66 MAX_RESULT_PER_PAGE = 200
70 PortType,sessionid = sugar.login(self.context.get('username',''), self.context.get('password',''), self.context.get('url',''))
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
76 def get_data(self, table):
81 r = sugar.search(self.context.get('port'), self.context.get('session_id'), table, offset, self.MAX_RESULT_PER_PAGE)
83 if len(r) < self.MAX_RESULT_PER_PAGE:
85 offset += self.MAX_RESULT_PER_PAGE
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)
94 def get_category(self, val, model, name):
95 fields = ['name', 'object_id']
97 return self.import_object(fields, data, 'crm.case.categ', 'crm_categ', name, [('object_id.model','=',model), ('name', 'ilike', name)])
99 def get_job_title(self, dict, salutation):
100 fields = ['shortcut', 'name', 'domain']
102 data = [salutation, salutation, 'Contact']
103 return self.import_object(fields, data, 'res.partner.title', 'contact_title', salutation, [('shortcut', '=', salutation)])
105 def get_channel_id(self, dict, val):
110 return self.import_object(fields, data, 'res.partner.canal', 'crm_channel', val)
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]
118 return self.import_object(fields, data, 'res.country.state', 'country_state', external_val)
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)
125 def get_float_time(self, dict, hour, min):
126 min = int(min) * 100 / 60
127 return "%s.%i" % (hour, min)
133 def import_related_document(self, val):
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
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
165 val['datas_fname'] = Filename
168 def get_document_mapping(self):
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'),
176 'datas_fname': 'datas_fname',
177 'res_model': 'res_model',
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')
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)])
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
199 val['res_id'] = model.res_id
200 val['model'] = model.model
203 def get_email_mapping(self):
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"),
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',
218 'partner_id/.id': 'partner_id/.id',
219 'user_id/id': ref(self.TABLE_USER, 'assigned_user_id'),
220 'description': ppconcat('description', 'description_html'),
225 import History(Notes)
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)])
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'))
242 val['datas_fname'] = Filename
245 def get_history_mapping(self):
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,
252 'user_id/id': ref(self.TABLE_USER, 'created_by'),
253 'description': ppconcat('description', 'description_html'),
255 'res_model': 'model',
256 'partner_id/.id' : 'partner_id/.id',
258 'datas_fname' : 'datas_fname'
265 def get_claim_priority(self, val):
271 return priority_dict.get(val.get('priority'), '')
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
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
293 def get_crm_claim_mapping(self):
295 'model' : 'crm.claim',
296 'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_LEAD],
297 'hook' : self.import_crm_claim,
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)
313 Import Project Issue(Bugs)
315 project_issue_state = {
319 'Pending': 'pending',
320 'Rejected': 'cancel',
323 def get_project_issue_priority(self, val):
330 return priority_dict.get(val.get('priority'), '')
332 def get_bug_project_id(self, dict, val):
335 return self.import_object(fields, data, 'project.project', 'project_issue', val)
337 def get_project_issue_mapping(self):
339 'model' : 'project.issue',
340 'dependencies' : [self.TABLE_USER],
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'),
355 project_task_state = {
356 'Not Started': 'draft',
357 'In Progress': 'open',
359 'Pending Input': 'pending',
360 'Deferred': 'cancelled',
363 def get_project_task_priority(self, val):
369 return priority_dict.get(val.get('priority'), '')
371 def get_project_task_mapping(self):
373 'model' : 'project.task',
374 'dependencies' : [self.TABLE_USER, self.TABLE_PROJECT],
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)
399 def import_project_account(self, val):
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
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
416 def get_project_mapping(self):
418 'model' : 'project.project',
419 'dependencies' : [self.TABLE_CONTACT, self.TABLE_ACCOUNT, self.TABLE_USER],
420 'hook' : self.import_project,
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)
436 'Completed' : 'done',
437 'Not Started':'draft',
438 'In Progress': 'open',
439 'Pending Input': 'draft',
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'),
448 def get_task_mapping(self):
450 'model' : 'crm.meeting',
451 'dependencies' : [self.TABLE_CONTACT, self.TABLE_ACCOUNT, self.TABLE_USER],
452 'hook' : self.import_task,
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)
468 #TODO adapt with project trunk-crm-imp
472 'Not Held': 'pending',
475 def get_calls_mapping(self):
477 'model' : 'crm.phonecall',
478 'dependencies' : [self.TABLE_ACCOUNT, self.TABLE_CONTACT, self.TABLE_OPPORTUNITY, self.TABLE_LEAD],
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)
502 def get_attendee_id(self, cr, uid, module_name, module_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))
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)
518 def get_alarm_id(self, dict_val, val):
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',
527 return self.mapped_id_if_exist('res.alarm', [('name', 'like', alarm_dict.get(val))], 'alarm', val)
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
536 def get_meeting_mapping(self):
538 'model' : 'crm.meeting',
539 'dependencies' : [self.TABLE_CONTACT, self.TABLE_OPPORTUNITY, self.TABLE_LEAD, self.TABLE_TASK],
540 'hook': self.import_meeting,
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)
559 'Need Analysis' : 'New',
560 'Closed Lost': 'Lost',
562 'Value Proposition': 'Proposition',
563 'Negotiation/Review': 'Negotiation'
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'])])
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))
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')
580 for contact in sugar_opportunities_contact:
581 address_id = self.get_mapped_id(self.TABLE_CONTACT, contact)
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
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
600 def get_opp_mapping(self):
602 'model' : 'crm.lead',
603 'dependencies' : [self.TABLE_USER, self.TABLE_ACCOUNT, self.TABLE_CONTACT,self.TABLE_COMPAIGN],
604 'hook' : self.import_opp,
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
626 def get_compaign_mapping(self):
628 'model' : 'crm.case.resource.type',
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', ''))])
646 'In Progress': 'open',
647 'Recycled': 'cancel',
652 def import_lead(self, val):
653 if val.get('opportunity_id'): #if lead is converted into opp, don't import as lead
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)
661 def get_lead_mapping(self):
663 'model' : 'crm.lead',
664 'dependencies' : [self.TABLE_COMPAIGN, self.TABLE_USER],
665 'hook' : self.import_lead,
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')),
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) ,
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'
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'))
701 return ','.join(email_address)
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
711 def get_contact_mapping(self):
713 'model' : 'res.partner.address',
714 'dependencies' : [self.TABLE_ACCOUNT],
715 'hook' : self.import_contact,
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',
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')
737 def get_address_type(self, val, type):
738 if type == 'invoice':
739 type_address = 'billing'
741 type_address = 'shipping'
743 if type == 'default':
744 map_partner_address = {
746 'type': const('default'),
750 map_partner_address = {
752 'phone': 'phone_office',
753 'mobile': 'phone_mobile',
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',
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
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)
773 def get_partner_address(self, val):
775 type_dict = {'billing_address_street' : 'invoice', 'shipping_address_street' : 'delivery', 'type': 'default'}
776 for key, type_value in type_dict.items():
778 id = self.get_address_type(val, type_value)
779 address_id.append(id)
781 return ','.join(address_id)
783 def get_partner_mapping(self):
785 'model' : 'res.partner',
786 'dependencies' : [self.TABLE_USER],
789 'website': 'website',
790 'user_id/id': ref(self.TABLE_USER,'assigned_user_id'),
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,
804 def get_ressource(self, val):
806 'name': concat('first_name', 'last_name'),
808 return self.import_object_mapping(map_resource, val, 'resource.resource', self.TABLE_RESSOURCE, val['id'], self.DO_NOT_FIND_DOMAIN)
810 def get_job_id(self, val):
812 data = [val.get('title')]
813 return self.import_object(fields, data, 'hr.job', 'hr_job', val.get('title'))
815 def get_user_address(self, val):
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',
824 'phone': 'phone_work',
825 'mobile':'phone_mobile',
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
835 return self.import_object_mapping(map_user_address, val, 'res.partner.address', self.TABLE_CONTACT, val['id'], self.DO_NOT_FIND_DOMAIN)
837 def get_employee_mapping(self):
839 'model' : 'hr.employee',
840 'dependencies' : [self.TABLE_USER],
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',
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'))])
862 val['.id'] = str(user_ids[0])
864 val['password'] = 'sugarcrm' #default password for all user #TODO needed in documentation
866 val['context_lang'] = self.context.get('lang','en_US')
869 def get_users_department(self, val):
870 dep = val.get('department')
875 return self.import_object(fields, data, 'hr.department', 'hr_department_user', dep)
877 def get_user_mapping(self):
879 'model' : 'res.users',
880 'hook' : self.import_user,
882 'name': concat('first_name', 'last_name'),
883 'login': 'user_name',
884 'context_lang' : 'context_lang',
885 'password' : 'password',
887 'context_department_id/id': self.get_users_department,
888 'user_email' : 'email1',
893 def get_mapping(self):
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()
917 def get_email_subject(self, result):
918 return "your sugarcrm data were successfully imported at %s" % self.date_ended
920 def get_body_header(self, result):
921 return "Sugarcrm import : report of last import"
924 class import_sugarcrm(osv.osv):
925 """Import SugarCRM DATA"""
927 _name = "import.sugarcrm"
928 _description = __doc__
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."),
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
953 _defaults = {#to be set to true, but easier for debugging
954 'opportunity': False,
961 'email_history' : False,
963 'project_task': False,
966 'instance_name': 'sugarcrm',
967 'email_from': _get_email_id,
970 'url': "http://localhost/sugarcrm/soap.php"
973 def check_url(self, url, context):
976 user = context.get('username')
977 password = context.get('password')
980 sugar.login(user, password, url)
986 def parse_valid_url(self, context=None):
989 url = context.get('url')
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
996 if url_split[-1] == 'soap.php':
997 url = "/".join(url_split)
998 elif url_split[-1] == '':
999 url = "/".join(url_split) + "soap.php"
1001 url = "/".join(url_split) + "/soap.php"
1003 if self.check_url(url, context):
1006 url_split = url_split[:-1] #take parent folder
1009 def get_key(self, cr, uid, ids, context=None):
1010 """Select Key as For which Module data we want import data."""
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')
1020 key_list.append('Contacts')
1022 key_list.append('Accounts')
1023 if current.employee:
1024 key_list.append('Employees')
1026 key_list.append('Meetings')
1028 key_list.append('Calls')
1030 key_list.append('Cases')
1031 if current.email_history:
1032 key_list.append('Emails')
1033 key_list.append('Notes')
1035 key_list.append('Project')
1036 if current.project_task:
1037 key_list.append('ProjectTask')
1039 key_list.append('Bugs')
1040 if current.document:
1041 key_list.append('Documents')
1045 def do_import_all(self, cr, uid, *args):
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])
1055 def import_from_scheduler_all(self, cr, uid, ids, context=None):
1056 keys = self.get_key(cr, uid, ids, context)
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})
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',
1073 def import_all(self, cr, uid, ids, context=None):
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)
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'])
1087 'view_type': 'form',
1088 'view_mode': 'form',
1089 'res_model': 'import.message',
1090 'views': [(resource_id,'form')],
1091 'type': 'ir.actions.act_window',