Turkesh Patel (openERP) has proposed merging 
lp:~openerp-dev/openobject-addons/trunk-addons-linkedin-jra-linkedin-mapping-tpa
 into lp:~openerp-dev/openobject-addons/trunk-addons-linkedin-jra.

Requested reviews:
  OpenERP R&D Team (openerp-dev)

For more details, see:
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-addons-linkedin-jra-linkedin-mapping-tpa/+merge/108108

                      web_linkedin

==========================================================

[IMP]: map linkedin fields with openerp
-- 
https://code.launchpad.net/~openerp-dev/openobject-addons/trunk-addons-linkedin-jra-linkedin-mapping-tpa/+merge/108108
Your team OpenERP R&D Team is requested to review the proposed merge of 
lp:~openerp-dev/openobject-addons/trunk-addons-linkedin-jra-linkedin-mapping-tpa
 into lp:~openerp-dev/openobject-addons/trunk-addons-linkedin-jra.
=== modified file 'web_linkedin/res_partner_view.xml'
--- web_linkedin/res_partner_view.xml	2012-05-11 13:30:51 +0000
+++ web_linkedin/res_partner_view.xml	2012-05-31 07:19:22 +0000
@@ -8,7 +8,7 @@
             <field name="inherit_id" ref="base.view_partner_form"/>
             <field name="arch" type="xml">
                 <field name="name" position="replace">
-                    <field name="name" nolabel="1" widget="Linkedin" />
+                    <field name="name" nolabel="1" widget="Linkedin" on_change="onchange_linkedin(name)"/>
                 </field>
                 <field name="title" position="before">
                     <field name="linkedin_id" invisible="1"/>

=== modified file 'web_linkedin/static/src/js/linkedin.js'
--- web_linkedin/static/src/js/linkedin.js	2012-05-31 06:04:48 +0000
+++ web_linkedin/static/src/js/linkedin.js	2012-05-31 07:19:22 +0000
@@ -172,9 +172,6 @@
                 }
             }
             else {
-               /* var error = "API Key is invalid or API key is not registered.API key is not configured please create from config."
-                instance.web.dialog($("<div />").text(_t(error)), { title: _t("Warning"), modal: true });
-                return false;*/
                 self.do_authorize();
             }
             e.preventDefault();
@@ -278,8 +275,27 @@
             if(!flag) mapping for people search
             mainfield : class of child_ids field
         */
