首页 / 教程文章 / WordPress柔性供应链软件实现多渠道订单聚合的教程

WordPress柔性供应链软件实现多渠道订单聚合的教程

WordPress柔性供应链软件实现多渠道订单聚合的教程

概述:为什么需要多渠道订单聚合

在当今电商多元化的市场环境中,许多企业同时在多个平台销售商品——淘宝、京东、亚马逊、自建网站等。每个平台都有独立的订单管理系统,导致商家需要登录不同后台处理订单,效率低下且容易出错。WordPress柔性供应链软件通过订单聚合功能,可以将所有渠道的订单集中到一个界面管理,极大提升运营效率。

本教程将详细介绍如何使用WordPress柔性供应链插件实现多渠道订单聚合,包括API对接、数据同步和统一管理等功能。

环境准备与插件安装

系统要求

  • WordPress 5.8或更高版本
  • PHP 7.4或更高版本
  • MySQL 5.7或更高版本
  • 至少256MB内存限制

安装柔性供应链插件

  1. 登录WordPress后台,进入"插件"→"安装插件"
  2. 搜索"Flexible Supply Chain"或上传插件ZIP文件
  3. 安装并激活插件

基础配置

激活插件后,您会在WordPress侧边栏看到"供应链管理"菜单。首先进行基础配置:

<?php
/**
 * 供应链插件初始化配置
 * 将此代码添加到主题的functions.php文件或自定义插件中
 */

add_action('admin_init', 'fsc_initial_setup');

function fsc_initial_setup() {
    // 检查插件是否已激活
    if (!class_exists('Flexible_Supply_Chain')) {
        return;
    }
    
    // 设置默认配置选项
    $default_settings = array(
        'order_sync_interval' => '300', // 订单同步间隔(秒)
        'auto_inventory_sync' => 'yes', // 自动库存同步
        'notification_email' => get_option('admin_email'), // 通知邮箱
        'multi_currency' => 'no', // 多币种支持
        'tax_calculation' => 'standard', // 税费计算方式
    );
    
    // 如果选项不存在,则添加
    foreach ($default_settings as $key => $value) {
        if (get_option('fsc_' . $key) === false) {
            update_option('fsc_' . $key, $value);
        }
    }
    
    // 创建必要的数据库表
    fsc_create_database_tables();
}

function fsc_create_database_tables() {
    global $wpdb;
    
    $charset_collate = $wpdb->get_charset_collate();
    
    // 多渠道订单聚合表
    $table_name = $wpdb->prefix . 'fsc_multi_channel_orders';
    
    $sql = "CREATE TABLE IF NOT EXISTS $table_name (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        channel_source varchar(100) NOT NULL, -- 订单来源渠道
        channel_order_id varchar(100) NOT NULL, -- 渠道订单ID
        order_data longtext NOT NULL, -- 订单原始数据
        status varchar(50) DEFAULT 'pending', -- 订单状态
        sync_status varchar(50) DEFAULT 'pending', -- 同步状态
        created_at datetime DEFAULT CURRENT_TIMESTAMP,
        updated_at datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
        PRIMARY KEY (id),
        UNIQUE KEY channel_order_unique (channel_source, channel_order_id),
        KEY status_index (status),
        KEY sync_status_index (sync_status)
    ) $charset_collate;";
    
    require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
    dbDelta($sql);
    
    // 渠道配置表
    $channels_table = $wpdb->prefix . 'fsc_sales_channels';
    
    $sql2 = "CREATE TABLE IF NOT EXISTS $channels_table (
        id bigint(20) NOT NULL AUTO_INCREMENT,
        channel_name varchar(100) NOT NULL,
        channel_type varchar(50) NOT NULL, -- 渠道类型:shopify, woocommerce, amazon等
        api_config longtext NOT NULL, -- API配置(加密存储)
        is_active tinyint(1) DEFAULT 1,
        sync_settings longtext, -- 同步设置
        last_sync datetime DEFAULT NULL,
        PRIMARY KEY (id),
        KEY channel_type_index (channel_type),
        KEY is_active_index (is_active)
    ) $charset_collate;";
    
    dbDelta($sql2);
}
?>

