Skip to content

电商订单处理系统 - 完整业务流程自动化

电商订单处理是一个复杂的业务流程,涉及库存管理、支付处理、物流配送等多个环节。今天我们来构建一个完整的订单处理自动化系统,让整个流程更加高效和可靠。

系统架构设计

业务流程概览

一个典型的电商订单处理流程包含以下环节:

mermaid
graph TD
    A[订单创建] --> B[库存检查]
    B --> C{库存充足?}
    C -->|是| D[锁定库存]
    C -->|否| E[缺货通知]
    D --> F[支付处理]
    F --> G{支付成功?}
    G -->|是| H[订单确认]
    G -->|否| I[释放库存]
    H --> J[生成发货单]
    J --> K[物流配送]
    K --> L[发货通知]
    L --> M[订单完成]

    E --> N[补货提醒]
    I --> O[支付失败处理]

数据模型设计

订单数据结构

javascript
// 订单主表
const orderSchema = {
  id: 'string',           // 订单ID
  orderNumber: 'string',  // 订单号
  customerId: 'string',   // 客户ID
  customerInfo: {
    name: 'string',
    email: 'string',
    phone: 'string',
    address: {
      street: 'string',
      city: 'string',
      province: 'string',
      postalCode: 'string',
      country: 'string'
    }
  },
  items: [{
    productId: 'string',
    productName: 'string',
    sku: 'string',
    quantity: 'number',
    unitPrice: 'number',
    totalPrice: 'number'
  }],
  pricing: {
    subtotal: 'number',    // 小计
    shipping: 'number',    // 运费
    tax: 'number',         // 税费
    discount: 'number',    // 折扣
    total: 'number'        // 总计
  },
  status: 'string',        // 订单状态
  paymentStatus: 'string', // 支付状态
  shippingStatus: 'string', // 配送状态
  createdAt: 'date',
  updatedAt: 'date'
};

// 订单状态枚举
const ORDER_STATUS = {
  PENDING: 'pending',           // 待处理
  CONFIRMED: 'confirmed',       // 已确认
  PROCESSING: 'processing',     // 处理中
  SHIPPED: 'shipped',          // 已发货
  DELIVERED: 'delivered',      // 已送达
  CANCELLED: 'cancelled',      // 已取消
  REFUNDED: 'refunded'         // 已退款
};

const PAYMENT_STATUS = {
  PENDING: 'pending',          // 待支付
  PAID: 'paid',               // 已支付
  FAILED: 'failed',           // 支付失败
  REFUNDED: 'refunded'        // 已退款
};

订单创建自动化

订单接收和验证

当客户在网站上下单时,我们需要对订单进行全面的验证和处理。

订单验证工作流

javascript
// 订单验证处理器
class OrderValidator {
  constructor() {
    this.validationRules = [
      this.validateCustomerInfo,
      this.validateProductInfo,
      this.validatePricing,
      this.validateShippingAddress,
      this.validatePaymentMethod
    ];
  }

  // 验证订单
  async validateOrder(orderData) {
    const validationResult = {
      isValid: true,
      errors: [],
      warnings: [],
      processedOrder: null
    };

    try {
      // 数据清洗
      const cleanedOrder = this.cleanOrderData(orderData);

      // 执行验证规则
      for (const rule of this.validationRules) {
        const ruleResult = await rule.call(this, cleanedOrder);
        if (!ruleResult.isValid) {
          validationResult.isValid = false;
          validationResult.errors.push(...ruleResult.errors);
        }
        if (ruleResult.warnings) {
          validationResult.warnings.push(...ruleResult.warnings);
        }
      }

      if (validationResult.isValid) {
        // 生成订单号
        cleanedOrder.orderNumber = this.generateOrderNumber();
        cleanedOrder.status = ORDER_STATUS.PENDING;
        cleanedOrder.paymentStatus = PAYMENT_STATUS.PENDING;
        cleanedOrder.createdAt = new Date().toISOString();

        validationResult.processedOrder = cleanedOrder;
      }

    } catch (error) {
      validationResult.isValid = false;
      validationResult.errors.push(`订单处理异常: ${error.message}`);
    }

    return validationResult;
  }

