StateSet Wholesale Order Management: Comprehensive Guide

Table of Contents

  1. Introduction
  2. Wholesale Order Management Overview
  3. Challenges in Wholesale Order Management
  4. StateSet’s Wholesale Order Management Solution
  5. Quickstart Guide
  6. API Components
  7. Workflow Orchestration with Temporal
  8. Integration with External Systems
  9. Search and Lookup Capabilities
  10. Email Notifications

1. Introduction

StateSet provides a powerful REST and GraphQL API for Wholesale Order Management. This API is specifically designed to handle the unique requirements of wholesale orders, enabling businesses to automate and streamline their B2B order processing workflows, from email order capture to integration with external systems.

2. Wholesale Order Management Overview

Wholesale order management involves processing large-volume orders from retailers or distributors. It’s a critical process for manufacturers, suppliers, and distributors, requiring efficient handling of bulk orders, complex pricing structures, and often, customized fulfillment processes.

3. Challenges in Wholesale Order Management

Several challenges are specific to wholesale order management:

  1. Complex Pricing Structures: Wholesale orders often involve tiered pricing, bulk discounts, or customer-specific rates.
  2. Large Order Volumes: Wholesale orders typically include larger quantities and more line items than B2C orders.
  3. Custom Terms and Conditions: Each wholesale customer may have unique payment terms, shipping requirements, or other special conditions.
  4. Integration with ERP Systems: Wholesale orders often need to be seamlessly integrated with robust ERP systems.
  5. Inventory Management: Balancing stock levels for both wholesale and retail channels can be complex.
  6. Order Approval Workflows: Many wholesale orders require multi-step approval processes before fulfillment.

4. StateSet’s Wholesale Order Management Solution

StateSet’s Wholesale Order Management API addresses these challenges by providing:

  1. Automated Email Order Capture: Extracts order details from emails, supporting various formats commonly used in B2B communications.
  2. Flexible Pricing Handling: Supports complex pricing structures including tiered pricing and customer-specific rates.
  3. Bulk Order Processing: Efficiently handles orders with large numbers of line items and high quantities.
  4. Customizable Workflows: Supports custom approval processes and business rules for different customers or order types.
  5. ERP Integration: Generates standardized XML output for seamless integration with ERP systems like SYSPRO.
  6. Inventory Sync: Provides real-time inventory updates across wholesale and retail channels.

5. Quickstart Guide

1

Sign Up

Set up your company’s StateSet instance by signing up at StateSet.io/signup

2

Create API Key

Generate a new API Key in the StateSet Cloud Console at cloud.stateset.com/api-keys

3

Install Node.js SDK

Install the stateset-node SDK in your project:

npm install stateset-node

6. API Components

The StateSet Wholesale Order Management API consists of several key components:

6.1 Email Order Capture

async function captureWholesaleOrderFromEmail(emailContent) {

    const orderDetails = await parseWholesaleEmailContent(emailContent);

    const lineItems = await getLineItemsFromEmail(functionList, chatHistory, stateset_api_key, emailContent);

    const contexts = await createOrderContext(lineItems);

    const orderHistoryContext = await getOrderHistoryLineItems(orderDetails.customer_number);

    const contextPrompt = await createOrderContextQuery(contexts, orderHistoryContext);
    
    return await createWholesaleOrder(orderDetails, lineItems, contextPrompt);
}

6.2 Wholesale Order Creation

async function createWholesaleOrder(orderDetails, lineItems, contextPrompt) {
    const order = await stateset.wholesaleOrders.create({
        ...orderDetails,
        line_items: lineItems,
        context: contextPrompt
    });
    return order;
}

6.3 Wholesale Order Retrieval

async function getWholesaleOrderDetails(orderId) {
    const order = await stateset.wholesaleOrders.retrieve(orderId);
    return order;
}

6.4 XML Generation for ERP Integration

function generateWholesaleOrderXML(order) {
    const xmlObj = {
        TransmissionHeader: {
            TransmissionReference: order.order_number,
            SenderCode: '',
            ReceiverCode: 'HO',
            DatePrepared: new Date().toISOString().split('T')[0],
            TimePrepared: new Date().toTimeString().split(' ')[0].substring(0, 5),
        },
        Orders: {
            OrderHeader: {
                CustomerPoNumber: order.order_number,
                OrderActionType: 'A',
                Customer: order.customer_number,
                OrderDate: order.created_date,
                OrderType: 'DE',
                RequestedShipDate: order.delivery_date,
            },
            OrderDetails: {
                StockLine: order.line_items.map((item, index) => ({
                    CustomerPoLine: (index + 1).toString(),
                    LineActionType: 'A',
                    StockCode: item.product_id,
                    OrderQty: item.quantity.toFixed(2),
                    OrderUom: item.unit,
                    PriceUom: item.price_unit
                })),
            },
        },
    };

    // Convert xmlObj to XML string
    const builder = new xml2js.Builder();
    return builder.buildObject(xmlObj);
}

