~uslocalizationteam/openerp-usa/US_Localization_v6

« back to all changes in this revision

Viewing changes to account_payment_cim_authdotnet/partner.py

  • Committer: npgllc
  • Date: 2012-08-30 17:51:54 UTC
  • mfrom: (76.1.1 openerp-usa)
  • Revision ID: npgllc-20120830175154-ianct01jfv012dve
Added cim module to integrate authorize CIM API with OERP

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding: utf-8 -*-
 
2
##############################################################################
 
3
#
 
4
#    OpenERP, Open Source Management Solution
 
5
#    Copyright (C) 2011 NovaPoint Group LLC (<http://www.novapointgroup.com>)
 
6
#    Copyright (C) 2004-2010 OpenERP SA (<http://www.openerp.com>)
 
7
#
 
8
#    This program is free software: you can redistribute it and/or modify
 
9
#    it under the terms of the GNU General Public License as published by
 
10
#    the Free Software Foundation, either version 3 of the License, or
 
11
#    (at your option) any later version.
 
12
#
 
13
#    This program is distributed in the hope that it will be useful,
 
14
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
 
15
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
16
#    GNU General Public License for more details.
 
17
#
 
18
#    You should have received a copy of the GNU General Public License
 
19
#    along with this program.  If not, see <http://www.gnu.org/licenses/>
 
20
#
 
21
##############################################################################
 
22
from osv import osv, fields
 
23
import httplib
 
24
from xml.dom.minidom import Document
 
25
import xml2dic
 
26
from tools.translate import _
 
27
 
 
28
class res_partner(osv.osv):
 
29
    _inherit = 'res.partner'
 
30
    _rec_name = 'payment_profile_id'
 
31
    _columns = {
 
32
        'payment_profile_id': fields.many2one('cust.profile', 'Payment Profiles', help='Store customers payment profile id', readonly='True'),
 
33
#        'payment_profile_ids':fields.one2many('cust.payment.profile', 'partner_id','Payment Profiles' ,help='Store customers payment profile id',readonly=True),
 
34
        'payment_profile_ids': fields.related('payment_profile_id', 'payment_profile_ids', type='one2many', relation='cust.payment.profile', string='Payment Profiles', readonly=True),
 
35
    }
 
36
 
 
37
    def request_to_server(self, Request_string, url, url_path):
 
38
            ''' Sends a POST request to url and returns the response from the server'''
 
39
            conn = httplib.HTTPSConnection(url)
 
40
            conn.putrequest('POST', url_path)
 
41
            conn.putheader('content-type', 'text/xml')
 
42
            print "Request_string",Request_string
 
43
            print "IRRR",url, url_path
 
44
            conn.putheader('content-length', len(Request_string))
 
45
            conn.endheaders()
 
46
            conn.send(Request_string)
 
47
            response = conn.getresponse()
 
48
            create_CustomerProfile_response_xml = response.read()
 
49
            return create_CustomerProfile_response_xml
 
50
 
 
51
    def search_dic(self, dic, key):
 
52
        ''' Returns the parent dictionary containing key None on Faliure'''
 
53
        if key in dic.keys():
 
54
            return dic
 
55
        for k in dic.keys():
 
56
            if type(dic[k]) == type([]):
 
57
                for i in dic[k]:
 
58
                    if type(i) == type({}):
 
59
                        ret = self.search_dic(i, key)
 
60
                        if ret and key in ret.keys():
 
61
                           return ret
 
62
        return None
 
63
 
 
64
    def _clean_string(self, text):
 
65
        lis = ['\t', '\n']
 
66
        if type(text) != type(''):
 
67
            text = str(text)
 
68
        for t in lis:
 
69
            text = text.replace(t, '')
 
70
        return text
 
71
 
 
72
    def _setparameter(self, dic, key, value):
 
73
        ''' Used to input parameters to corresponding dictionary'''
 
74
        if key == None or value == None :
 
