Exemplo n.º 1
0
    def get_transit_time(self, origin_zip, origin_country, dest_zip,
        dest_country):
        self.request = FedexAvailabilityCommitmentRequest(self.config)
        self.request.Origin.PostalCode = origin_zip
        self.request.Origin.CountryCode = origin_country
        self.request.Destination.PostalCode = dest_zip
        self.request.Destination.CountryCode = dest_country
        self.request.Service = 'FEDEX_GROUND'

        try:
            self.request.send_request()
            response_dict = sobject_to_dict(self.request.response)
            # output display formatting
            origin_str = '%s, %s' % (
                self.request.Origin.PostalCode,
                self.request.Origin.CountryCode)
            destination_str = '%s, %s' % (
                self.request.Destination.PostalCode,
                self.request.Destination.CountryCode)

            logging.info('origin: %s' % origin_str)
            logging.info('destination: %s' % destination_str)
            for option in response_dict['Options']:
                if option['Service'] == 'FEDEX_GROUND':
                    logging.info('TransitTime: %s' % option['TransitTime'])
                    return option['TransitTime'] # TODO: convert from type to int
                else:
                    logging.warning('No Fedex Ground Service found.')
                    return np.nan
        except Exception as e:
            logging.warning('Fedex request failed. Error: %s' % e)
            return np.nan
	def location_service(self, credentials, from_address_doc, from_country_doc):
		from fedex.services.location_service import FedexSearchLocationRequest
		customer_transaction_id = "*** LocationService Request v3 using Python ***"  
		# Optional transaction_id
		location_request = FedexSearchLocationRequest(credentials, \
			customer_transaction_id=customer_transaction_id)
		location_request.Constraints.RadiusDistance.Value = self.radius
		location_request.Constraints.RadiusDistance.Units = self.radius_uom
		location_request.Address.PostalCode = from_address_doc.pincode[0:10]
		location_request.Address.CountryCode = from_country_doc.code
		location_request.send_request()
		response_dict = sobject_to_dict(location_request.response)
		frappe.msgprint(str(response_dict))
Exemplo n.º 3
0
	def location_service(self, credentials, from_address_doc, from_country_doc):
		from fedex.services.location_service import FedexSearchLocationRequest
		customer_transaction_id = "*** LocationService Request v3 using Python ***"  
		# Optional transaction_id
		location_request = FedexSearchLocationRequest(credentials, \
			customer_transaction_id=customer_transaction_id)
		location_request.Constraints.RadiusDistance.Value = self.radius
		location_request.Constraints.RadiusDistance.Units = self.radius_uom
		location_request.Address.PostalCode = from_address_doc.pincode[0:10]
		location_request.Address.CountryCode = from_country_doc.code
		location_request.send_request()
		response_dict = sobject_to_dict(location_request.response)
		frappe.msgprint(str(response_dict))
Exemplo n.º 4
0
    getattr(result.MatchedAddress, 'Residential', '')))
print("MatchedAddressGeographicCoordinates: {}".format(
    result.MatchedAddressGeographicCoordinates.strip("/")))

locations = result.DistanceAndLocationDetails
for location in locations:
    print("Distance: {}{}".format(location.Distance.Value,
                                  location.Distance.Units))

    location_detail = location.LocationDetail
    print("LocationID: {}".format(location_detail.LocationId))
    print("StoreNumber: {}".format(location_detail.StoreNumber))

    if hasattr(location_detail, 'LocationContactAndAddress'):
        contact_and_address = location_detail.LocationContactAndAddress
        contact_and_address = sobject_to_dict(contact_and_address)
        print("LocationContactAndAddress Dict: {}".format(contact_and_address))

    print("GeographicCoordinates {}".format(
        getattr(location_detail, 'GeographicCoordinates', '')))
    print("LocationType {}".format(getattr(location_detail, 'LocationType',
                                           '')))

    if hasattr(location_detail, 'Attributes'):
        for attribute in location_detail.Attributes:
            print("Attribute: {}".format(attribute))

    print("MapUrl {}".format(getattr(location_detail, 'MapUrl', '')))

    if hasattr(location_detail, 'NormalHours'):
        for open_time in location_detail.NormalHours:
Exemplo n.º 5
0
# make it easier to work with.
# from fedex.tools.conversion import basic_sobject_to_dict
# print(basic_sobject_to_dict(rate_request.response))

# This will dump the response data dict to json.
# from fedex.tools.conversion import sobject_to_json
# print(sobject_to_json(rate_request.response))

# Here is the overall end result of the query.
print("HighestSeverity: {}".format(rate_request.response.HighestSeverity))

# RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
for service in rate_request.response.RateReplyDetails:
    for detail in service.RatedShipmentDetails:
        for surcharge in detail.ShipmentRateDetail.Surcharges:
            if surcharge.SurchargeType == 'OUT_OF_DELIVERY_AREA':
                print("{}: ODA rate_request charge {}".format(
                    service.ServiceType, surcharge.Amount.Amount))

    for rate_detail in service.RatedShipmentDetails:
        print("{}: Net FedEx Charge {} {}".format(
            service.ServiceType,
            rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
            rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount))

# Check for warnings, this is also logged by the base class.
if rate_request.response.HighestSeverity == 'NOTE':
    for notification in rate_request.response.Notifications:
        if notification.Severity == 'NOTE':
            print(sobject_to_dict(notification))
print("MatchedAddress: {}, {} Residential: {}".format(getattr(result.MatchedAddress, 'PostalCode', ''),
                                                      getattr(result.MatchedAddress, 'CountryCode', ''),
                                                      getattr(result.MatchedAddress, 'Residential', '')))
print("MatchedAddressGeographicCoordinates: {}".format(result.MatchedAddressGeographicCoordinates.strip("/")))

locations = result.DistanceAndLocationDetails
for location in locations:
    print("Distance: {}{}".format(location.Distance.Value, location.Distance.Units))

    location_detail = location.LocationDetail
    print("LocationID: {}".format(location_detail.LocationId))
    print("StoreNumber: {}".format(location_detail.StoreNumber))

    if hasattr(location_detail, 'LocationContactAndAddress'):
        contact_and_address = location_detail.LocationContactAndAddress
        contact_and_address = sobject_to_dict(contact_and_address)
        print("LocationContactAndAddress Dict: {}".format(contact_and_address))

    print("GeographicCoordinates {}".format(getattr(location_detail, 'GeographicCoordinates', '')))
    print("LocationType {}".format(getattr(location_detail, 'LocationType', '')))

    if hasattr(location_detail, 'Attributes'):
        for attribute in location_detail.Attributes:
            print("Attribute: {}".format(attribute))

    print("MapUrl {}".format(getattr(location_detail, 'MapUrl', '')))

    if hasattr(location_detail, 'NormalHours'):
        for open_time in location_detail.NormalHours:
            print("NormalHours Dict: {}".format(sobject_to_dict(open_time)))