  // 数据清洗
  cleanOrderData(orderData) {
    return {
      customerId: orderData.customerId?.trim(),
      customerInfo: {
        name: orderData.customerInfo?.name?.trim(),
        email: orderData.customerInfo?.email?.toLowerCase().trim(),
        phone: orderData.customerInfo?.phone?.replace(/\D/g, ''),
        address: {
          street: orderData.customerInfo?.address?.street?.trim(),
          city: orderData.customerInfo?.address?.city?.trim(),
          province: orderData.customerInfo?.address?.province?.trim(),
          postalCode: orderData.customerInfo?.address?.postalCode?.replace(/\s/g, ''),
          country: orderData.customerInfo?.address?.country?.trim()
        }
      },
      items: orderData.items?.map(item => ({
        productId: item.productId?.trim(),
        sku: item.sku?.trim(),
        quantity: parseInt(item.quantity) || 0,
        unitPrice: parseFloat(item.unitPrice) || 0
      })) || [],
      couponCode: orderData.couponCode?.trim().toUpperCase()
    };
  }

  // 验证客户信息
  async validateCustomerInfo(order) {
    const result = { isValid: true, errors: [], warnings: [] };

    if (!order.customerInfo.email || !this.isValidEmail(order.customerInfo.email)) {
      result.isValid = false;
      result.errors.push('邮箱地址无效');
    }

    if (!order.customerInfo.phone || order.customerInfo.phone.length < 10) {
      result.isValid = false;
      result.errors.push('手机号码无效');
    }

    // 检查客户是否存在黑名单
    const isBlacklisted = await this.checkCustomerBlacklist(order.customerInfo.email);
    if (isBlacklisted) {
      result.isValid = false;
      result.errors.push('客户账户已被限制');
    }

    return result;
  }

  // 验证商品信息
  async validateProductInfo(order) {
    const result = { isValid: true, errors: [], warnings: [] };

    if (!order.items || order.items.length === 0) {
      result.isValid = false;
      result.errors.push('订单中没有商品');
      return result;
    }

    for (const item of order.items) {
      // 检查商品是否存在
      const product = await this.getProductInfo(item.productId);
      if (!product) {
        result.isValid = false;
        result.errors.push(`商品不存在: ${item.productId}`);
        continue;
      }

      // 检查商品是否可售
      if (!product.isActive || product.status !== 'available') {
        result.isValid = false;
        result.errors.push(`商品不可售: ${product.name}`);
        continue;
      }

      // 验证价格
      if (Math.abs(item.unitPrice - product.price) > 0.01) {
        result.isValid = false;
        result.errors.push(`商品价格不匹配: ${product.name}`);
      }

      // 检查购买数量限制
      if (item.quantity > product.maxQuantityPerOrder) {
        result.warnings.push(`商品 ${product.name} 超出单次购买限制`);
      }
    }

    return result;
  }

  // 生成订单号
  generateOrderNumber() {
    const timestamp = Date.now().toString();
    const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0');
    return `ORD${timestamp}${random}`;
  }

  // 邮箱验证
  isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
  }
}

库存检查和锁定

订单验证通过后,我们需要检查库存并锁定商品,防止超卖。

库存管理系统

javascript
// 库存管理器
class InventoryManager {
  constructor() {
    this.lockTimeout = 15 * 60 * 1000; // 15分钟锁定超时
  }

  // 检查并锁定库存
  async checkAndLockInventory(orderItems) {
    const lockResult = {
      success: true,
      lockedItems: [],
      unavailableItems: [],
      lockId: this.generateLockId()
    };

    try {
      // 开始数据库事务
      await this.beginTransaction();

      for (const item of orderItems) {
        const inventoryCheck = await this.checkItemInventory(item);

        if (inventoryCheck.available >= item.quantity) {
          // 锁定库存
          const lockSuccess = await this.lockInventory(
            item.productId,
            item.quantity,
            lockResult.lockId
          );

          if (lockSuccess) {
            lockResult.lockedItems.push({
              productId: item.productId,
              quantity: item.quantity,
              availableBefore: inventoryCheck.available,
              availableAfter: inventoryCheck.available - item.quantity
            });
          } else {
            throw new Error(`库存锁定失败: ${item.productId}`);
          }
        } else {
          lockResult.success = false;
          lockResult.unavailableItems.push({
            productId: item.productId,
            requested: item.quantity,
            available: inventoryCheck.available,
            shortfall: item.quantity - inventoryCheck.available
          });
        }
      }

      if (lockResult.success) {
        // 提交事务
        await this.commitTransaction();

        // 设置锁定超时
        this.setLockTimeout(lockResult.lockId);
      } else {
        // 回滚事务
        await this.rollbackTransaction();
      }

    } catch (error) {
      await this.rollbackTransaction();
      lockResult.success = false;
      lockResult.error = error.message;
    }

    return lockResult;
  }