75
            return
 
76
        if type(value) == type(''):
 
77
            dic[key] = value.strip()
 
78
        else:
 
79
            dic[key] = value
 
80
 
 
81
    def createCustomerProfile(self, dic):
 
82
            '''Creates  CustomerProfile and returns the CustomerProfile id on success returns None or faliure '''
 
83
 
 
84
            KEYS = dic.keys()
 
85
            doc1 = Document()
 
86
            url_path = dic.get('url_extension', False)
 
87
            url = dic.get('url', False)
 
88
            xsd = dic.get('xsd', False)
 
89
 
 
90
            createCustomerProfileRequest = doc1.createElement("createCustomerProfileRequest")
 
91
            createCustomerProfileRequest.setAttribute("xmlns", xsd)
 
92
            doc1.appendChild(createCustomerProfileRequest)
 
93
 
 
94
            merchantAuthentication = doc1.createElement("merchantAuthentication")
 
95
            createCustomerProfileRequest.appendChild(merchantAuthentication)
 
96
 
 
97
            name = doc1.createElement("name")
 
98
            merchantAuthentication.appendChild(name)
 
99
 
 
100
            transactionKey = doc1.createElement("transactionKey")
 
101
            merchantAuthentication.appendChild(transactionKey)
 
102
 
 
103
            ##Create the Request for creating the customer profile
 
104
            if 'api_login_id' in KEYS and 'transaction_key' in KEYS:
 
105
 
 
106
                ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id']))
 
107
                name.appendChild(ptext1)
 
108
 
 
109
                ptext = doc1.createTextNode(self._clean_string(dic['transaction_key']))
 
110
                transactionKey.appendChild(ptext)
 
111
 
 
112
            if 'refId' in KEYS:
 
113
                refId = doc1.createElement("refId")
 
114
                ptext1 = doc1.createTextNode(self._clean_string(dic['refId']))
 
115
                refId.appendChild(ptext1)
 
116
                createCustomerProfileRequest.appendChild(refId)
 
117
 
 
118
            ##Now Add Profile INformation for the user
 
119
            profile = doc1.createElement("profile")
 
120
            createCustomerProfileRequest.appendChild(profile)
 
121
 
 
122
            if 'merchantCustomerId' in KEYS:
 
123
                merchantCustomerId = doc1.createElement("merchantCustomerId")
 
124
                profile.appendChild(merchantCustomerId)
 
125
                ptext = doc1.createTextNode(dic['merchantCustomerId'])
 
126
                merchantCustomerId.appendChild(ptext)
 
127
 
 
128
            if 'description' in KEYS:
 
129
                description = doc1.createElement("description")
 
130
                profile.appendChild(description)
 
131
                ptext = doc1.createTextNode(dic['description'])
 
132
                description.appendChild(ptext)
 
133
 
 
134
            if 'email' in KEYS:
 
135
                email = doc1.createElement("email")
 
136
                profile.appendChild(email)
 
137
                ptext = doc1.createTextNode(dic['email'])
 
138
                email.appendChild(ptext)
 
139
 
 
140
 
 
141
            if 'paymentProfiles' in KEYS:
 
142
                paymentProfiles = doc1.createElement("paymentProfiles")
 
143
                profile.appendChild(paymentProfiles)
 
144
                ptext1 = doc1.createTextNode(self._clean_string(dic['paymentProfiles']))
 
145
                paymentProfiles.appendChild(ptext1)
 
146
 
 
147
    #############TO DO ADD THE NECCESSARY OPTIONS INTO IT
 
148
 
 
149
    #        Request_string1=xml=doc1.toprettyxml( encoding="utf-8" )
 
150
            Request_string = xml = doc1.toxml(encoding="utf-8")
 
151
 
 
152
            #Select from production and test server
 
153
            create_CustomerProfile_response_xml = self.request_to_server(Request_string, url, url_path)
 