-        map_values: function (linkedinrecord, flag, mainfield){
-            var self = this, tempdata = {}, temp_data = 0, id = this.view.datarecord.id;
+ map_values: function (linkedinrecord, flag, mainfield){
+            var self = this;
+            self.linkedinrecord = linkedinrecord;
+            if (!flag && linkedinrecord.name) {
+                IN.API.Raw("/people-search:(people:(id,first-name,last-name,formatted-name,picture-url,publicProfileUrl,phone-numbers,im-accounts,main-address,location,relation-to-viewer:(related-connections)))")
+                .params({
+                    "keywords": linkedinrecord.name,
+                    "count": 100
+                })
+                .result(function (child_values){
+                   self.linkedinrecord['child_values'] = child_values.people.values;
+                   self.linkedinrecord['is_company'] = true;
+                   self.set_value(self.linkedinrecord);
+                   self.view.do_onchange(self);
+                });
+            }
+            else {
+                self.set_value(self.linkedinrecord);
+                self.view.do_onchange(self);
+            }
+            /*var self = this, tempdata = {}, temp_data = 0, id = this.view.datarecord.id;
             _(this.view.fields).each(function (field, f) {
                 if (f=='name') {
                     if (!flag) {
@@ -312,7 +328,8 @@
                     }else if (linkedinrecord.twitterId) {
                         (flag == 1) ? tempdata[f] = linkedinrecord.twitterId : field.set_value(linkedinrecord.twitterId);
                     } else {
-                        (flag == 1) ? tempdata[f] = false : field.set_value(false);
+                        field.set_value(false);
+                        tempdata[f] = false;
                     }
                 }
                 else if (f=='mobile') {
@@ -345,12 +362,12 @@
                 else if (f=='photo') {
                     if (!flag) {
                         if (linkedinrecord.pictureUrl && linkedinrecord['pictureUrl']) {
-                            /* Fetch binary data from URL for People */
+
                             self.rpc('/web_linkedin/binary/url2binary',{'url':linkedinrecord['pictureUrl']},function(data){
                                 field.set_value(data);
                             });
                         } else if (linkedinrecord.logoUrl && linkedinrecord['logoUrl']) {
-                            /* Fetch binary data from URL for Company */
+
                             self.rpc('/web_linkedin/binary/url2binary',{'url':linkedinrecord['logoUrl']},function(data){
                                 field.set_value(data);
                             });
@@ -361,7 +378,7 @@
                     else{
                         if (linkedinrecord['pictureUrl']) {
                             temp_data = 1;
-                            /* Fetch binary data from URL for contact of Company */
+
                             self.rpc('/web_linkedin/binary/url2binary',{'url':linkedinrecord['pictureUrl']}).done(function(res){
                                 tempdata[f] = res;
                                 self.set_o2mdata(tempdata,mainfield)
@@ -484,9 +501,9 @@
                     (flag == 1) ? tempdata[f] = true : field.set_value(false);
                 }
                 else if (f=='child_ids') {
-                    /* For Company Set value of child_ids field */
+
                     if (!flag && linkedinrecord.name) {
-                        /* Fetch contact of Company */
+
                         IN.API.Raw("/people-search:(people:(id,first-name,last-name,formatted-name,picture-url,publicProfileUrl,phone-numbers,im-accounts,main-address,location,relation-to-viewer:(related-connections)))")
                         //"id", "firstName", "lastName", "pictureUrl", "publicProfileUrl", "formatted-name", "headline", "location", "industry", "languages", "phone-numbers", "im-accounts", "main-address"
                         .params({
@@ -512,7 +529,8 @@
                             });
                             field.dataset.ids = self.totalids;
                             if (linkedinrecord.locations && linkedinrecord.locations._total >= 1) {
-                                var counter = 0; /* Indicates All searched records are Invalid or valid */
+                                field.dataset.to_create = [];
+                                var counter = 0;
                                 for (i in getresult.people.values) {
                                     var connectTemp = self.validName(getresult.people.values[i].firstName, getresult.people.values[i].lastName)
                                     if (connectTemp) {
@@ -526,7 +544,7 @@
                                 }else if (getresult.people._total) {
                                     var total_Count = getresult.people._total;
                                 }
-                                /* If counter == total no. of people then all searched records are invalid */
+
                                 if (counter == total_Count) {
                                     field.dataset.to_create = [];
                                     field.dataset.ids = [];
@@ -542,12 +560,12 @@
                             }
                         });
                     }
-                    /* For People Set value of child_ids field */
+
                     else if (!flag && linkedinrecord.formattedName) {
                         field.set_value(false);
                         field.set({'invisible':true});
                     }
-                    /* For Contact of company Set value of child_ids field */
+
                     else {
                         tempdata[f] = false;
                     }
@@ -578,7 +596,8 @@
             }
             if (flag && temp_data == 0) {
                 self.set_o2mdata(tempdata, mainfield);
-            }
+                self.set_childids( self.updteids );
+            }*/
          },
          /* Update existing value of child_ids field */
          set_childids: function( ids ) {

=== modified file 'web_linkedin/web_linkedin.py'
--- web_linkedin/web_linkedin.py	2012-05-31 06:04:48 +0000
+++ web_linkedin/web_linkedin.py	2012-05-31 07:19:22 +0000
@@ -19,7 +19,7 @@
 #
 ##############################################################################
 import base64
-import urllib2
+import urllib
 import xmlrpclib
 import zlib
 
@@ -37,40 +37,173 @@
 company()
 
 class res_partner(osv.osv):
-     _inherit = 'res.partner'
-
-     _columns = {
-        'linkedin_id': fields.char('Linkedin Id', size=64),
-        'twitter_id': fields.char('Twitter', size=128),
-        'profile_id': fields.char('Profile URL', size=240),
-     }
-
-     _sql_constraints = [
-         ('linkedin_id_uniq', 'unique (linkedin_id)', 'This Record from Linkedin is already exist!')
-     ]
-
-     def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
-         company_obj = self.pool.get('res.company')
-         res = super(res_partner, self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
-         company_id = company_obj._company_default_get(cr, user, 'res.users', context=context)
-         linkedin_api_key = company_obj.browse(cr, user, company_id, context=context).linkedin_api_key
-         fields = res['fields']
-         if fields.get('name'):
-             ctx = fields.get('name').get('context')
-             if ctx is None:
-                 ctx = {}
-             ctx.update({'api_key': linkedin_api_key})
-             fields.get('name')['context'] = ctx
-         return res
+    _inherit = 'res.partner'
+
+    _columns = {
+       'linkedin_id': fields.char('Linkedin Id', size=64),
+       'twitter_id': fields.char('Twitter', size=128),
+       'profile_id': fields.char('Profile URL', size=240),
+    }
+
+    _sql_constraints = [
+    ('linkedin_id_uniq', 'unique (linkedin_id)', 'This Record from Linkedin is exist!')
+    ]
+
+    def fields_view_get(self, cr, user, view_id=None, view_type='form', context=None, toolbar=False, submenu=False):
+        company_obj = self.pool.get('res.company')
+        res = super(res_partner, self).fields_view_get(cr, user, view_id, view_type, context, toolbar=toolbar, submenu=submenu)
+        company_id = company_obj._company_default_get(cr, user, 'res.users', context=context)
+        linkedin_api_key = company_obj.browse(cr, user, company_id, context=context).linkedin_api_key
+        fields = res['fields']
+        if fields.get('name'):
+            ctx = fields.get('name').get('context')
+            if ctx is None:
+                ctx = {}
+            ctx.update({'api_key': linkedin_api_key})
+            fields.get('name')['context'] = ctx
+        return res
+
+    def onchange_linkedin(self, cr, uid, ids, linkedin_data):
+        contact_values = {}
+        warning = {}
+        contact_keys = list(set(self.map_fields.values()))
+        for key in contact_keys:
+            if key == 'mail':
+                contact_values.update({key:None})
+            if key == 'name' or key == 'photo':
+                continue
+            contact_values.update({key:False})
+        for contact in self.browse(cr, uid, ids):
+            if contact.linkedin_id:
+                warning = 'already imported from linkedin'
+        if(type(linkedin_data) == dict):
+            contact_values = self.convert(cr, uid, linkedin_data)
+        return {'value': contact_values, 'warning': warning}
+
+    map_fields = {
+        #linkedin_field, value: openerp_field
+        'name': 'name',
+        'is_company': 'is_company',
+        'formattedName': 'name',
+        'id': 'linkedin_id',
+        #'twitterId': 'twitter_id',
+        #'twitterAccounts': 'twitter_id',
+        'publicProfileUrl': 'profile_id',
+        'phoneNumbers': 'phone',
+        'phone1': 'phone',
+        'phone2': 'mobile',
+        'pictureUrl': 'photo',
+        'logoUrl': 'photo',
+        'mainAddress': 'street',
+        'street1': 'street',
+        'street2' : 'street2',
+        'city': 'city',
+        'postalCode': 'zip',
+        'code': 'country_id',
+        'websiteUrl': 'website',
+        'fax': 'fax',
+        'isHeadquarters': 'use_parent_address',
+        'isActive': 'active',
+        'state': 'state_id',
+        'isCompany': 'is_company',
+    }
+
+    def _convert_data(self, cr, uid, data):
+        value = {}
+        for field_name, field_value in data.items():
+            if field_name == 'formattedName' and data.get('location').get('name'):
+                data.get('location').pop('name')
+            if field_name == 'state':
+                state_id = self.pool.get('res.country.state').search(cr, uid, [('name','=',field_value) or ('code','=',field_value.upper())])
+                if country_id:
+                    value['state_id'] = state_id[0]
+                continue
+            openerp_field_name = self.map_fields.get(field_name)
+            value[openerp_field_name] = field_value
+
+        return value
+
+    def _convert_location(self, cr, uid, location):
+        value = {}
+        address = location.get("address") or {}
+        country = location.get("country") or {}
+        contact_info = location.get("contactInfo") or {}
+        value.update(self._convert_data(cr, uid, contact_info))
+        value.update(self._convert_data(cr, uid, address))
+
+        country_code = country.get('code') or location.get('countryCode')
+        if country_code:
+            country_id = self.pool.get('res.country').search(cr, uid, [('code','=',country_code.upper())])
+            if country_id:
+                value['country_id'] = country_id[0]
+
+        value.update(self._convert_data(cr, uid, location))
+
+        return value
+
+    def child_data(self, cr, uid, child_data, linkedin_data):
+        value = {}
+        value['use_parent_address'] = True
+        value['active'] = True
+        value['type'] = 'default'
+        if child_data.get('pictureUrl'):
+            value['photo'] = base64.encodestring(urllib.urlopen(child_data.get('pictureUrl')).read())
+        value['customer'] = True
+        value['name'] = child_data.get('formattedName')
+        if linkedin_data.get('locations'):
+            for location in linkedin_data.get('locations').get('values',{}):
+                value.update(self._convert_location(cr, uid, location))
+        return value
+
+    def convert(self, cr, uid, linkedin_data):
+        '''
+        json_object contains contact details of linkedin profile in json format
+        '''
+        value = {}
+        # set warning message if already imported details from linkedin after checking linkedin_id
+        for linkedin_field_name, linkedin_field_value in linkedin_data.items():
+
+            if linkedin_field_name == 'formattedName' and linkedin_data.get('location').get('name'):
+                linkedin_data.get('location').pop('name')
+
+            if linkedin_field_name == 'location':
+                value.update(self._convert_location(cr, uid, linkedin_data.get('location')))
+                continue
+
+            if linkedin_field_name == 'locations':
+                for location in linkedin_field_value.get('values',{}):
+                    value.update(self._convert_location(cr, uid, location))
+                continue
+
+            if linkedin_field_name == 'child_values':
+                child_values = []
+                for child in linkedin_field_value:
+                    child_values.append(self.child_data(cr, uid, child, linkedin_data))
+                if child_values:
+                    value["child_ids"] = child_values
+                continue
+
+            if linkedin_field_name not in self.map_fields:
+                continue
+
+            #if first name found, name = first name + last name
+            if linkedin_field_name == 'firstName' and not linkedin_data.get("name"):
+                linkedin_field_value = linkedin_data.get("firstName")+' '+ linkedin_data.get("lastName")
+                value['name'] = linkedin_field_value
+                continue
+
+            openerp_field_name = self.map_fields.get(linkedin_field_name)
+
+            if linkedin_field_name == 'phoneNumbers':
+                linkedin_field_value = linkedin_field_value.get("values",{}) and linkedin_field_value.get("values")[0].get("phoneNumbers") or False
+
+            if openerp_field_name == 'photo': # photo url
+                linkedin_field_value = base64.encodestring(urllib.urlopen(linkedin_field_value).read())
+
+
+            value[openerp_field_name] = linkedin_field_value
+        return value
 
 res_partner()
 
-class Binary(openerpweb.Controller):
-    _cp_path = "/web_linkedin/binary"
-
-    @openerpweb.jsonrequest
-    def url2binary(self, req,url):
-        bfile = urllib2.urlopen(url)
-        return base64.b64encode(bfile.read())
-
 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4:

_______________________________________________
Mailing list: https://launchpad.net/~openerp-dev-gtk
Post to     : [email protected]
Unsubscribe : https://launchpad.net/~openerp-dev-gtk
More help   : https://help.launchpad.net/ListHelp

Reply via email to