  // 检查单个商品库存
  async checkItemInventory(item) {
    const query = `
      SELECT
        available_quantity,
        reserved_quantity,
        total_quantity,
        reorder_point,
        last_updated
      FROM inventory
      WHERE product_id = ? AND sku = ?
    `;

    const result = await this.executeQuery(query, [item.productId, item.sku]);

    if (!result || result.length === 0) {
      throw new Error(`商品库存信息不存在: ${item.productId}`);
    }

    const inventory = result[0];

    return {
      available: inventory.available_quantity,
      reserved: inventory.reserved_quantity,
      total: inventory.total_quantity,
      reorderPoint: inventory.reorder_point,
      needsReorder: inventory.available_quantity <= inventory.reorder_point
    };
  }

  // 锁定库存
  async lockInventory(productId, quantity, lockId) {
    const lockExpiry = new Date(Date.now() + this.lockTimeout);

    const updateQuery = `
      UPDATE inventory
      SET
        available_quantity = available_quantity - ?,
        reserved_quantity = reserved_quantity + ?,
        last_updated = NOW()
      WHERE product_id = ? AND available_quantity >= ?
    `;

    const result = await this.executeQuery(updateQuery, [
      quantity, quantity, productId, quantity
    ]);

    if (result.affectedRows === 0) {
      return false;
    }

    // 记录库存锁定
    const lockQuery = `
      INSERT INTO inventory_locks
      (lock_id, product_id, quantity, expires_at, created_at)
      VALUES (?, ?, ?, ?, NOW())
    `;

    await this.executeQuery(lockQuery, [lockId, productId, quantity, lockExpiry]);

    return true;
  }

  // 释放库存锁定
  async releaseLock(lockId) {
    try {
      await this.beginTransaction();

      // 获取锁定信息
      const locksQuery = `
        SELECT product_id, quantity
        FROM inventory_locks
        WHERE lock_id = ? AND expires_at > NOW()
      `;

      const locks = await this.executeQuery(locksQuery, [lockId]);

      // 释放每个锁定的商品
      for (const lock of locks) {
        const releaseQuery = `
          UPDATE inventory
          SET
            available_quantity = available_quantity + ?,
            reserved_quantity = reserved_quantity - ?,
            last_updated = NOW()
          WHERE product_id = ?
        `;

        await this.executeQuery(releaseQuery, [
          lock.quantity, lock.quantity, lock.product_id
        ]);
      }

      // 删除锁定记录
      const deleteLockQuery = `DELETE FROM inventory_locks WHERE lock_id = ?`;
      await this.executeQuery(deleteLockQuery, [lockId]);

      await this.commitTransaction();

      return { success: true, releasedItems: locks.length };

    } catch (error) {
      await this.rollbackTransaction();
      return { success: false, error: error.message };
    }
  }

  // 确认库存扣减(支付成功后)
  async confirmInventoryDeduction(lockId) {
    try {
      // 删除锁定记录(库存已经在锁定时扣减)
      const deleteLockQuery = `DELETE FROM inventory_locks WHERE lock_id = ?`;
      await this.executeQuery(deleteLockQuery, [lockId]);

      return { success: true };
    } catch (error) {
      return { success: false, error: error.message };
    }
  }

