Exemple #1
0
def get_config_obj(settings):
    return FedexConfig(key=settings.AUTHENTICATION_KEY.value,
                       password=settings.AUTHENTICATION_PASSWORD.value,
                       account_number=settings.ACCOUNT.value,
                       meter_number=settings.METER_NUMBER.value,
                       express_region_code=settings.SHIPPER_REGION.value,
                       use_test_server=settings.TEST_SERVER.value)
    def _get_cfg(self):
        """Makes and returns a FedexConfig object from the packagetrack
           configuration.  Caches it, so it doesn't create each time."""

        config = packagetrack.config

        # got one cached, so just return it
        if self.cfg:
            return self.cfg

        self.cfg = FedexConfig(
            key=config.get('FedEx', 'key'),
            password=config.get('FedEx', 'password'),
            account_number=config.get('FedEx', 'account_number'),
            meter_number=config.get('FedEx', 'meter_number'),
            use_test_server=False,
            express_region_code='US',
        )

        # these are optional, and afaik, not really used for tracking
        # at all, but you can still set them, so....
        if config.has_option('FedEx', 'express_region_code'):
            self.cfg.express_region_code = config.get('FedEx',
                                                      'express_region_code')

        if config.has_option('FedEx', 'integrator_id'):
            self.cfg.integrator_id = config.get('FedEx', 'integrator_id')

        if config.has_option('FedEx', 'use_test_server'):
            self.cfg.use_test_server = config.getboolean(
                'FedEx', 'use_test_server')

        return self.cfg
Exemple #3
0
	def get_fedex_credentials(self, transporter_doc):
		from fedex.config import FedexConfig
		credentials = FedexConfig(key = transporter_doc.fedex_key,
				password = transporter_doc.fedex_password,
				account_number = transporter_doc.fedex_account_number,
				meter_number = transporter_doc.fedex_meter_number,
				use_test_server = transporter_doc.is_test_server)
		return credentials
Exemple #4
0
    def fedex_get_rates(self, picking, data):
        sys.path.insert(
            0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

        # Change these values to match your testing account/meter number.
        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)
        logging.basicConfig(stream=sys.stdout, level=logging.INFO)
        rr = FedexRateServiceRequest(CONFIG_OBJ,
                                     customer_transaction_id=picking.name)
        rr.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
        # rr.RequestedShipment.ServiceType = 'GROUND_HOME_DELIVERY'
        rr.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
        rr.RequestedShipment.RateRequestTypes = 'LIST'
        # Shipper's address
        rr.RequestedShipment.Shipper.Address.StreetLines = '15004 3rd Ave'
        rr.RequestedShipment.Shipper.Address.City = 'Highland Park'
        rr.RequestedShipment.Shipper.Address.PostalCode = '48203-3718'
        rr.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'MI'
        rr.RequestedShipment.Shipper.Address.CountryCode = 'US'

        # Recipient address
        rr.RequestedShipment.Recipient.Address.StreetLines = picking.partner_id.street
        rr.RequestedShipment.Recipient.Address.City = data['toCity']
        rr.RequestedShipment.Recipient.Address.PostalCode = data[
            'toPostalCode']
        rr.RequestedShipment.Recipient.Address.StateOrProvinceCode = data[
            'toState']
        rr.RequestedShipment.Recipient.Address.CountryCode = data['toCountry']
        rr.RequestedShipment.Recipient.Address.Residential = picking.residential

        # rr.RequestedShipment.EdtRequestType = 'NONE'
        rr.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

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

        package1_dimensions = rr.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 = rr.create_wsdl_object_of_type('RequestedPackageLineItem')
        package1.Weight = package1_weight
        package1.Dimensions = package1_dimensions
        package1.PhysicalPackaging = 'BOX'
        package1.GroupPackageCount = 1

        rr.add_package(package1)

        rr.send_request()
        return rr
Exemple #5
0
def get(fedex_settings):
    fedex_settings = frappe.get_doc("Fedex Settings", fedex_settings)
    return FedexConfig(
        key=fedex_settings.key,
        password=fedex_settings.password,
        account_number=fedex_settings.account_number,
        meter_number=fedex_settings.meter_number,
        freight_account_number=fedex_settings.freight_account_number,
        use_test_server=fedex_settings.use_test_server)
