def availabiltiy_commitment(self, credentials, from_address_doc, to_address_doc, from_country_doc, to_country_doc): from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest avc_request = FedexAvailabilityCommitmentRequest(credentials) avc_request.Origin.PostalCode = str(from_address_doc.pincode)[0:10] avc_request.Origin.CountryCode = from_country_doc.code avc_request.Destination.PostalCode = str(to_address_doc.pincode)[0:10] avc_request.Destination.CountryCode = to_country_doc.code avc_request.ShipDate = datetime.date.today().isoformat() avc_request.send_request() for option in avc_request.response.Options: frappe.msgprint("Ship Option:") if hasattr(option, 'Service'): frappe.msgprint("Service {}".format(option.Service)) if hasattr(option, 'DeliveryDate'): frappe.msgprint("DeliveryDate {}".format(option.DeliveryDate)) if hasattr(option, 'DeliveryDay'): frappe.msgprint("DeliveryDay {}".format(option.DeliveryDay)) #if hasattr(option, 'DestinationStationId'): # frappe.msgprint("DestinationStationId {}".format(option.DestinationStationId)) #if hasattr(option, 'DestinationAirportId'): # frappe.msgprint("DestinationAirportId {}".format(option.DestinationAirportId)) if hasattr(option, 'TransitTime'): frappe.msgprint("TransitTime {}".format(option.TransitTime)) frappe.msgprint("")
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 test_track(self): # Test shipment tracking. Query for a tracking number and make sure the # first (and hopefully only) result matches up. avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ) avc_request.Origin.PostalCode = 'M5V 3A4' avc_request.Origin.CountryCode = 'CA' avc_request.Destination.PostalCode = '27577' # 29631 avc_request.Destination.CountryCode = 'US' avc_request.send_request() assert avc_request.response
class FedexHelper: def __init__(self, config, partition_size, storage_dir): self.df = pd.DataFrame() self.config = config self.partition_size = partition_size self.storage_dir = storage_dir 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 #traceback.print_exc() # for initial dev TODO: create debug mode def manage_partitioning(self, partition_number): if not self.df.empty: start = self.start_i end = start + self.partition_size partition = self.df[start:end].copy() transit_times = [] for i in range(len(partition)): o_zip = partition.origin_zip.iloc[i] o_country = partition.origin_country.iloc[i] d_zip = partition.dest_zip.iloc[i] d_country = partition.dest_country.iloc[i] tt = self.get_transit_time( origin_zip=o_zip, origin_country=o_country, dest_zip=d_zip, dest_country=d_country) if pd.isnull(tt): transit_times.append(tt) else: transit_times.append(transit_time_types[tt]) partition['transit_time'] = transit_times filename = 'partition_%s.csv' % partition_number filepath = os.path.join(self.storage_dir, filename) logging.info('Saving %s to %s' % (partition.shape, filepath)) partition.to_csv(filepath, index=False) self.start_i += self.partition_size return transit_times def run(self): self.start_i = 0 n_partitions = int(np.ceil(len(self.df)/self.partition_size)) transit_times = [] for i in range(n_partitions): transit_times += self.manage_partitioning(i) self.df['transit_time'] = transit_times
exception thrown by suds. """ import logging import sys import datetime from example_config import CONFIG_OBJ from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest # Un-comment to see the response from Fedex printed in stdout. logging.basicConfig(stream=sys.stdout, level=logging.INFO) # This is the object that will be handling our service availability request. # We're using the FedexConfig object from example_config.py in this dir. customer_transaction_id = "*** AvailabilityAndCommitment Request v4 using Python ***" # Optional transaction_id avc_request = FedexAvailabilityCommitmentRequest( CONFIG_OBJ, customer_transaction_id=customer_transaction_id) # Specify the origin postal code and country code. These fields are required. avc_request.Origin.PostalCode = '29631' avc_request.Origin.CountryCode = 'US' # Specify the destination postal code and country code. These fields are required. avc_request.Destination.PostalCode = '27577' avc_request.Destination.CountryCode = 'US' # Can be set to FEDEX_TUBE, YOUR_PACKAGING, FEDEX_BOX etc.. Defaults to YOUR_PACKAGING if not set. # avc_request.Packaging = 'FEDEX_ENVELOPE' # Can be set to the expected date. Defaults to today if not set. avc_request.ShipDate = datetime.date.today().isoformat()
exception thrown by suds. """ import logging import sys import datetime from example_config import CONFIG_OBJ from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest # Un-comment to see the response from Fedex printed in stdout. logging.basicConfig(stream=sys.stdout, level=logging.INFO) # This is the object that will be handling our service availability request. # We're using the FedexConfig object from example_config.py in this dir. customer_transaction_id = "*** AvailabilityAndCommitment Request v4 using Python ***" # Optional transaction_id avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ, customer_transaction_id=customer_transaction_id) # Specify the origin postal code and country code. These fields are required. avc_request.Origin.PostalCode = '29631' avc_request.Origin.CountryCode = 'US' # Specify the destination postal code and country code. These fields are required. avc_request.Destination.PostalCode = '27577' avc_request.Destination.CountryCode = 'US' # Can be set to FEDEX_TUBE, YOUR_PACKAGING, FEDEX_BOX etc.. Defaults to YOUR_PACKAGING if not set. # avc_request.Packaging = 'FEDEX_ENVELOPE' # Can be set to the expected date. Defaults to today if not set. avc_request.ShipDate = datetime.date.today().isoformat()
def fedex(info): from fedex.config import FedexConfig from fedex.services.rate_service import FedexRateServiceRequest # Set API KEY CONFIG_OBJ = FedexConfig(key='vMdHkxHdMhV2oMlI', password='******', account_number='787098177', meter_number='252470584') # Create request rate = FedexRateServiceRequest(CONFIG_OBJ) # service type rate.RequestedShipment.DropoffType = None rate.RequestedShipment.ServiceType = None rate.RequestedShipment.PackagingType = None # sender information rate.RequestedShipment.Shipper.Address.StateOrProvinceCode = info["ShipFrom"]["Address"]["StateProvinceCode"] rate.RequestedShipment.Shipper.Address.PostalCode = info["ShipFrom"]["Address"]["PostalCode"] rate.RequestedShipment.Shipper.Address.CountryCode = info["ShipFrom"]["Address"]["CountryCode"] # receiver information rate.RequestedShipment.Recipient.Address.StateOrProvinceCode = info["ShipTo"]["Address"]["StateProvinceCode"] rate.RequestedShipment.Recipient.Address.PostalCode = info["ShipTo"]["Address"]["PostalCode"] rate.RequestedShipment.Recipient.Address.CountryCode = info["ShipTo"]["Address"]["CountryCode"] # payer rate.RequestedShipment.EdtRequestType = 'NONE' rate.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER' # item information # Conversion unit of Dimension if info["Dimension units"] != "inches": # CM to Inches info["Dimension units"] = "inches" info["Height"] = round(float(info["Height"]) * 0.393700787, 2) info["Length"] = round(float(info["Length"]) * 0.393700787, 2) info["Width"] = round(float(info["Width"]) * 0.393700787, 2) if float(info["Length"]) > 108: print('Package exceeds the maximum length constraints of 108 inches ') return [] if float(info["Length"]) + 2 * float(info["Height"]) + 2 * float(info["Width"]) > 165: print('Package exceeds the maximum size total constraints of 165 inches ' \ '(length + girth, where girth is 2 x width plus 2 x height)') return [] package1_weight = rate.create_wsdl_object_of_type('Weight') # Conversion unit of Weight if info["Weight unit"] != "pounds": # KG to pounds info["Weight unit"] = "pounds" info["Weight"] = round(float(info["Weight"]) * 2.20462262, 2) if float(info["Weight"]) > 150.00: print('The maximum per package weight is 150.00 pounds.') return [] package1_weight.Value = round(float(info["Weight"]), 2) package1_weight.Units = "LB" package1 = rate.create_wsdl_object_of_type('RequestedPackageLineItem') package1.Weight = package1_weight package1.PhysicalPackaging = None package1.GroupPackageCount = 1 rate.add_package(package1) # shipping time from fedex.services.availability_commitment_service import FedexAvailabilityCommitmentRequest avc_request = FedexAvailabilityCommitmentRequest(CONFIG_OBJ) avc_request.Origin.PostalCode = info["ShipFrom"]["Address"]["PostalCode"] avc_request.Origin.CountryCode = info["ShipFrom"]["Address"]["CountryCode"] avc_request.Destination.PostalCode = info["ShipTo"]["Address"]["PostalCode"] avc_request.Destination.CountryCode = info["ShipTo"]["Address"]["CountryCode"] # Try operation try: # send request rate.send_request() avc_request.send_request() # print(type(avc_request.response.Options)) # for i in avc_request.response.Options: # print(dict(i)) # print(rate.response) rst = list() for service in rate.response.RateReplyDetails: for rate_detail in service.RatedShipmentDetails: # shipping time shipping_time = fedex_time(str(service.ServiceType), avc_request.response.Options) # service name try: ser_name = str(service.ServiceType).replace('_', ' ') except: ser_name = str(service.ServiceType) rst.append({"Company": "Fedex", 'Service': ser_name, 'Money': '$' + ' ' + str(rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount), 'Time': shipping_time}) return rst except Exception as e: print('Fedex error information:' + str(e)) return []
import logging import sys from example_config import CONFIG_OBJ 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)