def getCustomerPaymentProfileRequest(self, dic): profile_dictionary = dic KEYS = dic.keys() Payment_Profile_Details = {} doc1 = Document() url_path = dic.get('url_extension') url = dic.get('url') xsd = dic.get('xsd') getCustomerPaymentProfileRequest = doc1.createElement("getCustomerPaymentProfileRequest") getCustomerPaymentProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(getCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") getCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) customerProfileId = doc1.createElement("customerProfileId") getCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['customerProfileId']))) customerProfileId.appendChild(ptext) customerPaymentProfileId = doc1.createElement("customerPaymentProfileId") getCustomerPaymentProfileRequest.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['customerPaymentProfileId']))) customerPaymentProfileId.appendChild(ptext) Request_string = xml = doc1.toxml(encoding="utf-8") get_transaction_response_xml = self.request_to_server(Request_string, url, url_path) get_PaymentProfile_response_dictionary = xml2dic.main(get_transaction_response_xml) parent_card_number = self.search_dic(get_PaymentProfile_response_dictionary, 'cardNumber') parent_exp_date = self.search_dic(get_PaymentProfile_response_dictionary, 'expirationDate') if parent_card_number.get('cardNumber'): Payment_Profile_Details['cc_number'] = parent_card_number['cardNumber'] if parent_exp_date.get('expirationDate'): Payment_Profile_Details['cc_ed_year'] = parent_exp_date['expirationDate'] if parent_exp_date.get('cardCode'): Payment_Profile_Details['cardCode'] = parent_exp_date['cardCode'] return Payment_Profile_Details
def deleteCustomerPaymentProfile(self, dic): KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) deleteCustomerPaymentProfileRequest = doc1.createElement("deleteCustomerPaymentProfileRequest") deleteCustomerPaymentProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(deleteCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") deleteCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") deleteCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(dic['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerPaymentProfileId = doc1.createElement("customerPaymentProfileId") deleteCustomerPaymentProfileRequest.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode(self._clean_string(dic['customerPaymentProfileId'])) customerPaymentProfileId.appendChild(ptext) Request_string = doc1.toxml(encoding="utf-8") delete_CustomerPaymentProfile_response_xml = self.request_to_server(Request_string, url, url_path) delete_CustomerPaymentProfile_response_dictionary = xml2dic.main(delete_CustomerPaymentProfile_response_xml) parent_resultCode = self.search_dic(delete_CustomerPaymentProfile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': return True ret = {} Error_Code_dic = self.search_dic(delete_CustomerPaymentProfile_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(delete_CustomerPaymentProfile_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return
def getCustomerPaymentProfileRequest(self, dic): profile_dictionary = dic KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension') url = dic.get('url') xsd = dic.get('xsd') getCustomerPaymentProfileRequest = doc1.createElement("getCustomerPaymentProfileRequest") getCustomerPaymentProfileRequest.setAttribute("xmlns", "AnetApi/xml/v1/schema/AnetApiSchema.xsd") doc1.appendChild(getCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") getCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") getCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerPaymentProfileId = doc1.createElement("customerPaymentProfileId") getCustomerPaymentProfileRequest.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerPaymentProfileId'])) customerPaymentProfileId.appendChild(ptext) Request_string = xml = doc1.toxml(encoding="utf-8") get_profile_response_xml = self.request_to_server(Request_string, url, url_path) get_profile_response_dictionary = xml2dic.main(get_profile_response_xml) parent_resultCode = self.search_dic(get_profile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_directResponse = self.search_dic(get_profile_response_dictionary, 'cardNumber') cardNumber = parent_directResponse['cardNumber'] return cardNumber
def address_validation(self, cr, uid, address_id, context={}): """ This function is called from the wizard.Performs the actual computing in address validation """ status = "True" error_msg = "" ups_ids = self.pool.get('ups.account').search( cr, uid, [('ups_active', "=", True)]) if ups_ids and address_id: ups_account = self.pool.get('ups.account').browse(cr, uid, ups_ids[0], context=context) if type(address_id) is list or type(address_id) is tuple: address_id = address_id[0] address = self.pool.get('res.partner').browse(cr, uid, address_id, context=context) data_for_Access_Request = { 'AccessLicenseNumber': ups_account.accesslicensenumber, 'UserId': ups_account.userid, 'Password': ups_account.password } data_for_Address_Validation_Request = { 'Request': { 'Transaction Reference': { 'CustomerContext': "", 'XpciVersion': "1.0001", 'ToolVersion': "", }, 'RequestAction': "XAV", 'RequestOption': "3", }, 'RegionalRequestIndicator': "", 'MaximumListSize': str(ups_account.max_lim_size), 'AddressKeyFormat': { 'ConsigneeName': address.name or "", 'BuildingName': "", 'AddressLine1': str(address.street or ""), 'AddressLine2': str(address.street2 or ""), 'Region': "", 'PoliticalDivision2': str(address.city or ""), 'PoliticalDivision1': str(address.state_id and address.state_id.code), 'PostcodePrimaryLow': str(address.zip or ""), 'PostcodeExtendedLow': "", 'Urbanization': "", 'CountryCode': "US" } } Request_string = self._create_Address_Validation_Request_xml( cr, uid, data_for_Address_Validation_Request, data_for_Access_Request) response_string = self._create_https_connecetion( cr, uid, ups_account.url, Request_string) if response_string == 'Connection failed': addr_status = False error_msg = 'Connection to server failed' ret_list = [] else: response_dic = xml2dic.main(response_string) response = response_dic['AddressValidationResponse'][0][ 'Response'] ret_list = [] street1 = "" street2 = "" city = "" state = "" zip = "" country_code = "" status_description = '' for i in range(3, 16): if len( response_dic['AddressValidationResponse'] ) > i and response_dic['AddressValidationResponse'][i]: classification = str( response_dic['AddressValidationResponse'][i] ['AddressKeyFormat'][0]['AddressClassification'][0] ['Code']) j = 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].get('AddressLine'): street1 = response_dic[ 'AddressValidationResponse'][i][ 'AddressKeyFormat'][j]['AddressLine'] j += 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].has_key('AddressLine'): street2 = response_dic[ 'AddressValidationResponse'][i][ 'AddressKeyFormat'][j]['AddressLine'] j += 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].has_key('Region'): street2 = response_dic[ 'AddressValidationResponse'][i][ 'AddressKeyFormat'][j]['Region'] j += 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].has_key( 'PoliticalDivision2'): city = response_dic['AddressValidationResponse'][ i]['AddressKeyFormat'][j]['PoliticalDivision2'] j += 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].has_key( 'PoliticalDivision1'): state = response_dic['AddressValidationResponse'][ i]['AddressKeyFormat'][j]['PoliticalDivision1'] j += 1 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].get( 'PostcodePrimaryLow'): zip = response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j]['PostcodePrimaryLow'] j += 2 if response_dic['AddressValidationResponse'][i][ 'AddressKeyFormat'][j].get('CountryCode'): country_code = response_dic[ 'AddressValidationResponse'][i][ 'AddressKeyFormat'][j]['CountryCode'] addr_dict = { 'street1': street1, 'city': city, 'state': state, 'zip': zip, 'classification': classification } if addr_dict not in ret_list and (addr_dict['street1'] or addr_dict['city'] or addr_dict['state'] or addr_dict['zip']): ret_list.append(addr_dict) response_status = response_dic['AddressValidationResponse'][0][ 'Response'][1]['ResponseStatusCode'] if response_status == '1': if ret_list: if (len(ret_list) == 1) and (ret_list[0].get( 'street1', '').upper() == str( address.street).upper()): error_msg = "Success:The address is valid" else: error_msg = "Please review the suggested address." addr_status = True else: error_msg = "Success:No match found" addr_status = False elif response_status == '0': addr_status = False error_msg = response_dic['AddressValidationResponse'][0][ 'Response'][3]['Error'][2]['ErrorDescription'] if response_dic['AddressValidationResponse'][0]['Response'][1][ 'ResponseStatusCode'] == '0': error_msg = 'Error : ' + error_msg vals = { 'addr_status': addr_status, 'error_msg': error_msg, 'address_list': ret_list } return vals else: raise osv.except_osv(_('Warning !'), _('Address validation is not set up.')) return []
def process_void(self): ids=self._ids if type(ids) == list: ids = list(ids) do = self.browse(ids)[0] if do.ship_company_code != 'usps': return super(stock_picking, self).process_void() if not (do.logis_company and do.logis_company.ship_company_code == 'usps'): return super(stock_picking, self).process_void() userid = do.logis_company.usps_userid url = do.logis_company.test_mode and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_prd = do.logis_company.usps_url url_prd_secure = do.logis_company.usps_url_secure test = do.logis_company.test_mode error = False str_error = '' for pack in do.packages_ids: if pack.tracking_no: url = test and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_sec = test and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure if test: request_xml = """<CarrierPickupCancelRequest USERID="%(user_id)s"> <FirmName>ABC Corp.</FirmName> <SuiteOrApt>Suite 777</SuiteOrApt> <Address2>1390 Market Street</Address2> <Urbanization></Urbanization> <City>Houston</City> <State>TX</State> <ZIP5>77058</ZIP5> <ZIP4>1234</ZIP4> <ConfirmationNumber>WTC123456789</ConfirmationNumber> </CarrierPickupCancelRequest> """ % {'user_id': do.logis_company.usps_userid} else: request_xml = """<CarrierPickupCancelRequest USERID="%(user_id)"> <FirmName>ABC Corp.</FirmName> <SuiteOrApt>Suite 777</SuiteOrApt> <Address2>1390 Market Street</Address2> <Urbanization></Urbanization> <City>Houston</City> <State>TX</State> <ZIP5>77058</ZIP5> <ZIP4>1234</ZIP4> <ConfirmationNumber>%(confirmation_number)</ConfirmationNumber> </CarrierPickupCancelRequest> """ % { 'user_id': do.logis_company.usps_userid, 'confirmation_number' : pack.tracking_no, } if url and request_xml: request_url = url + '?API=CarrierPickupCancel&XML=' + request_xml try : import urllib f = urllib.urlopen(request_url) from xml.dom.minidom import parse, parseString import xml2dic str_response = f.read() except Exception: self.env['stock.packages'].write({'ship_message': str(Exception)}) xml_response = parseString(str_response) xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): self.env['stock.packages'].write({'ship_message': str_error}) break else: self.env['stock.packages'].write({ 'negotiated_rates' : 0.00, 'shipment_identific_no' :'', 'tracking_no': '', 'tracking_url': '', 'logo' : '', 'ship_message' : 'Shipment Cancelled'}) if not error: self.write({'ship_state' :'draft', 'ship_message' : 'Shipment has been cancelled.'}) else : self.write({ 'ship_message' : 'Cancellation of some of shipment has failed, please check the status of pakages.'}) return True
def process_ship_accept(self, cr, uid, ids, ret_res, context=None): quick_ship_id = self.browse(cr, uid, ids[0], context=context) ship_digest=ret_res.get('ship_digest') data_for_Access_Request = { 'AccessLicenseNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.access_license or '', 'UserId': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.userid or '', 'Password': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.password or '' } data_for_Ship_Accept = { 'ShipmentAcceptRequest': { 'Request': { 'RequestAction': 'ShipAccept', 'TransactionReference': {'CustomerContext': ''} }, 'ShipmentDigest': ship_digest } } doc1 = Document() AccessRequest = doc1.createElement("AccessRequest") AccessRequest.setAttribute("xml:lang", "en-US") doc1.appendChild(AccessRequest) AccessLicenseNumber = doc1.createElement("AccessLicenseNumber") ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"]) AccessLicenseNumber.appendChild(ptext) AccessRequest.appendChild(AccessLicenseNumber) UserId = doc1.createElement("UserId") ptext = doc1.createTextNode(data_for_Access_Request["UserId"]) UserId.appendChild(ptext) AccessRequest.appendChild(UserId) Password = doc1.createElement("Password") ptext = doc1.createTextNode(data_for_Access_Request["Password"]) Password.appendChild(ptext) AccessRequest.appendChild(Password) Request_string1 = doc1.toprettyxml() doc2 = Document() ShipmentAcceptRequest = doc2.createElement("ShipmentAcceptRequest") ShipmentAcceptRequest.setAttribute("xml:lang", "en-US") doc2.appendChild(ShipmentAcceptRequest) Request = doc2.createElement("Request") ShipmentAcceptRequest.appendChild(Request) RequestAction = doc2.createElement("RequestAction") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['RequestAction']) RequestAction.appendChild(ptext) Request.appendChild(RequestAction) TransactionReference = doc2.createElement("TransactionReference") Request.appendChild(TransactionReference) CustomerContext = doc2.createElement("CustomerContext") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['TransactionReference']['CustomerContext']) CustomerContext.appendChild(ptext) TransactionReference.appendChild(CustomerContext) ShipmentDigest = doc2.createElement("ShipmentDigest") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["ShipmentDigest"]) ShipmentDigest.appendChild(ptext) ShipmentAcceptRequest.appendChild(ShipmentDigest) Request_string2 = doc2.toprettyxml() serv = '' acce_port = '' serv_path = '' if quick_ship_id.logis_company.id: if quick_ship_id.logis_company.test_mode: acce_web = quick_ship_id.logis_company.ship_accpt_test_web or '' acce_port = quick_ship_id.logis_company.ship_accpt_test_port else: acce_web = quick_ship_id.logis_company.ship_accpt_web or '' acce_port = quick_ship_id.logis_company.ship_accpt_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv(_('Unable to find Shipping URL!'), _("Please configure the shipping company with websites.") ) else: raise osv.except_osv(_('No Company Selected!'), _("Please select a logistic company.") ) Request_string = Request_string1 + Request_string2 conn = httplib.HTTPSConnection(serv, acce_port) res = conn.request("POST", serv_path, Request_string) res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) NegotiatedRates = '' ShipmentIdentificationNumber = '' TrackingNumber = '' if len(response_dic['ShipmentAcceptResponse']) > 1 and 'ShipmentResults' in response_dic['ShipmentAcceptResponse'][1]: if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults']) > 1 and \ 'NegotiatedRates' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'] and \ 'NetSummaryCharges' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'] and \ 'GrandTotal' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0]: NegotiatedRates = response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0]\ ['GrandTotal'][1]['MonetaryValue'] if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'] and \ 'ShipmentIdentificationNumber' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3]: ShipmentIdentificationNumber = response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3]['ShipmentIdentificationNumber'] label_image = None if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults']) > 4 and \ 'PackageResults' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults']: TrackingNumber=response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][0]['TrackingNumber'] if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults']) > 2 and \ 'LabelImage' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2]: label_image =response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2]['LabelImage'][1]['GraphicImage'] if label_image: im_in_raw = base64.decodestring(label_image) path = tempfile.mktemp() temp = file(path, 'wb') temp.write(im_in_raw) temp.close() new_im = Image.open(path) new_im = new_im.rotate(270) new_im.save(path, 'JPEG') label_from_file = open(path, 'rb') label_image = base64.encodestring(label_from_file.read()) label_from_file.close() self.write(cr, uid, ids, {'shipcharge': NegotiatedRates or '0', 'logo': label_image}) if ret_res.get('ship_move_id'): self.write(cr,uid,ids,{'shipcharge': NegotiatedRates or '0', 'ship_log_id': ret_res.get('ship_move_id')}) tracking_url = '' if TrackingNumber: tracking_url = quick_ship_id.logis_company.ship_tracking_url if tracking_url: try: tracking_url = tracking_url%TrackingNumber except Exception, e: tracking_url = "Invalid tracking url on shipping company" ship_move_id = self.pool.get('shipping.move').write(cr, uid, [ret_res.get('ship_move_id')], { 'logo': label_image, 'shipment_identific_no': ShipmentIdentificationNumber, 'tracking_no': TrackingNumber, 'tracking_url': tracking_url })
def createCustomerProfileTransactionRequest(self, dic): ''' Creates the xml for TransactionRequest and returns the transaction id ''' profile_dictionary = dic KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) trans_type_list = ['AuthOnly', 'AuthCapture', 'CaptureOnly', 'PriorAuthCapture', 'Refund', ] createCustomerProfileTransactionRequest = doc1.createElement("createCustomerProfileTransactionRequest") createCustomerProfileTransactionRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerProfileTransactionRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerProfileTransactionRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) transaction = doc1.createElement("transaction") createCustomerProfileTransactionRequest.appendChild(transaction) if 'trans_type' in KEYS : if profile_dictionary.get('trans_type') in trans_type_list: transaction_type_tagname = 'profileTrans' + profile_dictionary.get('trans_type') transaction_type = doc1.createElement(transaction_type_tagname) transaction.appendChild(transaction_type) if 'amount' in KEYS : amount = doc1.createElement('amount') transaction_type.appendChild(amount) ptext = doc1.createTextNode(self._clean_string(dic.get('amount'))) amount.appendChild(ptext) if 'tax_amount' in KEYS : tax = doc1.createElement('tax') transaction_type.appendChild(tax) tax_amount = doc1.createElement('amount') tax.appendChild(tax_amount) ptext = doc1.createTextNode(self._clean_string(dic.get('tax_amount'))) tax_amount.appendChild(ptext) tax_name = doc1.createElement('name') tax.appendChild(tax_name) ptext = doc1.createTextNode(self._clean_string(dic.get('tax_name'))) tax_name.appendChild(ptext) tax_description = doc1.createElement('description') tax.appendChild(tax_description) ptext = doc1.createTextNode(self._clean_string(dic.get('tax_description'))) tax_description.appendChild(ptext) if 'shipping_amount' in KEYS : shipping = doc1.createElement('shipping') transaction_type.appendChild(shipping) shipping_amount = doc1.createElement('amount') tax.appendChild(shipping_amount) ptext = doc1.createTextNode(self._clean_string(dic.get('shipping_amount'))) shipping_amount.appendChild(ptext) shipping_name = doc1.createElement('name') tax.appendChild(shipping_name) ptext = doc1.createTextNode(self._clean_string(dic.get('shipping_name'))) shipping_name.appendChild(ptext) shipping_description = doc1.createElement('description') tax.appendChild(shipping_description) ptext = doc1.createTextNode(self._clean_string(dic.get('shipping_description'))) shipping_description.appendChild(ptext) if 'duty_amount' in KEYS : duty = doc1.createElement('duty') transaction_type.appendChild(duty) duty_amount = doc1.createElement('amount') tax.appendChild(duty_amount) ptext = doc1.createTextNode(self._clean_string(dic.get('duty_amount'))) duty_amount.appendChild(ptext) duty_name = doc1.createElement('name') tax.appendChild(duty_name) ptext = doc1.createTextNode(self._clean_string(dic.get('duty_name'))) duty_name.appendChild(ptext) duty_description = doc1.createElement('description') tax.appendChild(duty_description) ptext = doc1.createTextNode(self._clean_string(dic.get('duty_description'))) duty_description.appendChild(ptext) if 'items'in KEYS and len(profile_dictionary['items']) > 0: for i in range(0, len(profile_dictionary['items'])): lineItems = doc1.createElement('lineItems') transaction_type.appendChild(lineItems) if 'itemId' in profile_dictionary['items'][i].keys(): itemId = doc1.createElement('itemId') lineItems.appendChild(itemId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['itemId'])) itemId.appendChild(ptext) if 'name' in profile_dictionary['items'][i].keys(): name = doc1.createElement('name') lineItems.appendChild(name) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['name'])) name.appendChild(ptext) if 'description' in profile_dictionary['items'][i].keys(): description = doc1.createElement('description') lineItems.appendChild(description) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['description'])) description.appendChild(ptext) if 'quantity' in profile_dictionary['items'][i].keys(): quantity = doc1.createElement('quantity') lineItems.appendChild(quantity) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['quantity'])) quantity.appendChild(ptext) if 'unitPrice' in profile_dictionary['items'][i].keys(): unitPrice = doc1.createElement('unitPrice') lineItems.appendChild(unitPrice) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['unitPrice'])) unitPrice.appendChild(ptext) if 'taxable' in profile_dictionary['items'][i].keys(): taxable = doc1.createElement('taxable') lineItems.appendChild(taxable) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['taxable'])) taxable.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement('customerProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerProfileId = doc1.createElement('customerPaymentProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerPaymentProfileId'])) customerProfileId.appendChild(ptext) if 'customerShippingAddressId' in KEYS: customerShippingAddressId = doc1.createElement('customerShippingAddressId') transaction_type.appendChild(customerShippingAddressId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerShippingAddressId'])) customerShippingAddressId.appendChild(ptext) if transaction_type_tagname == 'profileTransCaptureOnly': approvalCode = doc1.createElement('approvalCode') transaction_type.appendChild(approvalCode) ptext = doc1.createTextNode('000000') approvalCode.appendChild(ptext) if transaction_type_tagname == 'profileTransPriorAuthCapture' or transaction_type_tagname == 'profileTransRefund' : transId = doc1.createElement('transId') transaction_type.appendChild(transId) if 'transId' in KEYS: ptext = doc1.createTextNode(self._clean_string(profile_dictionary['transId'])) transId.appendChild(ptext) if transaction_type_tagname == 'profileTransRefund': if 'creditCardNumberMasked' in KEYS: creditCardNumberMasked = doc1.createElement('creditCardNumberMasked') transaction_type.appendChild(creditCardNumberMasked) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['creditCardNumberMasked'])) creditCardNumberMasked.appendChild(ptext) elif profile_dictionary.get('trans_type') == 'Void': transaction_type_tagname = 'profileTrans' + profile_dictionary.get('trans_type') transaction_type = doc1.createElement(transaction_type_tagname) transaction.appendChild(transaction_type) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement('customerProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerProfileId = doc1.createElement('customerPaymentProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerPaymentProfileId'])) customerProfileId.appendChild(ptext) if 'customerShippingAddressId' in KEYS: customerShippingAddressId = doc1.createElement('customerShippingAddressId') transaction_type.appendChild(customerShippingAddressId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerShippingAddressId'])) customerShippingAddressId.appendChild(ptext) if 'transId' in KEYS: transId = doc1.createElement('transId') transaction_type.appendChild(transId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['transId'])) transId.appendChild(ptext) if 'extraOptions' in KEYS: extraOptions = doc1.createElement("extraOptions") createCustomerProfileTransactionRequest.appendChild(extraOptions) Request_string = xml = doc1.toxml(encoding="utf-8") create_transaction_response_xml = self.request_to_server(Request_string, url, url_path) create_transaction_response_dictionary = xml2dic.main(create_transaction_response_xml) parent_resultCode = self.search_dic(create_transaction_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_directResponse = self.search_dic(create_transaction_response_dictionary, 'directResponse') li = parent_directResponse['directResponse'].split(',') li[6]##Transaction ID li[4]##Authorization code return li[6] ret = {} Error_Code_dic = self.search_dic(create_transaction_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(create_transaction_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret
def updateCustomerPaymentProfile(self, dic): KEYS = dic.keys() doc1 = Document() url_path = dic['url_extension'] url = dic['url'] xsd = dic['xsd'] updateCustomerPaymentProfileResponse = doc1.createElement( "updateCustomerPaymentProfileRequest") updateCustomerPaymentProfileResponse.setAttribute("xmlns", xsd) doc1.appendChild(updateCustomerPaymentProfileResponse) merchantAuthentication = doc1.createElement("merchantAuthentication") updateCustomerPaymentProfileResponse.appendChild( merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode( self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode( self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") updateCustomerPaymentProfileResponse.appendChild(customerProfileId) ptext = doc1.createTextNode( self._clean_string(dic['customerProfileId'])) customerProfileId.appendChild(ptext) paymentProfile = doc1.createElement("paymentProfile") updateCustomerPaymentProfileResponse.appendChild(paymentProfile) if 'customerType' in KEYS: customerType = doc1.createElement("customerType") paymentProfile.appendChild(customerType) billTo = doc1.createElement("billTo") paymentProfile.appendChild(billTo) if 'firstName' in KEYS: firstName = doc1.createElement("firstName") billTo.appendChild(firstName) ptext = doc1.createTextNode( self._clean_string(dic['firstName'])) firstName.appendChild(ptext) if 'lastName' in KEYS: lastName = doc1.createElement("lastName") billTo.appendChild(lastName) ptext = doc1.createTextNode( self._clean_string(dic['lastName'])) lastName.appendChild(ptext) if 'company' in KEYS: company = doc1.createElement("company") billTo.appendChild(companycompany) ptext = doc1.createTextNode( self._clean_string(dic['company'])) company.appendChild(ptext) if 'address' in KEYS: address = doc1.createElement("address") billTo.appendChild(address) ptext = doc1.createTextNode( self._clean_string(dic['address'])) address.appendChild(ptext) ##State code must be given here if 'state' in KEYS: state = doc1.createElement("state") billTo.appendChild(state) ptext = doc1.createTextNode( self._clean_string(dic['state'])) state.appendChild(ptext) if 'city' in KEYS: city = doc1.createElement("city") billTo.appendChild(city) ptext = doc1.createTextNode(self._clean_string( dic['city'])) city.appendChild(ptext) if 'zip' in KEYS: zip = doc1.createElement("zip") billTo.appendChild(zip) ptext = doc1.createTextNode(self._clean_string(dic['zip'])) zip.appendChild(ptext) if 'country' in KEYS: country = doc1.createElement("country") billTo.appendChild(country) ptext = doc1.createTextNode( self._clean_string(dic['country'])) country.appendChild(ptext) if 'phoneNumber' in KEYS: phoneNumber = doc1.createElement("phoneNumber") billTo.appendChild(phoneNumber) ptext = doc1.createTextNode( self._clean_string(dic['phoneNumber'])) phoneNumber.appendChild(ptext) if 'faxNumber' in KEYS: faxNumber = doc1.createElement("faxNumber") billTo.appendChild(faxNumber) ptext = doc1.createTextNode( self._clean_string(dic['faxNumber'])) faxNumber.appendChild(ptext) payment = doc1.createElement("payment") paymentProfile.appendChild(payment) if 'cardNumber' in KEYS and 'expirationDate' in KEYS: creditCard = doc1.createElement("creditCard") payment.appendChild(creditCard) cardNumber = doc1.createElement("cardNumber") creditCard.appendChild(cardNumber) ptext = doc1.createTextNode( self._clean_string(dic['cardNumber'])) cardNumber.appendChild(ptext) expirationDate = doc1.createElement("expirationDate") creditCard.appendChild(expirationDate) ptext = doc1.createTextNode(dic['expirationDate']) expirationDate.appendChild(ptext) if 'cardCode' in KEYS: cardCode = doc1.createElement("cardCode") creditCard.appendChild(cardCode) ptext = doc1.createTextNode( self._clean_string(dic['cardCode'])) cardCode.appendChild(ptext) customerPaymentProfileId = doc1.createElement( "customerPaymentProfileId") paymentProfile.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode( self._clean_string(dic['customerPaymentProfileId'])) customerPaymentProfileId.appendChild(ptext) if 'validationMode' in KEYS: validationMode = doc1.createElement("validationMode") updateCustomerPaymentProfileResponse.appendChild( validationMode) Request_string = doc1.toxml(encoding="utf-8") update_CustomerPaymentProfile_response_xml = self.request_to_server( Request_string, url, url_path) update_CustomerPaymentProfile_response_dictionary = xml2dic.main( update_CustomerPaymentProfile_response_xml) parent_resultCode = self.search_dic( update_CustomerPaymentProfile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': return True else: ret = {} Error_Code_dic = self.search_dic( update_CustomerPaymentProfile_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic( update_CustomerPaymentProfile_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return
def createCustomerProfile(self, dic): '''Creates CustomerProfile and returns the CustomerProfile id on success returns None or faliure ''' dic.update({'merchantCustomerId': '1'}) KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) createCustomerProfileRequest = doc1.createElement("createCustomerProfileRequest") createCustomerProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(dic['transaction_key'])) transactionKey.appendChild(ptext) if 'refId' in KEYS: refId = doc1.createElement("refId") ptext1 = doc1.createTextNode(self._clean_string(dic['refId'])) refId.appendChild(ptext1) createCustomerProfileRequest.appendChild(refId) ##Now Add Profile INformation for the user profile = doc1.createElement("profile") createCustomerProfileRequest.appendChild(profile) if 'merchantCustomerId' in KEYS: merchantCustomerId = doc1.createElement("merchantCustomerId") profile.appendChild(merchantCustomerId) ptext = doc1.createTextNode(dic['merchantCustomerId']) merchantCustomerId.appendChild(ptext) if 'description' in KEYS: description = doc1.createElement("description") profile.appendChild(description) ptext = doc1.createTextNode(dic['description']) description.appendChild(ptext) if 'email' in KEYS: email = doc1.createElement("email") profile.appendChild(email) ptext = doc1.createTextNode(dic['email']) email.appendChild(ptext) if 'paymentProfiles' in KEYS: paymentProfiles = doc1.createElement("paymentProfiles") profile.appendChild(paymentProfiles) ptext1 = doc1.createTextNode(self._clean_string(dic['paymentProfiles'])) paymentProfiles.appendChild(ptext1) ######### TO DO ADD THE NECCESSARY OPTIONS INTO IT # Request_string1=xml=doc1.toprettyxml( encoding="utf-8" ) Request_string = xml = doc1.toxml(encoding="utf-8") #Select from production and test server create_CustomerProfile_response_xml = self.request_to_server(Request_string, url, url_path) create_CustomerProfile_response_dictionary = xml2dic.main(create_CustomerProfile_response_xml) parent_msg = self.search_dic(create_CustomerProfile_response_dictionary, "messages") if parent_msg['messages'][0]['resultCode'] == 'Ok': parent = self.search_dic(create_CustomerProfile_response_dictionary, "customerProfileId") return parent['customerProfileId'] return {'Error_Code':parent_msg['messages'][1]['message'][0]['code'], 'Error_Message' :parent_msg['messages'][1]['message'][1]['text']}
def process_ship_accept(self, cr, uid, do, packages, context=None): shipment_accept_request_xml = self.create_ship_accept_request_new( cr, uid, do, context=context) if do.logis_company.test_mode: acce_web = do.logis_company.ship_accpt_test_web or '' acce_port = do.logis_company.ship_accpt_test_port else: acce_web = do.logis_company.ship_accpt_web or '' acce_port = do.logis_company.ship_accpt_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv( _('Unable to find Shipping URL!'), _("Please configure the shipping company with websites.")) conn = httplib.HTTPSConnection(serv, acce_port) res = conn.request("POST", serv_path, shipment_accept_request_xml) import xml2dic res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) NegotiatedRates = '' ShipmentIdentificationNumber = '' TrackingNumber = '' label_image = '' control_log_image = '' status = 0 status_description = '' for response in response_dic['ShipmentAcceptResponse']: if response.get('Response'): for resp_items in response['Response']: if resp_items.get('ResponseStatusCode') and resp_items[ 'ResponseStatusCode'] == '1': status = 1 if resp_items.get('ResponseStatusDescription'): status_description = resp_items[ 'ResponseStatusDescription'] if resp_items.get('Error'): for err in resp_items['Error']: if err.get('ErrorSeverity'): status_description += '\n' + err.get( 'ErrorSeverity') if err.get('ErrorDescription'): status_description += '\n' + err.get( 'ErrorDescription') do.write({'ship_message': status_description}) packages_ids = [package.id for package in do.packages_ids] if status: shipment_identific_number, tracking_number_notes, ship_charge = '', '', 0.0 for shipmentresult in response_dic['ShipmentAcceptResponse']: if shipmentresult.get('ShipmentResults'): package_obj = self.pool.get('stock.packages') for package in response['ShipmentResults']: if package.get('ShipmentIdentificationNumber'): shipment_identific_number = package[ 'ShipmentIdentificationNumber'] continue ship_charge += package.get( 'ShipmentCharges') and float( package['ShipmentCharges'][2]['TotalCharges'] [1]['MonetaryValue']) or 0.0 if package.get('PackageResults'): label_image = '' tracking_number = '' label_code = '' tracking_url = do.logis_company.ship_tracking_url or '' for tracks in package['PackageResults']: if tracks.get('TrackingNumber'): tracking_number = tracks['TrackingNumber'] if tracking_url: try: tracking_url = tracking_url % tracking_number except Exception, e: tracking_url = "Invalid tracking url on shipping company" if tracks.get('LabelImage'): for label in tracks['LabelImage']: if label.get('LabelImageFormat'): for format in label[ 'LabelImageFormat']: label_code = format.get('Code') if label.get('GraphicImage'): label_image = label['GraphicImage'] im_in_raw = base64.decodestring( label_image) path = tempfile.mktemp('.txt') temp = file(path, 'wb') temp.write(im_in_raw) result = base64.b64encode( im_in_raw) (dirName, fileName) = os.path.split(path) self.pool.get( 'ir.attachment').create( cr, uid, { 'name': fileName, 'datas': result, 'datas_fname': fileName, 'res_model': self._name, 'res_id': do.id, 'type': 'binary' }, context=context) temp.close() try: new_im = Image.open(path) new_im = new_im.rotate(270) new_im.save(path, 'JPEG') except Exception, e: pass label_from_file = open(path, 'rb') label_image = base64.encodestring( label_from_file.read()) label_from_file.close() if label_code == 'GIF': package_obj.write( cr, uid, packages_ids[packages], { 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'logo': label_image, 'ship_state': 'in_process', 'tracking_url': tracking_url, 'att_file_name': fileName }, context=context) else: package_obj.write( cr, uid, packages_ids[packages], { 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'ship_state': 'in_process', 'tracking_url': tracking_url, 'att_file_name': fileName }, context=context) if int( time.strftime("%w") ) in range(1, 6) or ( time.strftime("%w") == '6' and do.sat_delivery): next_pic_date = time.strftime( "%Y-%m-%d") else: timedelta = datetime.timedelta( 7 - int(time.strftime("%w"))) next_pic_date = ( datetime.datetime.today() + timedelta ).strftime("%Y-%m-%d") package_data = package_obj.read( cr, uid, packages_ids[packages], ['weight', 'description'], context=context) # i += 1 ship_move_obj = self.pool.get( 'shipping.move') if label_code == 'GIF': ship_move_obj.create(cr, uid, { 'pick_id': do.id, 'package_weight': package_data['weight'], 'partner_id': do.partner_id.id, 'service': do.ups_service.id, 'ship_to': do.partner_id.id, 'ship_from': do.ship_from and do.ship_from_address.id or \ do.shipper and do.shipper.address and do.shipper.address.id, 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'logo': label_image, 'state': 'ready_pick', 'tracking_url': tracking_url, 'package': package_data['description'] and str(package_data['description'])[:126], 'pic_date': next_pic_date, 'sale_id': do.sale_id.id and do.sale_id.id or False, }, context=context) else: ship_move_obj.create(cr, uid, { 'pick_id': do.id, 'package_weight': package_data['weight'], 'partner_id': do.partner_id.id, 'service': do.ups_service.id, 'ship_to': do.partner_id.id, 'ship_from': do.ship_from and do.ship_from_address.id or \ do.shipper and do.shipper.address and do.shipper.address.id, 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'state': 'ready_pick', 'tracking_url': tracking_url, 'package': package_data['description'] and str(package_data['description'])[:126], 'pic_date': next_pic_date, 'sale_id': do.sale_id.id and do.sale_id.id or False, }, context=context) tracking_number_notes += '\n' + tracking_number if package.get('ControlLogReceipt'): for items in package['ControlLogReceipt']: if items.get('GraphicImage'): control_log_image = items['GraphicImage'] im_in_raw = base64.decodestring( control_log_image) file_name = tempfile.mktemp() path = file_name = '.html' temp = file(path, 'wb') temp.write(im_in_raw) temp.close() label_from_file = open(path, 'rb') control_log_image = base64.encodestring( label_from_file.read()) label_from_file.close() package_obj.write( cr, uid, packages_ids, { 'control_log_receipt': control_log_image, }, context=context)
def process_ship_accept(self, cr, uid, ids, ret_res, context=None): quick_ship_id = self.browse(cr, uid, ids[0], context=context) ship_digest=ret_res.get('ship_digest') data_for_Access_Request = { 'AccessLicenseNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.accesslicensenumber or '', 'UserId': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.userid or '', 'Password': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.password or '' } data_for_Ship_Accept = { 'ShipmentAcceptRequest': { 'Request': { 'RequestAction': 'ShipAccept', 'TransactionReference': {'CustomerContext': ''} }, 'ShipmentDigest': ship_digest } } doc1 = Document() AccessRequest = doc1.createElement("AccessRequest") AccessRequest.setAttribute("xml:lang", "en-US") doc1.appendChild(AccessRequest) AccessLicenseNumber = doc1.createElement("AccessLicenseNumber") ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"]) AccessLicenseNumber.appendChild(ptext) AccessRequest.appendChild(AccessLicenseNumber) UserId = doc1.createElement("UserId") ptext = doc1.createTextNode(data_for_Access_Request["UserId"]) UserId.appendChild(ptext) AccessRequest.appendChild(UserId) Password = doc1.createElement("Password") ptext = doc1.createTextNode(data_for_Access_Request["Password"]) Password.appendChild(ptext) AccessRequest.appendChild(Password) Request_string1 = doc1.toprettyxml() doc2 = Document() ShipmentAcceptRequest = doc2.createElement("ShipmentAcceptRequest") ShipmentAcceptRequest.setAttribute("xml:lang", "en-US") doc2.appendChild(ShipmentAcceptRequest) Request = doc2.createElement("Request") ShipmentAcceptRequest.appendChild(Request) RequestAction = doc2.createElement("RequestAction") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['RequestAction']) RequestAction.appendChild(ptext) Request.appendChild(RequestAction) TransactionReference = doc2.createElement("TransactionReference") Request.appendChild(TransactionReference) CustomerContext = doc2.createElement("CustomerContext") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["Request"]['TransactionReference']['CustomerContext']) CustomerContext.appendChild(ptext) TransactionReference.appendChild(CustomerContext) ShipmentDigest = doc2.createElement("ShipmentDigest") ptext = doc1.createTextNode(data_for_Ship_Accept['ShipmentAcceptRequest']["ShipmentDigest"]) ShipmentDigest.appendChild(ptext) ShipmentAcceptRequest.appendChild(ShipmentDigest) Request_string2 = doc2.toprettyxml() serv = '' acce_port = '' serv_path = '' if quick_ship_id.logis_company.id: if quick_ship_id.logis_company.test_mode: acce_web = quick_ship_id.logis_company.ship_accpt_test_web or '' acce_port = quick_ship_id.logis_company.ship_accpt_test_port else: acce_web = quick_ship_id.logis_company.ship_accpt_web or '' acce_port = quick_ship_id.logis_company.ship_accpt_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv(_('Unable to find Shipping URL!'), _("Please configure the shipping company with websites.") ) else: raise osv.except_osv(_('No Company Selected!'), _("Please select a logistic company.") ) Request_string = Request_string1 + Request_string2 conn = httplib.HTTPSConnection(serv, acce_port) res = conn.request("POST", serv_path, Request_string) res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) NegotiatedRates = '' ShipmentIdentificationNumber = '' TrackingNumber = '' if len(response_dic['ShipmentAcceptResponse']) > 1 and 'ShipmentResults' in response_dic['ShipmentAcceptResponse'][1]: if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults']) > 1 and \ 'NegotiatedRates' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'] and \ 'NetSummaryCharges' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'] and \ 'GrandTotal' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0]: NegotiatedRates = response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][1]['NegotiatedRates'][0]['NetSummaryCharges'][0]\ ['GrandTotal'][1]['MonetaryValue'] if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'] and \ 'ShipmentIdentificationNumber' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3]: ShipmentIdentificationNumber = response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][3]['ShipmentIdentificationNumber'] label_image = None if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults']) > 4 and \ 'PackageResults' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]: if response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults']: TrackingNumber=response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][0]['TrackingNumber'] if len(response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults']) > 2 and \ 'LabelImage' in response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2]: label_image =response_dic['ShipmentAcceptResponse'][1]['ShipmentResults'][4]['PackageResults'][2]['LabelImage'][1]['GraphicImage'] if label_image: im_in_raw = base64.decodestring(label_image) path = tempfile.mktemp() temp = file(path, 'wb') temp.write(im_in_raw) temp.close() new_im = Image.open(path) new_im = new_im.rotate(270) new_im.save(path, 'JPEG') label_from_file = open(path, 'rb') label_image = base64.encodestring(label_from_file.read()) label_from_file.close() self.write(cr, uid, ids, {'shipcharge': NegotiatedRates or '0', 'logo': label_image}) if ret_res.get('ship_move_id'): self.write(cr,uid,ids,{'shipcharge': NegotiatedRates or '0', 'ship_log_id': ret_res.get('ship_move_id')}) tracking_url = '' if TrackingNumber: tracking_url = quick_ship_id.logis_company.ship_tracking_url if tracking_url: try: tracking_url = tracking_url%TrackingNumber except Exception, e: tracking_url = "Invalid tracking url on shipping company" ship_move_id = self.pool.get('shipping.move').write(cr, uid, [ret_res.get('ship_move_id')], { 'logo': label_image, 'shipment_identific_no': ShipmentIdentificationNumber, 'tracking_no': TrackingNumber, 'tracking_url': tracking_url })
def process_ship(self, cr, uid, ids, context=None): quick_ship_id = self.browse(cr, uid, ids[0], context=context) data_for_Access_Request = { 'AccessLicenseNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.accesslicensenumber or '', 'UserId': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.userid or '', 'Password': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.password or '' } data_for_confirm_request = { 'ShipmentConfirmRequest': { 'Request': { 'RequestAction': "ShipConfirm", 'RequestOption': "nonvalidate", 'TransactionReference': {'CustomerContext': "",},#---------optional data },#Request 'Shipment': { 'Description': quick_ship_id.description or "Shipping", 'ReturnService': {'Code': "8", 'DocumentsOnly':"" }, 'Shipper': { 'Name': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.name or "", 'AttentionName': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.atten_name or "", 'ShipperNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.acc_no or "", 'TaxIdentificationNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.tax_id_no or "", 'PhoneNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.phone or "", 'FaxNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.fax or "", 'EMailAddress': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.email or "", 'Address': self.fill_addr(quick_ship_id.ups_shipper_id and quick_ship_id.ups_shipper_id.address or '') },#Shipper 'ShipTo': { 'CompanyName': quick_ship_id.address_id and quick_ship_id.address_id.name or '', 'AttentionName': "", 'TaxIdentificationNumber': "", 'PhoneNumber': "", 'FaxNumber': quick_ship_id.address_id.id and quick_ship_id.address_id.fax or '', 'EMailAddress': quick_ship_id.address_id.id and quick_ship_id.address_id.email or '', 'Address': self.fill_addr(quick_ship_id.address_id.id and quick_ship_id.address_id), 'LocationID': "", },#ShipTo 'ShipFrom': { 'CompanyName': quick_ship_id.send_addr.company_id and quick_ship_id.send_addr.company_id.name or '', 'AttentionName': quick_ship_id.send_addr.name or "", 'TaxIdentificationNumber': '', 'PhoneNumber': quick_ship_id.send_addr.id and quick_ship_id.send_addr.phone or '', 'FaxNumber': quick_ship_id.send_addr.id and quick_ship_id.send_addr.fax or '', 'Address': self.fill_addr(quick_ship_id.send_addr.id and quick_ship_id.send_addr or ''), }, 'PaymentInformation': { 'Prepaid': { 'BillShipper': {'AccountNumber': quick_ship_id.ups_shipper_id and quick_ship_id.ups_shipper_id.acc_no or ""},#BillShipper },#Prepaid },#PaymentInformation, 'GoodsNotInFreeCirculationIndicator': "", 'RateInformation': {'NegotiatedRatesIndicator': ""},#RateInformation 'Service': { 'Code': quick_ship_id.ups_service_id.id and str(quick_ship_id.ups_service_id.shipping_service_code) or "", 'Description': quick_ship_id.ups_service_id.id and quick_ship_id.ups_service_id.description or ""},#Service 'InvoiceLineTotal': {'CurrencyCode': "", 'MonetaryValue': str(quick_ship_id.amount) or ""},#InvoiceLineTotal 'Package': self.get_package(quick_ship_id) },#Shipment 'LabelSpecification': { 'LabelPrintMethod': {'Code': "GIF", 'Description': "GIF"}, 'HTTPUserAgent': "", 'LabelStockSize': {'Height': "4", 'Width': "6"}, 'LabelImageFormat': {'Code': "GIF", 'Description': "GIF"}, },#LabelSpecification },#ShipmentConfirmRequest } doc1 = Document() AccessRequest = doc1.createElement("AccessRequest") AccessRequest.setAttribute("xml:lang", "en-US") doc1.appendChild(AccessRequest) AccessLicenseNumber = doc1.createElement("AccessLicenseNumber") ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"]) AccessLicenseNumber.appendChild(ptext) AccessRequest.appendChild(AccessLicenseNumber) UserId = doc1.createElement("UserId") ptext = doc1.createTextNode(data_for_Access_Request["UserId"]) UserId.appendChild(ptext) AccessRequest.appendChild(UserId) Password = doc1.createElement("Password") ptext = doc1.createTextNode(data_for_Access_Request["Password"]) Password.appendChild(ptext) AccessRequest.appendChild(Password) Request_string1 = doc1.toprettyxml() ######SECOND PART Package_count = 0#max value =200 doc2 = Document() ShipmentConfirmRequest = doc2.createElement("ShipmentConfirmRequest") doc2.appendChild(ShipmentConfirmRequest) Request = doc2.createElement("Request") ShipmentConfirmRequest.appendChild(Request) RequestAction = doc2.createElement("RequestAction") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestAction"]) RequestAction.appendChild(ptext) Request.appendChild(RequestAction) RequestOption = doc2.createElement("RequestOption") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestOption"]) RequestOption.appendChild(ptext) Request.appendChild(RequestOption) TransactionReference = doc2.createElement("TransactionReference") Request.appendChild(TransactionReference) CustomerContext = doc2.createElement("CustomerContext") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["TransactionReference"]['CustomerContext']) CustomerContext.appendChild(ptext) TransactionReference.appendChild(CustomerContext) Shipment = doc2.createElement("Shipment") ShipmentConfirmRequest.appendChild(Shipment) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Description"]) Description.appendChild(ptext) Shipment.appendChild(Description) if 0:#quick_ship_id.with_ret_service: ReturnService = doc2.createElement("ReturnService") Shipment.appendChild(ReturnService) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ReturnService"]["Code"]) Code.appendChild(ptext) ReturnService.appendChild(Code) Shipper = doc2.createElement("Shipper") Shipment.appendChild(Shipper) Name = doc2.createElement("Name") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Name"]) Name.appendChild(ptext) Shipper.appendChild(Name) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["AttentionName"]) AttentionName.appendChild(ptext) Shipper.appendChild(AttentionName) ShipperNumber = doc2.createElement("ShipperNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["ShipperNumber"]) ShipperNumber.appendChild(ptext) Shipper.appendChild(ShipperNumber) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) Shipper.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) Shipper.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["FaxNumber"]) FaxNumber.appendChild(ptext) Shipper.appendChild(FaxNumber) EMailAddress = doc2.createElement("EMailAddress") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["EMailAddress"]) EMailAddress.appendChild(ptext) Shipper.appendChild(EMailAddress) # Address Address = doc2.createElement("Address") Shipper.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine3 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) ShipTo = doc2.createElement("ShipTo") Shipment.appendChild(ShipTo) CompanyName = doc2.createElement("CompanyName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["CompanyName"]) CompanyName.appendChild(ptext) ShipTo.appendChild(CompanyName) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["AttentionName"]) AttentionName.appendChild(ptext) ShipTo.appendChild(AttentionName) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) ShipTo.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) ShipTo.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["FaxNumber"]) FaxNumber.appendChild(ptext) ShipTo.appendChild(FaxNumber) EMailAddress = doc2.createElement("EMailAddress") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["EMailAddress"]) EMailAddress.appendChild(ptext) ShipTo.appendChild(EMailAddress) LocationID = doc2.createElement("LocationID") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["LocationID"]) LocationID.appendChild(ptext) ShipTo.appendChild(LocationID) Address = doc2.createElement("Address") ShipTo.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine2 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) ShipFrom = doc2.createElement("ShipFrom") Shipment.appendChild(ShipFrom) CompanyName = doc2.createElement("CompanyName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["CompanyName"]) CompanyName.appendChild(ptext) ShipFrom.appendChild(CompanyName) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["AttentionName"]) AttentionName.appendChild(ptext) ShipFrom.appendChild(AttentionName) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) ShipFrom.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) ShipFrom.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["FaxNumber"]) FaxNumber.appendChild(ptext) ShipFrom.appendChild(FaxNumber) Address = doc2.createElement("Address") ShipFrom.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine3 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) PaymentInformation = doc2.createElement("PaymentInformation") Shipment.appendChild(PaymentInformation) Prepaid = doc2.createElement("Prepaid") PaymentInformation.appendChild(Prepaid) BillShipper = doc2.createElement("BillShipper") Prepaid.appendChild(BillShipper) AccountNumber = doc2.createElement("AccountNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["PaymentInformation"]["Prepaid"]\ ["BillShipper"]["AccountNumber"]) AccountNumber.appendChild(ptext) BillShipper.appendChild(AccountNumber) GoodsNotInFreeCirculationIndicator = doc2.createElement("GoodsNotInFreeCirculationIndicator") Shipment.appendChild(GoodsNotInFreeCirculationIndicator) RateInformation = doc2.createElement("RateInformation") Shipment.appendChild(RateInformation) NegotiatedRatesIndicator = doc2.createElement("NegotiatedRatesIndicator") RateInformation.appendChild(NegotiatedRatesIndicator) Service = doc2.createElement("Service") Shipment.appendChild(Service) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Code"]) Code.appendChild(ptext) Service.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Description"]) Description.appendChild(ptext) Service.appendChild(Description) if (quick_ship_id.send_addr.id and quick_ship_id.send_addr.country_id.code == 'US') and quick_ship_id.address_id.id and \ quick_ship_id.address_id.country_id.code in ('PR', 'CA'): InvoiceLineTotal = doc2.createElement("InvoiceLineTotal") Shipment.appendChild(InvoiceLineTotal) MonetaryValue = doc2.createElement("MonetaryValue") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["InvoiceLineTotal"]["MonetaryValue"]) MonetaryValue.appendChild(ptext) InvoiceLineTotal.appendChild(MonetaryValue) Package_count = len(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"]) for i in range(0,Package_count): Package = doc2.createElement("Package") Shipment.appendChild(Package) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Description"]) Description.appendChild(ptext) Package.appendChild(Description) PackagingType = doc2.createElement("PackagingType") Package.appendChild(PackagingType) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]["Code"]) Code.appendChild(ptext) PackagingType.appendChild(Code) # Description = doc2.createElement("Description") # # ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]["Description"]) # Description.appendChild(ptext) # PackagingType.appendChild(Description) Dimensions = doc2.createElement("Dimensions") Package.appendChild(Dimensions) Length = doc2.createElement("Length") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Length"]) Length.appendChild(ptext) Dimensions.appendChild(Length) Width = doc2.createElement("Width") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Width"]) Width.appendChild(ptext) Dimensions.appendChild(Width) Height = doc2.createElement("Height") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Height"]) Height.appendChild(ptext) Dimensions.appendChild(Height) UnitOfMeasurement = doc2.createElement("UnitOfMeasurement") Dimensions.appendChild(UnitOfMeasurement) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]\ ['UnitOfMeasurement']["Code"]) Code.appendChild(ptext) UnitOfMeasurement.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]\ ['UnitOfMeasurement']["Description"]) Description.appendChild(ptext) UnitOfMeasurement.appendChild(Description) PackageWeight = doc2.createElement("PackageWeight") Package.appendChild(PackageWeight) UnitOfMeasurement = doc2.createElement("UnitOfMeasurement") PackageWeight.appendChild(UnitOfMeasurement) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']\ ['UnitOfMeasurement']["Code"]) Code.appendChild(ptext) UnitOfMeasurement.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']\ ['UnitOfMeasurement']["Description"]) Description.appendChild(ptext) UnitOfMeasurement.appendChild(Description) Weight = doc2.createElement("Weight") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']["Weight"]) Weight.appendChild(ptext) PackageWeight.appendChild(Weight) from_country_code = quick_ship_id.send_addr.id and quick_ship_id.send_addr.country_id.id and quick_ship_id.send_addr.country_id.code to_country_code = quick_ship_id.address_id.id and quick_ship_id.address_id.country_id.id and quick_ship_id.address_id.country_id.code if not(from_country_code == 'US' and to_country_code == 'US' or from_country_code == 'PR' and to_country_code == 'PR'): ReferenceNumber = doc2.createElement("ReferenceNumber") Package.appendChild(ReferenceNumber) BarCodeIndicator = doc2.createElement("BarCodeIndicator") ReferenceNumber.appendChild(BarCodeIndicator) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["ReferenceNumber"]["Code"]) Code.appendChild(ptext) ReferenceNumber.appendChild(Code) Value = doc2.createElement("Value") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["ReferenceNumber"]["Value"]) Value.appendChild(ptext) ReferenceNumber.appendChild(Value) LabelSpecification = doc2.createElement("LabelSpecification") ShipmentConfirmRequest.appendChild(LabelSpecification) LabelPrintMethod = doc2.createElement("LabelPrintMethod") LabelSpecification.appendChild(LabelPrintMethod) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Code"]) Code.appendChild(ptext) LabelPrintMethod.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Description"]) Description.appendChild(ptext) LabelPrintMethod.appendChild(Description) LabelStockSize = doc2.createElement("LabelStockSize") LabelSpecification.appendChild(LabelStockSize) Height = doc2.createElement("Height") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Height"]) Height.appendChild(ptext) LabelStockSize.appendChild(Height) Width = doc2.createElement("Width") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Width"]) Width.appendChild(ptext) LabelStockSize.appendChild(Width) LabelImageFormat = doc2.createElement("LabelImageFormat") LabelSpecification.appendChild(LabelImageFormat) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Code"]) Code.appendChild(ptext) LabelImageFormat.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Description"]) Description.appendChild(ptext) LabelImageFormat.appendChild(Description) ret = [] serv = '' acce_port = '' serv_path = '' if quick_ship_id.logis_company.id: if quick_ship_id.logis_company.test_mode: acce_web = quick_ship_id.logis_company.ship_req_test_web or '' acce_port = quick_ship_id.logis_company.ship_req_test_port else: acce_web = quick_ship_id.logis_company.ship_req_web or '' acce_port = quick_ship_id.logis_company.ship_req_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv(_('Unable to find Shipping URL!'),_("Please configure the shipping company with websites.") ) else: raise osv.except_osv(_('No Company Selected!'),_("Please select a logistic company.") ) request_xml = doc1.toprettyxml() + doc2.toprettyxml() conn = httplib.HTTPSConnection(serv,acce_port) res = conn.request("POST",serv_path,request_xml) res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) response = '' err_flag = False for res_elm in response_dic['ShipmentConfirmResponse'][0]['Response']: if res_elm.get('ResponseStatusCode'): response = '\nResponse Status Code: ' + str(res_elm['ResponseStatusCode']) if res_elm.get('ResponseStatusDescription'): response += '\nResponse Description: ' + str(res_elm['ResponseStatusDescription']) if res_elm.get('ResponseStatusCode', False) and str(res_elm.get('ResponseStatusCode')) != 1: if res_elm.get('Error'): err_flag = True for err_elm in res_elm.get('Error'): if err_elm.get('ErrorCode', False): response += '\nErrorCode: ' + str(err_elm['ErrorCode']) if err_elm.get('ErrorDescription', False): response += '\nErrorDescription: ' + str(err_elm['ErrorDescription']) self.write(cr, uid, ids, {'response': response}) ship_digest = "" if len(response_dic['ShipmentConfirmResponse']) > 4 and response_dic['ShipmentConfirmResponse'][4].has_key('ShipmentDigest'): ship_digest += str(response_dic['ShipmentConfirmResponse'][4]['ShipmentDigest']) ship_move_ids = [] value_dic = { 'package_weight': quick_ship_id.weight, 'state': 'in_process', 'partner_id': quick_ship_id.recipient.id, 'ups_service_id': quick_ship_id.ups_service_id.id, # 'package_weight': quick_ship_id.weight, 'ship_to': quick_ship_id.address_id.id, 'ship_from': quick_ship_id.send_addr.id, 'sale_id': quick_ship_id.saleorder_id.id and quick_ship_id.saleorder_id.id, 'ship_cost': quick_ship_id.shipcharge } ship_move_id = self.pool.get('shipping.move').create(cr, uid, value_dic) if err_flag: ret = False else: ret = {'response': response, 'ship_digest': ship_digest, 'ship_move_id': ship_move_id} return ret
def process_ship_accept(self, cr, uid, do, packages, context=None): shipment_accept_request_xml = self.create_ship_accept_request_new(cr, uid, do, context=context) if do.logis_company.test_mode: acce_web = do.logis_company.ship_accpt_test_web or '' acce_port = do.logis_company.ship_accpt_test_port else: acce_web = do.logis_company.ship_accpt_web or '' acce_port = do.logis_company.ship_accpt_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv(_('Unable to find Shipping URL!'), _("Please configure the shipping company with websites.")) conn = httplib.HTTPSConnection(serv, acce_port) res = conn.request("POST", serv_path, shipment_accept_request_xml) import xml2dic res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) NegotiatedRates = '' ShipmentIdentificationNumber = '' TrackingNumber = '' label_image = '' control_log_image = '' status = 0 status_description = '' for response in response_dic['ShipmentAcceptResponse']: if response.get('Response'): for resp_items in response['Response']: if resp_items.get('ResponseStatusCode') and resp_items['ResponseStatusCode'] == '1': status = 1 if resp_items.get('ResponseStatusDescription'): status_description = resp_items['ResponseStatusDescription'] if resp_items.get('Error'): for err in resp_items['Error']: if err.get('ErrorSeverity'): status_description += '\n' + err.get('ErrorSeverity') if err.get('ErrorDescription'): status_description += '\n' + err.get('ErrorDescription') do.write({'ship_message': status_description}) packages_ids = [package.id for package in do.packages_ids] if status: shipment_identific_number, tracking_number_notes, ship_charge = '', '', 0.0 for shipmentresult in response_dic['ShipmentAcceptResponse']: if shipmentresult.get('ShipmentResults'): package_obj = self.pool.get('stock.packages') for package in response['ShipmentResults']: if package.get('ShipmentIdentificationNumber'): shipment_identific_number = package['ShipmentIdentificationNumber'] continue ship_charge += package.get('ShipmentCharges') and float(package['ShipmentCharges'][2]['TotalCharges'][1]['MonetaryValue']) or 0.0 if package.get('PackageResults'): label_image = '' tracking_number = '' label_code = '' tracking_url = do.logis_company.ship_tracking_url or '' for tracks in package['PackageResults']: if tracks.get('TrackingNumber'): tracking_number = tracks['TrackingNumber'] if tracking_url: try: tracking_url = tracking_url % tracking_number except Exception, e: tracking_url = "Invalid tracking url on shipping company" if tracks.get('LabelImage'): for label in tracks['LabelImage']: if label.get('LabelImageFormat'): for format in label['LabelImageFormat']: label_code = format.get('Code') if label.get('GraphicImage'): label_image = label['GraphicImage'] im_in_raw = base64.decodestring(label_image) path = tempfile.mktemp('.txt') temp = file(path, 'wb') temp.write(im_in_raw) result = base64.b64encode(im_in_raw) (dirName, fileName) = os.path.split(path) self.pool.get('ir.attachment').create(cr, uid, { 'name': fileName, 'datas': result, 'datas_fname': fileName, 'res_model': self._name, 'res_id': do.id, 'type': 'binary' }, context=context) temp.close() try: new_im = Image.open(path) new_im = new_im.rotate(270) new_im.save(path, 'JPEG') except Exception, e: pass label_from_file = open(path, 'rb') label_image = base64.encodestring(label_from_file.read()) label_from_file.close() if label_code == 'GIF': package_obj.write(cr, uid, packages_ids[packages], { 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'logo': label_image, 'ship_state': 'in_process', 'tracking_url': tracking_url, 'att_file_name': fileName }, context=context) else: package_obj.write(cr, uid, packages_ids[packages], { 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'ship_state': 'in_process', 'tracking_url': tracking_url, 'att_file_name': fileName }, context=context) if int(time.strftime("%w")) in range(1, 6) or (time.strftime("%w") == '6' and do.sat_delivery): next_pic_date = time.strftime("%Y-%m-%d") else: timedelta = datetime.timedelta(7 - int(time.strftime("%w"))) next_pic_date = (datetime.datetime.today() + timedelta).strftime("%Y-%m-%d") package_data = package_obj.read(cr, uid, packages_ids[packages], ['weight', 'description'], context=context) # i += 1 ship_move_obj = self.pool.get('shipping.move') if label_code == 'GIF': ship_move_obj.create(cr, uid, { 'pick_id': do.id, 'package_weight': package_data['weight'], 'partner_id': do.partner_id.id, 'service': do.ups_service.id, 'ship_to': do.partner_id.id, 'ship_from': do.ship_from and do.ship_from_address.id or \ do.shipper and do.shipper.address and do.shipper.address.id, 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'logo': label_image, 'state': 'ready_pick', 'tracking_url': tracking_url, 'package': package_data['description'] and str(package_data['description'])[:126], 'pic_date': next_pic_date, 'sale_id': do.sale_id.id and do.sale_id.id or False, }, context=context) else: ship_move_obj.create(cr, uid, { 'pick_id': do.id, 'package_weight': package_data['weight'], 'partner_id': do.partner_id.id, 'service': do.ups_service.id, 'ship_to': do.partner_id.id, 'ship_from': do.ship_from and do.ship_from_address.id or \ do.shipper and do.shipper.address and do.shipper.address.id, 'tracking_no': tracking_number, 'shipment_identific_no': shipment_identific_number, 'state': 'ready_pick', 'tracking_url': tracking_url, 'package': package_data['description'] and str(package_data['description'])[:126], 'pic_date': next_pic_date, 'sale_id': do.sale_id.id and do.sale_id.id or False, }, context=context) tracking_number_notes += '\n' + tracking_number if package.get('ControlLogReceipt'): for items in package['ControlLogReceipt']: if items.get('GraphicImage'): control_log_image = items['GraphicImage'] im_in_raw = base64.decodestring(control_log_image) file_name = tempfile.mktemp() path = file_name = '.html' temp = file(path, 'wb') temp.write(im_in_raw) temp.close() label_from_file = open(path, 'rb') control_log_image = base64.encodestring(label_from_file.read()) label_from_file.close() package_obj.write(cr, uid, packages_ids, {'control_log_receipt': control_log_image, }, context=context)
def createCustomerShippingAddressRequest(self, dic): '''Creates shippingAddressRequest for Customer and returns the shippingAddressRequest id on success returns None or failure ''' KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) createCustomerShippingAddressRequest = doc1.createElement("createCustomerShippingAddressRequest") createCustomerShippingAddressRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerShippingAddressRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerShippingAddressRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") createCustomerShippingAddressRequest.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(dic['customerProfileId'])) customerProfileId.appendChild(ptext) billTo = doc1.createElement("address") createCustomerShippingAddressRequest.appendChild(billTo) if 'firstName' in KEYS: firstName = doc1.createElement("firstName") billTo.appendChild(firstName) ptext = doc1.createTextNode(self._clean_string(dic['firstName'])) firstName.appendChild(ptext) if 'lastName' in KEYS: lastName = doc1.createElement("lastName") billTo.appendChild(lastName) ptext = doc1.createTextNode(self._clean_string(dic['lastName'])) lastName.appendChild(ptext) if 'company' in KEYS: company = doc1.createElement("company") billTo.appendChild(companycompany) ptext = doc1.createTextNode(self._clean_string(dic['company'])) company.appendChild(ptext) if 'address' in KEYS: address = doc1.createElement("address") billTo.appendChild(address) ptext = doc1.createTextNode(self._clean_string(dic['address'])) address.appendChild(ptext) if 'city' in KEYS: city = doc1.createElement("city") billTo.appendChild(city) ptext = doc1.createTextNode(self._clean_string(dic['city'])) city.appendChild(ptext) ##State code must be given here if 'state' in KEYS: state = doc1.createElement("state") billTo.appendChild(state) ptext = doc1.createTextNode(self._clean_string(dic['state'])) state.appendChild(ptext) if 'zip' in KEYS: zip = doc1.createElement("zip") billTo.appendChild(zip) ptext = doc1.createTextNode(self._clean_string(dic['zip'])) zip.appendChild(ptext) if 'country' in KEYS: country = doc1.createElement("country") billTo.appendChild(country) ptext = doc1.createTextNode(self._clean_string(dic['country'])) country.appendChild(ptext) if 'phoneNumber' in KEYS: phoneNumber = doc1.createElement("phoneNumber") billTo.appendChild(phoneNumber) ptext = doc1.createTextNode(self._clean_string(dic['phoneNumber'])) phoneNumber.appendChild(ptext) if 'faxNumber' in KEYS: faxNumber = doc1.createElement("faxNumber") billTo.appendChild(faxNumber) ptext = doc1.createTextNode(self._clean_string(dic['faxNumber'])) faxNumber.appendChild(ptext) ret = {} Request_string = xml = doc1.toxml(encoding="utf-8") print 'Request_string',Request_string createCustomerShippingAddress_response_xml = self.request_to_server(Request_string, url, url_path) createCustomerShippingAddress_response_dictionary = xml2dic.main(createCustomerShippingAddress_response_xml) parent_resultCode = self.search_dic(createCustomerShippingAddress_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_customerPaymentProfileId = self.search_dic(createCustomerShippingAddress_response_dictionary, 'customerAddressId') return parent_customerPaymentProfileId['customerAddressId'] else: ret = {} Error_Code_dic = self.search_dic(createCustomerShippingAddress_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(createCustomerShippingAddress_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return ret
def process_void(self): ids = self._ids if type(ids) == list: ids = list(ids) do = self.browse(ids)[0] if do.ship_company_code != 'usps': return super(stock_picking, self).process_void() if not (do.logis_company and do.logis_company.ship_company_code == 'usps'): return super(stock_picking, self).process_void() userid = do.logis_company.usps_userid url = do.logis_company.test_mode and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_prd = do.logis_company.usps_url url_prd_secure = do.logis_company.usps_url_secure test = do.logis_company.test_mode error = False str_error = '' for pack in do.packages_ids: if pack.tracking_no: url = test and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_sec = test and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure if test: request_xml = """<CarrierPickupCancelRequest USERID="%(user_id)s"> <FirmName>ABC Corp.</FirmName> <SuiteOrApt>Suite 777</SuiteOrApt> <Address2>1390 Market Street</Address2> <Urbanization></Urbanization> <City>Houston</City> <State>TX</State> <ZIP5>77058</ZIP5> <ZIP4>1234</ZIP4> <ConfirmationNumber>WTC123456789</ConfirmationNumber> </CarrierPickupCancelRequest> """ % { 'user_id': do.logis_company.usps_userid } else: request_xml = """<CarrierPickupCancelRequest USERID="%(user_id)"> <FirmName>ABC Corp.</FirmName> <SuiteOrApt>Suite 777</SuiteOrApt> <Address2>1390 Market Street</Address2> <Urbanization></Urbanization> <City>Houston</City> <State>TX</State> <ZIP5>77058</ZIP5> <ZIP4>1234</ZIP4> <ConfirmationNumber>%(confirmation_number)</ConfirmationNumber> </CarrierPickupCancelRequest> """ % { 'user_id': do.logis_company.usps_userid, 'confirmation_number': pack.tracking_no, } if url and request_xml: request_url = url + '?API=CarrierPickupCancel&XML=' + request_xml try: import urllib f = urllib.urlopen(request_url) from xml.dom.minidom import parse, parseString import xml2dic str_response = f.read() except Exception: self.env['stock.packages'].write( {'ship_message': str(Exception)}) xml_response = parseString(str_response) xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): self.env['stock.packages'].write( {'ship_message': str_error}) break else: self.env['stock.packages'].write({ 'negotiated_rates': 0.00, 'shipment_identific_no': '', 'tracking_no': '', 'tracking_url': '', 'logo': '', 'ship_message': 'Shipment Cancelled' }) if not error: self.write({ 'ship_state': 'draft', 'ship_message': 'Shipment has been cancelled.' }) else: self.write({ 'ship_message': 'Cancellation of some of shipment has failed, please check the status of pakages.' }) return True
def createCustomerProfileTransactionRequest(self, dic): """ Creates the xml for TransactionRequest and returns the transaction id """ profile_dictionary = dic KEYS = dic.keys() doc1 = Document() url_path = dic.get("url_extension", False) url = dic.get("url", False) xsd = dic.get("xsd", False) trans_type_list = ["AuthOnly", "AuthCapture", "CaptureOnly", "PriorAuthCapture", "Refund"] createCustomerProfileTransactionRequest = doc1.createElement("createCustomerProfileTransactionRequest") createCustomerProfileTransactionRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerProfileTransactionRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerProfileTransactionRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if "api_login_id" in KEYS and "transaction_key" in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic["api_login_id"])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic["transaction_key"]))) transactionKey.appendChild(ptext) transaction = doc1.createElement("transaction") createCustomerProfileTransactionRequest.appendChild(transaction) if "trans_type" in KEYS: if profile_dictionary.get("trans_type") in trans_type_list: transaction_type_tagname = "profileTrans" + profile_dictionary.get("trans_type") transaction_type = doc1.createElement(transaction_type_tagname) transaction.appendChild(transaction_type) if "amount" in KEYS: amount = doc1.createElement("amount") transaction_type.appendChild(amount) ptext = doc1.createTextNode(self._clean_string(dic.get("amount"))) amount.appendChild(ptext) if "tax_amount" in KEYS: tax = doc1.createElement("tax") transaction_type.appendChild(tax) tax_amount = doc1.createElement("amount") tax.appendChild(tax_amount) ptext = doc1.createTextNode(self._clean_string(dic.get("tax_amount"))) tax_amount.appendChild(ptext) tax_name = doc1.createElement("name") tax.appendChild(tax_name) ptext = doc1.createTextNode(self._clean_string(dic.get("tax_name"))) tax_name.appendChild(ptext) tax_description = doc1.createElement("description") tax.appendChild(tax_description) ptext = doc1.createTextNode(self._clean_string(dic.get("tax_description"))) tax_description.appendChild(ptext) if "shipping_amount" in KEYS: shipping = doc1.createElement("shipping") transaction_type.appendChild(shipping) shipping_amount = doc1.createElement("amount") tax.appendChild(shipping_amount) ptext = doc1.createTextNode(self._clean_string(dic.get("shipping_amount"))) shipping_amount.appendChild(ptext) shipping_name = doc1.createElement("name") tax.appendChild(shipping_name) ptext = doc1.createTextNode(self._clean_string(dic.get("shipping_name"))) shipping_name.appendChild(ptext) shipping_description = doc1.createElement("description") tax.appendChild(shipping_description) ptext = doc1.createTextNode(self._clean_string(dic.get("shipping_description"))) shipping_description.appendChild(ptext) if "duty_amount" in KEYS: duty = doc1.createElement("duty") transaction_type.appendChild(duty) duty_amount = doc1.createElement("amount") tax.appendChild(duty_amount) ptext = doc1.createTextNode(self._clean_string(dic.get("duty_amount"))) duty_amount.appendChild(ptext) duty_name = doc1.createElement("name") tax.appendChild(duty_name) ptext = doc1.createTextNode(self._clean_string(dic.get("duty_name"))) duty_name.appendChild(ptext) duty_description = doc1.createElement("description") tax.appendChild(duty_description) ptext = doc1.createTextNode(self._clean_string(dic.get("duty_description"))) duty_description.appendChild(ptext) if "items" in KEYS and len(profile_dictionary["items"]) > 0: for i in range(0, len(profile_dictionary["items"])): lineItems = doc1.createElement("lineItems") transaction_type.appendChild(lineItems) if "itemId" in profile_dictionary["items"][i].keys(): itemId = doc1.createElement("itemId") lineItems.appendChild(itemId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["items"][0]["itemId"])) itemId.appendChild(ptext) if "name" in profile_dictionary["items"][i].keys(): name = doc1.createElement("name") lineItems.appendChild(name) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["items"][0]["name"])) name.appendChild(ptext) if "description" in profile_dictionary["items"][i].keys(): description = doc1.createElement("description") lineItems.appendChild(description) ptext = doc1.createTextNode( self._clean_string(profile_dictionary["items"][0]["description"]) ) description.appendChild(ptext) if "quantity" in profile_dictionary["items"][i].keys(): quantity = doc1.createElement("quantity") lineItems.appendChild(quantity) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["items"][0]["quantity"])) quantity.appendChild(ptext) if "unitPrice" in profile_dictionary["items"][i].keys(): unitPrice = doc1.createElement("unitPrice") lineItems.appendChild(unitPrice) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["items"][0]["unitPrice"])) unitPrice.appendChild(ptext) if "taxable" in profile_dictionary["items"][i].keys(): taxable = doc1.createElement("taxable") lineItems.appendChild(taxable) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["items"][0]["taxable"])) taxable.appendChild(ptext) if "customerProfileId" in KEYS: customerProfileId = doc1.createElement("customerProfileId") transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerProfileId"])) customerProfileId.appendChild(ptext) if "customerPaymentProfileId" in KEYS: customerProfileId = doc1.createElement("customerPaymentProfileId") transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerPaymentProfileId"])) customerProfileId.appendChild(ptext) if "customerShippingAddressId" in KEYS: customerShippingAddressId = doc1.createElement("customerShippingAddressId") transaction_type.appendChild(customerShippingAddressId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerShippingAddressId"])) customerShippingAddressId.appendChild(ptext) if transaction_type_tagname == "profileTransCaptureOnly": approvalCode = doc1.createElement("approvalCode") transaction_type.appendChild(approvalCode) ptext = doc1.createTextNode("000000") approvalCode.appendChild(ptext) if ( transaction_type_tagname == "profileTransPriorAuthCapture" or transaction_type_tagname == "profileTransRefund" ): transId = doc1.createElement("transId") transaction_type.appendChild(transId) if "transId" in KEYS: ptext = doc1.createTextNode(self._clean_string(profile_dictionary["transId"])) transId.appendChild(ptext) if transaction_type_tagname == "profileTransRefund": if "creditCardNumberMasked" in KEYS: creditCardNumberMasked = doc1.createElement("creditCardNumberMasked") transaction_type.appendChild(creditCardNumberMasked) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["creditCardNumberMasked"])) creditCardNumberMasked.appendChild(ptext) elif profile_dictionary.get("trans_type") == "Void": transaction_type_tagname = "profileTrans" + profile_dictionary.get("trans_type") transaction_type = doc1.createElement(transaction_type_tagname) transaction.appendChild(transaction_type) if "customerProfileId" in KEYS: customerProfileId = doc1.createElement("customerProfileId") transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerProfileId"])) customerProfileId.appendChild(ptext) if "customerPaymentProfileId" in KEYS: customerProfileId = doc1.createElement("customerPaymentProfileId") transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerPaymentProfileId"])) customerProfileId.appendChild(ptext) if "customerShippingAddressId" in KEYS: customerShippingAddressId = doc1.createElement("customerShippingAddressId") transaction_type.appendChild(customerShippingAddressId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["customerShippingAddressId"])) customerShippingAddressId.appendChild(ptext) if "transId" in KEYS: transId = doc1.createElement("transId") transaction_type.appendChild(transId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary["transId"])) transId.appendChild(ptext) if "extraOptions" in KEYS: extraOptions = doc1.createElement("extraOptions") createCustomerProfileTransactionRequest.appendChild(extraOptions) Request_string = xml = doc1.toxml(encoding="utf-8") create_transaction_response_xml = self.request_to_server(Request_string, url, url_path) create_transaction_response_dictionary = xml2dic.main(create_transaction_response_xml) parent_resultCode = self.search_dic(create_transaction_response_dictionary, "resultCode") if parent_resultCode: if parent_resultCode["resultCode"] == "Ok": parent_directResponse = self.search_dic(create_transaction_response_dictionary, "directResponse") li = parent_directResponse["directResponse"].split(",") li[6] ##Transaction ID li[4] ##Authorization code return li[6] ret = {} Error_Code_dic = self.search_dic(create_transaction_response_dictionary, "code") if Error_Code_dic.get("code"): ret["Error_Code"] = Error_Code_dic["code"] Error_message_dic = self.search_dic(create_transaction_response_dictionary, "text") if Error_message_dic.get("text"): ret["Error_Message"] = Error_message_dic["text"] return ret
def createCustomerProfileTransactionRequest(self, dic): ''' Creates the xml for TransactionRequest and returns the transaction id ''' profile_dictionary = dic KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) trans_type_list = ['AuthOnly', 'PriorAuthCapture', 'Refund'] createCustomerProfileTransactionRequest = doc1.createElement("createCustomerProfileTransactionRequest") createCustomerProfileTransactionRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerProfileTransactionRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerProfileTransactionRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) transaction = doc1.createElement("transaction") createCustomerProfileTransactionRequest.appendChild(transaction) if 'trans_type' in KEYS : if profile_dictionary.get('trans_type', False) in trans_type_list: transaction_type_tagname = 'profileTrans' + profile_dictionary.get('trans_type', False) transaction_type = doc1.createElement(transaction_type_tagname) transaction.appendChild(transaction_type) if 'amount' in KEYS : amount = doc1.createElement('amount') transaction_type.appendChild(amount) ptext = doc1.createTextNode(self._clean_string(dic['amount'])) amount.appendChild(ptext) if 'tax_amount' in KEYS : tax = doc1.createElement('tax') transaction_type.appendChild(tax) tax_amount = doc1.createElement('amount') tax.appendChild(tax_amount) ptext = doc1.createTextNode(self._clean_string(dic['tax_amount'])) tax_amount.appendChild(ptext) tax_name = doc1.createElement('name') tax.appendChild(tax_name) ptext = doc1.createTextNode(self._clean_string(dic['tax_name'])) tax_name.appendChild(ptext) tax_description = doc1.createElement('description') tax.appendChild(tax_description) ptext = doc1.createTextNode(self._clean_string(dic['tax_description'])) tax_description.appendChild(ptext) if 'shipping_amount' in KEYS : shipping = doc1.createElement('shipping') transaction_type.appendChild(shipping) shipping_amount = doc1.createElement('amount') tax.appendChild(shipping_amount) ptext = doc1.createTextNode(self._clean_string(dic['shipping_amount'])) shipping_amount.appendChild(ptext) shipping_name = doc1.createElement('name') tax.appendChild(shipping_name) ptext = doc1.createTextNode(self._clean_string(dic['shipping_name'])) shipping_name.appendChild(ptext) shipping_description = doc1.createElement('description') tax.appendChild(shipping_description) ptext = doc1.createTextNode(self._clean_string(dic['shipping_description'])) shipping_description.appendChild(ptext) if 'duty_amount' in KEYS : duty = doc1.createElement('duty') transaction_type.appendChild(duty) duty_amount = doc1.createElement('amount') tax.appendChild(duty_amount) ptext = doc1.createTextNode(self._clean_string(dic['duty_amount'])) duty_amount.appendChild(ptext) duty_name = doc1.createElement('name') tax.appendChild(duty_name) ptext = doc1.createTextNode(self._clean_string(dic['duty_name'])) duty_name.appendChild(ptext) duty_description = doc1.createElement('description') tax.appendChild(duty_description) ptext = doc1.createTextNode(self._clean_string(dic['duty_description'])) duty_description.appendChild(ptext) if 'items'in KEYS and len(profile_dictionary.get('items')) > 0: for i in range(0, len(profile_dictionary.get('items'))): lineItems = doc1.createElement('lineItems') transaction_type.appendChild(lineItems) if 'itemId' in profile_dictionary['items'][i].keys(): itemId = doc1.createElement('itemId') lineItems.appendChild(itemId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['itemId'])) itemId.appendChild(ptext) if 'name' in profile_dictionary['items'][i].keys(): name = doc1.createElement('name') lineItems.appendChild(name) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['name'])) name.appendChild(ptext) if 'description' in profile_dictionary['items'][i].keys(): description = doc1.createElement('description') lineItems.appendChild(description) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['description'])) description.appendChild(ptext) if 'quantity' in profile_dictionary['items'][i].keys(): quantity = doc1.createElement('quantity') lineItems.appendChild(quantity) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['quantity'])) quantity.appendChild(ptext) if 'unitPrice' in profile_dictionary['items'][i].keys(): unitPrice = doc1.createElement('unitPrice') lineItems.appendChild(unitPrice) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['unitPrice'])) unitPrice.appendChild(ptext) if 'taxable' in profile_dictionary['items'][i].keys(): taxable = doc1.createElement('taxable') lineItems.appendChild(taxable) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['items'][0]['taxable'])) taxable.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement('customerProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerProfileId = doc1.createElement('customerPaymentProfileId') transaction_type.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerPaymentProfileId'])) customerProfileId.appendChild(ptext) if 'customerShippingAddressId' in KEYS: customerShippingAddressId = doc1.createElement('customerShippingAddressId') transaction_type.appendChild(customerShippingAddressId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['customerShippingAddressId'])) customerShippingAddressId.appendChild(ptext) if transaction_type_tagname in ['profileTransRefund', 'profileTransPriorAuthCapture']: if 'transId' in KEYS: transId = doc1.createElement('transId') transaction_type.appendChild(transId) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['transId'])) transId.appendChild(ptext) if 'creditCardNumberMasked' in KEYS: creditCardNumberMasked = doc1.createElement('creditCardNumberMasked') transaction_type.appendChild(creditCardNumberMasked) ptext = doc1.createTextNode(self._clean_string(profile_dictionary['creditCardNumberMasked'])) creditCardNumberMasked.appendChild(ptext) Request_string = xml = doc1.toxml(encoding="utf-8") create_transaction_response_xml = self.request_to_server(Request_string, url, url_path) create_transaction_response_dictionary = xml2dic.main(create_transaction_response_xml) parent_resultCode = self.search_dic(create_transaction_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_directResponse = self.search_dic(create_transaction_response_dictionary, 'directResponse') li = parent_directResponse['directResponse'].split(',') li[6]##Transaction ID li[4]##Authorization code return li ret = {} Error_Code_dic = self.search_dic(create_transaction_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(create_transaction_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret
def getCustomerPaymentProfileRequest(self, dic): profile_dictionary = dic KEYS = dic.keys() Payment_Profile_Details = {} doc1 = Document() url_path = dic.get('url_extension') url = dic.get('url') xsd = dic.get('xsd') getCustomerPaymentProfileRequest = doc1.createElement( "getCustomerPaymentProfileRequest") getCustomerPaymentProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(getCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") getCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode( self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode( self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) customerProfileId = doc1.createElement("customerProfileId") getCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode( self._clean_string(self._clean_string(dic['customerProfileId']))) customerProfileId.appendChild(ptext) customerPaymentProfileId = doc1.createElement( "customerPaymentProfileId") getCustomerPaymentProfileRequest.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode( self._clean_string( self._clean_string(dic['customerPaymentProfileId']))) customerPaymentProfileId.appendChild(ptext) Request_string = xml = doc1.toxml(encoding="utf-8") get_transaction_response_xml = self.request_to_server( Request_string, url, url_path) get_PaymentProfile_response_dictionary = xml2dic.main( get_transaction_response_xml) parent_card_number = self.search_dic( get_PaymentProfile_response_dictionary, 'cardNumber') parent_exp_date = self.search_dic( get_PaymentProfile_response_dictionary, 'expirationDate') if parent_card_number.get('cardNumber'): Payment_Profile_Details['cc_number'] = parent_card_number[ 'cardNumber'] if parent_exp_date.get('expirationDate'): Payment_Profile_Details['cc_ed_year'] = parent_exp_date[ 'expirationDate'] if parent_exp_date.get('cardCode'): Payment_Profile_Details['cardCode'] = parent_exp_date['cardCode'] return Payment_Profile_Details
creditCard.appendChild(bankAccount) ptext = doc1.createTextNode(self._clean_string(dic['bankAccount'])) bankAccount .appendChild(ptext) if 'validationMode' in KEYS: validationMode = doc1.createElement("validationMode") createCustomerPaymentProfileRequest.appendChild(validationMode) <<<<<<< HEAD ======= >>>>>>> c1979f64b3360c86d60e00c92be0271d89f97f2d ret = {} Request_string = xml = doc1.toxml(encoding="utf-8") create_CustomerPaymentProfile_response_xml = self.request_to_server(Request_string, url, url_path) create_CustomerPaymentProfile_response_dictionary = xml2dic.main(create_CustomerPaymentProfile_response_xml) parent_resultCode = self.search_dic(create_CustomerPaymentProfile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_customerPaymentProfileId = self.search_dic(create_CustomerPaymentProfile_response_dictionary, 'customerPaymentProfileId') return parent_customerPaymentProfileId['customerPaymentProfileId'] else: ret = {} Error_Code_dic = self.search_dic(create_CustomerPaymentProfile_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(create_CustomerPaymentProfile_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return ret
def address_validation(self,cr, uid, address_id, context={}): """ This function is called from the wizard.Performs the actual computing in address validation """ status="True" error_msg="" ups_ids=self.pool.get('ups.account').search(cr, uid,[('ups_active',"=",True)]) if ups_ids and address_id: ups_account = self.pool.get('ups.account').browse(cr, uid, ups_ids[0], context=context) if type(address_id) is list or type(address_id) is tuple: address_id=address_id[0] address = self.pool.get('res.partner').browse(cr, uid, address_id, context=context) data_for_Access_Request={ 'AccessLicenseNumber':ups_account.accesslicensenumber, 'UserId':ups_account.userid, 'Password':ups_account.password } data_for_Address_Validation_Request={ 'Request':{ 'Transaction Reference':{ 'CustomerContext':"", 'XpciVersion':"1.0001", 'ToolVersion':"", }, 'RequestAction':"XAV", 'RequestOption':"3", }, 'RegionalRequestIndicator':"", 'MaximumListSize':str(ups_account.max_lim_size), 'AddressKeyFormat':{ 'ConsigneeName':address.name or "", 'BuildingName':"", 'AddressLine1':str(address.street or ""), 'AddressLine2':str(address.street2 or ""), 'Region':"", 'PoliticalDivision2':str(address.city or ""), 'PoliticalDivision1':str(address.state_id and address.state_id.code), 'PostcodePrimaryLow':str(address.zip or ""), 'PostcodeExtendedLow':"", 'Urbanization':"", 'CountryCode':"US" } } Request_string=self._create_Address_Validation_Request_xml(cr, uid, data_for_Address_Validation_Request,data_for_Access_Request) response_string=self._create_https_connecetion(cr,uid,ups_account.url,Request_string) if response_string == 'Connection failed': addr_status=False error_msg='Connection to server failed' ret_list=[] else: response_dic=xml2dic.main(response_string) response=response_dic['AddressValidationResponse'][0]['Response'] ret_list=[] street1="" street2="" city="" state="" zip="" country_code="" status_description = '' for i in range(3,16): if len(response_dic['AddressValidationResponse']) > i and response_dic['AddressValidationResponse'][i] : classification = str(response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][0]['AddressClassification'][0]['Code']) j=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].get('AddressLine'): street1=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['AddressLine'] j+=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].has_key('AddressLine'): street2=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['AddressLine'] j+=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].has_key('Region'): street2=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['Region'] j+=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].has_key('PoliticalDivision2'): city=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['PoliticalDivision2'] j+=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].has_key('PoliticalDivision1'): state=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['PoliticalDivision1'] j+=1 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].get('PostcodePrimaryLow'): zip=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['PostcodePrimaryLow'] j+=2 if response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j].get('CountryCode'): country_code=response_dic['AddressValidationResponse'][i]['AddressKeyFormat'][j]['CountryCode'] addr_dict = { 'street1':street1, 'city':city, 'state':state, 'zip':zip, 'classification' : classification } if addr_dict not in ret_list and (addr_dict['street1'] or addr_dict['city'] or addr_dict['state'] or addr_dict['zip']): ret_list.append(addr_dict) response_status=response_dic['AddressValidationResponse'][0]['Response'][1]['ResponseStatusCode'] if response_status == '1': if ret_list: if (len(ret_list) == 1) and (ret_list[0].get('street1','').upper() == str(address.street).upper()): error_msg="Success:The address is valid" else: error_msg="Please review the suggested address." addr_status = True else: error_msg="Success:No match found" addr_status = False elif response_status == '0': addr_status=False error_msg=response_dic['AddressValidationResponse'][0]['Response'][3]['Error'][2]['ErrorDescription'] if response_dic['AddressValidationResponse'][0]['Response'][1]['ResponseStatusCode'] == '0': error_msg = 'Error : '+ error_msg vals = {'addr_status':addr_status, 'error_msg':error_msg, 'address_list':ret_list} return vals else: raise osv.except_osv(_('Warning !'), _('Address validation is not set up.')) return []
def get_rate(self): ids = self._ids context = self._context data = self.browse(self._ids) if not (data['rate_selection'] == 'rate_request' and data['ship_company_code'] == 'usps'): return super(shipping_rate_wizard, self).get_rate() if context.get('active_model', False) == 'sale.order': sale_id = context.get('active_id', False) sale = self.env['sale.order'].browse(sale_id) test = data.logis_company.test_mode or False url = '' url_sec = '' if data.logis_company: url = test and data.logis_company.usps_url_test or data.logis_company.usps_url url_sec = test and data.logis_company.usps_url_secure_test or data.logis_company.usps_url_secure url_prd = data.logis_company.usps_url address_from = sale.company_id.partner_id and sale.company_id.partner_id zip_origin = '' if address_from: zip_origin = address_from.zip or '' zip_destination = sale.partner_shipping_id.zip or '' weight = math.modf(sale.total_weight_net) pounds = int(weight[1]) ounces = round(weight[0], 2) * 16 request_xml = """<RateV4Request USERID="%(user_id)s"> <Revision/> <Package ID="1ST"> <Service>%(service_type)s</Service> <FirstClassMailType>%(first_class_mail_type)s</FirstClassMailType> <ZipOrigination>%(zip_origin)s</ZipOrigination> <ZipDestination>%(zip_desitination)s</ZipDestination> <Pounds>%(pounds)s</Pounds> <Ounces>%(ounces)s</Ounces> <Container>%(container)s</Container> <Size>REGULAR</Size> <Machinable>true</Machinable> </Package> </RateV4Request>""" % { 'user_id': data.logis_company and data.logis_company.usps_userid, 'service_type': data.usps_service_type, 'first_class_mail_type': data.usps_first_class_mail_type, 'zip_origin': zip_origin, 'zip_desitination': zip_destination, 'pounds': str(pounds), 'ounces': str(ounces), 'container': str(data.usps_container), } if url_prd and request_xml: request_url = url_prd + '?API=RateV4&XML=' + request_xml # not supported with test accounts str_response = '' error = False try: f = urllib.urlopen(request_url) str_response = f.read() except Exception, e: self.write({'status_message': str(e)}) if str_response: xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): if 'Description' in item: self.write({ 'status_message': 'Error : ' + item['Description'] }) else: for pack in xml_dic['RateV4Response']: if 'Package' in pack: for item in pack['Package']: if 'Error' in item: error = True for i in item['Error']: if 'Description' in i: self.write({ 'status_message': 'Error : ' + i['Description'] }) break if error: break if error: break if not error: for pack in xml_dic['RateV4Response']: if 'Package' in pack: for item in pack['Package']: if 'Postage' in item: for i in item['Postage']: if 'Rate' in i: self.write( [data.id], { 'status_message': '', 'shipping_cost': i['Rate'] }) sale.write({ 'shipcharge': float(i['Rate']) or 0.00, 'ship_method': data.ship_company_code + ':' + data.usps_service_type, 'status_message': '' }) return True
def process_ship(self, cr, uid, ids, context=None): quick_ship_id = self.browse(cr, uid, ids[0], context=context) data_for_Access_Request = { 'AccessLicenseNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.access_license or '', 'UserId': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.userid or '', 'Password': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.password or '' } data_for_confirm_request = { 'ShipmentConfirmRequest': { 'Request': { 'RequestAction': "ShipConfirm", 'RequestOption': "nonvalidate", 'TransactionReference': {'CustomerContext': "",},#---------optional data },#Request 'Shipment': { 'Description': quick_ship_id.description or "Shipping", 'ReturnService': {'Code': "8", 'DocumentsOnly':"" }, 'Shipper': { 'Name': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.name or "", 'AttentionName': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.atten_name or "", 'ShipperNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.acc_no or "", 'TaxIdentificationNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.tax_id_no or "", 'PhoneNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.phone or "", 'FaxNumber': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.fax or "", 'EMailAddress': quick_ship_id.ups_shipper_id.id and quick_ship_id.ups_shipper_id.address and quick_ship_id.ups_shipper_id.address.email or "", 'Address': self.fill_addr(quick_ship_id.ups_shipper_id and quick_ship_id.ups_shipper_id.address or '') },#Shipper 'ShipTo': { 'CompanyName': quick_ship_id.address_id and quick_ship_id.address_id.name or '', 'AttentionName': "", 'TaxIdentificationNumber': "", 'PhoneNumber': "", 'FaxNumber': quick_ship_id.address_id.id and quick_ship_id.address_id.fax or '', 'EMailAddress': quick_ship_id.address_id.id and quick_ship_id.address_id.email or '', 'Address': self.fill_addr(quick_ship_id.address_id.id and quick_ship_id.address_id), 'LocationID': "", },#ShipTo 'ShipFrom': { 'CompanyName': quick_ship_id.send_addr.company_id and quick_ship_id.send_addr.company_id.name or '', 'AttentionName': quick_ship_id.send_addr.name or "", 'TaxIdentificationNumber': '', 'PhoneNumber': quick_ship_id.send_addr.id and quick_ship_id.send_addr.phone or '', 'FaxNumber': quick_ship_id.send_addr.id and quick_ship_id.send_addr.fax or '', 'Address': self.fill_addr(quick_ship_id.send_addr.id and quick_ship_id.send_addr or ''), }, 'PaymentInformation': { 'Prepaid': { 'BillShipper': {'AccountNumber': quick_ship_id.ups_shipper_id and quick_ship_id.ups_shipper_id.acc_no or ""},#BillShipper },#Prepaid },#PaymentInformation, 'GoodsNotInFreeCirculationIndicator': "", 'RateInformation': {'NegotiatedRatesIndicator': ""},#RateInformation 'Service': { 'Code': quick_ship_id.ups_service_id.id and str(quick_ship_id.ups_service_id.shipping_service_code) or "", 'Description': quick_ship_id.ups_service_id.id and quick_ship_id.ups_service_id.description or ""},#Service 'InvoiceLineTotal': {'CurrencyCode': "", 'MonetaryValue': str(quick_ship_id.amount) or ""},#InvoiceLineTotal 'Package': self.get_package(quick_ship_id) },#Shipment 'LabelSpecification': { 'LabelPrintMethod': {'Code': "GIF", 'Description': "GIF"}, 'HTTPUserAgent': "", 'LabelStockSize': {'Height': "4", 'Width': "6"}, 'LabelImageFormat': {'Code': "GIF", 'Description': "GIF"}, },#LabelSpecification },#ShipmentConfirmRequest } doc1 = Document() AccessRequest = doc1.createElement("AccessRequest") AccessRequest.setAttribute("xml:lang", "en-US") doc1.appendChild(AccessRequest) AccessLicenseNumber = doc1.createElement("AccessLicenseNumber") ptext = doc1.createTextNode(data_for_Access_Request["AccessLicenseNumber"]) AccessLicenseNumber.appendChild(ptext) AccessRequest.appendChild(AccessLicenseNumber) UserId = doc1.createElement("UserId") ptext = doc1.createTextNode(data_for_Access_Request["UserId"]) UserId.appendChild(ptext) AccessRequest.appendChild(UserId) Password = doc1.createElement("Password") ptext = doc1.createTextNode(data_for_Access_Request["Password"]) Password.appendChild(ptext) AccessRequest.appendChild(Password) Request_string1 = doc1.toprettyxml() ######SECOND PART Package_count = 0#max value =200 doc2 = Document() ShipmentConfirmRequest = doc2.createElement("ShipmentConfirmRequest") doc2.appendChild(ShipmentConfirmRequest) Request = doc2.createElement("Request") ShipmentConfirmRequest.appendChild(Request) RequestAction = doc2.createElement("RequestAction") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestAction"]) RequestAction.appendChild(ptext) Request.appendChild(RequestAction) RequestOption = doc2.createElement("RequestOption") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["RequestOption"]) RequestOption.appendChild(ptext) Request.appendChild(RequestOption) TransactionReference = doc2.createElement("TransactionReference") Request.appendChild(TransactionReference) CustomerContext = doc2.createElement("CustomerContext") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Request"]["TransactionReference"]['CustomerContext']) CustomerContext.appendChild(ptext) TransactionReference.appendChild(CustomerContext) Shipment = doc2.createElement("Shipment") ShipmentConfirmRequest.appendChild(Shipment) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Description"]) Description.appendChild(ptext) Shipment.appendChild(Description) if 0:#quick_ship_id.with_ret_service: ReturnService = doc2.createElement("ReturnService") Shipment.appendChild(ReturnService) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ReturnService"]["Code"]) Code.appendChild(ptext) ReturnService.appendChild(Code) Shipper = doc2.createElement("Shipper") Shipment.appendChild(Shipper) Name = doc2.createElement("Name") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Name"]) Name.appendChild(ptext) Shipper.appendChild(Name) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["AttentionName"]) AttentionName.appendChild(ptext) Shipper.appendChild(AttentionName) ShipperNumber = doc2.createElement("ShipperNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["ShipperNumber"]) ShipperNumber.appendChild(ptext) Shipper.appendChild(ShipperNumber) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) Shipper.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) Shipper.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["FaxNumber"]) FaxNumber.appendChild(ptext) Shipper.appendChild(FaxNumber) EMailAddress = doc2.createElement("EMailAddress") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["EMailAddress"]) EMailAddress.appendChild(ptext) Shipper.appendChild(EMailAddress) # Address Address = doc2.createElement("Address") Shipper.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine3 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Shipper"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) ShipTo = doc2.createElement("ShipTo") Shipment.appendChild(ShipTo) CompanyName = doc2.createElement("CompanyName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["CompanyName"]) CompanyName.appendChild(ptext) ShipTo.appendChild(CompanyName) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["AttentionName"]) AttentionName.appendChild(ptext) ShipTo.appendChild(AttentionName) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) ShipTo.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) ShipTo.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["FaxNumber"]) FaxNumber.appendChild(ptext) ShipTo.appendChild(FaxNumber) EMailAddress = doc2.createElement("EMailAddress") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["EMailAddress"]) EMailAddress.appendChild(ptext) ShipTo.appendChild(EMailAddress) LocationID = doc2.createElement("LocationID") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["LocationID"]) LocationID.appendChild(ptext) ShipTo.appendChild(LocationID) Address = doc2.createElement("Address") ShipTo.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine2 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipTo"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) ShipFrom = doc2.createElement("ShipFrom") Shipment.appendChild(ShipFrom) CompanyName = doc2.createElement("CompanyName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["CompanyName"]) CompanyName.appendChild(ptext) ShipFrom.appendChild(CompanyName) AttentionName = doc2.createElement("AttentionName") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["AttentionName"]) AttentionName.appendChild(ptext) ShipFrom.appendChild(AttentionName) TaxIdentificationNumber = doc2.createElement("TaxIdentificationNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["TaxIdentificationNumber"]) TaxIdentificationNumber.appendChild(ptext) ShipFrom.appendChild(TaxIdentificationNumber) PhoneNumber = doc2.createElement("PhoneNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["PhoneNumber"]) PhoneNumber.appendChild(ptext) ShipFrom.appendChild(PhoneNumber) FaxNumber = doc2.createElement("FaxNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["FaxNumber"]) FaxNumber.appendChild(ptext) ShipFrom.appendChild(FaxNumber) Address = doc2.createElement("Address") ShipFrom.appendChild(Address) AddressLine1 = doc2.createElement("AddressLine1") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine1"]) AddressLine1.appendChild(ptext) Address.appendChild(AddressLine1) AddressLine2 = doc2.createElement("AddressLine2") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine2"]) AddressLine2.appendChild(ptext) Address.appendChild(AddressLine2) AddressLine3 = doc2.createElement("AddressLine3") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["AddressLine3"]) AddressLine3.appendChild(ptext) Address.appendChild(AddressLine3) City = doc2.createElement("City") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["City"]) City.appendChild(ptext) Address.appendChild(City) StateProvinceCode = doc2.createElement("StateProvinceCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["StateProvinceCode"]) StateProvinceCode.appendChild(ptext) Address.appendChild(StateProvinceCode) PostalCode = doc2.createElement("PostalCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["PostalCode"]) PostalCode.appendChild(ptext) Address.appendChild(PostalCode) CountryCode = doc2.createElement("CountryCode") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["ShipFrom"]["Address"]["CountryCode"]) CountryCode.appendChild(ptext) Address.appendChild(CountryCode) PaymentInformation = doc2.createElement("PaymentInformation") Shipment.appendChild(PaymentInformation) Prepaid = doc2.createElement("Prepaid") PaymentInformation.appendChild(Prepaid) BillShipper = doc2.createElement("BillShipper") Prepaid.appendChild(BillShipper) AccountNumber = doc2.createElement("AccountNumber") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["PaymentInformation"]["Prepaid"]\ ["BillShipper"]["AccountNumber"]) AccountNumber.appendChild(ptext) BillShipper.appendChild(AccountNumber) GoodsNotInFreeCirculationIndicator = doc2.createElement("GoodsNotInFreeCirculationIndicator") Shipment.appendChild(GoodsNotInFreeCirculationIndicator) RateInformation = doc2.createElement("RateInformation") Shipment.appendChild(RateInformation) NegotiatedRatesIndicator = doc2.createElement("NegotiatedRatesIndicator") RateInformation.appendChild(NegotiatedRatesIndicator) Service = doc2.createElement("Service") Shipment.appendChild(Service) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Code"]) Code.appendChild(ptext) Service.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Service"]["Description"]) Description.appendChild(ptext) Service.appendChild(Description) if (quick_ship_id.send_addr.id and quick_ship_id.send_addr.country_id.code == 'US') and quick_ship_id.address_id.id and \ quick_ship_id.address_id.country_id.code in ('PR', 'CA'): InvoiceLineTotal = doc2.createElement("InvoiceLineTotal") Shipment.appendChild(InvoiceLineTotal) MonetaryValue = doc2.createElement("MonetaryValue") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["InvoiceLineTotal"]["MonetaryValue"]) MonetaryValue.appendChild(ptext) InvoiceLineTotal.appendChild(MonetaryValue) Package_count = len(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"]) for i in range(0,Package_count): Package = doc2.createElement("Package") Shipment.appendChild(Package) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Description"]) Description.appendChild(ptext) Package.appendChild(Description) PackagingType = doc2.createElement("PackagingType") Package.appendChild(PackagingType) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]["Code"]) Code.appendChild(ptext) PackagingType.appendChild(Code) # Description = doc2.createElement("Description") # # ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["PackagingType"]["Description"]) # Description.appendChild(ptext) # PackagingType.appendChild(Description) Dimensions = doc2.createElement("Dimensions") Package.appendChild(Dimensions) Length = doc2.createElement("Length") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Length"]) Length.appendChild(ptext) Dimensions.appendChild(Length) Width = doc2.createElement("Width") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Width"]) Width.appendChild(ptext) Dimensions.appendChild(Width) Height = doc2.createElement("Height") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]["Height"]) Height.appendChild(ptext) Dimensions.appendChild(Height) UnitOfMeasurement = doc2.createElement("UnitOfMeasurement") Dimensions.appendChild(UnitOfMeasurement) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]\ ['UnitOfMeasurement']["Code"]) Code.appendChild(ptext) UnitOfMeasurement.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["Dimensions"]\ ['UnitOfMeasurement']["Description"]) Description.appendChild(ptext) UnitOfMeasurement.appendChild(Description) PackageWeight = doc2.createElement("PackageWeight") Package.appendChild(PackageWeight) UnitOfMeasurement = doc2.createElement("UnitOfMeasurement") PackageWeight.appendChild(UnitOfMeasurement) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']\ ['UnitOfMeasurement']["Code"]) Code.appendChild(ptext) UnitOfMeasurement.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']\ ['UnitOfMeasurement']["Description"]) Description.appendChild(ptext) UnitOfMeasurement.appendChild(Description) Weight = doc2.createElement("Weight") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]['PackageWeight']["Weight"]) Weight.appendChild(ptext) PackageWeight.appendChild(Weight) from_country_code = quick_ship_id.send_addr.id and quick_ship_id.send_addr.country_id.id and quick_ship_id.send_addr.country_id.code to_country_code = quick_ship_id.address_id.id and quick_ship_id.address_id.country_id.id and quick_ship_id.address_id.country_id.code if not(from_country_code == 'US' and to_country_code == 'US' or from_country_code == 'PR' and to_country_code == 'PR'): ReferenceNumber = doc2.createElement("ReferenceNumber") Package.appendChild(ReferenceNumber) BarCodeIndicator = doc2.createElement("BarCodeIndicator") ReferenceNumber.appendChild(BarCodeIndicator) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["ReferenceNumber"]["Code"]) Code.appendChild(ptext) ReferenceNumber.appendChild(Code) Value = doc2.createElement("Value") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["Shipment"]["Package"][i]["ReferenceNumber"]["Value"]) Value.appendChild(ptext) ReferenceNumber.appendChild(Value) LabelSpecification = doc2.createElement("LabelSpecification") ShipmentConfirmRequest.appendChild(LabelSpecification) LabelPrintMethod = doc2.createElement("LabelPrintMethod") LabelSpecification.appendChild(LabelPrintMethod) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Code"]) Code.appendChild(ptext) LabelPrintMethod.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelPrintMethod"]["Description"]) Description.appendChild(ptext) LabelPrintMethod.appendChild(Description) LabelStockSize = doc2.createElement("LabelStockSize") LabelSpecification.appendChild(LabelStockSize) Height = doc2.createElement("Height") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Height"]) Height.appendChild(ptext) LabelStockSize.appendChild(Height) Width = doc2.createElement("Width") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelStockSize"]["Width"]) Width.appendChild(ptext) LabelStockSize.appendChild(Width) LabelImageFormat = doc2.createElement("LabelImageFormat") LabelSpecification.appendChild(LabelImageFormat) Code = doc2.createElement("Code") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Code"]) Code.appendChild(ptext) LabelImageFormat.appendChild(Code) Description = doc2.createElement("Description") ptext = doc1.createTextNode(data_for_confirm_request["ShipmentConfirmRequest"]["LabelSpecification"]["LabelImageFormat"]["Description"]) Description.appendChild(ptext) LabelImageFormat.appendChild(Description) ret = [] serv = '' acce_port = '' serv_path = '' if quick_ship_id.logis_company.id: if quick_ship_id.logis_company.test_mode: acce_web = quick_ship_id.logis_company.ship_req_test_web or '' acce_port = quick_ship_id.logis_company.ship_req_test_port else: acce_web = quick_ship_id.logis_company.ship_req_web or '' acce_port = quick_ship_id.logis_company.ship_req_port if acce_web: parse_url = urlparse(acce_web) serv = parse_url.netloc serv_path = parse_url.path else: raise osv.except_osv(_('Unable to find Shipping URL!'),_("Please configure the shipping company with websites.") ) else: raise osv.except_osv(_('No Company Selected!'),_("Please select a logistic company.") ) request_xml = doc1.toprettyxml() + doc2.toprettyxml() conn = httplib.HTTPSConnection(serv,acce_port) res = conn.request("POST",serv_path,request_xml) res = conn.getresponse() result = res.read() response_dic = xml2dic.main(result) response = '' err_flag = False for res_elm in response_dic['ShipmentConfirmResponse'][0]['Response']: if res_elm.get('ResponseStatusCode'): response = '\nResponse Status Code: ' + str(res_elm['ResponseStatusCode']) if res_elm.get('ResponseStatusDescription'): response += '\nResponse Description: ' + str(res_elm['ResponseStatusDescription']) if res_elm.get('ResponseStatusCode', False) and str(res_elm.get('ResponseStatusCode')) != 1: if res_elm.get('Error'): err_flag = True for err_elm in res_elm.get('Error'): if err_elm.get('ErrorCode', False): response += '\nErrorCode: ' + str(err_elm['ErrorCode']) if err_elm.get('ErrorDescription', False): response += '\nErrorDescription: ' + str(err_elm['ErrorDescription']) self.write(cr, uid, ids, {'response': response}) ship_digest = "" if len(response_dic['ShipmentConfirmResponse']) > 4 and response_dic['ShipmentConfirmResponse'][4].has_key('ShipmentDigest'): ship_digest += str(response_dic['ShipmentConfirmResponse'][4]['ShipmentDigest']) ship_move_ids = [] value_dic = { 'package_weight': quick_ship_id.weight, 'state': 'in_process', 'partner_id': quick_ship_id.recipient.id, 'ups_service_id': quick_ship_id.ups_service_id.id, # 'package_weight': quick_ship_id.weight, 'ship_to': quick_ship_id.address_id.id, 'ship_from': quick_ship_id.send_addr.id, 'sale_id': quick_ship_id.saleorder_id.id and quick_ship_id.saleorder_id.id, 'ship_cost': quick_ship_id.shipcharge } ship_move_id = self.pool.get('shipping.move').create(cr, uid, value_dic) if err_flag: ret = False else: ret = {'response': response, 'ship_digest': ship_digest, 'ship_move_id': ship_move_id} return ret
def get_rate(self): ids=self._ids context=self._context data = self.browse(self._ids) if not ( data['rate_selection'] == 'rate_request' and data['ship_company_code']=='usps'): return super(shipping_rate_wizard, self).get_rate() if context.get('active_model',False) == 'sale.order': sale_id = context.get('active_id',False) sale = self.env['sale.order'].browse(sale_id) test = data.logis_company.test_mode or False url = '' url_sec = '' if data.logis_company: url = test and data.logis_company.usps_url_test or data.logis_company.usps_url url_sec = test and data.logis_company.usps_url_secure_test or data.logis_company.usps_url_secure url_prd = data.logis_company.usps_url address_from = sale.company_id.partner_id and sale.company_id.partner_id zip_origin = '' if address_from: zip_origin = address_from.zip or '' zip_destination=sale.partner_shipping_id.zip or '' weight = math.modf(sale.total_weight_net) pounds = int(weight[1]) ounces = round(weight[0],2) * 16 request_xml = """<RateV4Request USERID="%(user_id)s"> <Revision/> <Package ID="1ST"> <Service>%(service_type)s</Service> <FirstClassMailType>%(first_class_mail_type)s</FirstClassMailType> <ZipOrigination>%(zip_origin)s</ZipOrigination> <ZipDestination>%(zip_desitination)s</ZipDestination> <Pounds>%(pounds)s</Pounds> <Ounces>%(ounces)s</Ounces> <Container>%(container)s</Container> <Size>REGULAR</Size> <Machinable>true</Machinable> </Package> </RateV4Request>"""%{ 'user_id' : data.logis_company and data.logis_company.usps_userid, 'service_type' : data.usps_service_type , 'first_class_mail_type' : data.usps_first_class_mail_type, 'zip_origin' : zip_origin, 'zip_desitination' : zip_destination, 'pounds' : str(pounds), 'ounces' : str(ounces), 'container' : str(data.usps_container) , } if url_prd and request_xml: request_url = url_prd + '?API=RateV4&XML=' + request_xml # not supported with test accounts str_response = '' error = False try : f = urllib.urlopen(request_url) str_response = f.read() except Exception, e: self.write({'status_message': str(e)}) if str_response: xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): if 'Description' in item: self.write({'status_message': 'Error : ' + item['Description'] }) else: for pack in xml_dic['RateV4Response']: if 'Package' in pack: for item in pack['Package']: if 'Error' in item: error = True for i in item['Error']: if 'Description' in i: self.write({'status_message': 'Error : ' + i['Description'] }) break if error: break if error: break if not error: for pack in xml_dic['RateV4Response']: if 'Package' in pack: for item in pack['Package']: if 'Postage' in item: for i in item['Postage']: if 'Rate' in i: self.write([data.id], {'status_message': '', 'shipping_cost': i['Rate'] }) sale.write({'shipcharge': float(i['Rate']) or 0.00, 'ship_method':data.ship_company_code + ':' + data.usps_service_type, 'status_message': ''}) return True
def process_ship(self): ids=self._ids do = self.browse(type(ids) == type([]) and ids[0] or ids) user = self.env['res.users'].browse(self._ids) if do.ship_company_code != 'usps': return super(stock_picking, self).process_ship() if not (do.logis_company and do.logis_company.ship_company_code == 'usps'): return super(stock_picking, self).process_ship() userid = do.logis_company.usps_userid url = do.logis_company.test_mode and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_prd = do.logis_company.usps_url url_prd_secure = do.logis_company.usps_url_secure test = do.logis_company.test_mode str_error = '' ship_message = '' error = False for package in do.packages_ids: str_error = '' # if do.packages_ids: # @Changing to production URL SINCE DelivConfirmCertifyV3.0Request works only with production url and test data url = do.logis_company.usps_url_secure if test: request_xml = """<DelivConfirmCertifyV3.0Request USERID="%(user_id)s"> <Option>1</Option> <ImageParameters></ImageParameters> <FromName>Joe Smith</FromName> <FromFirm>ABD Corp.</FromFirm> <FromAddress1>Apt. 3C</FromAddress1> <FromAddress2>6406 Ivy Lane</FromAddress2> <FromCity>Greenbelt</FromCity> <FromState>MD</FromState> <FromZip5>20770</FromZip5> <FromZip4>1234</FromZip4> <ToName>Tom Collins</ToName> <ToFirm>XYZ Corp.</ToFirm> <ToAddress1>Suite 4D</ToAddress1> <ToAddress2>8 Wildwood Drive</ToAddress2> <ToCity>Old Lyme</ToCity> <ToState>CT</ToState> <ToZip5>06371</ToZip5> <ToZip4></ToZip4> <WeightInOunces>1</WeightInOunces> <ServiceType>Priority</ServiceType> <SeparateReceiptPage></SeparateReceiptPage> <POZipCode></POZipCode> <ImageType>TIF</ImageType> <LabelDate></LabelDate> <CustomerRefNo></CustomerRefNo> <AddressServiceRequested></AddressServiceRequested> <SenderName></SenderName> <SenderEMail></SenderEMail> <RecipientName></RecipientName> <RecipientEMail></RecipientEMail> </DelivConfirmCertifyV3.0Request> """ % { 'user_id' : userid, } if url and request_xml: request_url = url + '?API=DelivConfirmCertifyV3&XML=' + request_xml elif do.company_id.partner_id.address: from_address = do.company_id.partner_id.address[0] request_xml = """<DeliveryConfirmationV3.0Request USERID="%(user_id)s"> <Option>1</Option> <ImageParameters /> <FromName>%(from_name)s</FromName> <FromFirm>%(from_firm)s</FromFirm> <FromAddress1 /> <FromAddress2>%(from_address2)s</FromAddress2> <FromCity>%(from_city)s</FromCity> <FromState>%(from_state)s</FromState> <FromZip5>%(from_zip5)s</FromZip5> <FromZip4>%(from_zip4)s</FromZip4> <ToName>%(to_name)s</ToName> <ToFirm>%(to_firm)s</ToFirm> <ToAddress1>%(to_address1)s</ToAddress1> <ToAddress2>%(to_address2)s</ToAddress2> <ToCity>%(to_city)s</ToCity> <ToState>%(to_state)s</ToState> <ToZip5>%(to_zip5)s</ToZip5> <ToZip4>%(to_zip4)s</ToZip4> <WeightInOunces>%(weight)s</WeightInOunces> <ServiceType>%(service_type)s</ServiceType> <POZipCode></POZipCode> <ImageType>TIF</ImageType> <LabelDate></LabelDate> <CustomerRefNo></CustomerRefNo> <AddressServiceRequested>TRUE</AddressServiceRequested> </DeliveryConfirmationV3.0Request> """ % { 'user_id' : userid, 'from_name' : from_address.name, 'from_firm' : '', 'from_address2' : from_address.street or '', 'from_city' : from_address.city or '', 'from_state' : from_address.state_id and from_address.state_id.code or '', 'from_zip5' : from_address.zip or '', 'from_zip4' : from_address.zip or '', 'to_name' : do.address_id.name , 'to_firm' : '', 'to_address1' : do.address_id.street, 'to_address2' : do.address_id.street2, 'to_city' : do.address_id.city, 'to_state' : do.address_id.state_id and do.address_id.state_id.code or '', 'to_zip5' : do.address_id.zip or '', 'to_zip4' : do.address_id.zip, 'weight' : package.weight, 'service_type' : do.usps_service_type, } if url and request_xml: request_url = url + '?API=DeliveryConfirmationV3&XML=' + request_xml try : import urllib f = urllib.urlopen(request_url) from xml.dom.minidom import parse, parseString import xml2dic str_response = f.read() xml_response = parseString(str_response) xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): if item.get('Number'): if str_error: str_error = str_error + "\n----------------------" str_error = str_error + "\nNumber : " + item['Number'] if item.get('Description'): str_error = str_error + "\nDescription : " + item['Description'] else: confirmation_number = xml_dic['DelivConfirmCertifyV3.0Response'][0]['DeliveryConfirmationNumber'] label_data = xml_dic['DelivConfirmCertifyV3.0Response'][1]['DeliveryConfirmationLabel'] # logo = binascii.b2a_base64(str(b64decode(label_data))) # logo = str(b64decode(label_data)) logo = base64.decodestring(label_data) import os import tempfile dir_temp = tempfile.gettempdir() f = open(dir_temp + '/usps.tif', 'w+') f.write(logo) f.close() label_image = '' cp = False if os.name == 'posix' or 'nt': try: os.system("tiffcp -c none " + dir_temp + "/usps.tif " + dir_temp + "/usps_temp.tif") cp = True except Exception, e: str_error = "Please install tiffcp." if cp: im = Image.open(dir_temp + '/usps_temp.tif') im.thumbnail(im.size) im.save(dir_temp + '/usps_temp.jpg', "JPEG", quality=100) label_from_file = open(dir_temp + '/usps_temp.jpg', 'rb') label_image = base64.encodestring(label_from_file.read()) self.env['stock.packages'].write({'logo': label_image, 'tracking_no': confirmation_number, 'usps_confirmation_number': confirmation_number, 'ship_message': 'Shipment has processed'}) except Exception, e: str_error = str(e) self._cr.commit() if str_error: self.env['stock.packages'].write({'ship_message': str_error})
<<<<<<< HEAD rates_obj = self.pool.get('shipping.rates.sales') so = data.id rids = rates_obj.search(cr,uid,[('sales_id','=', so )]) rates_obj.unlink(cr, uid, rids, context) serv_obj = self.pool.get('ups.shipping.service.type') try: print rate_request from urllib2 import Request, urlopen, URLError, quote request = Request(url.encode('utf-8').strip(), rate_request.encode('utf-8').strip()) response_text = urlopen(request).read() # p.agent_info = u' '.join((agent_contact, agent_telno)).encode('utf-8').strip() print response_text response_dic = xml2dic.main(response_text) str_error = '' for response in response_dic['RatingServiceSelectionResponse'][0]['Response']: if response.get('Error'): for item in response['Error']: if item.get('ErrorDescription'): str_error = item['ErrorDescription'] self.write(cr, uid, [data.id], {'status_message': "Error : " + item['ErrorDescription'] }) if not str_error: # print response_dic amount = None ups_service_id = None # Get all the return Shipping rates as options for response in response_dic['RatingServiceSelectionResponse']:
def updateCustomerPaymentProfile(self, dic): KEYS = dic.keys() doc1 = Document() url_path = dic['url_extension'] url = dic['url'] xsd = dic['xsd'] updateCustomerPaymentProfileResponse = doc1.createElement("updateCustomerPaymentProfileRequest") updateCustomerPaymentProfileResponse.setAttribute("xmlns", xsd) doc1.appendChild(updateCustomerPaymentProfileResponse) merchantAuthentication = doc1.createElement("merchantAuthentication") updateCustomerPaymentProfileResponse.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode(self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode(self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") updateCustomerPaymentProfileResponse.appendChild(customerProfileId) ptext = doc1.createTextNode(self._clean_string(dic['customerProfileId'])) customerProfileId.appendChild(ptext) paymentProfile = doc1.createElement("paymentProfile") updateCustomerPaymentProfileResponse.appendChild(paymentProfile) if 'customerType' in KEYS: customerType = doc1.createElement("customerType") paymentProfile.appendChild(customerType) billTo = doc1.createElement("billTo") paymentProfile.appendChild(billTo) if 'firstName' in KEYS: firstName = doc1.createElement("firstName") billTo.appendChild(firstName) ptext = doc1.createTextNode(self._clean_string(dic['firstName'])) firstName.appendChild(ptext) if 'lastName' in KEYS: lastName = doc1.createElement("lastName") billTo.appendChild(lastName) ptext = doc1.createTextNode(self._clean_string(dic['lastName'])) lastName.appendChild(ptext) if 'company' in KEYS: company = doc1.createElement("company") billTo.appendChild(companycompany) ptext = doc1.createTextNode(self._clean_string(dic['company'])) company.appendChild(ptext) if 'address' in KEYS: address = doc1.createElement("address") billTo.appendChild(address) ptext = doc1.createTextNode(self._clean_string(dic['address'])) address.appendChild(ptext) ##State code must be given here if 'state' in KEYS: state = doc1.createElement("state") billTo.appendChild(state) ptext = doc1.createTextNode(self._clean_string(dic['state'])) state.appendChild(ptext) if 'city' in KEYS: city = doc1.createElement("city") billTo.appendChild(city) ptext = doc1.createTextNode(self._clean_string(dic['city'])) city.appendChild(ptext) if 'zip' in KEYS: zip = doc1.createElement("zip") billTo.appendChild(zip) ptext = doc1.createTextNode(self._clean_string(dic['zip'])) zip.appendChild(ptext) if 'country' in KEYS: country = doc1.createElement("country") billTo.appendChild(country) ptext = doc1.createTextNode(self._clean_string(dic['country'])) country.appendChild(ptext) if 'phoneNumber' in KEYS: phoneNumber = doc1.createElement("phoneNumber") billTo.appendChild(phoneNumber) ptext = doc1.createTextNode(self._clean_string(dic['phoneNumber'])) phoneNumber.appendChild(ptext) if 'faxNumber' in KEYS: faxNumber = doc1.createElement("faxNumber") billTo.appendChild(faxNumber) ptext = doc1.createTextNode(self._clean_string(dic['faxNumber'])) faxNumber.appendChild(ptext) payment = doc1.createElement("payment") paymentProfile.appendChild(payment) if 'cardNumber' in KEYS and 'expirationDate' in KEYS: creditCard = doc1.createElement("creditCard") payment.appendChild(creditCard) cardNumber = doc1.createElement("cardNumber") creditCard.appendChild(cardNumber) ptext = doc1.createTextNode(self._clean_string(dic['cardNumber'])) cardNumber.appendChild(ptext) expirationDate = doc1.createElement("expirationDate") creditCard.appendChild(expirationDate) ptext = doc1.createTextNode(dic['expirationDate']) expirationDate.appendChild(ptext) if 'cardCode' in KEYS: cardCode = doc1.createElement("cardCode") creditCard.appendChild(cardCode) ptext = doc1.createTextNode(self._clean_string(dic['cardCode'])) cardCode .appendChild(ptext) customerPaymentProfileId = doc1.createElement("customerPaymentProfileId") paymentProfile.appendChild(customerPaymentProfileId) ptext = doc1.createTextNode(self._clean_string(dic['customerPaymentProfileId'])) customerPaymentProfileId .appendChild(ptext) if 'validationMode' in KEYS: validationMode = doc1.createElement("validationMode") updateCustomerPaymentProfileResponse.appendChild(validationMode) Request_string = doc1.toxml(encoding="utf-8") update_CustomerPaymentProfile_response_xml = self.request_to_server(Request_string, url, url_path) update_CustomerPaymentProfile_response_dictionary = xml2dic.main(update_CustomerPaymentProfile_response_xml) parent_resultCode = self.search_dic(update_CustomerPaymentProfile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': return True else: ret = {} Error_Code_dic = self.search_dic(update_CustomerPaymentProfile_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic(update_CustomerPaymentProfile_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return
def deleteCustomerPaymentProfile(self, dic): KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) deleteCustomerPaymentProfileRequest = doc1.createElement( "deleteCustomerPaymentProfileRequest") deleteCustomerPaymentProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(deleteCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") deleteCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode( self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode( self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") deleteCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode( self._clean_string(dic['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerPaymentProfileId = doc1.createElement( "customerPaymentProfileId") deleteCustomerPaymentProfileRequest.appendChild( customerPaymentProfileId) ptext = doc1.createTextNode( self._clean_string(dic['customerPaymentProfileId'])) customerPaymentProfileId.appendChild(ptext) Request_string = doc1.toxml(encoding="utf-8") delete_CustomerPaymentProfile_response_xml = self.request_to_server( Request_string, url, url_path) delete_CustomerPaymentProfile_response_dictionary = xml2dic.main( delete_CustomerPaymentProfile_response_xml) parent_resultCode = self.search_dic( delete_CustomerPaymentProfile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': return True ret = {} Error_Code_dic = self.search_dic( delete_CustomerPaymentProfile_response_dictionary, 'code') if Error_Code_dic.get('code'): ret['Error_Code'] = Error_Code_dic['code'] Error_message_dic = self.search_dic( delete_CustomerPaymentProfile_response_dictionary, 'text') if Error_message_dic.get('text'): ret['Error_Message'] = Error_message_dic['text'] return ret return
def get_rate(self, cr, uid, ids, context=None): sale_obj = self.pool.get('sale.order') data = self.browse(cr, uid, ids[0], context=context) sale_obj.write(cr,uid,context.get('active_ids'),{'ups_shipper_id':data.ups_shipper_id.id, 'ups_service_id':data.ups_service_id.id, 'ups_pickup_type':data.ups_pickup_type, 'ups_packaging_type':data.ups_packaging_type.id},context=context) if context is None: context = {} if not (data['rate_selection'] == 'rate_request' and data['ship_company_code'] == 'ups'): return super(shipping_rate_wizard, self).get_rate(cr, uid, ids, context) # if context.get('active_model', False) == 'sale.order': if context.get('active_model', False) in ['sale.order', 'account.invoice'] and 'active_id' in context: if context['active_model'] == 'sale.order': sale = sale_obj.browse(cr, uid, context['active_id'], context=context) weight = sale.total_weight_net or 0.00 elif context['active_model'] == 'account.invoice': invoice = self.pool.get('account.invoice').browse(cr, uid, context['active_id'], context=context) weight = invoice.total_weight_net or 0.00 receipient_zip = data.partner_shipping_id and data.partner_shipping_id.zip or '' receipient_country_code = data.partner_shipping_id.country_id and data.partner_shipping_id.country_id.code or '' access_license_no = data.ups_shipper_id and data.ups_shipper_id.access_license or '' user_id = data.ups_shipper_id and data.ups_shipper_id.userid or '' password = data.ups_shipper_id and data.ups_shipper_id.password or '' pickup_type_ups = data.ups_pickup_type shipper_zip = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.zip or '' shipper_country_code = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.country_id and \ data.ups_shipper_id.address.country_id.code or '' ups_info_shipper_no = data.ups_shipper_id and data.ups_shipper_id.acc_no or '' service_type_ups = data.ups_service_id and data.ups_service_id.shipping_service_code or '' packaging_type_ups = data.ups_packaging_type.code test_mode = False test_mode = data.logis_company and data.logis_company.test_mode or True url = 'https://wwwcie.ups.com/ups.app/xml/Rate' or 'https://onlinetools.ups.com/ups.app/xml/Rate' rate_request = """<?xml version=\"1.0\"?> <AccessRequest xml:lang=\"en-US\"> <AccessLicenseNumber>%s</AccessLicenseNumber> <UserId>%s</UserId> <Password>%s</Password> </AccessRequest> <?xml version=\"1.0\"?> <RatingServiceSelectionRequest xml:lang=\"en-US\"> <Request> <TransactionReference> <CustomerContext>Rating and Service</CustomerContext> <XpciVersion>1.0001</XpciVersion> </TransactionReference> <RequestAction>Rate</RequestAction> <RequestOption>Rate</RequestOption> </Request> <PickupType> <Code>%s</Code> </PickupType> <Shipment> <Shipper> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> <ShipperNumber>%s</ShipperNumber> </Shipper> <ShipTo> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> <ResidentialAddressIndicator/> </Address> </ShipTo> <ShipFrom> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> </ShipFrom> <Service> <Code>%s</Code> </Service> <Package> <PackagingType> <Code>%s</Code> </PackagingType> <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code> </UnitOfMeasurement> <Weight>%s</Weight> </PackageWeight> </Package> </Shipment> </RatingServiceSelectionRequest>""" % (access_license_no, user_id, password, pickup_type_ups, shipper_zip,shipper_country_code, ups_info_shipper_no,receipient_zip, receipient_country_code, shipper_zip, shipper_country_code, service_type_ups, packaging_type_ups, weight) try: from urllib2 import Request, urlopen, URLError, quote request = Request(url, rate_request) response_text = urlopen(request).read() response_dic = xml2dic.main(response_text) str_error = '' for response in response_dic['RatingServiceSelectionResponse'][0]['Response']: if response.get('Error'): for item in response['Error']: if item.get('ErrorDescription'): str_error = item['ErrorDescription'] self.write(cr, uid, [data.id], {'status_message': "Error : " + item['ErrorDescription'] }) if not str_error: for response in response_dic['RatingServiceSelectionResponse'][1]['RatedShipment']: if response.get('TotalCharges'): amount = response['TotalCharges'][1]['MonetaryValue'] sale_obj.write(cr, uid, context.get('active_ids'), {'shipcharge': amount or 0.00, 'status_message': 'Success!'},context=context) return True except URLError, e: if hasattr(e, 'reason'): print 'Could not reach the server, reason: %s' % e.reason elif hasattr(e, 'code'): print 'Could not fulfill the request, code: %d' % e.code raise
def getCustomerPaymentProfileRequest(self, dic): profile_dictionary = dic KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension') url = dic.get('url') xsd = dic.get('xsd') getCustomerPaymentProfileRequest = doc1.createElement( "getCustomerPaymentProfileRequest") getCustomerPaymentProfileRequest.setAttribute( "xmlns", "AnetApi/xml/v1/schema/AnetApiSchema.xsd") doc1.appendChild(getCustomerPaymentProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") getCustomerPaymentProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode( self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode( self._clean_string(self._clean_string(dic['transaction_key']))) transactionKey.appendChild(ptext) if 'customerProfileId' in KEYS: customerProfileId = doc1.createElement("customerProfileId") getCustomerPaymentProfileRequest.appendChild(customerProfileId) ptext = doc1.createTextNode( self._clean_string(profile_dictionary['customerProfileId'])) customerProfileId.appendChild(ptext) if 'customerPaymentProfileId' in KEYS: customerPaymentProfileId = doc1.createElement( "customerPaymentProfileId") getCustomerPaymentProfileRequest.appendChild( customerPaymentProfileId) ptext = doc1.createTextNode( self._clean_string( profile_dictionary['customerPaymentProfileId'])) customerPaymentProfileId.appendChild(ptext) Request_string = xml = doc1.toxml(encoding="utf-8") get_profile_response_xml = self.request_to_server( Request_string, url, url_path) get_profile_response_dictionary = xml2dic.main( get_profile_response_xml) parent_resultCode = self.search_dic(get_profile_response_dictionary, 'resultCode') if parent_resultCode: if parent_resultCode['resultCode'] == 'Ok': parent_directResponse = self.search_dic( get_profile_response_dictionary, 'cardNumber') cardNumber = parent_directResponse['cardNumber'] return cardNumber
def process_ship(self): ids = self._ids do = self.browse(type(ids) == type([]) and ids[0] or ids) user = self.env['res.users'].browse(self._ids) if do.ship_company_code != 'usps': return super(stock_picking, self).process_ship() if not (do.logis_company and do.logis_company.ship_company_code == 'usps'): return super(stock_picking, self).process_ship() userid = do.logis_company.usps_userid url = do.logis_company.test_mode and do.logis_company.usps_url_secure_test or do.logis_company.usps_url_secure url_prd = do.logis_company.usps_url url_prd_secure = do.logis_company.usps_url_secure test = do.logis_company.test_mode str_error = '' ship_message = '' error = False for package in do.packages_ids: str_error = '' # if do.packages_ids: # @Changing to production URL SINCE DelivConfirmCertifyV3.0Request works only with production url and test data url = do.logis_company.usps_url_secure if test: request_xml = """<DelivConfirmCertifyV3.0Request USERID="%(user_id)s"> <Option>1</Option> <ImageParameters></ImageParameters> <FromName>Joe Smith</FromName> <FromFirm>ABD Corp.</FromFirm> <FromAddress1>Apt. 3C</FromAddress1> <FromAddress2>6406 Ivy Lane</FromAddress2> <FromCity>Greenbelt</FromCity> <FromState>MD</FromState> <FromZip5>20770</FromZip5> <FromZip4>1234</FromZip4> <ToName>Tom Collins</ToName> <ToFirm>XYZ Corp.</ToFirm> <ToAddress1>Suite 4D</ToAddress1> <ToAddress2>8 Wildwood Drive</ToAddress2> <ToCity>Old Lyme</ToCity> <ToState>CT</ToState> <ToZip5>06371</ToZip5> <ToZip4></ToZip4> <WeightInOunces>1</WeightInOunces> <ServiceType>Priority</ServiceType> <SeparateReceiptPage></SeparateReceiptPage> <POZipCode></POZipCode> <ImageType>TIF</ImageType> <LabelDate></LabelDate> <CustomerRefNo></CustomerRefNo> <AddressServiceRequested></AddressServiceRequested> <SenderName></SenderName> <SenderEMail></SenderEMail> <RecipientName></RecipientName> <RecipientEMail></RecipientEMail> </DelivConfirmCertifyV3.0Request> """ % { 'user_id': userid, } if url and request_xml: request_url = url + '?API=DelivConfirmCertifyV3&XML=' + request_xml elif do.company_id.partner_id.address: from_address = do.company_id.partner_id.address[0] request_xml = """<DeliveryConfirmationV3.0Request USERID="%(user_id)s"> <Option>1</Option> <ImageParameters /> <FromName>%(from_name)s</FromName> <FromFirm>%(from_firm)s</FromFirm> <FromAddress1 /> <FromAddress2>%(from_address2)s</FromAddress2> <FromCity>%(from_city)s</FromCity> <FromState>%(from_state)s</FromState> <FromZip5>%(from_zip5)s</FromZip5> <FromZip4>%(from_zip4)s</FromZip4> <ToName>%(to_name)s</ToName> <ToFirm>%(to_firm)s</ToFirm> <ToAddress1>%(to_address1)s</ToAddress1> <ToAddress2>%(to_address2)s</ToAddress2> <ToCity>%(to_city)s</ToCity> <ToState>%(to_state)s</ToState> <ToZip5>%(to_zip5)s</ToZip5> <ToZip4>%(to_zip4)s</ToZip4> <WeightInOunces>%(weight)s</WeightInOunces> <ServiceType>%(service_type)s</ServiceType> <POZipCode></POZipCode> <ImageType>TIF</ImageType> <LabelDate></LabelDate> <CustomerRefNo></CustomerRefNo> <AddressServiceRequested>TRUE</AddressServiceRequested> </DeliveryConfirmationV3.0Request> """ % { 'user_id': userid, 'from_name': from_address.name, 'from_firm': '', 'from_address2': from_address.street or '', 'from_city': from_address.city or '', 'from_state': from_address.state_id and from_address.state_id.code or '', 'from_zip5': from_address.zip or '', 'from_zip4': from_address.zip or '', 'to_name': do.address_id.name, 'to_firm': '', 'to_address1': do.address_id.street, 'to_address2': do.address_id.street2, 'to_city': do.address_id.city, 'to_state': do.address_id.state_id and do.address_id.state_id.code or '', 'to_zip5': do.address_id.zip or '', 'to_zip4': do.address_id.zip, 'weight': package.weight, 'service_type': do.usps_service_type, } if url and request_xml: request_url = url + '?API=DeliveryConfirmationV3&XML=' + request_xml try: import urllib f = urllib.urlopen(request_url) from xml.dom.minidom import parse, parseString import xml2dic str_response = f.read() xml_response = parseString(str_response) xml_dic = xml2dic.main(str_response) if 'Error' in xml_dic.keys(): error = True for item in xml_dic.get('Error'): if item.get('Number'): if str_error: str_error = str_error + "\n----------------------" str_error = str_error + "\nNumber : " + item[ 'Number'] if item.get('Description'): str_error = str_error + "\nDescription : " + item[ 'Description'] else: confirmation_number = xml_dic[ 'DelivConfirmCertifyV3.0Response'][0][ 'DeliveryConfirmationNumber'] label_data = xml_dic['DelivConfirmCertifyV3.0Response'][1][ 'DeliveryConfirmationLabel'] # logo = binascii.b2a_base64(str(b64decode(label_data))) # logo = str(b64decode(label_data)) logo = base64.decodestring(label_data) import os import tempfile dir_temp = tempfile.gettempdir() f = open(dir_temp + '/usps.tif', 'w+') f.write(logo) f.close() label_image = '' cp = False if os.name == 'posix' or 'nt': try: os.system("tiffcp -c none " + dir_temp + "/usps.tif " + dir_temp + "/usps_temp.tif") cp = True except Exception, e: str_error = "Please install tiffcp." if cp: im = Image.open(dir_temp + '/usps_temp.tif') im.thumbnail(im.size) im.save(dir_temp + '/usps_temp.jpg', "JPEG", quality=100) label_from_file = open(dir_temp + '/usps_temp.jpg', 'rb') label_image = base64.encodestring( label_from_file.read()) self.env['stock.packages'].write({ 'logo': label_image, 'tracking_no': confirmation_number, 'usps_confirmation_number': confirmation_number, 'ship_message': 'Shipment has processed' }) except Exception, e: str_error = str(e) self._cr.commit() if str_error: self.env['stock.packages'].write({'ship_message': str_error})
def get_rate(self, cr, uid, ids, context=None): sale_obj = self.pool.get('sale.order') data = self.browse(cr, uid, ids[0], context=context) sale_obj.write(cr,uid,context.get('active_ids'),{'ups_shipper_id':data.ups_shipper_id.id, 'ups_service_id':data.ups_service_id.id, 'ups_pickup_type':data.ups_pickup_type, 'ups_packaging_type':data.ups_packaging_type.id},context=context) if context is None: context = {} if not (data['rate_selection'] == 'rate_request' and data['ship_company_code'] == 'ups'): return super(shipping_rate_wizard, self).get_rate(cr, uid, ids, context) # if context.get('active_model', False) == 'sale.order': if context.get('active_model', False) in ['sale.order', 'account.invoice'] and 'active_id' in context: if context['active_model'] == 'sale.order': sale = sale_obj.browse(cr, uid, context['active_id'], context=context) weight = sale.total_weight_net or 0.00 elif context['active_model'] == 'account.invoice': invoice = self.pool.get('account.invoice').browse(cr, uid, context['active_id'], context=context) weight = invoice.total_weight_net or 0.00 receipient_zip = data.partner_shipping_id and data.partner_shipping_id.zip or '' receipient_country_code = data.partner_shipping_id.country_id and data.partner_shipping_id.country_id.code or '' access_license_no = data.ups_shipper_id and data.ups_shipper_id.accesslicensenumber or '' user_id = data.ups_shipper_id and data.ups_shipper_id.userid or '' password = data.ups_shipper_id and data.ups_shipper_id.password or '' pickup_type_ups = data.ups_pickup_type shipper_zip = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.zip or '' shipper_country_code = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.country_id and \ data.ups_shipper_id.address.country_id.code or '' ups_info_shipper_no = data.ups_shipper_id and data.ups_shipper_id.acc_no or '' service_type_ups = data.ups_service_id and data.ups_service_id.shipping_service_code or '' packaging_type_ups = data.ups_packaging_type.code test_mode = False test_mode = data.logis_company and data.logis_company.test_mode or True if test_mode: url = unicode(data.logis_company.ship_rate_test_web) # port = data.logis_company.ship_rate_test_port else: url = unicode(data.logis_company.ship_rate_web) # port = data.logis_company.ship_rate_port if data.ups_service_id: request_action ="rate" request_option ="rate" else: request_action ="shop" request_option ="shop" # url = 'https://wwwcie.ups.com/ups.app/xml/Rate' or 'https://onlinetools.ups.com/ups.app/xml/Rate' rate_request = """<?xml version=\"1.0\"?> <AccessRequest xml:lang=\"en-US\"> <AccessLicenseNumber>%s</AccessLicenseNumber> <UserId>%s</UserId> <Password>%s</Password> </AccessRequest> <?xml version=\"1.0\"?> <RatingServiceSelectionRequest xml:lang=\"en-US\"> <Request> <TransactionReference> <CustomerContext>Rating and Service</CustomerContext> <XpciVersion>1.0001</XpciVersion> </TransactionReference> <RequestAction>%s</RequestAction> <RequestOption>%s</RequestOption> </Request> <PickupType> <Code>%s</Code> </PickupType> <Shipment> <Shipper> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> <ShipperNumber>%s</ShipperNumber> </Shipper> <ShipTo> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> <ResidentialAddressIndicator/> </Address> </ShipTo> <ShipFrom> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> </ShipFrom> <Service> <Code>%s</Code> </Service> <Package> <PackagingType> <Code>%s</Code> </PackagingType> <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code> </UnitOfMeasurement> <Weight>%s</Weight> </PackageWeight> </Package> </Shipment> </RatingServiceSelectionRequest>""" % (access_license_no, user_id, password,request_action,request_option, pickup_type_ups, shipper_zip,shipper_country_code, ups_info_shipper_no,receipient_zip, receipient_country_code, shipper_zip, shipper_country_code, service_type_ups, packaging_type_ups, weight) rates_obj = self.pool.get('shipping.rates.sales') so = context.get('active_id') rids = rates_obj.search(cr,uid,[('sales_id','=', so )]) rates_obj.unlink(cr, uid, rids, context) serv_obj = self.pool.get('ups.shipping.service.type') try: print rate_request from urllib2 import Request, urlopen, URLError, quote request = Request(url, rate_request) response_text = urlopen(request).read() print response_text response_dic = xml2dic.main(response_text) str_error = '' for response in response_dic['RatingServiceSelectionResponse'][0]['Response']: if response.get('Error'): for item in response['Error']: if item.get('ErrorDescription'): str_error = item['ErrorDescription'] self.write(cr, uid, [data.id], {'status_message': "Error : " + item['ErrorDescription'] }) if not str_error: # print response_dic amount = None ups_service_id = None # Get all the return Shipping rates as options for response in response_dic['RatingServiceSelectionResponse']: if response.get('RatedShipment'): warning = None vals = {} for val in response['RatedShipment']: if val.get('TotalCharges'): vals['totalcharges'] = float(val['TotalCharges'][1]['MonetaryValue']) if val.get('GuaranteedDaysToDelivery'): vals['daystodelivery'] = val['GuaranteedDaysToDelivery'] if val.get('Service'): service_code = val['Service'][0]['Code'] service = serv_obj.search(cr,uid,[('shipping_service_code','=',service_code)]) vals['service'] =service[0] if val.get('RatedShipmentWarning'): if not warning: warning = val['RatedShipmentWarning'] else: warning = warning + ", " + val['RatedShipmentWarning'] # get the lowest cost shipping rate as default on Sales Order if (amount is None) or amount > vals['totalcharges']: amount = vals['totalcharges'] ups_service_id = vals['service'] status_mesage = warning vals['ratedshipmentwarning'] = warning vals['sales_id'] = context.get('active_id') rates_obj.create(cr,uid,vals,context) sale_obj.write(cr,uid,context.get('active_ids'),{'shipcharge':amount or 0.00,'ups_service_id':ups_service_id,'status_message':warning},context=context) return True rates_obj.write(cr, uid, context.get('active_ids'), { 'status_message': 'Success!'},context=context) except URLError, e: if hasattr(e, 'reason'): print 'Could not reach the server, reason: %s' % e.reason elif hasattr(e, 'code'): print 'Could not fulfill the request, code: %d' % e.code raise
def get_rate(self): ids = self._ids context = self._context sale_obj = self.env['sale.order'] data = self.browse(ids)[0] sale_obj.write({ 'ups_shipper_id': data.ups_shipper_id.id, 'ups_service_id': data.ups_service_id.id, 'ups_pickup_type': data.ups_pickup_type, 'ups_packaging_type': data.ups_packaging_type.id }) if context is None: context = {} if not (data['rate_selection'] == 'rate_request' and data['ship_company_code'] == 'ups'): return super(shipping_rate_wizard, self).get_rate() # if context.get('active_model', False) == 'sale.order': if context.get('active_model', False) in [ 'sale.order', 'account.invoice' ] and 'active_id' in context: if context['active_model'] == 'sale.order': sale = sale_obj.browse(context['active_id']) weight = sale.total_weight_net or 0.00 print elif context['active_model'] == 'account.invoice': invoice = self.env['account.invoice'].browse( context['active_id']) weight = invoice.total_weight_net or 0.00 receipient_zip = data.partner_shipping_id and data.partner_shipping_id.zip or '' receipient_country_code = data.partner_shipping_id.country_id and data.partner_shipping_id.country_id.code or '' access_license_no = data.ups_shipper_id and data.ups_shipper_id.accesslicensenumber or '' user_id = data.ups_shipper_id and data.ups_shipper_id.userid or '' password = data.ups_shipper_id and data.ups_shipper_id.password or '' pickup_type_ups = data.ups_pickup_type shipper_zip = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.zip or '' shipper_country_code = data.ups_shipper_id and data.ups_shipper_id.address and data.ups_shipper_id.address.country_id and \ data.ups_shipper_id.address.country_id.code or '' ups_info_shipper_no = data.ups_shipper_id and data.ups_shipper_id.acc_no or '' service_type_ups = data.ups_service_id and data.ups_service_id.shipping_service_code or '' packaging_type_ups = data.ups_packaging_type.code test_mode = False test_mode = data.logis_company and data.logis_company.test_mode or True url = 'https://wwwcie.ups.com/ups.app/xml/Rate' or 'https://onlinetools.ups.com/ups.app/xml/Rate' rate_request = """<?xml version=\"1.0\"?> <AccessRequest xml:lang=\"en-US\"> <AccessLicenseNumber>%s</AccessLicenseNumber> <UserId>%s</UserId> <Password>%s</Password> </AccessRequest> <?xml version=\"1.0\"?> <RatingServiceSelectionRequest xml:lang=\"en-US\"> <Request> <TransactionReference> <CustomerContext>Rating and Service</CustomerContext> <XpciVersion>1.0001</XpciVersion> </TransactionReference> <RequestAction>Rate</RequestAction> <RequestOption>Rate</RequestOption> </Request> <PickupType> <Code>%s</Code> </PickupType> <Shipment> <Shipper> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> <ShipperNumber>%s</ShipperNumber> </Shipper> <ShipTo> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> <ResidentialAddressIndicator/> </Address> </ShipTo> <ShipFrom> <Address> <PostalCode>%s</PostalCode> <CountryCode>%s</CountryCode> </Address> </ShipFrom> <Service> <Code>%s</Code> </Service> <Package> <PackagingType> <Code>%s</Code> </PackagingType> <PackageWeight> <UnitOfMeasurement> <Code>LBS</Code> </UnitOfMeasurement> <Weight>%s</Weight> </PackageWeight> </Package> </Shipment> </RatingServiceSelectionRequest>""" % ( access_license_no, user_id, password, pickup_type_ups, shipper_zip, shipper_country_code, ups_info_shipper_no, receipient_zip, receipient_country_code, shipper_zip, shipper_country_code, service_type_ups, packaging_type_ups, weight) try: from urllib2 import Request, urlopen, URLError, quote request = Request(url, rate_request) response_text = urlopen(request).read() response_dic = xml2dic.main(response_text) str_error = '' for response in response_dic['RatingServiceSelectionResponse'][ 0]['Response']: if response.get('Error'): for item in response['Error']: if item.get('ErrorDescription'): str_error = item['ErrorDescription'] self.write({ 'status_message': "Error : " + item['ErrorDescription'] }) if not str_error: for response in response_dic[ 'RatingServiceSelectionResponse'][1][ 'RatedShipment']: if response.get('TotalCharges'): amount = response['TotalCharges'][1][ 'MonetaryValue'] if context['active_model'] == 'sale.order': sale.write({ 'shipcharge': amount or 0.00, 'status_message': 'Success!' }) elif context['active_model'] == 'account.invoice': invoice.write({ 'shipcharge': amount or 0.00, 'status_message': 'Success!' }) return True except URLError, e: if hasattr(e, 'reason'): print 'Could not reach the server, reason: %s' % e.reason elif hasattr(e, 'code'): print 'Could not fulfill the request, code: %d' % e.code raise
def createCustomerProfile(self, dic): '''Creates CustomerProfile and returns the CustomerProfile id on success returns None or faliure ''' dic.update({'merchantCustomerId': '1'}) KEYS = dic.keys() doc1 = Document() url_path = dic.get('url_extension', False) url = dic.get('url', False) xsd = dic.get('xsd', False) createCustomerProfileRequest = doc1.createElement( "createCustomerProfileRequest") createCustomerProfileRequest.setAttribute("xmlns", xsd) doc1.appendChild(createCustomerProfileRequest) merchantAuthentication = doc1.createElement("merchantAuthentication") createCustomerProfileRequest.appendChild(merchantAuthentication) name = doc1.createElement("name") merchantAuthentication.appendChild(name) transactionKey = doc1.createElement("transactionKey") merchantAuthentication.appendChild(transactionKey) ##Create the Request for creating the customer profile if 'api_login_id' in KEYS and 'transaction_key' in KEYS: ptext1 = doc1.createTextNode( self._clean_string(dic['api_login_id'])) name.appendChild(ptext1) ptext = doc1.createTextNode( self._clean_string(dic['transaction_key'])) transactionKey.appendChild(ptext) if 'refId' in KEYS: refId = doc1.createElement("refId") ptext1 = doc1.createTextNode(self._clean_string(dic['refId'])) refId.appendChild(ptext1) createCustomerProfileRequest.appendChild(refId) ##Now Add Profile INformation for the user profile = doc1.createElement("profile") createCustomerProfileRequest.appendChild(profile) if 'merchantCustomerId' in KEYS: merchantCustomerId = doc1.createElement("merchantCustomerId") profile.appendChild(merchantCustomerId) ptext = doc1.createTextNode(dic['merchantCustomerId']) merchantCustomerId.appendChild(ptext) if 'description' in KEYS: description = doc1.createElement("description") profile.appendChild(description) ptext = doc1.createTextNode(dic['description']) description.appendChild(ptext) if 'email' in KEYS: email = doc1.createElement("email") profile.appendChild(email) ptext = doc1.createTextNode(dic['email']) email.appendChild(ptext) if 'paymentProfiles' in KEYS: paymentProfiles = doc1.createElement("paymentProfiles") profile.appendChild(paymentProfiles) ptext1 = doc1.createTextNode( self._clean_string(dic['paymentProfiles'])) paymentProfiles.appendChild(ptext1) ######### TO DO ADD THE NECCESSARY OPTIONS INTO IT # Request_string1=xml=doc1.toprettyxml( encoding="utf-8" ) Request_string = xml = doc1.toxml(encoding="utf-8") #Select from production and test server create_CustomerProfile_response_xml = self.request_to_server( Request_string, url, url_path) create_CustomerProfile_response_dictionary = xml2dic.main( create_CustomerProfile_response_xml) parent_msg = self.search_dic( create_CustomerProfile_response_dictionary, "messages") if parent_msg['messages'][0]['resultCode'] == 'Ok': parent = self.search_dic( create_CustomerProfile_response_dictionary, "customerProfileId") return parent['customerProfileId'] return { 'Error_Code': parent_msg['messages'][1]['message'][0]['code'], 'Error_Message': parent_msg['messages'][1]['message'][1]['text'] }