配置销售渠道API连接

获取各平台API凭证

  1. Shopify:在Shopify后台创建私有应用获取API密钥
  2. Amazon SP-API:注册亚马逊开发者账户获取访问令牌
  3. WooCommerce:使用REST API密钥
  4. 自定义平台:根据平台文档获取API访问权限

添加渠道配置代码示例

<?php
/**
 * 添加销售渠道配置
 * 示例:添加Shopify渠道
 */

class Channel_Manager {
    
    /**
     * 添加新的销售渠道
     * @param string $channel_name 渠道名称
     * @param string $channel_type 渠道类型
     * @param array $api_config API配置数组
     * @return int|false 成功返回渠道ID,失败返回false
     */
    public function add_sales_channel($channel_name, $channel_type, $api_config) {
        global $wpdb;
        
        // 验证渠道类型
        $valid_channels = array('shopify', 'amazon', 'woocommerce', 'ebay', 'custom');
        if (!in_array($channel_type, $valid_channels)) {
            error_log('无效的渠道类型: ' . $channel_type);
            return false;
        }
        
        // 加密API配置(安全存储)
        $encrypted_config = $this->encrypt_api_config($api_config);
        
        // 默认同步设置
        $default_sync_settings = array(
            'sync_orders' => true,
            'sync_products' => true,
            'sync_inventory' => true,
            'sync_interval' => 300,
            'auto_fulfill' => false
        );
        
        $data = array(
            'channel_name' => sanitize_text_field($channel_name),
            'channel_type' => sanitize_text_field($channel_type),
            'api_config' => $encrypted_config,
            'sync_settings' => serialize($default_sync_settings),
            'is_active' => 1
        );
        
        $format = array('%s', '%s', '%s', '%s', '%d');
        
        $result = $wpdb->insert(
            $wpdb->prefix . 'fsc_sales_channels',
            $data,
            $format
        );
        
        if ($result) {
            return $wpdb->insert_id;
        }
        
        return false;
    }
    
    /**
     * 加密API配置
     * @param array $config API配置数组
     * @return string 加密后的字符串
     */
    private function encrypt_api_config($config) {
        // 使用WordPress盐值进行加密
        $key = wp_salt('secure_auth');
        $iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length('aes-256-cbc'));
        
        $encrypted = openssl_encrypt(
            serialize($config),
            'aes-256-cbc',
            $key,
            0,
            $iv
        );
        
