def get_ship_from(country="GB"): """Returns a shipfrom from a known country""" if country == "GB": ship_from_address = ShipmentConfirm.address_type( AddressLine1="2,Hope Rd", AddressLine2="Anson Road", City="Manchester", CountryCode="GB", PostalCode="M145EU" ) elif country == "US": ship_from_address = ShipmentConfirm.address_type( AddressLine1="245 NE 24th Street", AddressLine2="Suite 108", City="Miami", StateProvinceCode="FL", CountryCode="US", PostalCode="33137" ) else: raise Exception("This country is not supported") return ShipmentConfirm.ship_from_type( ship_from_address, CompanyName="Openlabs", AttentionName="Someone other than Sharoon", TaxIdentificationNumber="33065", PhoneNumber='0987654321', )
def get_packages(packing_slips, package_type_code): packages = [] for docname in packing_slips: doc = frappe.get_doc("Packing Slip",docname) item = frappe.get_doc("Item", doc.package_used) package_ref = "%s/%s"%(doc.delivery_note, doc.name) package_weight = ShipmentConfirm.package_weight_type( Weight= str(doc.gross_weight_pkg), Code="LBS", Description="Weight In Pounds") dimensions = ShipmentConfirm.dimensions_type( Code="IN", Description="Deimensions In Inches", Length= str(item.length) or "0", Width= str(item.width) or "0", Height= str(item.height) or "0", ) package_type = ShipmentConfirm.packaging_type(Code=package_type_code) package = ShipmentConfirm.package_type( package_type, package_weight, dimensions, # E.ReferenceNumber(E.Value(package_ref)), ) packages.append(package) return packages
def get_ship_from(country="GB"): """Returns a shipfrom from a known country""" if country == "GB": ship_from_address = ShipmentConfirm.address_type( AddressLine1="2,Hope Rd", AddressLine2="Anson Road", City="Manchester", CountryCode="GB", PostalCode="M145EU") elif country == "US": ship_from_address = ShipmentConfirm.address_type( AddressLine1="245 NE 24th Street", AddressLine2="Suite 108", City="Miami", StateProvinceCode="FL", CountryCode="US", PostalCode="33137") else: raise Exception("This country is not supported") return ShipmentConfirm.ship_from_type( ship_from_address, CompanyName="Openlabs", AttentionName="Someone other than Sharoon", TaxIdentificationNumber="33065", PhoneNumber='0987654321', )
def test_0020_gb_gb(self): "GB to GB UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request)
def _get_ups_packages(self): """ Return UPS Packages XML """ UPSConfiguration = Pool().get('ups.configuration') ups_config = UPSConfiguration(1) package_type = ShipmentConfirm.packaging_type( Code=self.ups_package_type ) # FIXME: Support multiple packaging type weight = self.package_weight.quantize( Decimal('.01'), rounding=ROUND_UP ) package_weight = ShipmentConfirm.package_weight_type( Weight=str(weight), Code=ups_config.weight_uom_code, ) package_service_options = ShipmentConfirm.package_service_options_type( ShipmentConfirm.insured_value_type(MonetaryValue='0') ) package_container = ShipmentConfirm.package_type( package_type, package_weight, package_service_options ) return [package_container]
def test_0020_gb_gb(self): "GB to GB UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50]) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request)
def get_ship_to(country="GB"): """Returns a shipto to a known country""" if country == "GB": ship_to_address = ShipmentConfirm.address_type( AddressLine1="205, Copper Gate House", AddressLine2="16 Brune Street", City="London", # StateProvinceCode="E1 7NJ", CountryCode="GB", PostalCode="E1 7NJ") elif country == "US": ship_to_address = ShipmentConfirm.address_type( AddressLine1="1 Infinite Loop", City="Cupertino", StateProvinceCode="CA", CountryCode="US", PostalCode="95014") else: raise Exception("This country is not supported") return ShipmentConfirm.ship_to_type( ship_to_address, CompanyName="Apple", AttentionName="Someone other than Steve", TaxIdentificationNumber="123456", PhoneNumber='4089961010', )
def get_packages(packing_slips, package_type_code): packages = [] for docname in packing_slips: doc = frappe.get_doc("Packing Slip",docname) # item = frappe.get_doc("Item", doc.package_used) item = frappe.db.get_value("Custom UOM Conversion Details", { "parent": doc.package_used, "uom": "Nos" }, ["length", "width", "height"], as_dict=True) package_ref = "%s/%s"%(doc.delivery_note, doc.name) package_weight = ShipmentConfirm.package_weight_type( Weight= str(doc.gross_weight_pkg), Code="LBS", Description="Weight In Pounds") dimensions = ShipmentConfirm.dimensions_type( Code="IN", Description="Deimensions In Inches", Length= str(item.get("length")) or "0", Width= str(item.get("width")) or "0", Height= str(item.get("height")) or "0", ) package_type = ShipmentConfirm.packaging_type(Code=package_type_code) package = ShipmentConfirm.package_type( package_type, package_weight, dimensions, # E.ReferenceNumber(E.Value(package_ref)), ) packages.append(package) return packages
def get_ship_to(country="GB"): """Returns a shipto to a known country""" if country == "GB": ship_to_address = ShipmentConfirm.address_type( AddressLine1="205, Copper Gate House", AddressLine2="16 Brune Street", City="London", # StateProvinceCode="E1 7NJ", CountryCode="GB", PostalCode="E1 7NJ" ) elif country == "US": ship_to_address = ShipmentConfirm.address_type( AddressLine1="1 Infinite Loop", City="Cupertino", StateProvinceCode="CA", CountryCode="US", PostalCode="95014" ) else: raise Exception("This country is not supported") return ShipmentConfirm.ship_to_type( ship_to_address, CompanyName="Apple", AttentionName="Someone other than Steve", TaxIdentificationNumber="123456", PhoneNumber='4089961010', )
def test_0010_blow_up(self): """Send a stupid request which should blow up because its valid in the client but not in UPS server. Example: dont send packages""" with self.assertRaises(PyUPSException): ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code="11"), # UPS Standard Description=__doc__[:50], ) self.shipment_confirm_api.request(ship_confirm_request)
def test_0010_blow_up(self): """Send a stupid request which should blow up because its valid in the client but not in UPS server. Example: dont send packages""" with self.assertRaises(PyUPSException): ship_confirm_request = \ ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) self.shipment_confirm_api.request(ship_confirm_request)
def get_payment_info(type="prepaid", **kwargs): """Returns the payment info filled :param type: The payment type. .. note:: if payment type is prepaid AccountNumber must be provided. """ if type == 'prepaid': assert 'AccountNumber' in kwargs return ShipmentConfirm.payment_information_type( ShipmentConfirm.payment_information_prepaid_type( AccountNumber=kwargs['AccountNumber']) ) else: raise Exception("Type %s is not supported" % type)
def _get_ups_address_xml(self): """ Return Address XML """ if not all([self.street, self.city, self.country]): self.raise_user_error("Street, City and Country are required.") if self.country.code in ["US", "CA"] and not self.subdivision: self.raise_user_error("State is required for %s" % self.country.code) if self.country.code in ["US", "CA", "PR"] and not self.zip: # If Shipper country is US or Puerto Rico, 5 or 9 digits is # required. The character - may be used to separate the first five # digits and the last four digits. If the Shipper country is CA, # then the postal code is required and must be 6 alphanumeric # characters whose format is A#A#A# where A is an uppercase letter # and # is a digit. For all other countries the postal code is # optional and must be no more than 9 alphanumeric characters long. self.raise_user_error("ZIP is required for %s" % self.country.code) vals = { "AddressLine1": self.street[:35], # Limit to 35 Char "City": self.city[:30], # Limit 30 Char "CountryCode": self.country.code, } if self.streetbis: vals["AddressLine2"] = self.streetbis[:35] # Limit to 35 char if self.subdivision: # TODO: Handle Ireland Case vals["StateProvinceCode"] = self.subdivision.code[3:] if self.zip: vals["PostalCode"] = self.zip return ShipmentConfirm.address_type(**vals)
def get_address(doc, is_ship_from= False): addr = "" if is_ship_from: address_line1 = doc.address_line_1 or "" address_line2 = doc.address_line_2 or "" city = doc.city or "" state = doc.state or "" country_code = doc.country or "" pincode = doc.pin_code or "" addr = "warehouse" else: address_line1 = doc.address_line1 or "" address_line2 = doc.address_line2 or "" city = doc.city or "" state = doc.state or "" country_code = frappe.db.get_value("Country",doc.country,"code") or "" pincode = str(doc.pincode) or "" addr = "shipping" if address_line1 and city and state and country_code and pincode: return ShipmentConfirm.address_type( AddressLine1= address_line1, AddressLine2= address_line2, City= city, StateProvinceCode= state, CountryCode= country_code, PostalCode= pincode, ) else: frappe.throw("Invalid address details, Please check the %s address"%(addr))
def _get_shipment_confirm_xml(self): """ Return XML of shipment for shipment_confirm """ Company = Pool().get('company.company') UPSConfiguration = Pool().get('ups.configuration') ups_config = UPSConfiguration(1) if not self.ups_service_type: self.raise_user_error('ups_service_type_missing') payment_info_prepaid = \ ShipmentConfirm.payment_information_prepaid_type( AccountNumber=ups_config.shipper_no ) payment_info = ShipmentConfirm.payment_information_type( payment_info_prepaid) packages = self._get_ups_packages() shipment_service = ShipmentConfirm.shipment_service_option_type( SaturdayDelivery='1' if self.ups_saturday_delivery else 'None' ) description = ','.join([ move.product.name for move in self.outgoing_moves ]) shipment_args = [ self.warehouse.address.to_ups_shipper(), self.delivery_address.to_ups_to_address(), self.warehouse.address.to_ups_from_address(), ShipmentConfirm.service_type(Code=self.ups_service_type.code), payment_info, shipment_service, ] if ups_config.negotiated_rates: shipment_args.append( ShipmentConfirm.rate_information_type(negotiated=True) ) if self.warehouse.address.country.code == 'US' and \ self.delivery_address.country.code in ['PR', 'CA']: # Special case for US to PR or CA InvoiceLineTotal should be sent monetary_value = str(sum(map( lambda move: move.get_monetary_value_for_ups(), self.outgoing_moves ))) company_id = Transaction().context.get('company') if not company_id: self.raise_user_error("Company is not in context") company = Company(company_id) shipment_args.append(ShipmentConfirm.invoice_line_total_type( MonetaryValue=monetary_value, CurrencyCode=company.currency.code )) shipment_args.extend(packages) shipment_confirm = ShipmentConfirm.shipment_confirm_request_type( *shipment_args, Description=description[:35] ) return shipment_confirm
def get_shipment_confirm_service(params): return ShipmentConfirm( params.get("ups_license"), params.get("ups_user_name"), params.get("ups_password"), params.get( "ups_mode" ), # sandbox for testing purpose set as True for production set it to False )
def setUp(self): """Initialise a ShipmentConfirm and ShipmentAccept class each. """ logging.disable(logging.DEBUG) self.shipper_number = os.environ['UPS_SHIPPER_NO'] self.shipment_confirm_api = ShipmentConfirm( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway ) self.shipment_accept_api = ShipmentAccept( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway )
def get_ups_package_container(self): """ Return UPS package container for a single package """ shipment = self.shipment carrier = shipment.carrier package_type = ShipmentConfirm.packaging_type( Code=shipment.ups_package_type ) # FIXME: Support multiple packaging type package_weight = ShipmentConfirm.package_weight_type( Weight="%.2f" % self.weight, Code=carrier.ups_weight_uom_code ) package_service_options = ShipmentConfirm.package_service_options_type( ShipmentConfirm.insured_value_type(MonetaryValue="0") ) package_container = ShipmentConfirm.package_type(package_type, package_weight, package_service_options) return package_container
def test_0030_gb_gb_saturday(self): "GB to GB UPS Standard with 2 packages and Saturday delivery" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package("GB", weight="15.0", package_type_code="02"), # Customer Supplied Package # Package 2 Helper.get_package("GB", weight="15.0", package_type_code="02"), # Customer Supplied Package ShipmentConfirm.shipment_service_option_type(SaturdayDelivery="1"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code="11"), # UPS Standard Description=__doc__[:50], ) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request)
def get_ups_shipment_confirm_request(delivery_note, params): dn = delivery_note packing_slips = [row.packing_slip for row in dn.packing_slip_details] if not packing_slips: frappe.throw("Can not find the linked Packing Slip ...") ship_from_address_name = params.get("default_warehouse") shipper_number = params.get("shipper_number") package_type = ups_packages.get(params.get("package_type")) rates = {} if dn.ups_rates: rates = json.loads(dn.ups_rates) service_code = rates.get("service_used") or "03" ship_to_params = { "customer":dn.customer, "contact_display":dn.contact_display, "contact_mobile":dn.contact_mobile } packages = Helper.get_packages(packing_slips, package_type) request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(params), Helper.get_ship_to_address(ship_to_params, dn.shipping_address_name,), Helper.get_ship_from_address(params, ship_from_address_name), Helper.get_payment_info(AccountNumber=shipper_number), ShipmentConfirm.service_type(Code=service_code), # Labal specification container LabelSpecification = E.LabelSpecification( E.LabelPrintMethod(E.Code("ZPL"),), E.LabelStockSize(E.Height("4"),E.Width("6"),), E.LabelImageFormat(E.Code("ZPL"),), ), Description="Description" ) request.find("Shipment").extend(packages) return request
def get_ship_from_address(params, address_name): doc = frappe.get_doc("Warehouse",address_name) if not doc: frappe.throw("Can not fetch Shipper Address") else: ship_from_address = UPSHelper.get_address(doc,True) return ShipmentConfirm.ship_from_type( ship_from_address, CompanyName= params.get("attention_name") or "", AttentionName= params.get("user_name") or "", # TaxIdentificationNumber="", PhoneNumber= doc.phone_no or "", )
def get_ship_to_address(params, address_name): doc = frappe.get_doc("Address", address_name) if not doc: frappe.throw("Can not fetch Customer Address") else: ship_to_address = UPSHelper.get_address(doc, False) return ShipmentConfirm.ship_to_type( ship_to_address, CompanyName= params.get("customer") or "", AttentionName= params.get("contact_display") or doc.customer_name or "", # TaxIdentificationNumber="", # PhoneNumber= params.get("contact_mobile"), PhoneNumber= doc.phone or "" )
def get_shipper(params): if params: doc = frappe.get_doc("Warehouse",params.get("default_warehouse")) if not doc: frappe.throw("Can not fetch shipper Address") else: return ShipmentConfirm.shipper_type( # shipper_address, UPSHelper.get_address(doc, True), Name= params.get("user_name") or "", AttentionName= params.get("attention_name") or "", # TaxIdentificationNumber="33065", PhoneNumber= doc.phone_no or "", ShipperNumber= params.get("shipper_number") or "", ) else: frappe.throw("Shipper Address and Shipper Number fields required")
def to_ups_shipper(self): ''' Converts party address to UPS `Shipper Address`. :return: Returns instance of ShipperAddress ''' Company = Pool().get('company.company') UPSConfiguration = Pool().get('ups.configuration') vals = {} if not self.party.phone: self.raise_user_error( "ups_field_missing", error_args=('Phone no.', '"Shipper Address"') ) company_id = Transaction().context.get('company') if not company_id: self.raise_user_error( "ups_field_missing", error_args=('Company', 'context') ) company_party = Company(company_id).party vals = { 'CompanyName': company_party.name, 'TaxIdentificationNumber': company_party.vat_number, 'Name': self.name or self.party.name, 'AttentionName': self.name or self.party.name, 'PhoneNumber': digits_only_re.sub('', self.party.phone), 'ShipperNumber': UPSConfiguration(1).shipper_no, } fax = self.party.fax if fax: vals['FaxNumber'] = fax # EMailAddress email = self.party.email if email: vals['EMailAddress'] = email return ShipmentConfirm.shipper_type( self._get_ups_address_xml(), **vals )
def _get_shipment_confirm_xml(self): """ Return XML of shipment for shipment_confirm """ Company = Pool().get("company.company") carrier = self.carrier if not self.ups_service_type: self.raise_user_error("ups_service_type_missing") payment_info_prepaid = ShipmentConfirm.payment_information_prepaid_type(AccountNumber=carrier.ups_shipper_no) payment_info = ShipmentConfirm.payment_information_type(payment_info_prepaid) packages = self._get_ups_packages() shipment_service = ShipmentConfirm.shipment_service_option_type( SaturdayDelivery="1" if self.ups_saturday_delivery else "None" ) description = ",".join([move.product.name for move in self.outgoing_moves]) from_address = self._get_ship_from_address() shipment_args = [ from_address.to_ups_shipper(carrier=carrier), self.delivery_address.to_ups_to_address(), from_address.to_ups_from_address(), ShipmentConfirm.service_type(Code=self.ups_service_type.code), payment_info, shipment_service, ] if carrier.ups_negotiated_rates: shipment_args.append(ShipmentConfirm.rate_information_type(negotiated=True)) if from_address.country.code == "US" and self.delivery_address.country.code in ["PR", "CA"]: # Special case for US to PR or CA InvoiceLineTotal should be sent monetary_value = str(sum(map(lambda move: move.get_monetary_value_for_ups(), self.outgoing_moves))) company_id = Transaction().context.get("company") if not company_id: self.raise_user_error("Company is not in context") company = Company(company_id) shipment_args.append( ShipmentConfirm.invoice_line_total_type( MonetaryValue=monetary_value, CurrencyCode=company.currency.code ) ) shipment_args.extend(packages) shipment_confirm = ShipmentConfirm.shipment_confirm_request_type(*shipment_args, Description=description[:35]) return shipment_confirm
def to_ups_shipper(self, carrier): """ Converts party address to UPS `Shipper Address`. :return: Returns instance of ShipperAddress """ Company = Pool().get("company.company") vals = {} if not self.party.phone and not getattr(self, "phone"): self.raise_user_error("ups_field_missing", error_args=("Phone no.", '"Shipper Address"')) company_id = Transaction().context.get("company") if not company_id: self.raise_user_error("ups_field_missing", error_args=("Company", "context")) company_party = Company(company_id).party if getattr(self, "phone"): phone = getattr(self, "phone") else: phone = self.party.phone vals = { "CompanyName": company_party.name, "TaxIdentificationNumber": company_party.identifiers and company_party.identifiers[0].code or "", "Name": self.name or self.party.name, "AttentionName": self.name or self.party.name, "PhoneNumber": digits_only_re.sub("", phone), "ShipperNumber": carrier.ups_shipper_no, } fax = self.party.fax if fax: vals["FaxNumber"] = fax # EMailAddress email = self.party.email if email: vals["EMailAddress"] = email return ShipmentConfirm.shipper_type(self._get_ups_address_xml(), **vals)
def to_ups_to_address(self): """ Converts party address to UPS `To Address`. :return: Returns instance of ToAddress """ party = self.party tax_identification_number = "" if party.identifiers: tax_identification_number = party.identifiers[0].code elif hasattr(party, "tax_exemption_number") and party.tax_exemption_number: tax_identification_number = party.tax_exemption_number vals = { "CompanyName": self.name or party.name, "TaxIdentificationNumber": tax_identification_number, "AttentionName": self.name or party.name, } if getattr(self, "phone"): phone = getattr(self, "phone") else: phone = party.phone if phone: vals["PhoneNumber"] = digits_only_re.sub("", phone) fax = party.fax if fax: vals["FaxNumber"] = fax # EMailAddress email = party.email if email: vals["EMailAddress"] = email # TODO: LocationID is optional return ShipmentConfirm.ship_to_type(self._get_ups_address_xml(), **vals)
def get_package(country="GB", package_type_code='02', weight='14.1', dimensions=None): """UPS really expects units that are used in the country :param package_type_code: Str of the Code :param weight: Str eg '14.1' :param dimensions: A dict with length, width and height eg {'length': 10, 'width': 10, 'height': 10} """ if dimensions is None: dimensions = { 'length': '10', 'width': '10', 'height': '10', } if country == "GB": package_weight = ShipmentConfirm.package_weight_type( Weight=weight, Code="KGS", Description="Kilograms") dimensions = ShipmentConfirm.dimensions_type( Code="CM", Length=dimensions['length'], Width=dimensions['width'], Height=dimensions['height'], ) elif country == "US": package_weight = ShipmentConfirm.package_weight_type( Weight=weight, Code="LBS", Description="Pounds") dimensions = ShipmentConfirm.dimensions_type( Code="IN", Length=dimensions['length'], Width=dimensions['width'], Height=dimensions['height'], ) else: raise Exception("This country is not supported") package_type = ShipmentConfirm.packaging_type(Code=package_type_code) return ShipmentConfirm.package_type( package_type, package_weight, dimensions, )
def get_ups_package_container(self): """ Return UPS package container for a single package """ shipment = self.shipment carrier = shipment.carrier if self.box_type: code = self.box_type.code length = self.box_type.length height = self.box_type.height width = self.box_type.width dimensions_symbol = self.box_type.distance_unit and \ self.box_type.distance_unit.symbol.upper() else: code = '02' length = self.length height = self.height width = self.width dimensions_symbol = self.distance_unit and \ self.distance_unit.symbol.upper() package_type = ShipmentConfirm.packaging_type(Code=code) package_weight = ShipmentConfirm.package_weight_type( Weight="%.2f" % self.weight, Code=carrier.ups_weight_uom_code, ) package_service_options = ShipmentConfirm.package_service_options_type( ShipmentConfirm.insured_value_type(MonetaryValue='0') ) args = [package_type, package_weight, package_service_options] # Only send dimensions if the box type is 'Customer Supplied Package' if code == '02' and length and width and height and dimensions_symbol: package_dimensions = ShipmentConfirm.dimensions_type( Code=dimensions_symbol, Length=str(length), Width=str(width), Height=str(height) ) args.append(package_dimensions) package_container = ShipmentConfirm.package_type(*args) return package_container
def get_package( country="GB", package_type_code='02', weight='14.1', dimensions=None ): """UPS really expects units that are used in the country :param package_type_code: Str of the Code :param weight: Str eg '14.1' :param dimensions: A dict with length, width and height eg {'length': 10, 'width': 10, 'height': 10} """ if dimensions is None: dimensions = { 'length': '10', 'width': '10', 'height': '10', } if country == "GB": package_weight = ShipmentConfirm.package_weight_type( Weight=weight, Code="KGS", Description="Kilograms") dimensions = ShipmentConfirm.dimensions_type( Code="CM", Length=dimensions['length'], Width=dimensions['width'], Height=dimensions['height'], ) elif country == "US": package_weight = ShipmentConfirm.package_weight_type( Weight=weight, Code="LBS", Description="Pounds") dimensions = ShipmentConfirm.dimensions_type( Code="IN", Length=dimensions['length'], Width=dimensions['width'], Height=dimensions['height'], ) else: raise Exception("This country is not supported") package_type = ShipmentConfirm.packaging_type(Code=package_type_code) return ShipmentConfirm.package_type( package_type, package_weight, dimensions, )
def to_ups_to_address(self): ''' Converts party address to UPS `To Address`. :return: Returns instance of ToAddress ''' party = self.party tax_identification_number = '' if party.vat_number: tax_identification_number = party.vat_number elif hasattr(party, 'tax_exemption_number') and \ party.tax_exemption_number: tax_identification_number = party.tax_exemption_number vals = { 'CompanyName': self.name or party.name, 'TaxIdentificationNumber': tax_identification_number, 'AttentionName': self.name or party.name, } if party.phone: vals['PhoneNumber'] = digits_only_re.sub('', party.phone) fax = party.fax if fax: vals['FaxNumber'] = fax # EMailAddress email = party.email if email: vals['EMailAddress'] = email # TODO: LocationID is optional return ShipmentConfirm.ship_to_type(self._get_ups_address_xml(), **vals)
class TestShippingPackage(unittest.TestCase): """Test the :class:`ShipmentConfirm` and :class:`ShipmentAccept` classes for various cases originating from GB. """ @classmethod def setUpClass(self): """Check if the variables for initialising the test case is available in the environment""" assert 'UPS_LICENSE_NO' in os.environ, \ "UPS_LICENSE_NO not given. Hint:Use export UPS_LICENSE_NO=<number>" assert 'UPS_SHIPPER_NO' in os.environ, \ "UPS_SHIPPER_NO not given. Hint:Use export UPS_SHIPPER_NO=<number>" assert 'UPS_USER_ID' in os.environ, \ "UPS_USER_ID not given. Hint:Use export UPS_USER_ID=<user_id>" assert 'UPS_PASSWORD' in os.environ, \ "UPS_PASSWORD not given. Hint:Use export UPS_PASSWORD=<password>" def setUp(self): """Initialise a ShipmentConfirm and ShipmentAccept class each. """ logging.disable(logging.DEBUG) self.shipper_number = os.environ['UPS_SHIPPER_NO'] self.shipment_confirm_api = ShipmentConfirm( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway ) self.shipment_accept_api = ShipmentAccept( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway ) def test_0010_blow_up(self): """Send a stupid request which should blow up because its valid in the client but not in UPS server. Example: dont send packages""" with self.assertRaises(PyUPSException): ship_confirm_request = \ ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) self.shipment_confirm_api.request(ship_confirm_request) def test_0020_gb_gb(self): "GB to GB UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50]) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request) @unittest.skipUnless(datetime.today().weekday() == 4, "since not a friday") def test_0030_gb_gb_saturday(self): "GB to GB UPS Standard with 2 packages and Saturday delivery" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package ShipmentConfirm.shipment_service_option_type(SaturdayDelivery="1"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50]) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request) def test_0040_gb_us(self): "GB to US UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("US"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02'), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='07'), # UPS Standard Description=__doc__[:50]) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request)
) logger.debug('--------SHIPMENT CONFIRM REQUEST--------') logger.debug(str(shipment_confirm)) logger.debug('--------END REQUEST--------') try: response = shipment_confirm_instance.request(shipment_confirm) except PyUPSException, e: self.raise_user_error(unicode(e[0])) # Logging. logger.debug('--------SHIPMENT CONFIRM RESPONSE--------') logger.debug(str(response)) logger.debug('--------END RESPONSE--------') digest = ShipmentConfirm.extract_digest(response) shipment_accept = ShipmentAccept.shipment_accept_request_type(digest) shipment_accept_instance = ups_config.api_instance(call="accept") # Logging. logger.debug( 'Making Shipment Accept Request for' 'Shipment ID: {0} and Carrier ID: {1}' .format(self.id, self.carrier.id) ) logger.debug('--------SHIPMENT ACCEPT REQUEST--------') logger.debug(str(shipment_confirm)) logger.debug('--------END REQUEST--------')
class TestShippingPackage(unittest.TestCase): """Test the :class:`ShipmentConfirm` and :class:`ShipmentAccept` classes for various cases originating from GB. """ @classmethod def setUpClass(self): """Check if the variables for initialising the test case is available in the environment""" assert 'UPS_LICENSE_NO' in os.environ, \ "UPS_LICENSE_NO not given. Hint:Use export UPS_LICENSE_NO=<number>" assert 'UPS_SHIPPER_NO' in os.environ, \ "UPS_SHIPPER_NO not given. Hint:Use export UPS_SHIPPER_NO=<number>" assert 'UPS_USER_ID' in os.environ, \ "UPS_USER_ID not given. Hint:Use export UPS_USER_ID=<user_id>" assert 'UPS_PASSWORD' in os.environ, \ "UPS_PASSWORD not given. Hint:Use export UPS_PASSWORD=<password>" def setUp(self): """Initialise a ShipmentConfirm and ShipmentAccept class each. """ logging.disable(logging.DEBUG) self.shipper_number = os.environ['UPS_SHIPPER_NO'] self.shipment_confirm_api = ShipmentConfirm( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway ) self.shipment_accept_api = ShipmentAccept( os.environ['UPS_LICENSE_NO'], os.environ['UPS_USER_ID'], os.environ['UPS_PASSWORD'], True # Test must be performed in sandbox anyway ) def test_0010_blow_up(self): """Send a stupid request which should blow up because its valid in the client but not in UPS server. Example: dont send packages""" with self.assertRaises(PyUPSException): ship_confirm_request = \ ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) self.shipment_confirm_api.request(ship_confirm_request) def test_0020_gb_gb(self): "GB to GB UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request) @unittest.skipUnless(datetime.today().weekday() == 4, "since not a friday") def test_0030_gb_gb_saturday(self): "GB to GB UPS Standard with 2 packages and Saturday delivery" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("GB"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package ShipmentConfirm.shipment_service_option_type(SaturdayDelivery="1"), Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='11'), # UPS Standard Description=__doc__[:50] ) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request) def test_0040_gb_us(self): "GB to US UPS Standard with 2 packages" ship_confirm_request = ShipmentConfirm.shipment_confirm_request_type( Helper.get_shipper(self.shipper_number, "GB"), Helper.get_ship_to("US"), Helper.get_ship_from("GB"), # Package 1 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package # Package 2 Helper.get_package( "GB", weight='15.0', package_type_code='02' ), # Customer Supplied Package Helper.get_payment_info(AccountNumber=self.shipper_number), ShipmentConfirm.service_type(Code='07'), # UPS Standard Description=__doc__[:50] ) response = self.shipment_confirm_api.request(ship_confirm_request) digest = self.shipment_confirm_api.extract_digest(response) # now accept the package accept_request = ShipmentAccept.shipment_accept_request_type(digest) self.shipment_accept_api.request(accept_request)