Exemple #6
0
    def address_validation(self, address_id):
        """ This function is called from the wizard.Performs the actual computing in address validation """
        status = 0
        error_msg = ''
        fedex_accounts = self.env['fedex.account'].search([])
        if not fedex_accounts:
            warning = {
                'title': "No FedEx account!",
                'message': "No FedEx account found for validation."
            }
            return {'warning': warning}
        if fedex_accounts and address_id:
            fedex_account = fedex_accounts[0]
            if type(address_id) == type([]):
                address_id = address_id[0]
            partner_address = self.env['res.partner'].browse(address_id)
            from fedex.config import FedexConfig

            config_obj = FedexConfig(
                key=fedex_account.fedex_key,
                password=fedex_account.fedex_password,
                account_number=fedex_account.fedex_account_number,
                meter_number=fedex_account.fedex_meter_number,
                use_test_server=fedex_account.test_mode)
            from fedex.services.address_validation_service import FedexAddressValidationRequest

            address = FedexAddressValidationRequest(config_obj)
            address1 = address.create_wsdl_object_of_type('AddressToValidate')
            address1.CompanyName = partner_address.name or ''
            address1.Address.StreetLines = [
                partner_address.street, partner_address.street2
            ]
            address1.Address.City = partner_address.city
            address1.Address.StateOrProvinceCode = partner_address.state_id and partner_address.state_id.code or ''
            address1.Address.PostalCode = partner_address.zip
            address1.Address.CountryCode = partner_address.country_id and partner_address.country_id.code or ''
            address1.Address.Residential = False

            address.add_address(address1)

            ret_list = []
            try:
                address.send_request()
                response = address.response
                #Possible values ERROR, FAILURE, NOTE, WARNING, SUCCESS
                if response.HighestSeverity == 'SUCCESS':
                    error_msg = "The address is valid"
                    status = 1
                elif response.HighestSeverity == 'ERROR' or response.HighestSeverity == 'FAILURE':
                    error_msg = str(response.Notifications[0].Message)
            except Exception, e:
                error_msg = error_msg + str(e)
            return {
                'addr_status': status,
                'error_msg': error_msg,
                'address_list': ret_list
            }
Exemple #7
0
def get_fedex_config():
    """
    Returns a basic FedexConfig to test with.
    """
    # Test server (Enter your credentials here)
    return FedexConfig(key='',
                       password='',
                       account_number='',
                       meter_number='',
                       use_test_server=True)
 def config_fedex(self):
     config = self._get_config('fedex.config.settings')
     CONFIG_OBJ = FedexConfig(
         key=config['fedex_key'],
         password=config['fedex_password'],
         account_number=config['fedex_account_no'],
         meter_number=config['fedex_meter_no'],
         integrator_id=config['fedex_integration_id'],
         use_test_server=config['fedex_enviroment'] == 'test')
     return CONFIG_OBJ
 def __init__(self, fedex_account):
     settings = frappe.db.get_value("Shipment Forwarder", fedex_account,
                                    "*")
     self.config_obj = FedexConfig(
         key=settings.get("fedex_key"),
         password=client.get_password("Shipment Forwarder", fedex_account,
                                      "password"),
         account_number=settings.get("account_no"),
         meter_number=settings.get("fedex_meter_no"),
         freight_account_number=settings.get("account_no"),
         use_test_server=True if settings.get("is_test_account") else False)
Exemple #10
0
    def _get_cfg(self):
        """Makes and returns a FedexConfig object from the packagetrack
           configuration.  Caches it, so it doesn't create each time."""

        return FedexConfig(
            key=self._cfg_value('key'),
            password=self._cfg_value('password'),
            account_number=self._cfg_value('account_number'),
            meter_number=self._cfg_value('meter_number'),
            use_test_server=False,
            express_region_code='US',
        )
    def test_fedex_config(self):
        # Need to pass at least key and password
        with self.assertRaises(TypeError):
            FedexConfig()

        # Test minimum set of credentials, key and password
        config = FedexConfig('key', 'password')
        assert config.key
        assert config.password

        # Test with all parameters, including overwrite wsdl path
        config = FedexConfig(key='',
                             password='',
                             account_number='',
                             meter_number='',
                             freight_account_number='',
                             integrator_id='',
                             wsdl_path='/wsdls',
                             express_region_code=None,
                             use_test_server=False)

        assert config.wsdl_path
Exemple #12
0
 def __init__(self,
              key=None,
              password=None,
              account_number=None,
              meter_number=None,
              freight_account_number=None,
              use_test_server=True):
     self.CONFIG_OBJ = FedexConfig(
         key=key,
         password=password,
         account_number=account_number,
         meter_number=meter_number,
         freight_account_number=freight_account_number,
         use_test_server=use_test_server)
Exemple #13
0
 def __init__(self, to_country, postcode, weight, length, width, height, value, partner_name):
     fedex_config = FedexConfig(
         key=settings.FEDEX_ACCOUNT_KEY[partner_name],
         password=settings.FEDEX_ACCOUNT_PASSWORD[partner_name],
         account_number=settings.FEDEX_ACCOUNT_NUMBER[partner_name],
         meter_number=settings.FEDEX_METER_NUMBER[partner_name],
         freight_account_number=settings.FEDEX_FREIGHT_ACCOUNT_NUMBER[partner_name])
     self.rate_request = FedexRateServiceRequest(fedex_config)
     self.country_code = to_country.iso_3166_1_a2
     self.weight = float(weight)
     self.width = width
     self.length = length
     self.height = height
     self.value = value
     self.postcode = postcode
     self.partner_name = partner_name
Exemple #14
0
    def get_shipping_methods(self, user, basket, shipping_addr=None, **kwargs):

        if shipping_addr:
            config = FedexConfig(key='YvEfQwGwT1TvCU2h',
                                 password='******',
                                 account_number='510087763',
                                 meter_number='118597992',
                                 use_test_server=True)
            ##rate request
            rate_request = FedexRateServiceRequest(config)
            rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'
            rate_request.RequestedShipment.ServiceType = 'FEDEX_GROUND'
            rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'
            rate_request.RequestedShipment.PackageDetail = 'INDIVIDUAL_PACKAGES'

            # Shipper's address
            rate_request.RequestedShipment.Shipper.Address.PostalCode = '29631'
            rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
            rate_request.RequestedShipment.Shipper.Address.Residential = False

            # Recipient address
            rate_request.RequestedShipment.Recipient.Address.PostalCode = shipping_addr.postcode
            rate_request.RequestedShipment.Recipient.Address.CountryCode = shipping_addr.country_id
            rate_request.RequestedShipment.EdtRequestType = 'NONE'
            rate_request.RequestedShipment.ShippingChargesPayment.PaymentType = 'SENDER'

            package1_weight = rate_request.create_wsdl_object_of_type('Weight')
            # Weight, in LB.
            package1_weight.Value = 10.0
            package1_weight.Units = "LB"

            package1 = rate_request.create_wsdl_object_of_type(
                'RequestedPackageLineItem')
            package1.Weight = package1_weight
            package1.PhysicalPackaging = 'BOX'
            rate_request.add_package(package1)
            rate_request.send_request()
            for rate_detail in rate_request.response.RateReplyDetails[
                    0].RatedShipmentDetails:
                fedex_price = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
            ##set tax here (1.00)
            methods = [FixedPrice(D(fedex_price), D(fedex_price + 1.00))]
            return self.prime_methods(basket, methods)
        else:
            methods = [Free()]
            return self.prime_methods(basket, methods)
    def get_fedex_credentials(self):
        """
        Returns the fedex account credentials in tuple
        :return: FedexConfig object
        """
        if not all([
                self.fedex_key,
                self.fedex_account_number,
                self.fedex_password,
                self.fedex_meter_number,
        ]):
            self.raise_user_error('fedex_settings_missing')

        return FedexConfig(key=self.fedex_key,
                           password=self.fedex_password,
                           account_number=self.fedex_account_number,
                           meter_number=self.fedex_meter_number,
                           use_test_server=self.fedex_is_test)
Exemple #16
0
    def fedex_validate_address(self, picking, data):
        # NOTE: TO USE ADDRESS VALIDATION SERVICES, YOU NEED TO REQUEST FEDEX TO ENABLE THIS SERVICE FOR YOUR ACCOUNT.
        # BY DEFAULT, THE SERVICE IS DISABLED AND YOU WILL RECEIVE AUTHENTICATION FAILED, 1000 RESPONSE.
        client_language_code = 'EN'
        client_locale_code = 'US'
        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)
        customer_transaction_id = 'Address validation for %s' % picking.name
        avs_request = FedexAddressValidationRequest(
            CONFIG_OBJ,
            customer_transaction_id=customer_transaction_id,
            client_locale_code=client_locale_code,
            client_language_code=client_language_code)

        # Create some addresses to validate
        address1 = avs_request.create_wsdl_object_of_type('AddressToValidate')
        address1.ClientReferenceId = picking.partner_id
        address1.Address.StreetLines = picking.partner_id.street
        address1.Address.City = data['toCity']
        address1.Address.StateOrProvinceCode = data['toState']
        address1.Address.PostalCode = data['toPostalCode']
        address1.Address.CountryCode = data['toCountry']
        avs_request.add_address(address1)

        avs_request.send_request()

        if len(avs_request.response.AddressResults):
            is_resident = avs_request.response.AddressResults[
                0].Classification != 'BUSINESS'  # Non BUSINESS means residential address
            return is_resident
        else:
            return False  # by default consider it false
Exemple #17
0
    def url_scrapping(self,cr,uid,ids,ups_browse,fedex_browse,context=None):
        print ids[0]
        obj = self.browse(cr, uid, ids[0], context=context)
        print '>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>',obj

        if obj.carrier_selection == 'dhl' and obj.delivered == False:
            try:
                url = "http://www.dhl.co.in/shipmentTracking"
                querystring = {"AWB":obj.tracking_no, "countryCode": "in", "languageCode": "en", "_": "1511447699608"}
                headers = {
                    'cache-control': "no-cache",
                    'postman-token': "cb9efd5e-f6be-248f-cf53-9bb555403121"
                }
                response = requests.request("GET", url, headers=headers, params=querystring)
                print response.text
                data=json.loads(response.text)
                # print'>>>>>>>>>>jsonloads', data
                for result in data['results']:
                    count=0
                    for check in result.get('checkpoints'):
                        count +=1
                        print count
                        result_description=check.get('description')
                        print ">>>",result_description
                        result_time=check.get('time')
                        result_date=check.get('date')
                        result_date=parse(result_date).strftime('%d/%m/%Y')
                        print ">>>", result_date
                        result_location=check.get('location')
                        print ">>>", result_date
                        vsa_line_env=self.pool.get('vsa.line')
                        vsa_id=vsa_line_env.search(cr,uid,[('date','=',result_date+'-'+result_time)],context)
                        if not vsa_id:
                            vals={'name':result_location,
                                  'description':result_description,
                                  'date':result_date+'-'+result_time,
                                  'vsa_line':ids[0]}
                            vsa_line_create=vsa_line_env.create(cr, uid, vals, context)
                            result_edd='NA'
                            if result.get('edd'):
                                result_edd=result.get('edd').get('date')
                                result_edd = parse(result_edd).strftime('%d/%m/%Y')
                            result_signatory=result.get('signature').get('signatory')
                            print '>>>>?>>>>>>',result_signatory
                            if count ==1:
                                write=obj.write({'expected_arrival':result_edd,'last_status':result_description+ " On "+result_date })
                                print '>>>>>>>>>>>>>>>>>>>>>>>>>>>write',write
                            if "Delivered" in result_description:
                                write=obj.write({'delivered':True})

            except Exception:
                _logger.error("NO Records Found for DHL")
                vsa_line_env = self.pool.get('vsa.line')
                vals = {'name': "NOT FOUND",
                        'description': "NOT FOUND",
                        'date': "NOT FOUND",
                        'vsa_line': ids[0]}
                vsa_line_create = vsa_line_env.create(cr, uid, vals, context)



        if obj.carrier_selection =='ups' and obj.delivered == False:
            try:
                print ups_browse.name
                print ups_browse.password
                url_ups = "https://wwwcie.ups.com/rest/Track"

                payload ="""{
                              "Security": {
                                "UsernameToken": {
                                  "Username":""" +ups_browse.name+""",
                                  "Password":"""+ups_browse.password+"""
                                },
                                "UPSServiceAccessToken": {
                                  "AccessLicenseNumber":"""+ups_browse.access_key+"""
                                }
                              },
                              "TrackRequest": {
                                "Request": {
                                  "RequestOption": "15",
                                  "TransactionReference": {
                                    "CustomerContext": "Your Test Case Summary Description"
                                  }
                                },
                                "InquiryNumber":"""+obj.tracking_no+""",
                                "TrackingOption": "02"
                              }
                            }"""
                headers = {
                    'content-type': "application/json",
                    'cache-control': "no-cache",
                    'postman-token': "12a378d9-76ec-08f6-e365-5e56d1a49479"
                }

                response = requests.request("POST", url_ups, data=payload, headers=headers)

                print response.text
                data=json.loads(response.text)
                count =0
                for activity in data['TrackResponse']['Shipment']['Package']['Activity']:
                    count +=1
                    if activity.get('ActivityLocation').get('Address'):
                        city=activity.get('ActivityLocation').get('Address').get('City')
                        print'>>>>>>>>>>>>>>>>>>>>',city
                        description=activity.get("Status").get("Description")
                        print'>>>>>>>>>>>>>>>>>>>>', description
                        date = activity.get("Date")
                        time_api = activity.get("Time")
                        date_time=date+time_api
                        date = parse(date_time).strftime('%d/%m/%Y %H:%M:%S')
                        print'>>>>>>>>>>>>>>>>>>>>', date


                        vsa_line_env = self.pool.get('vsa.line')
                        vsa_id=vsa_line_env.search(cr,uid,[('date','=',date)],context)
                        if not vsa_id:
                            vals={'name':city,
                                  'description':description,
                                  'date':date,
                                  'vsa_line':ids[0]}
                            vsa_line_create=vsa_line_env.create(cr, uid, vals, context)
                            if count ==1:
                                write = obj.write({'expected_arrival': "NA", 'last_status': description +" at "+ city +" on " + date})
                            if "Delivered" in description:
                                write=obj.write({'delivered':True})
            except Exception:
                _logger.error("NO Records Found for UPS")
                vsa_line_env = self.pool.get('vsa.line')
                vals = {'name': "NOT FOUND",
                        'description': "NOT FOUND",
                        'date': "NOT FOUND",
                        'vsa_line': ids[0]}
                vsa_line_create = vsa_line_env.create(cr, uid, vals, context)

        if obj.carrier_selection =='fedex' and obj.delivered == False:
            try:

                CONFIG_OBJ = FedexConfig(key=fedex_browse.name,
                                         password=fedex_browse.password,
                                         account_number=fedex_browse.account_no,
                                         meter_number=fedex_browse.meter_no,
                                       # freight_account_number='xxxxxxxxxxx',
                                         use_test_server=True)

                customer_transaction_id = "*** TrackService Request v10 using Python ***"  # Optional transaction_id
                track = FedexTrackRequest(CONFIG_OBJ, customer_transaction_id=customer_transaction_id)

                # Track by Tracking Number
                track.SelectionDetails.PackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
                track.SelectionDetails.PackageIdentifier.Value = obj.tracking_no

                # FedEx operating company or delete
                del track.SelectionDetails.OperatingCompany
                track.send_request()
                print(track.response)
                data=track.response
                # print '>>>>>>>>>>>>>>>>>>>>>>>>>>EstimatedDeliveryTimestamp',data.CompletedTrackDetails
                for record in data.CompletedTrackDetails:
                    for set in record.TrackDetails:
                        print type(set)

                        # print '>>>>>>>>>>>>>>>>>>>>>>>>>>EstimatedDeliveryTimestamp',time

                        for event in set.Events:
                            timestamp=event.Timestamp
                            timestamp = timestamp.strftime('%d/%m/%Y-%H:%M:%S')
                            print '>>>>>>>>>>>>>>>>>>>>>>>>>>timestamp', timestamp
                            EventDescription=event.EventDescription
                            print '>>>>>>>>>>>>>>>>>>>>>>>>>>EventDescription', EventDescription
                            city='(Address Not Provided)'
                            if 'City' in event.Address:
                                city=event.Address.City
                                print '>>>>>>>>>>>>>>>>>>>>>>>>>>city', city

                            vsa_line_env = self.pool.get('vsa.line')
                            vsa_id = vsa_line_env.search(cr, uid, [('date', '=', timestamp)], context)
                            if not vsa_id:
                                vals = {'name': city ,
                                        'description': EventDescription,
                                        'date': timestamp,
                                        'vsa_line': ids[0]}
                                vsa_line_create = vsa_line_env.create(cr, uid, vals, context)
                                split_time=timestamp.split('-')
                                write=obj.write({'expected_arrival': "NA",'last_status': EventDescription + " at " + city + " on " + split_time[0]})
                                if "Delivered" in EventDescription:
                                    write = obj.write({'delivered': True})
                                cr.commit()
                        if 'EstimatedDeliveryTimestamp' in set:
                            time = set.EstimatedDeliveryTimestamp
                            time = time.strftime('%d/%m/%Y')
                            write = obj.write({'expected_arrival': time})
            except Exception:
                _logger.error("NO Records Found for Fedex")
                vsa_line_env = self.pool.get('vsa.line')
                vals = {'name': "NOT FOUND",
                        'description': "Server is UnReachable or This Order is Arrived",
                        'date': "NOT FOUND",
                        'vsa_line': ids[0]}
                write = obj.write({'expected_arrival': "Server is UnReachable or This Order is Arrived"})
                vsa_line_create = vsa_line_env.create(cr, uid, vals, context)

        return True
Exemple #18
0
    def fedex_address_validation(self, cr, uid, ids, context=None):
        partneraddr_obj = self.pool.get('res.partner')
        shippingfedex_obj = self.pool.get('shipping.fedex')
        status = None
        shippingfedex_id = shippingfedex_obj.search(cr, uid,
                                                    [('active', '=', True)])

        for sales_order in self.browse(cr, uid, ids):
            partner_id = sales_order.partner_shipping_id
            if not shippingfedex_id:
                raise osv.except_osv(_('Error'),
                                     _('Default Fedex settings not defined'))
            else:
                shippingfedex_id = shippingfedex_id[0]

            shippingfedex_ptr = shippingfedex_obj.browse(
                cr, uid, shippingfedex_id)
            account_no = shippingfedex_ptr.account_no
            key = shippingfedex_ptr.key
            password = shippingfedex_ptr.password
            meter_no = shippingfedex_ptr.meter_no
            is_test = shippingfedex_ptr.test

            CONFIG_OBJ = FedexConfig(key=key,
                                     password=password,
                                     account_number=account_no,
                                     meter_number=meter_no,
                                     use_test_server=is_test)
            connection = FedexAddressValidationRequest(CONFIG_OBJ)

            # The AddressValidationOptions are created with default values of None, which
            # will cause WSDL validation errors. To make things work, each option needs to
            # be explicitly set or deleted.

            ### Get Address from sale order

            cust_name = partner_id.name or ''
            cust_id = partner_id.id or ''

            street = partner_id.street or ''

            street2 = partner_id.street2 or ''

            city = partner_id.city or ''

            postal_code = partner_id.zip or ''

            phone = partner_id.phone or ''

            email = partner_id.email or ''

            receipient = Address(cust_name or cust_id, street, city,
                                 partner_id.state_id.code or '', postal_code,
                                 partner_id.country_id.code, street2 or '',
                                 phone or '', email or '',
                                 partner_id.company_id.name or '')

            ## Set the flags we want to True (or a value).
            connection.RequestTimestamp = datetime.datetime.now().isoformat()
            #connection.AddressValidationOptions.CheckResidentialStatus = True
            #connection.AddressValidationOptions.VerifyAddresses = True
            #connection.AddressValidationOptions.RecognizeAlternateCityNames = True
            #connection.AddressValidationOptions.MaximumNumberOfMatches = 3

            ## Delete the flags we don't want.
            #del connection.AddressValidationOptions.ConvertToUpperCase
            #del connection.AddressValidationOptions.ReturnParsedElements

            ## *Accuracy fields can be TIGHT, EXACT, MEDIUM, or LOOSE. Or deleted.
            #connection.AddressValidationOptions.StreetAccuracy = 'LOOSE'
            #del connection.AddressValidationOptions.DirectionalAccuracy
            #del connection.AddressValidationOptions.CompanyNameAccuracy

            ## Create some addresses to validate
            ### Shipper
            cust_address = sales_order.company_id
            if not cust_address:
                raise osv.except_osv(
                    _('Error'),
                    _('Shop Address not defined!'),
                )

            shipper = Address(cust_address.name or cust_address.id,
                              cust_address.street, cust_address.city,
                              cust_address.state_id.code or '',
                              cust_address.zip, cust_address.country_id.code,
                              cust_address.street2 or '', cust_address.phone
                              or '', cust_address.email, cust_address.name)

            source_address = connection.create_wsdl_object_of_type(
                'AddressToValidate')
            source_address.Address.StreetLines = shipper.address1  # ['320 S Cedros', '#200']
            source_address.Address.City = shipper.city  # 'Solana Beach'
            source_address.Address.StateOrProvinceCode = shipper.state_code  # 'CA'
            source_address.Address.PostalCode = shipper.zip  # 92075
            source_address.Address.CountryCode = shipper.country_code  # 'US'
            connection.add_address(source_address)

            sale_order_destination_address = connection.create_wsdl_object_of_type(
                'AddressToValidate')
            #sale_order_destination_address.CompanyName = receipient.company_name
            sale_order_destination_address.Address.StreetLines = receipient.address1  #['155 Old Greenville Hwy', 'Suite 103']
            sale_order_destination_address.Address.City = receipient.city  #'Clemson'
            sale_order_destination_address.Address.StateOrProvinceCode = receipient.state_code  #'SC'
            sale_order_destination_address.Address.PostalCode = receipient.zip  #29631
            sale_order_destination_address.Address.CountryCode = receipient.country_code  #'US'
            sale_order_destination_address.Address.Residential = False
            connection.add_address(sale_order_destination_address)

            try:
                ## Send the request and print the response
                connection.send_request()
                sales_order.is_test = True
                self.write(cr, uid, ids, {
                    'is_test': True,
                    'valid_note': 'Address is Valid'
                }, context)
                cr.commit()
            except Exception, e:
                sales_order.invalid_addr = False
                self.write(cr, uid, ids, {
                    'is_test': False,
                    'valid_note': 'Address is InValid'
                }, context)
                cr.commit()
                raise osv.except_osv(
                    _('Error'),
                    _('Invalid address, Please fill correct shipping address'))
            results = len(connection.response.AddressResults)
"""
This file holds various configuration options used for all of the examples.

You will need to change the values below to match your test account.
"""
import os
import sys
# Use the fedex directory included in the downloaded package instead of
# any globally installed versions.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fedex.config import FedexConfig

# Change these values to match your testing account/meter number.
CONFIG_OBJ = FedexConfig(key='xxxxxxxxxxxxxxxx',
                         password='******',
                         account_number='#########',
                         meter_number='#########',
                         use_test_server=True)
def main():

    CONFIG_OBJ = FedexConfig(key='',
                             password='******',
                             account_number='',
                             meter_number='',
                             use_test_server=False)
    rate = FedexRateServiceRequest(CONFIG_OBJ)
    logging.basicConfig(stream=sys.stdout, level=logging.INFO)

    customer_transaction_id = "*** RateService Request v18 using Python ***"  # Optional transaction_id

    # This is the object that will be handling our request which is utilized to retrieve rates
    rate_request = FedexRateServiceRequest(
        CONFIG_OBJ, customer_transaction_id=customer_transaction_id)
    #print(rate_request)

    # If you wish to have transit data returned with your request you
    # need to uncomment the following
    # rate_request.ReturnTransitAndCommit = True

    # This is very generalized, top-level information.
    # REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER or STATION
    rate_request.RequestedShipment.DropoffType = 'BUSINESS_SERVICE_CENTER'

    # 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
    # To receive rates for multiple ServiceTypes set to None.
    rate_request.RequestedShipment.ServiceType = 'PRIORITY_OVERNIGHT'

    # What kind of package this will be shipped in.
    # FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING
    rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

    # Shipper's address
    rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'TX'
    rate_request.RequestedShipment.Shipper.Address.PostalCode = '78728'
    rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Recipient address
    rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'NC'
    rate_request.RequestedShipment.Recipient.Address.PostalCode = '27577'
    rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US'
    # This is needed to ensure an accurate rate quote with the response.
    # rate_request.RequestedShipment.Recipient.Address.Residential = True
    # include estimated duties and taxes in rate quote, can be ALL or NONE
    rate_request.RequestedShipment.EdtRequestType = 'NONE'

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

    # See https://www.fedex.com/us/developer/downloads/pdfs/2021/FedEx_WebServices_RateServices_WSDLGuide_v2021.pdf  for a full list.
    #Here are the common ones:
    # Weight, Dimensions

    package1_weight = rate_request.create_wsdl_object_of_type('Weight')
    # Weight, in LB. and limit is 150lbs for box shipments
    package1_weight.Value = 300
    package1_weight.Units = "LB"

    package1_dimensions = rate_request.create_wsdl_object_of_type('Dimensions')
    # Dimensions, in IN
    # Box size choices: 22X15X15, 24X18X18, 12X10X6, 18X12X12, 14X14X6
    package1_dimensions.Length = 48
    package1_dimensions.Width = 40
    package1_dimensions.Height = 55
    package1_dimensions.Units = "IN"

    package1 = rate_request.create_wsdl_object_of_type(
        'RequestedPackageLineItem')
    package1.Weight = package1_weight
    package1.Dimensions = package1_dimensions
    # can be other values this is probably the most common
    package1.PhysicalPackaging = 'BOX'
    # Required, but according to FedEx docs:
    # "Used only with PACKAGE_GROUPS, as a count of packages within a
    # group of identical packages". In practice you can use this to get rates
    # for a shipment with multiple packages of an identical package size/weight
    # on rate request without creating multiple RequestedPackageLineItem elements.
    # You can OPTIONALLY specify a package group:
    # package1.GroupNumber = 0  # default is 0
    # The result will be found in RatedPackageDetail, with specified GroupNumber.
    package1.GroupPackageCount = 1

    # Un-comment this to see the other variables you may set on a package.
    # print(package1)

    # This adds the RequestedPackageLineItem WSDL object to the rate_request. It
    # increments the package count and total weight of the rate_request for you.
    rate_request.add_package(package1)

    # If you'd like to see some documentation on the ship service WSDL, un-comment
    # this line. (Spammy).
    # print(rate_request.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(rate_request.RequestedShipment)

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

    # This will show the reply to your rate_request being sent. You can access the
    # attributes through the response attribute on the request object. This is
    # good to un-comment to see the variables returned by the FedEx reply.
    # print(rate_request.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(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))

    df = pd.DataFrame()
    df2 = pd.DataFrame()
    counter = 0

    # 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))

        #print fedex charge details (cost)
        for rate_detail in service.RatedShipmentDetails:
            #rate_detail=("{}: Net FedEx Charge {} {}".format(service.ServiceType,
            #                                          rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Currency,
            #                                       rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount))
            rate_detail = rate_detail.ShipmentRateDetail.TotalNetFedExCharge.Amount
            if counter == 0:
                your_rate = float(rate_detail)
                print('\nYour rate \n', your_rate)
                df = df.append({'Your_rate': your_rate}, ignore_index=True)

            else:
                more_rates = float(rate_detail)
                print('\nMultiweight Rate \n', more_rates)
                df['Multiweight_rate'] = more_rates

            counter = +1

            my_dir = ''
            file_name = 'Fedex_Box_Quote.csv'
            fname = os.path.join(my_dir, file_name)
            df.to_csv(fname, index=False)
Exemple #21
0
"""
This file holds various configuration options used for all of the examples.
You will need to change the values below to match your test account.
"""
import os
import sys
# Use the fedex directory included in the downloaded package instead of
# any globally installed versions.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fedex.config import FedexConfig

# Change these values to match your testing account/meter number.
CONFIG_OBJ = FedexConfig(key='XXX',
                         password='******',
                         account_number='XXX',
                         meter_number='XXX',
                         use_test_server=True,
                         customer_transaction_id='XXXXXX')
Exemple #22
0
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 []
from fedex.config import FedexConfig

CONFIG_OBJ = FedexConfig(key='',
                         password='',
                         account_number='',
                         meter_number='')

api_key = ""
Exemple #24
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
Exemple #25
0
def main():

    CONFIG_OBJ = FedexConfig(key='',
                             password='',
                             account_number='',
                             meter_number='',
                             freight_account_number='',
                             use_test_server=False)

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

    customer_transaction_id = "*** RateService Request v18 using Python ***"  # Optional transaction_id

    # This is the object that will be handling our request which is utilized to retrieve rates
    rate_request = FedexRateServiceRequest(
        CONFIG_OBJ, customer_transaction_id=customer_transaction_id)

    rate_request.RequestedShipment.ServiceType = 'FEDEX_FREIGHT_ECONOMY'

    rate_request.RequestedShipment.DropoffType = 'REGULAR_PICKUP'

    rate_request.RequestedShipment.PackagingType = 'YOUR_PACKAGING'

    rate_request.RequestedShipment.FreightShipmentDetail.TotalHandlingUnits = 1

    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightAccountNumber = CONFIG_OBJ.freight_account_number

    # Shipper
    rate_request.RequestedShipment.Shipper.AccountNumber = CONFIG_OBJ.freight_account_number
    rate_request.RequestedShipment.Shipper.Contact.PersonName = 'Sender Name'
    rate_request.RequestedShipment.Shipper.Contact.CompanyName = 'Customer ABC'
    rate_request.RequestedShipment.Shipper.Address.StreetLines = [
        '123 Parker Drive'
    ]
    rate_request.RequestedShipment.Shipper.Address.City = 'Austin'
    rate_request.RequestedShipment.Shipper.Address.StateOrProvinceCode = 'TX'
    rate_request.RequestedShipment.Shipper.Address.PostalCode = '78728'
    rate_request.RequestedShipment.Shipper.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Recipient
    rate_request.RequestedShipment.Recipient.Address.City = 'Harrison'
    rate_request.RequestedShipment.Recipient.Address.StateOrProvinceCode = 'AR'
    rate_request.RequestedShipment.Recipient.Address.PostalCode = '72601'
    rate_request.RequestedShipment.Recipient.Address.CountryCode = 'US'
    rate_request.RequestedShipment.Shipper.Address.Residential = False

    # Payment
    payment = rate_request.create_wsdl_object_of_type('Payment')
    payment.PaymentType = "SENDER"
    payment.Payor.ResponsibleParty = rate_request.RequestedShipment.Shipper
    rate_request.RequestedShipment.ShippingChargesPayment = payment

    # include estimated duties and taxes in rate quote, can be ALL or NONE
    rate_request.RequestedShipment.EdtRequestType = 'NONE'

    # note: in order for this to work in test, you may need to use the
    # specially provided LTL addresses emailed to you when signing up.
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.PersonName = 'Sender Name'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Contact.CompanyName = 'Customer ABC'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StreetLines = [
        '111 Circle Drive'
    ]
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.City = 'Engelwood'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.StateOrProvinceCode = 'CO'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.PostalCode = '80111'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.CountryCode = 'US'
    rate_request.RequestedShipment.FreightShipmentDetail.FedExFreightBillingContactAndAddress.Address.Residential = False

    spec = rate_request.create_wsdl_object_of_type(
        'ShippingDocumentSpecification')

    spec.ShippingDocumentTypes = [spec.CertificateOfOrigin]

    rate_request.RequestedShipment.ShippingDocumentSpecification = spec

    role = rate_request.create_wsdl_object_of_type('FreightShipmentRoleType')
    rate_request.RequestedShipment.FreightShipmentDetail.Role = role.SHIPPER

    # Designates the terms of the "collect" payment for a Freight
    # Shipment. Can be NON_RECOURSE_SHIPPER_SIGNED or STANDARD
    rate_request.RequestedShipment.FreightShipmentDetail.CollectTermsType = 'STANDARD'

    package1_weight = rate_request.create_wsdl_object_of_type('Weight')
    package1_weight.Value = 300.0
    package1_weight.Units = "LB"

    rate_request.RequestedShipment.FreightShipmentDetail.PalletWeight = package1_weight

    package1_dimensions = rate_request.create_wsdl_object_of_type('Dimensions')
    package1_dimensions.Length = 48
    package1_dimensions.Width = 40
    package1_dimensions.Height = 40
    package1_dimensions.Units = "IN"

    #rate_request.RequestedShipment.FreightShipmentDetail= package1_dimensions
    #print (package1_dimensions)
    package1 = rate_request.create_wsdl_object_of_type(
        'FreightShipmentLineItem')
    print(package1)

    package1.Weight = package1_weight
    package1.Dimensions = package1_dimensions
    package1.Packaging = 'PALLET'
    package1.Description = 'Products'
    package1.FreightClass = 'CLASS_500'

    rate_request.RequestedShipment.FreightShipmentDetail.LineItems = package1
    print(package1)
    # If you'd like to see some documentation on the ship service WSDL, un-comment
    # this line. (Spammy).
    print(rate_request.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(rate_request.RequestedShipment)

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

    # This will show the reply to your rate_request being sent. You can access the
    # attributes through the response attribute on the request object. This is
    # good to un-comment to see the variables returned by the FedEx reply.
    # print(rate_request.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(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))
"""
This file holds various configuration options used for all of the examples.

You will need to change the values below to match your test account.
"""
import os
import sys
# Use the fedex directory included in the downloaded package instead of
# any globally installed versions.
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from fedex.config import FedexConfig

# Change these values to match your testing account/meter number.
CONFIG_OBJ = FedexConfig(key='pJWiO448Vp2l5Lwu',
                         password='******',
                         account_number='510087623',
                         meter_number='118694899',
                         freight_account_number=None,
                         use_test_server=True)
Exemple #27
0
import os
from fedex.config import FedexConfig

MAX_WEIGHT = 68
WS_URL = os.environ.get('FEDEX_URL')
"""
This file holds various configuration options used for Fedex services
"""

CONFIG_OBJ = FedexConfig(key=os.environ.get('FEDEX_KEY'),
                         password=os.environ.get('FEDEX_PW'),
                         account_number=os.environ.get('FEDEX_ACC_NO'),
                         meter_number=os.environ.get('FEDEX_METER_NO'),
                         use_test_server=False)