        // 返回IV和加密数据的组合(存储时需一起保存)
        return base64_encode($iv . $encrypted);
    }
    
    /**
     * 解密API配置
     * @param string $encrypted_config 加密的配置字符串
     * @return array 解密后的配置数组
     */
    public function decrypt_api_config($encrypted_config) {
        $key = wp_salt('secure_auth');
        $data = base64_decode($encrypted_config);
        
        $iv_length = openssl_cipher_iv_length('aes-256-cbc');
        $iv = substr($data, 0, $iv_length);
        $encrypted = substr($data, $iv_length);
        
        $decrypted = openssl_decrypt(
            $encrypted,
            'aes-256-cbc',
            $key,
            0,
            $iv
        );
        
        return unserialize($decrypted);
    }
    
    /**
     * 测试渠道连接
     * @param int $channel_id 渠道ID
     * @return array 测试结果
     */
    public function test_channel_connection($channel_id) {
        global $wpdb;
        
        $channel = $wpdb->get_row($wpdb->prepare(
            "SELECT * FROM {$wpdb->prefix}fsc_sales_channels WHERE id = %d",
            $channel_id
        ));
        
        if (!$channel) {
            return array('success' => false, 'message' => '渠道不存在');
        }
        
        $api_config = $this->decrypt_api_config($channel->api_config);
        
        // 根据渠道类型测试连接
        switch ($channel->channel_type) {
            case 'shopify':
                return $this->test_shopify_connection($api_config);
            case 'amazon':
                return $this->test_amazon_connection($api_config);
            case 'woocommerce':
                return $this->test_woocommerce_connection($api_config);
            default:
                return array('success' => false, 'message' => '不支持的渠道类型');
        }
    }
    
    /**
     * 测试Shopify连接
     */
    private function test_shopify_connection($config) {
        // Shopify API测试代码
        $url = "https://{$config['store_url']}/admin/api/2023-01/shop.json";
        
        $response = wp_remote_get($url, array(
            'headers' => array(
                'X-Shopify-Access-Token' => $config['access_token'],
                'Content-Type' => 'application/json'
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            return array(
                'success' => false,
                'message' => '连接失败: ' . $response->get_error_message()
            );
        }
        
        $status_code = wp_remote_retrieve_response_code($response);
        
        if ($status_code === 200) {
            return array('success' => true, 'message' => '连接成功');
        } else {
            return array(
                'success' => false,
                'message' => "连接失败,HTTP状态码: {$status_code}"
            );
        }
    }
}

// 使用示例
$channel_manager = new Channel_Manager();

// 添加Shopify渠道
$shopify_config = array(
    'store_url' => 'your-store.myshopify.com',
    'access_token' => 'shpat_your_access_token',
    'api_version' => '2023-01'
);

$channel_id = $channel_manager->add_sales_channel(
    '我的Shopify店铺',
    'shopify',
    $shopify_config
);

if ($channel_id) {
    // 测试连接
    $test_result = $channel_manager->test_channel_connection($channel_id);
    if ($test_result['success']) {
        echo '渠道添加并测试成功!';
    } else {
        echo '渠道添加成功但测试失败: ' . $test_result['message'];
    }
}
?>

订单同步与聚合实现

订单同步调度器

<?php
/**
 * 订单同步调度器
 * 定期从各渠道拉取订单并聚合
 */

class Order_Sync_Scheduler {
    
    private $sync_interval = 300; // 默认5分钟
    
    public function __construct() {
        $this->sync_interval = get_option('fsc_order_sync_interval', 300);
        
        // 注册定时任务
        add_action('init', array($this, 'schedule_order_sync'));
        add_action('fsc_sync_orders_event', array($this, 'sync_all_channels'));
    }
    
    /**
     * 安排定时同步任务
     */
    public function schedule_order_sync() {
        if (!wp_next_scheduled('fsc_sync_orders_event')) {
            wp_schedule_event(time(), 'fsc_five_minutes', 'fsc_sync_orders_event');
        }
    }
    
    /**
     * 自定义时间间隔
     */
    public function add_cron_interval($schedules) {
        $schedules['fsc_five_minutes'] = array(
            'interval' => $this->sync_interval,
            'display'  => esc_html__('每5分钟(柔性供应链)')
        );
        return $schedules;
    }
    
    /**
     * 同步所有渠道订单
     */
    public function sync_all_channels() {
        global $wpdb;
        
        // 获取所有活跃渠道
        $channels = $wpdb->get_results(
            "SELECT * FROM {$wpdb->prefix}fsc_sales_channels WHERE is_active = 1"
        );
        
        foreach ($channels as $channel) {
            $this->sync_channel_orders($channel);
        }
        
        // 更新最后同步时间
        update_option('fsc_last_sync_time', current_time('mysql'));
        
        // 发送同步完成通知(可选)
        $this->send_sync_notification(count($channels));
    }
    
    /**
     * 同步单个渠道订单
     */
    private function sync_channel_orders($channel) {
        $channel_manager = new Channel_Manager();
        $api_config = $channel_manager->decrypt_api_config($channel->api_config);
        
        switch ($channel->channel_type) {
            case 'shopify':
                $orders = $this->fetch_shopify_orders($api_config);
                break;
            case 'woocommerce':
                $orders = $this->fetch_woocommerce_orders($api_config);
                break;
            // 其他渠道...
            default:
                $orders = array();
        }
        
        // 处理并存储订单
        foreach ($orders as $order_data) {
            $this->process_and_store_order($order_data, $channel);
        }
        
        // 更新渠道最后同步时间
        $this->update_channel_sync_time($channel->id);
    }
    
    /**
     * 从Shopify获取订单
     */
    private function fetch_shopify_orders($config) {
        $url = "https://{$config['store_url']}/admin/api/2023-01/orders.json";
        
        // 获取上次同步后的新订单
        $last_sync = get_option("fsc_shopify_last_sync_{$config['store_url']}", '');
        
        $query_params = array(
            'status' => 'any',
            'limit' => 250,
            'created_at_min' => $last_sync
        );
        
        $url = add_query_arg($query_params, $url);
        
        $response = wp_remote_get($url, array(
            'headers' => array(
                'X-Shopify-Access-Token' => $config['access_token'],
                'Content-Type' => 'application/json'
            ),
            'timeout' => 30
        ));
        
        if (is_wp_error($response)) {
            error_log('Shopify订单获取失败: ' . $response->get_error_message());
            return array();
        }
        
        $body = wp_remote_retrieve_body($response);
        $data = json_decode($body, true);
        
        return isset($data['orders']) ? $data['orders'] : array();
    }
    
    /**
     * 处理并存储订单到聚合表
     */
    private function process_and_store_order($order_data, $channel) {
        global $wpdb;
        
        // 标准化订单数据
        $standardized_order = $this->standardize_order_data($order_data, $channel->channel_type);
        
        // 检查订单是否已存在
        $existing = $wpdb->get_var($wpdb->prepare(
            "SELECT id FROM {$wpdb->prefix}fsc_multi_channel_orders 
             WHERE channel_source = %s AND channel_order_id = %s",
            $channel->channel_name,
            $standardized_order['channel_order_id']
        ));
        
        if ($existing) {
            // 更新现有订单
            $wpdb->update(
                $wpdb->prefix . 'fsc_multi_channel_orders',
                array(
                    'order_data' => serialize($standardized_order),
                    'status' => $standardized_order['status'],
                    'updated_at' => current_time('mysql')
                ),
                array('id' => $existing),
                array('%s', '%s', '%s'),
                array('%d')
            );
        } else {
            // 插入新订单
            $wpdb->insert(
                $wpdb->prefix . 'fsc_multi_channel_orders',
                array(
                    'channel_source' => $channel->channel_name,
                    'channel_order_id' => $standardized_order['channel_order_id'],
                    'order_data' => serialize($standardized_order),
                    'status' => $standardized_order['status'],
                    'sync_status' => 'synced'
                ),
                array('%s', '%s', '%s', '%s', '%s')
            );
        }
    }
    
    /**
     * 标准化不同渠道的订单数据
     */
    private function standardize_order_data($order_data, $channel_type) {
        $standardized = array(
            'order_id' => '',
            'customer' => array(),
            'items' => array(),
            'totals' => array(),
            'shipping' => array(),
            'status' => 'pending',
            'order_date' => '',
            'channel_specific' => array() // 保留渠道特定数据
        );
        
        switch ($channel_type) {
            case 'shopify':
                $standardized['order_id'] = $order_data['id'];
                $standardized['channel_order_id'] = $order_data['order_number'];
                $standardized['customer'] = array(
                    'name' => $order_data['customer']['first_name'] . ' ' . $order_data['customer']['last_name'],
                    'email' => $order_data['customer']['email'],
                    'phone' => $order_data['customer']['phone'] ?? ''
                );
                // 处理商品项
                foreach ($order_data['line_items'] as $item) {
                    $standardized['items'][] = array(
                        'product_id' => $item['product_id'],
                        'sku' => $item['sku'],
                        'name' => $item['name'],

quantity' => $item['quantity'],

                    'price' => $item['price'],
                    'total' => $item['quantity'] * $item['price']
                );
            }
            $standardized['totals'] = array(
                'subtotal' => $order_data['subtotal_price'],
                'shipping' => $order_data['total_shipping_price_set']['shop_money']['amount'],
                'tax' => $order_data['total_tax'],
                'total' => $order_data['total_price']
            );
            $standardized['status'] = $this->map_shopify_status($order_data['financial_status'], $order_data['fulfillment_status']);
            $standardized['order_date'] = $order_data['created_at'];
            $standardized['channel_specific'] = array(
                'financial_status' => $order_data['financial_status'],
                'fulfillment_status' => $order_data['fulfillment_status']
            );
            break;
            
        case 'woocommerce':
            $standardized['order_id'] = $order_data['id'];
            $standardized['channel_order_id'] = $order_data['number'];
            $standardized['customer'] = array(
                'name' => $order_data['billing']['first_name'] . ' ' . $order_data['billing']['last_name'],
                'email' => $order_data['billing']['email'],
                'phone' => $order_data['billing']['phone']
            );
            // 处理商品项
            foreach ($order_data['line_items'] as $item) {
                $standardized['items'][] = array(
                    'product_id' => $item['product_id'],
                    'sku' => $item['sku'],
                    'name' => $item['name'],
                    'quantity' => $item['quantity'],
                    'price' => $item['price'],
                    'total' => $item['quantity'] * $item['price']
                );
            }
            $standardized['totals'] = array(
                'subtotal' => $order_data['subtotal'],
                'shipping' => $order_data['shipping_total'],
                'tax' => $order_data['total_tax'],
                'total' => $order_data['total']
            );
            $standardized['status'] = $order_data['status'];
            $standardized['order_date'] = $order_data['date_created'];
            break;
            
        // 其他渠道的标准化处理...
    }
    
    return $standardized;
}

/**
 * 映射Shopify状态到统一状态
 */
private function map_shopify_status($financial_status, $fulfillment_status) {
    if ($fulfillment_status === 'fulfilled') {
        return 'completed';
    } elseif ($financial_status === 'paid' && $fulfillment_status === null) {
        return 'processing';
    } elseif ($financial_status === 'pending') {
        return 'pending';
    } else {
        return 'on-hold';
    }
}

/**
 * 更新渠道同步时间
 */
private function update_channel_sync_time($channel_id) {
    global $wpdb;
    
    $wpdb->update(
        $wpdb->prefix . 'fsc_sales_channels',
        array('last_sync' => current_time('mysql')),
        array('id' => $channel_id),
        array('%s'),
        array('%d')
    );
}

/**
 * 发送同步通知
 */
private function send_sync_notification($channel_count) {
    $notification_enabled = get_option('fsc_sync_notifications', 'yes');
    
    if ($notification_enabled === 'yes') {
        $to = get_option('fsc_notification_email', get_option('admin_email'));
        $subject = '多渠道订单同步完成';
        $message = sprintf(
            "订单同步已完成。nn同步时间: %sn同步渠道数: %dnn请登录WordPress后台查看详情。",
            current_time('mysql'),
            $channel_count
        );
        
        wp_mail($to, $subject, $message);
    }
}

}

// 初始化调度器
add_action('plugins_loaded', function() {

$scheduler = new Order_Sync_Scheduler();
add_filter('cron_schedules', array($scheduler, 'add_cron_interval'));

});
?>


## 聚合订单管理与展示

### 创建订单管理界面

<?php
/**

  • 聚合订单管理界面
    */

class Aggregated_Orders_Admin {


public function __construct() {
    add_action('admin_menu', array($this, 'add_admin_menu'));
    add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
    add_action('wp_ajax_fsc_update_order_status', array($this, 'ajax_update_order_status'));
    add_action('wp_ajax_fsc_export_orders', array($this, 'ajax_export_orders'));
}

/**
 * 添加管理菜单
 */
public function add_admin_menu() {
    add_menu_page(
        '聚合订单管理',
        '聚合订单',
        'manage_options',
        'fsc-orders',
        array($this, 'render_orders_page'),
        'dashicons-cart',
        30
    );
    
    // 子菜单:渠道管理
    add_submenu_page(
        'fsc-orders',
        '销售渠道管理',
        '渠道管理',
        'manage_options',
        'fsc-channels',
        array($this, 'render_channels_page')
    );
    
    // 子菜单:同步日志
    add_submenu_page(
        'fsc-orders',
        '同步日志',
        '同步日志',
        'manage_options',
        'fsc-sync-logs',
        array($this, 'render_sync_logs_page')
    );
}

/**
 * 渲染订单管理页面
 */
public function render_orders_page() {
    global $wpdb;
    
    // 处理批量操作
    if (isset($_POST['bulk_action']) && isset($_POST['order_ids'])) {
        $this->handle_bulk_actions($_POST['bulk_action'], $_POST['order_ids']);
    }
    
    // 获取筛选参数
    $status_filter = isset($_GET['status']) ? sanitize_text_field($_GET['status']) : '';
    $channel_filter = isset($_GET['channel']) ? sanitize_text_field($_GET['channel']) : '';
    $date_from = isset($_GET['date_from']) ? sanitize_text_field($_GET['date_from']) : '';
    $date_to = isset($_GET['date_to']) ? sanitize_text_field($_GET['date_to']) : '';
    
    // 构建查询
    $query = "SELECT * FROM {$wpdb->prefix}fsc_multi_channel_orders WHERE 1=1";
    $query_params = array();
    
    if ($status_filter) {
        $query .= " AND status = %s";
        $query_params[] = $status_filter;
    }
    
    if ($channel_filter) {
        $query .= " AND channel_source = %s";
        $query_params[] = $channel_filter;
    }
    
    if ($date_from) {
        $query .= " AND DATE(created_at) >= %s";
        $query_params[] = $date_from;
    }
    
    if ($date_to) {
        $query .= " AND DATE(created_at) <= %s";
        $query_params[] = $date_to;
    }
    
    $query .= " ORDER BY created_at DESC LIMIT 100";
    
    if (!empty($query_params)) {
        $orders = $wpdb->get_results($wpdb->prepare($query, $query_params));
    } else {
        $orders = $wpdb->get_results($query);
    }
    
    // 获取所有渠道用于筛选
    $channels = $wpdb->get_col("SELECT DISTINCT channel_source FROM {$wpdb->prefix}fsc_multi_channel_orders");
    
    ?>
    <div class="wrap">
        <h1 class="wp-heading-inline">聚合订单管理</h1>
        <a href="<?php echo admin_url('admin.php?page=fsc-orders&action=sync_now'); ?>" class="page-title-action">立即同步</a>
        <hr class="wp-header-end">
        
        <!-- 筛选表单 -->
        <div class="fsc-filters">
            <form method="get" action="<?php echo admin_url('admin.php'); ?>">
                <input type="hidden" name="page" value="fsc-orders">
                
                <div class="filter-row">
                    <select name="status">
                        <option value="">所有状态</option>
                        <option value="pending" <?php selected($status_filter, 'pending'); ?>>待处理</option>
                        <option value="processing" <?php selected($status_filter, 'processing'); ?>>处理中</option>
                        <option value="completed" <?php selected($status_filter, 'completed'); ?>>已完成</option>
                        <option value="cancelled" <?php selected($status_filter, 'cancelled'); ?>>已取消</option>
                    </select>
                    
                    <select name="channel">
                        <option value="">所有渠道</option>
                        <?php foreach ($channels as $channel): ?>
                            <option value="<?php echo esc_attr($channel); ?>" <?php selected($channel_filter, $channel); ?>>
                                <?php echo esc_html($channel); ?>
                            </option>
                        <?php endforeach; ?>
                    </select>
                    
                    <input type="date" name="date_from" value="<?php echo esc_attr($date_from); ?>" placeholder="开始日期">
                    <input type="date" name="date_to" value="<?php echo esc_attr($date_to); ?>" placeholder="结束日期">
                    
                    <button type="submit" class="button">筛选</button>
                    <a href="<?php echo admin_url('admin.php?page=fsc-orders'); ?>" class="button">重置</a>
                </div>
            </form>
        </div>
        
        <!-- 订单表格 -->
        <form method="post" action="">
            <div class="tablenav top">
                <div class="alignleft actions bulkactions">
                    <select name="bulk_action">
                        <option value="">批量操作</option>
                        <option value="mark_processing">标记为处理中</option>
                        <option value="mark_completed">标记为已完成</option>
                        <option value="export_selected">导出选中订单</option>
                    </select>
                    <button type="submit" class="button action">应用</button>
                </div>
                <div class="tablenav-pages">
                    <span class="displaying-num"><?php echo count($orders); ?> 个订单</span>
                </div>
            </div>
            
            <table class="wp-list-table widefat fixed striped">
                <thead>
                    <tr>
                        <td class="manage-column column-cb check-column">
                            <input type="checkbox" id="cb-select-all-1">
                        </td>
                        <th>订单号</th>
                        <th>渠道</th>
                        <th>客户</th>
                        <th>商品</th>
                        <th>金额</th>
                        <th>状态</th>
                        <th>下单时间</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <?php if (empty($orders)): ?>
                        <tr>
                            <td colspan="9" style="text-align: center;">暂无订单</td>
                        </tr>
                    <?php else: ?>
                        <?php foreach ($orders as $order): 
                            $order_data = unserialize($order->order_data);
                        ?>
                            <tr>
                                <th scope="row" class="check-column">
                                    <input type="checkbox" name="order_ids[]" value="<?php echo $order->id; ?>">
                                </th>
                                <td>
                                    <strong>#<?php echo esc_html($order_data['channel_order_id']); ?></strong>
                                    <div class="row-actions">
                                        <span class="view">
                                            <a href="#" class="view-order-details" data-order-id="<?php echo $order->id; ?>">查看详情</a> |
                                        </span>
                                        <span class="edit">
                                            <a href="#" class="edit-order-status" data-order-id="<?php echo $order->id; ?>">编辑状态</a>
                                        </span>
                                    </div>
                                </td>
                                <td><?php echo esc_html($order->channel_source); ?></td>
                                <td>
                                    <?php echo esc_html($order_data['customer']['name']); ?><br>
                                    <small><?php echo esc_html($order_data['customer']['email']); ?></small>
                                </td>
                                <td>
                                    <?php 
                                    $item_count = count($order_data['items']);
                                    $first_item = $order_data['items'][0]['name'] ?? '';
                                    echo $item_count . ' 件商品';
                                    if ($first_item) {
                                        echo '<br><small>' . esc_html($first_item) . '...</small>';
                                    }
                                    ?>
                                </td>
                                <td><?php echo get_woocommerce_currency_symbol() . number_format($order_data['totals']['total'], 2); ?></td>
                                <td>
                                    <span class="order-status status-<?php echo esc_attr($order->status); ?>">
                                        <?php echo $this->get_status_label($order->status); ?>
                                    </span>
                                </td>
                                <td><?php echo date('Y-m-d H:i', strtotime($order_data['order_date'])); ?></td>
                                <td>
                                    <button class="button button-small update-status" data-order-id="<?php echo $order->id; ?>">
                                        更新状态
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </tbody>
            </table>
        </form>
        
        <!-- 订单详情模态框 -->
        <div id="order-details-modal" class="fsc-modal" style="display: none;">
            <div class="modal-content">
                <div class="modal-header">
                    <h2>订单详情</h2>
                    <span class="close-modal">&times;</span>
                </div>
                <div class="modal-body" id="order-details-content">
                    <!-- 通过AJAX加载内容 -->
                </div>
            </div>
        </div>
    </div>
    
    <style>
        .fsc-filters {
            background: #fff;
            padding: 15px;
            margin-bottom: 20px;
            border: 1px solid #ccd0d4;
        }
        .filter-row {
            display: flex;
            gap: 10px;
            align-items: center;
        }
        .filter-row select,
        .filter-row input {
            height: 32px;
        }
        .order-status {
            padding: 3px 8px;
            border-radius: 3px;
            font-size: 12px;
            font-weight: 600;
        }
        .status-pending { background: #f0ad4e; color: #fff; }
        .status-processing { background: #5bc0de; color: #fff; }
        .status-completed { background: #5cb85c; color: #fff; }
        .status-cancelled { background: #d9534f; color: #fff; }
        .fsc-modal {
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0,0,0,0.5);
        }
        .modal-content {
            background-color: #fff;
            margin: 5% auto;
            padding: 0;
            width: 80%;
            max-width: 800px;
            border-radius: 5px;
        }
        .modal-header {
            padding: 15px;
            border-bottom: 1px solid #ddd;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .modal-body {
            padding: 20px;
            max-height: 60vh;
            overflow-y: auto;
        }
        .close-modal {
            font-size: 28px;
            cursor: pointer;
        }
    </style>
    
    <script>
    jQuery(document).ready(function($) {
        // 查看订单详情
        $('.view-order-details').on('click', function(e) {
            e.preventDefault();
            var orderId = $(this).data('order-id');
            
            $.ajax({
                url: ajaxurl,
                type: 'POST',
                data: {
                    action: 'fsc_get_order_details',
                    order_id: orderId,
                    nonce: '<?php echo wp_create_nonce('fsc_order_details'); ?>'
                },
                success: function(response) {
                    if (response.success) {
                        $('#order-details-content').html(response.data.html);
                        $('#order-details-modal').show();
                    }
                }
            });
        });
        
        // 关闭模态框
        $('.close-modal').on('click', function() {
            $('#order-details-modal').hide();
        });
        
        // 更新订单状态
        $('.update-status').on('click', function() {
            var orderId = $(this).data('order-id');
            var newStatus = prompt('请输入新状态 (pending, processing, completed, cancelled):');
            
            if (newStatus) {
                $.ajax({
                    url: ajaxurl,
                    type: 'POST',
                    data: {
                        action: 'fsc_update_order_status',
                        order_id: orderId,
                        new_status: newStatus,
                        nonce: '<?php echo wp_create_nonce('fsc_update_status'); ?>'
                    },
                    success: function(response) {
                        if (response.success) {
                            location.reload();
                        } else {
                            alert('更新失败: ' + response.data.message);
                        }
                    }
                });
            }
        });
    });
    </script>
    <?php
}

/**
 * 处理批量操作
 */
private function handle_bulk_actions($action, $order_ids) {
    global $wpdb;
    
    if (!is_array($order_ids) || empty($order_ids)) {
        return;
    }
    
    $order_ids = array_map('intval', $order_ids);
    $placeholders = implode(',', array_fill(0, count($order_ids), '%d'));
    
    switch ($action) {
        case 'mark_processing':
            $wpdb->query($wpdb
本文来自网络,不代表柔性供应链服务中心立场,转载请注明出处:https://mall.org.cn/6437.html

EXCHANGES®作者

上一篇
下一篇

为您推荐

发表回复

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@exchanges.center

工作时间:周一至周五,9:00-17:30,节假日休息
返回顶部