7. Workflow Orchestration with Temporal

StateSet uses Temporal for workflow orchestration, allowing for complex, multi-step wholesale order processing:

import { proxyActivities } from '@temporalio/workflow';

const {
    captureWholesaleOrderFromEmail,
    createWholesaleOrder,
    generateWholesaleOrderXML,
    sendToERP,
    sendNotification,
    checkInventory,
    initiateApprovalProcess
} = proxyActivities({
    startToCloseTimeout: '1 minute',
});

export async function wholesaleOrderProcessingWorkflow(emailContent) {

    const orderDetails = await captureWholesaleOrderFromEmail(emailContent);
    const order = await createWholesaleOrder(orderDetails);
    
    // Check inventory
    const inventoryStatus = await checkInventory(order.line_items);
    if (inventoryStatus !== 'SUFFICIENT') {
        await sendNotification(order.customer_email, 'Inventory Issue');
        return { status: 'INVENTORY_ISSUE', order };
    }

    // Initiate approval process
    const approvalStatus = await initiateApprovalProcess(order);
    if (approvalStatus !== 'APPROVED') {
        await sendNotification(order.customer_email, 'Order Requires Further Approval');
        return { status: 'PENDING_APPROVAL', order };
    }

    const orderXML = await generateWholesaleOrderXML(order);
    await sendToERP(orderXML);
    await sendNotification(order.customer_email, 'Order Confirmation');
    return { status: 'PROCESSED', order };
}

8. Integration with External Systems

8.1 ERP Integration (e.g., SYSPRO)

async function sendToSyspro(sessionId, orderXML) {

    const syspro_address = '';
    const syspro_port = '';

    const url = `http://${syspro_address}/${syspro_port}/Transaction/Post?UserId=${sessionId}&BusinessObject=SORTOI&XmlIn=${encodeURIComponent(orderXML)}`;
    
    const response = await fetch(url, {
        method: 'GET',
        headers: {
            'Content-Type': 'application/xml',
            'User-Agent': 'StateSet Wholesale Order Management API Client',
        },
    });

    if (!response.ok) {
        throw new Error(`HTTP error! Status: ${response.status}`);
    }

    return await response.text();
}

9. Search and Lookup Capabilities

StateSet uses Algolia for powerful search and lookup capabilities, crucial for managing large volumes of wholesale orders:

async function indexWholesaleOrder(order) {
    await order_index.saveObject({
        objectID: order.id,
        order_number: order.order_number,
        customer_name: order.customer_name,
        customer_number: order.customer_number,
        total_price: order.total_price,
        order_status: order.order_status,
        created_date: order.created_date,
        payment_terms: order.payment_terms
    });
}

10. Email Notifications

Automated email notifications for wholesale orders:

async function sendWholesaleOrderConfirmation(order) {
    const msg = {
        to: order.customer_email,
        from: 'wholesale@yourcompany.com',
        subject: `Wholesale Order Confirmation: ${order.order_number}`,
        text: `Thank you for your wholesale order. Your order number is ${order.order_number}.`,
        html: `
            <p>Thank you for your wholesale order. Details are as follows:</p>
            <ul>
                <li>Order Number: <strong>${order.order_number}</strong></li>
                <li>Total Amount: <strong>${order.currency} ${order.total_price.toFixed(2)}</strong></li>
                <li>Payment Terms: <strong>${order.payment_terms}</strong></li>
            </ul>
            <p>Please refer to the attached document for the full order details.</p>
        `,
        attachments: [
            {
                content: Buffer.from(generateOrderPDF(order)).toString('base64'),
                filename: `WholesaleOrder_${order.order_number}.pdf`,
                type: 'application/pdf',
                disposition: 'attachment'
            }
        ]
    };

    await sgMail.send(msg);
}

Support

For assistance with your wholesale order management implementation or any questions, please contact StateSet support at support@stateset.com.