Esempio n. 1
0
    def track(self, tracking_number):
        if not self.validate(tracking_number):
            raise InvalidTrackingNumber()

        track = FedexTrackRequest(self._get_cfg())

        track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
        track.TrackPackageIdentifier.Value = tracking_number
        track.IncludeDetailedScans = True

        # Fires off the request, sets the 'response' attribute on the object.
        try:
            track.send_request()
        except FedexInvalidTrackingNumber as e:
            raise InvalidTrackingNumber(e)
        except FedexError as e:
            raise TrackFailed(e)

        # TODO: I haven't actually seen an unsuccessful query yet
        if track.response.HighestSeverity != "SUCCESS":
            raise TrackFailed(
                "%d: %s" % (track.response.Notifications[0].Code,
                            track.response.Notifications[0].LocalizedMessage))

        return self._parse_response(track.response.TrackDetails[0],
                                    tracking_number)
    def track(self, tracking_number):
        if not self.validate(tracking_number):
            raise InvalidTrackingNumber()

        track = FedexTrackRequest(self._get_cfg())

        track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
        track.TrackPackageIdentifier.Value = tracking_number
        track.IncludeDetailedScans = True

        # Fires off the request, sets the 'response' attribute on the object.
        try:
            track.send_request()
        except FedexInvalidTrackingNumber as e:
            raise InvalidTrackingNumber(e)
        except FedexError as e:
            raise TrackFailed(e)

        # TODO: I haven't actually seen an unsuccessful query yet
        if track.response.HighestSeverity != "SUCCESS":
            raise TrackFailed("%d: %s" % (
                    track.response.Notifications[0].Code,
                    track.response.Notifications[0].LocalizedMessage
            ))

        return self._parse_response(track.response.TrackDetails[0], tracking_number)
Esempio n. 3
0
    def test_track(self):
        """
        Test shipment tracking. Query for a tracking number and make sure the
        first (and hopefully only) result matches up.
        """
        track = FedexTrackRequest(CONFIG_OBJ)
        track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
        track.TrackPackageIdentifier.Value = '798114182456'
        track.send_request()

        for match in track.response.TrackDetails:
            # This should be the same tracking number on the response that we
            # asked for in the request.
            self.assertEqual(match.TrackingNumber, tracking_num)
Esempio n. 4
0
 def test_track(self):
     """
     Test shipment tracking. Query for a tracking number and make sure the
     first (and hopefully only) result matches up.
     """
     track = FedexTrackRequest(CONFIG_OBJ)
     track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
     track.TrackPackageIdentifier.Value = '798114182456'
     track.send_request()
         
     for match in track.response.TrackDetails:
         # This should be the same tracking number on the response that we
         # asked for in the request.
         self.assertEqual(match.TrackingNumber, tracking_num)
    def track_shipment(self, tracking_id):
        customer_transaction_id = "*** TrackService Request v10 using Python ***"  # Optional transaction_id
        track = FedexTrackRequest(self.config_obj)

        # Track by Tracking Number
        track.SelectionDetails.PackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
        track.SelectionDetails.PackageIdentifier.Value = '{0}'.format(
            tracking_id)

        # FedEx operating company or delete
        del track.SelectionDetails.OperatingCompany
        track.send_request()
        package_tracking_details = {}
        for c_t_d in track.response.CompletedTrackDetails:
            for t_d in c_t_d.TrackDetails:
                if hasattr(t_d, 'EstimatedDeliveryTimestamp'):
                    package_tracking_details[
                        "EstimatedDelivery"] = t_d.EstimatedDeliveryTimestamp.strftime(
                            "%Y-%m-%d %H:%M:%S")
                if hasattr(t_d, 'ActualDeliveryTimestamp'):
                    package_tracking_details[
                        "ActualDelivery"] = t_d.ActualDeliveryTimestamp.strftime(
                            "%Y-%m-%d %H:%M:%S")
                if hasattr(t_d, "Notification"):
                    if t_d.Notification.Severity == "SUCCESS":
                        package_tracking_details[
                            'track_code'] = t_d.StatusDetail.Code
                        package_tracking_details[
                            'shipment_status'] = packing_slip_tracking_status(
                                t_d.StatusDetail.Code
                            ) if packing_slip_tracking_status(
                                t_d.StatusDetail.Code) else ""
                        package_tracking_details[
                            'shipment_description'] = t_d.StatusDetail.Description
                        package_tracking_details['message'] = "<b>Tracking ID -</b> {0}<br><b>Tracking Status -</b> {1} - {2}<br><b>Description - </b>{3}<br>".format(tracking_id,\
                                  t_d.StatusDetail.Code,package_tracking_details['shipment_status'],t_d.StatusDetail.Description,t_d.Notification.LocalizedMessage)
                    if t_d.Notification.Severity == "ERROR":
                        package_tracking_details[
                            'message'] = """<b>Tracking ID -</b> {0}<br>
																<b>Notification Code -</b> {1}<br>{2}""".format(
                                tracking_id, t_d.Notification.Code,
                                t_d.Notification.LocalizedMessage)
                        package_tracking_details['shipment_status'] = ""
                        package_tracking_details['shipment_description'] = ""
                        package_tracking_details[
                            'track_code'] = t_d.Notification.Code
        return package_tracking_details
    def test_track(self):
        # Test shipment tracking. Query for a tracking number and make sure the
        # first (and hopefully only) result matches up.

        tracking_num = '781820562774'

        track = FedexTrackRequest(CONFIG_OBJ)

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

        # FedEx operating company or delete
        del track.SelectionDetails.OperatingCompany

        track.send_request()

        assert track.response
Esempio n. 7
0
    def test_track(self):
        # Test shipment tracking. Query for a tracking number and make sure the
        # first (and hopefully only) result matches up.

        tracking_num = '781820562774'

        track = FedexTrackRequest(CONFIG_OBJ)

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

        # FedEx operating company or delete
        del track.SelectionDetails.OperatingCompany

        track.send_request()

        assert track.response
def get_delivery_date(tracking_number):
    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 = tracking_number

    del track.SelectionDetails.OperatingCompany

    track.send_request()

    for match in track.response.CompletedTrackDetails[0].TrackDetails:
        event_details = []
        if hasattr(match, 'Events'):
            for j in range(len(match.Events)):
                event_match = match.Events[j]
                event_details.append({
                    'created':
                    event_match.Timestamp,
                    'type':
                    event_match.EventType,
                    'description':
                    event_match.EventDescription
                })

                if hasattr(event_match, 'StatusExceptionDescription'):
                    event_details[j][
                        'exception_description'] = event_match.StatusExceptionDescription

    delivery_date = None

    for item in event_details:
        if item["description"] == "Delivered":
            delivery_date = item["created"].strftime("%b %d, %Y")

    return delivery_date
Esempio n. 9
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
Esempio n. 10
0
#!/usr/bin/env python
"""
This example shows how to track shipments.
"""
import logging
from example_config import CONFIG_OBJ
from fedex.services.track_service import FedexTrackRequest

# Set this to the INFO level to see the response from Fedex printed in stdout.
logging.basicConfig(level=logging.INFO)

# NOTE: TRACKING IS VERY ERRATIC ON THE TEST SERVERS. YOU MAY NEED TO USE
# PRODUCTION KEYS/PASSWORDS/ACCOUNT #.
# We're using the FedexConfig object from example_config.py in this dir.
track = FedexTrackRequest(CONFIG_OBJ)
track.TrackPackageIdentifier.Type = 'TRACKING_NUMBER_OR_DOORTAG'
track.TrackPackageIdentifier.Value = '798114182456'

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

# See the response printed out.
print track.response

# Look through the matches (there should only be one for a tracking number
# query), and show a few details about each shipment.
print "== Results =="
for match in track.response.TrackDetails:
    print "Tracking #:", match.TrackingNumber
    print "Status:", match.StatusDescription
import logging
import sys

from example_config import CONFIG_OBJ
from fedex.services.track_service import FedexTrackRequest

# Un-comment to see the response from Fedex printed in stdout.
logging.basicConfig(stream=sys.stdout, level=logging.INFO)

# NOTE: TRACKING IS VERY ERRATIC ON THE TEST SERVERS. YOU MAY NEED TO USE
# PRODUCTION KEYS/PASSWORDS/ACCOUNT #. THE TEST SERVERS OFTEN RETURN A NOT FOUND ERROR.
# WHEN TESTING IN PRODUCTION, GIVE SOME TIME FOR THE TRACKING TO PROPAGATE.

# We're using the FedexConfig object from example_config.py in this dir.
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 = '781820562774'

# FedEx operating company or delete
del track.SelectionDetails.OperatingCompany

# Can optionally set the TrackingNumberUniqueIdentifier
# del track.SelectionDetails.TrackingNumberUniqueIdentifier

# If you'd like to see some documentation on the ship service WSDL, un-comment
# this line. (Spammy).
# print(track.client)
Esempio n. 12
0
def get_status(tracking_id, tracking_id_name=None, process_type=None, ship_zip=None):
    # Set this to the INFO level to see the response from Fedex printed in stdout.
    logging.basicConfig(level=logging.INFO)
    """
    added the below to capture more logs during debugging and to limit logs during production
    """
    logging.getLogger().setLevel(logging.ERROR)
    """
    added the below to get more data during debugging.
    uncomment these to log suds SOAP exchanges. Can set them to DEBUG or INFO, etc.
    via http://blogs.it.ox.ac.uk/inapickle/2011/05/15/using-logging-to-debug-what-suds-is-sending-across-the-wire/
    """
#    handler = logging.StreamHandler(sys.stderr)
#    logger = logging.getLogger('suds.transport.http')
#    logger.setLevel(logging.DEBUG), handler.setLevel(logging.DEBUG)
#    logger.addHandler(handler)
    
    # NOTE: TRACKING IS VERY ERRATIC ON THE TEST SERVERS. YOU MAY NEED TO USE
    # PRODUCTION KEYS/PASSWORDS/ACCOUNT #.
    # We're using the FedexConfig object from example_config.py in this dir.
    track = FedexTrackRequest(CONFIG_OBJ)
    """
    added very rough validation of input.
    """
    if not isinstance(tracking_id, str):

        tracking_id_str = tracking_id[0]

        if len(tracking_id) == 2:

            process_type = tracking_id[1]

        else:

            tracking_id_name = tracking_id[1]
            process_type = tracking_id[2]
    
    else:

        tracking_id_str = tracking_id

    track.TrackSelectionDetail.PackageIdentifier.Value = tracking_id_str

    """
    changed to set tracking id name only if one is provided.
    """
    if tracking_id_name:
        track.TrackSelectionDetail.PackageIdentifier.Type = tracking_id_name
    
    """
    added set processing option.
    """
    if process_type == 'True':
        track.ProcessingOptions = 'INCLUDE_DETAILED_SCANS'

    """
    added the ship zip if we have one.
    """
    if ship_zip:
        track.TrackSelectionDetail.Destination.PostalCode = ship_zip
        track.TrackSelectionDetail.Destination.CountryCode = 'US'

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

    # See the response printed out.
#    print track.response
    
    """
    added retrieve severity
    """
    severity = track.response.HighestSeverity

    """
    modified to collect result to return
    """
    match_list = list()
    # Look through the matches (there should only be one for a tracking number
    # query), and show a few details about each shipment.
    for match in track.response.CompletedTrackDetails:
        match_list.append(match)

    """
    Added for testing
    """
#    print match_list

    """
    added return result
    """
    return {'severity': severity, 'tracking': match_list}