Exemplo n.º 7
0
    def fedex_get_label(self, picking, data):
        GENERATE_IMAGE_TYPE = 'PDF'
        CONFIG_OBJ = FedexConfig(key=self.fedex_developer_key,
                                 password=self.fedex_developer_password,
                                 account_number=self.fedex_account_number,
                                 meter_number=self.fedex_meter_number,
                                 use_test_server=True if self.fedex_environment
                                 == 'test' else False)
        shipment = FedexProcessShipmentRequest(
            CONFIG_OBJ, customer_transaction_id="Label for %s" % picking.name)
        # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
        shipment.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        # See page 355 in WS_ShipService.pdf for a full list. Here are the common ones:
        # STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, FEDEX_EXPRESS_SAVER,
        # FEDEX_2_DAY, INTERNATIONAL_PRIORITY, SAME_DAY, INTERNATIONAL_ECONOMY
        # shipment.RequestedShipment.ServiceType = data['serviceCode'].upper()  # TODO mapping SS and FedEx
        shipment.RequestedShipment.ServiceType = data['fedex_code']
        # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, FEDEX_ENVELOPE
        shipment.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
        # Shipper contact info.
        # shipment.RequestedShipment.Shipper.Contact.PersonName = 'Sender Name'
        shipment.RequestedShipment.Shipper.Contact.CompanyName = 'Vertical4'
        shipment.RequestedShipment.Shipper.Contact.PhoneNumber = '3136408402'
        # Shipper address.
        shipment.RequestedShipment.Shipper.Address.StreetLines = '15004 3rd Ave'
        shipment.RequestedShipment.Shipper.Address.City = 'Highland Park'
        shipment.RequestedShipment.Shipper.Address.PostalCode = '48203-3718'
        shipment.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'MI'
        shipment.RequestedShipment.Shipper.Address.CountryCode = 'US'
        # Recipient contact info.
        shipment.RequestedShipment.Recipient.Contact.PersonName = data[
            'shipTo']['name']
        # shipment.RequestedShipment.Recipient.Contact.CompanyName =
        shipment.RequestedShipment.Recipient.Contact.PhoneNumber = data[
            'shipTo']['phone']
        # Recipient address
        shipment.RequestedShipment.Recipient.Address.StreetLines = picking.partner_id.street
        shipment.RequestedShipment.Recipient.Address.City = data['shipTo'][
            'city']
        shipment.RequestedShipment.Recipient.Address.PostalCode = data[
            'shipTo']['postalCode']
        shipment.RequestedShipment.Recipient.Address.StateOrProvinceCode = data[
            'shipTo']['state']
        shipment.RequestedShipment.Recipient.Address.CountryCode = data[
            'shipTo']['country']
        shipment.RequestedShipment.Recipient.Address.Residential = picking.residential
        # shipment.RequestedShipment.Recipient.Address.Residential = False
        # This is needed to ensure an accurate rate quote with the response. Use AddressValidation to get ResidentialStatus
        # shipment.RequestedShipment.Recipient.Address.Residential = True
        shipment.RequestedShipment.EdtRequestType = 'NONE'

        # Senders account information
        shipment.RequestedShipment.ShippingChargesPayment.Payor.ResponsibleParty.AccountNumber = CONFIG_OBJ.account_number

        # Who pays for the shipment?
        # RECIPIENT, SENDER or THIRD_PARTY
        shipment.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

        # Specifies the label type to be returned.
        # LABEL_DATA_ONLY or COMMON2D
        shipment.RequestedShipment.LabelSpecification.LabelFormatType = 'COMMON2D'

        # Specifies which format the label file will be sent to you in.
        # DPL, EPL2, PDF, PNG, ZPLII
        shipment.RequestedShipment.LabelSpecification.ImageType = GENERATE_IMAGE_TYPE

        # To use doctab stocks, you must change ImageType above to one of the
        # label printer formats (ZPLII, EPL2, DPL).
        # See documentation for paper types, there quite a few.
        shipment.RequestedShipment.LabelSpecification.LabelStockType = 'STOCK_4X6'
        # This indicates if the top or bottom of the label comes out of the
        # printer first.
        # BOTTOM_EDGE_OF_TEXT_FIRST or TOP_EDGE_OF_TEXT_FIRST
        # Timestamp in YYYY-MM-DDThh:mm:ss format, e.g. 2002-05-30T09:00:00
        shipment.RequestedShipment.ShipTimestamp = datetime.now().replace(
            microsecond=0).isoformat()

        # BOTTOM_EDGE_OF_TEXT_FIRST, TOP_EDGE_OF_TEXT_FIRST
        shipment.RequestedShipment.LabelSpecification.LabelPrintingOrientation = 'TOP_EDGE_OF_TEXT_FIRST'

        # Delete the flags we don't want.
        # Can be SHIPPING_LABEL_FIRST, SHIPPING_LABEL_LAST or delete
        if hasattr(shipment.RequestedShipment.LabelSpecification,
                   'LabelOrder'):
            del shipment.RequestedShipment.LabelSpecification.LabelOrder  # Delete, not using.

        package1_weight = shipment.create_wsdl_object_of_type('Weight')
        package1_weight.Value = int(data['weight']['value'])
        package1_weight.Units = "LB"

        package1_dimensions = shipment.create_wsdl_object_of_type('Dimensions')
        package1_dimensions.Length = int(data['dimensions']['length'])
        package1_dimensions.Width = int(data['dimensions']['width'])
        package1_dimensions.Height = int(data['dimensions']['height'])
        package1_dimensions.Units = 'IN'

        package1 = shipment.create_wsdl_object_of_type(
            'RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.Dimensions = package1_dimensions
        package1.PhysicalPackaging = 'BOX'
        package1.GroupPackageCount = 1
        customer_reference = shipment.create_wsdl_object_of_type(
            'CustomerReference')
        customer_reference.CustomerReferenceType = 'CUSTOMER_REFERENCE'
        customer_reference.Value = picking.origin
        package1.CustomerReferences.append(customer_reference)

        # Add a signature option for the package using SpecialServicesRequested or comment out.
        # SpecialServiceTypes can be APPOINTMENT_DELIVERY, COD, DANGEROUS_GOODS, DRY_ICE, SIGNATURE_OPTION etc..
        # package1.SpecialServicesRequested.SpecialServiceTypes = 'SIGNATURE_OPTION'
        # SignatureOptionType can be ADULT, DIRECT, INDIRECT, NO_SIGNATURE_REQUIRED, SERVICE_DEFAULT
        # package1.SpecialServicesRequested.SignatureOptionDetail.OptionType = 'SERVICE_DEFAULT'
        shipment.add_package(package1)
        shipment.send_request()
        # This will convert the response to a python dict object. To
        # make it easier to work with. Also see basic_sobject_to_dict, it's faster but lacks options.
        response_dict = sobject_to_dict(shipment.response)
        response_dict['CompletedShipmentDetail']['CompletedPackageDetails'][0][
            'Label']['Parts'][0]['Image'] = ''
        print(response_dict)  # Image is empty string for display purposes.
        # Here is the overall end result of the query.
        print("HighestSeverity: {}".format(shipment.response.HighestSeverity))
        # Getting the tracking number from the new shipment.
        print("Tracking #: {}"
              "".format(
                  shipment.response.CompletedShipmentDetail.
                  CompletedPackageDetails[0].TrackingIds[0].TrackingNumber))
        # Net shipping costs. Only show if available. Sometimes sandbox will not include this in the response.
        CompletedPackageDetails = shipment.response.CompletedShipmentDetail.CompletedPackageDetails[
            0]
        if hasattr(CompletedPackageDetails, 'PackageRating'):
            print("Net Shipping Cost (US$): {}"
                  "".format(CompletedPackageDetails.PackageRating.
                            PackageRateDetails[0].NetCharge.Amount))
        else:
            print('WARNING: Unable to get shipping rate.')
        ascii_label_data = shipment.response.CompletedShipmentDetail.CompletedPackageDetails[
            0].Label.Parts[0].Image
        label_binary_data = binascii.a2b_base64(ascii_label_data)
        out_path = '/var/tmp/example_shipment_label.%s' % GENERATE_IMAGE_TYPE.lower(
        )
        print("Writing to file {}".format(out_path))
        out_file = open(out_path, 'wb')
        out_file.write(label_binary_data)
        out_file.close()
        result = {
            'trackingNumber':
            shipment.response.CompletedShipmentDetail.
            CompletedPackageDetails[0].TrackingIds[0].TrackingNumber,
            'voided':
            False,
            'shipmentId':
            '',
            'labelData':
            ascii_label_data
        }
        return result
# If you'd like to see some documentation on the ship service WSDL, un-comment
# this line. (Spammy).
# print(inquiry.client)

# Un-comment this to see your complete, ready-to-send request as it stands
# before it is actually sent. This is useful for seeing what values you can
# change.
# print(inquiry.CarrierCode)
# print(inquiry.ClientDetail)
# print(inquiry.TransactionDetail)

# Fires off the request, sets the 'response' attribute on the object.
inquiry.send_request()

# See the response printed out.
# print(inquiry.response)

# This will convert the response to a python dict object. To
# make it easier to work with.
# from fedex.tools.conversion import basic_sobject_to_dict
# print(basic_sobject_to_dict(inquiry.response))

# This will dump the response data dict to json.
# from fedex.tools.conversion import sobject_to_json
# print(sobject_to_json(inquiry.response))

# Here is the overall end result of the query.
print("HighestSeverity: {}".format(inquiry.response.HighestSeverity))
print("ExpressFreightContractorDeliveryArea: {}".format(sobject_to_dict(inquiry.response.ExpressDescription)))
print("ExpressDescription: {}".format(sobject_to_dict(inquiry.response.ExpressFreightDescription)))
Exemplo n.º 9
0
# print(basic_sobject_to_dict(rate_request.response))

# This will dump the response data dict to json.
# from fedex.tools.conversion import sobject_to_json
# print(sobject_to_json(rate_request.response))

# Here is the overall end result of the query.
print("HighestSeverity: {}".format(rate_request.response.HighestSeverity))

# RateReplyDetails can contain rates for multiple ServiceTypes if ServiceType was set to None
for service in rate_request.response.RateReplyDetails:
    for detail in service.RatedShipmentDetails:
        for surcharge in detail.ShipmentRateDetail.Surcharges:
            if surcharge.SurchargeType == "OUT_OF_DELIVERY_AREA":
                print("{}: ODA rate_request charge {}".format(service.ServiceType, surcharge.Amount.Amount))

    for rate_detail in service.RatedShipmentDetails:
        print(
            "{}: Net FedEx Charge {} {}".format(
                service.ServiceType,
                rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
                rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount,
            )
        )

# Check for warnings, this is also logged by the base class.
if rate_request.response.HighestSeverity == "NOTE":
    for notification in rate_request.response.Notifications:
        if notification.Severity == "NOTE":
            print(sobject_to_dict(notification))
# print(inquiry.client)

# Un-comment this to see your complete, ready-to-send request as it stands
# before it is actually sent. This is useful for seeing what values you can
# change.
# print(inquiry.CarrierCode)
# print(inquiry.ClientDetail)
# print(inquiry.TransactionDetail)

# Fires off the request, sets the 'response' attribute on the object.
inquiry.send_request()

# See the response printed out.
# print(inquiry.response)

# This will convert the response to a python dict object. To
# make it easier to work with.
# from fedex.tools.conversion import basic_sobject_to_dict
# print(basic_sobject_to_dict(inquiry.response))

# This will dump the response data dict to json.
# from fedex.tools.conversion import sobject_to_json
# print(sobject_to_json(inquiry.response))

# Here is the overall end result of the query.
print("HighestSeverity: {}".format(inquiry.response.HighestSeverity))
print("ExpressFreightContractorDeliveryArea: {}".format(
    sobject_to_dict(inquiry.response.ExpressDescription)))
print("ExpressDescription: {}".format(
    sobject_to_dict(inquiry.response.ExpressFreightDescription)))
from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest
from fedex.tools.conversion import sobject_to_dict

logging.basicConfig(stream=sys.stdout, level=logging.INFO)

avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ)

# .StateOrProvinceCode available as well
avc_request.Origin.PostalCode = '60634'
avc_request.Origin.CountryCode = 'US'
avc_request.Destination.PostalCode = '19106'
avc_request.Destination.CountryCode = 'US'
avc_request.Service = 'FEDEX_GROUND'

avc_request.send_request()
response_dict = sobject_to_dict(avc_request.response)

# output display formatting
origin_str = '%s, %s' % (
    avc_request.Origin.PostalCode,
    avc_request.Origin.CountryCode)
destination_str = '%s, %s' % (
    avc_request.Destination.PostalCode,
    avc_request.Destination.CountryCode)

logging.info('origin: %s' % origin_str)
logging.info('destination: %s' % destination_str)
for option in response_dict['Options']:
    if option['Service'] == 'FEDEX_GROUND':
        logging.info('TransitTime: %s' % option['TransitTime'])
    else: