Beispiel #1
0
def submit_dropships():
    # Get all Dropship Ready orders associated with Meyer
    logger.info("Requesting all Meyer orders with 'Dropship Ready' from Ordoro...")
    robj = ordoro.get_dropship_ready_orders(ordoro.supplier_meyer_id)

    if robj['count'] < 1:
        logger.info("No orders returned. Nothing to do.")
        return

    orders = robj['order']

    logger.info(f"Found {robj['count']} to process.")

    # Loop through orders
    for order in orders:
        # Determine if order should be skipped based on what mode we're in
        if config.should_skip(order['order_number']):
            logger.info(f"Skipping order {order['order_number']}.")
            continue

        logger.info(f"Processing order {order['order_number']}...")

        shipinf = order['shipping_address']

        # Create dictionary for order information
        order_info = {
            'ShipMethod': 'UPS GRND RES',
            'ShipToName': shipinf['name'],
            'ShipToAddress1': shipinf['street1'],
            'ShipToAddress2': shipinf['street2'],
            'ShipToCity': shipinf['city'],
            'ShipToState': shipinf['state'],
            'ShipToZipcode': shipinf['zip'],
            'ShipToPhone': shipinf['phone'],
            'CustPO': order['order_number'],
            'Items': []
        }

        # Meyer requires 3-char country code
        if shipinf['country'] == 'US':
            order_info['ShipToCountry'] = 'USA'
        else:
            order_info['ShipToCountry'] = shipinf['country']

        try:
            product_list = ordoro.get_product_list(order['lines'], ordoro.supplier_meyer_id)
            for product in product_list:
                order_info['Items'].append({'ItemNumber': product['sku'], 'Quantity': product['qty']})
        except errors.SupplierSKUNotFound as e:
            logger.error(f"Error: {e.msg()}")
            logger.error("Unable to parse product list. Skipping order.")
            continue

        # Send to Meyer
        logger.info(f"Sending order {order['order_number']} to Meyer...")
        logger.debug(f"{order_info}")

        rob = __post_create_order(order_info)
        logger.info(f"Parsing response from Meyer...")

        try:
            mey_orders = rob['Orders']
        except KeyError:
            logger.error("Error! Unexpected response from Meyer.")
            logger.error(f"Error code: {rob['errorCode']}")
            logger.error(f"Error message: {rob['errorMessage']}")

            logger.info("Removing 'Dropship Ready' tag...")
            ordoro.delete_tag_drop_ready(order['order_number'])

            logger.info("Adding 'Dropship Failed' tag...")
            ordoro.post_tag_drop_fail(order['order_number'])

            logger.info("Skipping order.")
            continue

        try:
            for mey_order in mey_orders:
                # Loop through responses and add order ids returned as comments
                logger.info(f"Adding Meyer order number {mey_order['OrderNumber']} as comment...")
                ordoro.post_comment(order['order_number'], f"[SR-MID]: {mey_order['OrderNumber']}")

            logger.info("Removing 'Dropship Ready' tag...")
            ordoro.delete_tag_drop_ready(order['order_number'])

            logger.info("Adding 'Awaiting Tracking' tag...")
            ordoro.post_tag_await_track(order['order_number'])
        except Exception as err:
            logger.info("Unable to parse response from Meyer. Error:")
            logger.info(f"{err}")
            logger.debug(f"{rob}")
            logger.info("Skipping.\n\r")
            continue

        logger.info(f"Done submitting order {order['order_number']}.\n\r")

    logger.info("Done submitting Meyer dropships.\n\r")
Beispiel #2
0
def get_tracking():
    logger.info(
        "Requesting all TAW orders with 'Awaiting Tracking' from Ordoro...")
    robj = ordoro.get_await_track_orders(ordoro.supplier_taw_id)

    ord_orders = robj['order']

    logger.info(f"Found {len(ord_orders)} to process.")

    for eachOrder in ord_orders:
        # Determine if order should be skipped based on what mode we're in
        if config.should_skip(eachOrder['order_number']):
            logger.info(f"Skipping order {eachOrder['order_number']}.\n\r")
            continue

        PONumber = eachOrder['order_number']

        logger.info(f"Processing order {PONumber}...")
        logger.info("Requesting tracking info from TAW...")

        # ASK FOR TRACKING INFO FROM TAW
        try:
            r = __post_get_tracking(PONumber)
        except requests.exceptions.ConnectionError:
            logger.error(
                "Error! Unable to connect to TAW services. Skipping order.")
            continue

        logger.debug(f"Response from TAW:\n\r{r.content.decode('UTF-8')}")

        try:
            # PARSE TRACKING INFO FROM TAW RESPONSE
            root = ET.ElementTree(ET.fromstring(r.content)).getroot()

            records = root.findall('Record')
            if len(records) < 1:
                logger.info("No records received, skipping.\n\r")
                continue

            logger.info(
                f"{len(records)} records received, checking for tracking info..."
            )

            i = 1
            for record in records:
                # For the first record, actually add the tracking number as shipping info
                if i == 1:
                    data = dict()

                    data['tracking_number'] = record.find(
                        'TrackNum').text.strip()

                    # IF NO TRACKING NUMBER, LOG IT AND GO ON TO THE NEXT ONE
                    if data['tracking_number'] == "":
                        logger.info("No tracking number found. Skipping.\n\r")
                        continue

                    order_date_str = record.find('OrderDate').text
                    order_date_obj = datetime.datetime.strptime(
                        order_date_str, '%m/%d/%Y')
                    order_date_str = order_date_obj.strftime(
                        '%Y-%m-%dT%H:%M:%S.000Z')

                    data['ship_date'] = order_date_str
                    data['carrier_name'] = record.find('Type').text.strip()

                    # IF NO VENDOR, LOG IT AND GO ON TO THE NEXT ONE
                    if data['carrier_name'] == "":
                        logger.info("No vendor found. Skipping.\n\r")
                        continue

                    data['shipping_method'] = "ground"
                    data['cost'] = 14

                    logger.info(
                        f"Applying {data['tracking_number']} as official shipping method..."
                    )
                    logger.debug(f"{data}")

                    # SEND TRACKING INFO TO ORDORO
                    r = ordoro.post_shipping_info(PONumber, data)

                    logger.info(f"Removing 'Awaiting Tracking' tag...")
                    ordoro.delete_tag_await_track(PONumber)
                else:
                    taw_invoice_num = record.find('InvoiceNumber').text.strip()
                    tracking_number = record.find('TrackNum').text.strip()

                    if tracking_number == "":
                        continue

                    logger.info(f"Applying {tracking_number} in a comment...")
                    ordoro.post_comment(
                        PONumber, f'Additional tracking information: '
                        f'\n\rTAW Order ID: {taw_invoice_num}'
                        f'\n\rTracking Number: {tracking_number}')
                i = i + 1

        except Exception as err:
            logger.error(f"[{PONumber}] Error parsing tracking info..."
                         f"\n\rException:"
                         f"\n\r{err}"
                         f"\n\rLast Response:"
                         f"\n\r{r.content.decode('UTF-8')}")

        logger.info(
            f"Finished applying tracking for Ordoro order {PONumber}.\n\r")

    logger.info(f"Finished getting tracking info from TAW.\n\r")
Beispiel #3
0
def get_tracking():
    # Get all Awaiting Tracking orders associate with Meyer
    logger.info("Requesting all Meyer orders with 'Awaiting Tracking' from Ordoro...")
    rob = ordoro.get_await_track_orders(ordoro.supplier_meyer_id)

    if rob['count'] < 1:
        logger.info("No orders returned. Nothing to do.")
        return

    orders = rob['order']

    logger.info(f"Found {rob['count']} to process.")

    # Loop through orders
    for order in orders:
        # Determine if order should be skipped based on what mode we're in
        if config.should_skip(order['order_number']):
            logger.info(f"Skipping order {order['order_number']}.\n\r")
            continue

        logger.info(f"Processing order {order['order_number']}...")

        # Keep track of how many tracking numbers we get back, 1st is added as official shipping method
        num_tracking = 1
        for comment in order['comments']:
            if '[SR-MID]' in comment['text']:
                mey_order_id = comment['text'].split(':')[1].strip()

                logger.info(f"Asking Meyer for tracking info on order {mey_order_id}...")
                tracking_info = __get_sales_tracking(mey_order_id)

                # If what we get back isn't a list, it means nothing was found
                if not isinstance(tracking_info, list):
                    logger.info(f"Could not retrieve tracking info: {tracking_info['errorMessage']}, skipping.\n\r")
                    continue

                logger.info(f"Tracking info retrieved, processing...")

                for tracking in tracking_info:
                    # If this is the first tracking number, we add it as the official shipping method
                    if num_tracking == 1:
                        shipping_data = dict()

                        shipping_data['tracking_number'] = tracking['TrackingNumber']
                        shipping_data['ship_date'] = order['order_placed_date']
                        shipping_data['carrier_name'] = 'UPS'
                        shipping_data['shipping_method'] = 'ground'
                        shipping_data['cost'] = 13

                        logger.info(f"Applying {shipping_data['tracking_number']} as official shipping method...")
                        ordoro.post_shipping_info(order['order_number'], shipping_data)

                        logger.info("Removing 'Awaiting Tracking' tag...")
                        ordoro.delete_tag_await_track(order['order_number'])

                        num_tracking = num_tracking + 1
                    else:
                        # If this is not the first tracking number, add it as a comment
                        tracking_number = tracking['TrackingNumber']

                        logger.info(f"Applying {tracking_number} in a comment...")
                        ordoro.post_comment(
                            order['order_number'],
                            f"Additional tracking information: "
                            f"Order ID: {mey_order_id} "
                            f"Tracking Number: {tracking_number}"
                        )
                        num_tracking = num_tracking + 1

                logger.info(f"Finished applying tracking for Meyer order {mey_order_id}.")

        logger.info(f"Finished applying tracking for Ordoro order {order['order_number']}.\n\r")

    logger.info("Finished getting tracking info from Meyer.\n\r")