  // 生成锁定ID
  generateLockId() {
    return `LOCK_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;
  }

  // 设置锁定超时
  setLockTimeout(lockId) {
    setTimeout(async () => {
      await this.releaseLock(lockId);
    }, this.lockTimeout);
  }
}

支付处理集成

支付是订单流程的关键环节,我们需要集成多种支付方式。

支付处理器

javascript
// 支付处理管理器
class PaymentProcessor {
  constructor() {
    this.paymentGateways = {
      stripe: new StripeGateway(),
      paypal: new PayPalGateway(),
      alipay: new AlipayGateway(),
      wechatpay: new WeChatPayGateway()
    };
  }

  // 处理支付
  async processPayment(order, paymentMethod) {
    const paymentResult = {
      success: false,
      transactionId: null,
      gatewayResponse: null,
      error: null
    };

    try {
      // 选择支付网关
      const gateway = this.selectPaymentGateway(paymentMethod);
      if (!gateway) {
        throw new Error(`不支持的支付方式: ${paymentMethod.type}`);
      }

      // 创建支付请求
      const paymentRequest = this.createPaymentRequest(order, paymentMethod);

      // 执行支付
      const gatewayResult = await gateway.processPayment(paymentRequest);

      if (gatewayResult.success) {
        paymentResult.success = true;
        paymentResult.transactionId = gatewayResult.transactionId;
        paymentResult.gatewayResponse = gatewayResult;

        // 更新订单支付状态
        await this.updateOrderPaymentStatus(order.id, PAYMENT_STATUS.PAID, {
          transactionId: gatewayResult.transactionId,
          gateway: paymentMethod.type,
          paidAt: new Date().toISOString()
        });

        // 确认库存扣减
        if (order.inventoryLockId) {
          const inventoryManager = new InventoryManager();
          await inventoryManager.confirmInventoryDeduction(order.inventoryLockId);
        }

      } else {
        paymentResult.error = gatewayResult.error;

        // 更新订单支付状态为失败
        await this.updateOrderPaymentStatus(order.id, PAYMENT_STATUS.FAILED, {
          error: gatewayResult.error,
          gateway: paymentMethod.type,
          failedAt: new Date().toISOString()
        });

        // 释放库存锁定
        if (order.inventoryLockId) {
          const inventoryManager = new InventoryManager();
          await inventoryManager.releaseLock(order.inventoryLockId);
        }
      }

    } catch (error) {
      paymentResult.error = error.message;

      // 记录支付错误
      await this.logPaymentError(order.id, error);
    }

    return paymentResult;
  }

  // 选择支付网关
  selectPaymentGateway(paymentMethod) {
    return this.paymentGateways[paymentMethod.type];
  }

  // 创建支付请求
  createPaymentRequest(order, paymentMethod) {
    return {
      orderId: order.id,
      orderNumber: order.orderNumber,
      amount: order.pricing.total,
      currency: order.currency || 'CNY',
      customer: {
        id: order.customerId,
        email: order.customerInfo.email,
        name: order.customerInfo.name
      },
      paymentMethod: paymentMethod,
      description: `订单支付 - ${order.orderNumber}`,
      metadata: {
        orderNumber: order.orderNumber,
        customerId: order.customerId
      }
    };
  }

  // 处理支付回调
  async handlePaymentCallback(gatewayType, callbackData) {
    const gateway = this.paymentGateways[gatewayType];
    if (!gateway) {
      throw new Error(`未知的支付网关: ${gatewayType}`);
    }

    // 验证回调数据
    const verification = await gateway.verifyCallback(callbackData);
    if (!verification.isValid) {
      throw new Error('支付回调验证失败');
    }

    const orderId = verification.orderId;
    const paymentStatus = verification.status;

    // 更新订单状态
    await this.updateOrderPaymentStatus(orderId, paymentStatus, {
      transactionId: verification.transactionId,
      gateway: gatewayType,
      callbackData: callbackData,
      verifiedAt: new Date().toISOString()
    });

    // 如果支付成功,触发后续流程
    if (paymentStatus === PAYMENT_STATUS.PAID) {
      await this.triggerOrderFulfillment(orderId);
    }

    return { success: true, orderId, status: paymentStatus };
  }
}

订单履行自动化

支付成功后,订单进入履行阶段,包括仓库拣货、打包、发货等环节。

仓库管理集成

订单履行管理器

javascript
// 订单履行管理器
class OrderFulfillmentManager {
  constructor() {
    this.warehouseAPI = new WarehouseAPI();
    this.shippingAPI = new ShippingAPI();
    this.notificationService = new NotificationService();
  }

  // 开始订单履行
  async startFulfillment(orderId) {
    try {
      const order = await this.getOrderDetails(orderId);

      // 更新订单状态为处理中
      await this.updateOrderStatus(orderId, ORDER_STATUS.PROCESSING);

      // 创建拣货单
      const pickingList = await this.createPickingList(order);

      // 发送到仓库系统
      const warehouseResult = await this.sendToWarehouse(pickingList);

      if (warehouseResult.success) {
        // 记录履行开始
        await this.recordFulfillmentStart(orderId, {
          pickingListId: pickingList.id,
          warehouseId: warehouseResult.warehouseId,
          estimatedShipDate: warehouseResult.estimatedShipDate
        });

        // 发送处理中通知
        await this.notificationService.sendOrderProcessingNotification(order);
      }

      return warehouseResult;

    } catch (error) {
      await this.handleFulfillmentError(orderId, error);
      throw error;
    }
  }

  // 创建拣货单
  async createPickingList(order) {
    const pickingList = {
      id: this.generatePickingListId(),
      orderId: order.id,
      orderNumber: order.orderNumber,
      priority: this.calculateOrderPriority(order),
      items: [],
      shippingAddress: order.customerInfo.address,
      specialInstructions: order.specialInstructions || '',
      createdAt: new Date().toISOString()
    };

    // 处理订单商品
    for (const orderItem of order.items) {
      const productInfo = await this.getProductLocationInfo(orderItem.productId);

      pickingList.items.push({
        productId: orderItem.productId,
        sku: orderItem.sku,
        productName: orderItem.productName,
        quantity: orderItem.quantity,
        location: productInfo.location,
        weight: productInfo.weight,
        dimensions: productInfo.dimensions,
        fragile: productInfo.fragile || false,
        batchNumber: productInfo.batchNumber
      });
    }

    // 优化拣货路径
    pickingList.items = this.optimizePickingRoute(pickingList.items);

    return pickingList;
  }

  // 处理发货通知
  async handleShippingNotification(shippingData) {
    const {
      orderId,
      trackingNumber,
      carrier,
      shippedAt,
      estimatedDelivery
    } = shippingData;

    try {
      // 更新订单状态
      await this.updateOrderStatus(orderId, ORDER_STATUS.SHIPPED);

      // 更新物流信息
      await this.updateShippingInfo(orderId, {
        trackingNumber,
        carrier,
        shippedAt,
        estimatedDelivery,
        status: 'in_transit'
      });

      // 获取订单详情
      const order = await this.getOrderDetails(orderId);

      // 发送发货通知
      await this.notificationService.sendShippingNotification(order, {
        trackingNumber,
        carrier,
        estimatedDelivery,
        trackingUrl: this.generateTrackingUrl(carrier, trackingNumber)
      });

      // 启动配送跟踪
      await this.startDeliveryTracking(orderId, trackingNumber, carrier);

      return { success: true };

    } catch (error) {
      console.error('处理发货通知失败:', error);
      return { success: false, error: error.message };
    }
  }

  // 配送跟踪
  async startDeliveryTracking(orderId, trackingNumber, carrier) {
    const trackingJob = {
      orderId,
      trackingNumber,
      carrier,
      lastStatus: 'in_transit',
      checkInterval: 4 * 60 * 60 * 1000, // 4小时检查一次
      maxChecks: 72 // 最多检查3天
    };

    // 定期检查配送状态
    const checkDeliveryStatus = async () => {
      try {
        const trackingInfo = await this.shippingAPI.getTrackingInfo(
          carrier,
          trackingNumber
        );

        if (trackingInfo.status !== trackingJob.lastStatus) {
          trackingJob.lastStatus = trackingInfo.status;

          // 更新订单配送状态
          await this.updateShippingInfo(orderId, {
            status: trackingInfo.status,
            lastUpdate: new Date().toISOString(),
            location: trackingInfo.currentLocation
          });

          // 如果已送达
          if (trackingInfo.status === 'delivered') {
            await this.handleOrderDelivered(orderId, trackingInfo);
            return; // 停止跟踪
          }

          // 发送状态更新通知
          const order = await this.getOrderDetails(orderId);
          await this.notificationService.sendDeliveryUpdateNotification(
            order,
            trackingInfo
          );
        }

        // 继续跟踪
        if (trackingJob.maxChecks > 0) {
          trackingJob.maxChecks--;
          setTimeout(checkDeliveryStatus, trackingJob.checkInterval);
        }

      } catch (error) {
        console.error('配送状态检查失败:', error);
      }
    };

    // 开始第一次检查
    setTimeout(checkDeliveryStatus, trackingJob.checkInterval);
  }

  // 处理订单送达
  async handleOrderDelivered(orderId, deliveryInfo) {
    try {
      // 更新订单状态为已送达
      await this.updateOrderStatus(orderId, ORDER_STATUS.DELIVERED);

      // 更新配送信息
      await this.updateShippingInfo(orderId, {
        status: 'delivered',
        deliveredAt: deliveryInfo.deliveredAt,
        recipient: deliveryInfo.recipient,
        signature: deliveryInfo.signature
      });

      // 获取订单详情
      const order = await this.getOrderDetails(orderId);

      // 发送送达通知
      await this.notificationService.sendDeliveryConfirmationNotification(
        order,
        deliveryInfo
      );

      // 启动售后服务流程
      await this.startAfterSalesProcess(orderId);

    } catch (error) {
      console.error('处理订单送达失败:', error);
    }
  }
}

客户通知系统

通知服务管理器

javascript
// 通知服务管理器
class NotificationService {
  constructor() {
    this.emailService = new EmailService();
    this.smsService = new SMSService();
    this.pushService = new PushNotificationService();
    this.templates = new NotificationTemplates();
  }

  // 发送订单确认通知
  async sendOrderConfirmationNotification(order) {
    const notifications = [];

    // 邮件通知
    const emailContent = this.templates.generateOrderConfirmationEmail(order);
    notifications.push(
      this.emailService.send({
        to: order.customerInfo.email,
        subject: `订单确认 - ${order.orderNumber}`,
        html: emailContent.html,
        attachments: [
          {
            filename: `订单详情-${order.orderNumber}.pdf`,
            content: await this.generateOrderPDF(order)
          }
        ]
      })
    );

    // 短信通知
    const smsContent = this.templates.generateOrderConfirmationSMS(order);
    notifications.push(
      this.smsService.send({
        to: order.customerInfo.phone,
        message: smsContent
      })
    );

    // 推送通知(如果有APP)
    if (order.customerId) {
      const pushContent = this.templates.generateOrderConfirmationPush(order);
      notifications.push(
        this.pushService.send({
          userId: order.customerId,
          title: '订单确认',
          body: pushContent,
          data: {
            orderId: order.id,
            orderNumber: order.orderNumber,
            type: 'order_confirmation'
          }
        })
      );
    }

    // 等待所有通知发送完成
    const results = await Promise.allSettled(notifications);

    // 记录通知结果
    await this.recordNotificationResults(order.id, 'order_confirmation', results);

    return results;
  }

  // 发送发货通知
  async sendShippingNotification(order, shippingInfo) {
    const emailContent = this.templates.generateShippingNotificationEmail(
      order,
      shippingInfo
    );

    await this.emailService.send({
      to: order.customerInfo.email,
      subject: `您的订单已发货 - ${order.orderNumber}`,
      html: emailContent.html
    });

    const smsContent = this.templates.generateShippingNotificationSMS(
      order,
      shippingInfo
    );

    await this.smsService.send({
      to: order.customerInfo.phone,
      message: smsContent
    });
  }

  // 发送送达确认通知
  async sendDeliveryConfirmationNotification(order, deliveryInfo) {
    const emailContent = this.templates.generateDeliveryConfirmationEmail(
      order,
      deliveryInfo
    );

    await this.emailService.send({
      to: order.customerInfo.email,
      subject: `订单已送达 - ${order.orderNumber}`,
      html: emailContent.html
    });

    // 发送评价邀请(延迟24小时)
    setTimeout(async () => {
      await this.sendReviewInvitation(order);
    }, 24 * 60 * 60 * 1000);
  }

  // 发送评价邀请
  async sendReviewInvitation(order) {
    const emailContent = this.templates.generateReviewInvitationEmail(order);

    await this.emailService.send({
      to: order.customerInfo.email,
      subject: `分享您的购物体验 - ${order.orderNumber}`,
      html: emailContent.html
    });
  }
}

异常处理和监控

电商系统需要完善的异常处理和监控机制,确保系统稳定运行。

异常处理策略

订单异常处理器

javascript
// 订单异常处理器
class OrderExceptionHandler {
  constructor() {
    this.retryConfig = {
      maxRetries: 3,
      retryDelay: 1000,
      backoffMultiplier: 2
    };
  }

  // 处理支付失败
  async handlePaymentFailure(orderId, error) {
    const order = await this.getOrderDetails(orderId);

    // 释放库存锁定
    if (order.inventoryLockId) {
      const inventoryManager = new InventoryManager();
      await inventoryManager.releaseLock(order.inventoryLockId);
    }

    // 更新订单状态
    await this.updateOrderStatus(orderId, ORDER_STATUS.CANCELLED);

    // 发送支付失败通知
    await this.sendPaymentFailureNotification(order, error);

    // 记录异常
    await this.logException('payment_failure', {
      orderId,
      error: error.message,
      customerEmail: order.customerInfo.email
    });
  }

  // 处理库存不足
  async handleInventoryShortage(orderId, shortageInfo) {
    const order = await this.getOrderDetails(orderId);

    // 更新订单状态为待补货
    await this.updateOrderStatus(orderId, 'pending_restock');

    // 发送缺货通知
    await this.sendInventoryShortageNotification(order, shortageInfo);

    // 触发补货流程
    await this.triggerRestockProcess(shortageInfo);
  }

  // 重试机制
  async retryWithBackoff(operation, context) {
    let lastError;

    for (let attempt = 1; attempt <= this.retryConfig.maxRetries; attempt++) {
      try {
        return await operation(context);
      } catch (error) {
        lastError = error;

        if (attempt === this.retryConfig.maxRetries) {
          break;
        }

        const delay = this.retryConfig.retryDelay *
          Math.pow(this.retryConfig.backoffMultiplier, attempt - 1);

        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }

    throw lastError;
  }
}

性能监控

订单处理监控

javascript
// 订单处理性能监控
class OrderProcessingMonitor {
  constructor() {
    this.metrics = {
      orderProcessingTime: [],
      paymentProcessingTime: [],
      fulfillmentTime: [],
      errorRates: {}
    };
  }

  // 监控订单处理性能
  async monitorOrderProcessing(orderId, startTime) {
    const endTime = Date.now();
    const processingTime = endTime - startTime;

    this.metrics.orderProcessingTime.push({
      orderId,
      processingTime,
      timestamp: new Date().toISOString()
    });

    // 性能告警
    if (processingTime > 30000) { // 超过30秒
      await this.sendPerformanceAlert('slow_order_processing', {
        orderId,
        processingTime,
        threshold: 30000
      });
    }

    // 计算平均处理时间
    const avgProcessingTime = this.calculateAverageProcessingTime();

    return {
      processingTime,
      avgProcessingTime,
      isSlowProcessing: processingTime > avgProcessingTime * 2
    };
  }

  // 生成性能报告
  generatePerformanceReport() {
    const report = {
      timestamp: new Date().toISOString(),
      orderProcessing: {
        averageTime: this.calculateAverageProcessingTime(),
        p95Time: this.calculatePercentile(this.metrics.orderProcessingTime, 95),
        totalOrders: this.metrics.orderProcessingTime.length
      },
      errorRates: this.calculateErrorRates(),
      recommendations: this.generateRecommendations()
    };

    return report;
  }
}

小结

通过本文的电商订单处理系统实战,我们学会了:

  1. 系统架构设计:构建完整的订单处理流程
  2. 订单验证:确保订单数据的准确性和完整性
  3. 库存管理:实现库存检查、锁定和扣减机制
  4. 支付集成:集成多种支付方式和处理支付回调
  5. 订单履行:自动化仓库管理和物流配送
  6. 客户通知:多渠道的订单状态通知系统
  7. 异常处理:完善的错误处理和重试机制
  8. 性能监控:实时监控系统性能和业务指标

这个订单处理系统展示了如何用 n8n 构建复杂的业务流程自动化。在实际应用中,你可以根据具体的业务需求调整和扩展这些功能。

关键要点:

  • 数据一致性:使用事务确保数据的一致性
  • 异步处理:合理使用异步处理提升系统性能
  • 监控告警:建立完善的监控和告警机制
  • 用户体验:及时的状态通知提升客户满意度

下一篇文章我们将学习数据分析与报告系统,了解如何自动化商业智能流程。