154
            create_CustomerProfile_response_dictionary = xml2dic.main(create_CustomerProfile_response_xml)
 
155
            parent_msg = self.search_dic(create_CustomerProfile_response_dictionary, "messages")
 
156
            if parent_msg['messages'][0]['resultCode'] == 'Ok':
 
157
                parent = self.search_dic(create_CustomerProfile_response_dictionary, "customerProfileId")
 
158
                return parent['customerProfileId']
 
159
 
 
160
            return {'Error_Code':parent_msg['messages'][1]['message'][0]['code'],
 
161
                        'Error_Message' :parent_msg['messages'][1]['message'][1]['text']}
 
162
 
 
163
    def create_cust_profile(self, cr, uid, ids, address_id=False, context=None):
 
164
        ret = {}
 
165
        Param_Dic = {}
 
166
        email = ''
 
167
        merchantCustomerId = ''
 
168
        description = ''
 
169
        cust_obj = self.pool.get('res.partner')
 
170
        customers = cust_obj.browse(cr, uid, ids)
 
171
        for customer in customers:
 
172
            Trans_key = customer.company_id.auth_config_id.transaction_key or ''
 
173
            Login_id = customer.company_id.auth_config_id.login_id or ''
 
174
            url_extension = customer.company_id.auth_config_id.url_extension or ''
 
175
            xsd = customer.company_id.auth_config_id.xsd_link or ''
 
176
            description += (customer.ref or '') + (customer.name or '')
 
177
            if customer.company_id.auth_config_id.test_mode:
 
178
                url = customer.company_id.auth_config_id.url_test or ''
 
179
            else:
 
180
                url = customer.company_id.auth_config_id.url or ''
 
181
 
 
182
            if not address_id:
 
183
                address = cust_obj.address_get(cr, uid, [customer.id], ['invoice'])
 
184
                address = self.pool.get('res.partner.address').browse(cr, uid, address['invoice'])
 
185
            else:
 
186
                address = self.pool.get('res.partner.address').browse(cr, uid, address_id)
 
187
 
 
188
            email = address.email or ''
 
189
 
 
190
            if Trans_key and Login_id:
 
191
                self._setparameter(Param_Dic, 'api_login_id', Login_id)
 
192
                self._setparameter(Param_Dic, 'transaction_key', Trans_key)
 
193
 
 
194
                self._setparameter(Param_Dic, 'email', email)
 
195
                self._setparameter(Param_Dic, 'description', description)
 
196
                self._setparameter(Param_Dic, 'merchantCustomerId', merchantCustomerId)
 
197
 
 
198
                if url:
 
199
                    self._setparameter(Param_Dic, 'url', url)
 
200
                    self._setparameter(Param_Dic, 'url_extension', url_extension)
 
201
                if xsd:
 
202
                    self._setparameter(Param_Dic, 'xsd', xsd)
 
203
 
 
204
                Customer_Profile_ID = self.createCustomerProfile(Param_Dic)
 
205
                if Customer_Profile_ID and type(Customer_Profile_ID) == type(''):
 
206
                    cust_prof_id = self.pool.get('cust.profile').create(cr, uid, {'name':Customer_Profile_ID})
 
207
                    cust_obj.write(cr, uid, ids, {'payment_profile_id':cust_prof_id})
 
208
                    self._setparameter(Param_Dic, 'customerProfileId', Customer_Profile_ID)
 
209
                    return Customer_Profile_ID
 
210
                else:
 
211
                    raise osv.except_osv(_('Transaction Error in Creating Customer Profile ID'), _('Error code : ' + Customer_Profile_ID['Error_Code'] + '\nError Message :' + Customer_Profile_ID['Error_Message']))
 
212
            else:
 
213
                raise osv.except_osv(_('Transaction Error'), _('Cannot process without valid Transaction Key and/or Login ID.Please check the configuration'))
 
214
 
 
215
        return ret
 
216
 
 
217
res_partner()
 
218
# vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: