首页 / 教程文章 / WordPress柔性供应链软件的多级经销商管理模块开发教程

WordPress柔性供应链软件的多级经销商管理模块开发教程

本教程详细指导如何在WordPress平台上开发柔性供应链软件的多级经销商管理模块。系统采用自定义文章类型管理经销商信息,通过树形结构建立层级关系,并集成订单分配、佣金计算、后台管理及数据分析等核心功能。旨在帮助企业构建灵活可扩展的经销商网络,提升供应链管理效率。

WordPress柔性供应链软件的多级经销商管理模块开发教程

引言:柔性供应链与多级经销商管理的必要性

在当今快速变化的市场环境中,企业需要灵活应对供应链的各种挑战。WordPress作为全球最流行的内容管理系统,其强大的扩展性使其成为开发企业级供应链管理软件的理想平台。多级经销商管理是供应链中的关键环节,它涉及从总代理到各级分销商再到终端客户的完整销售网络管理。

本教程将指导您开发一个完整的WordPress多级经销商管理模块,帮助您构建一个灵活、可扩展的经销商管理体系。

系统架构设计

在开始编码之前,我们需要设计系统的整体架构。我们的多级经销商管理系统将包含以下核心组件:

  1. 经销商层级管理(树形结构)
  2. 经销商信息管理
  3. 订单分配与跟踪
  4. 佣金计算系统
  5. 报表与分析功能

我们将使用WordPress的自定义文章类型(Custom Post Type)来管理经销商,并建立他们之间的层级关系。

环境准备与基础配置

首先,确保您的WordPress环境已准备好开发插件:

<?php
/**
 * Plugin Name: 柔性供应链多级经销商管理
 * Plugin URI: https://yourwebsite.com/
 * Description: WordPress柔性供应链软件的多级经销商管理模块
 * Version: 1.0.0
 * Author: Your Name
 * License: GPL v2 or later
 */

// 防止直接访问
if (!defined('ABSPATH')) {
    exit;
}

// 定义插件常量
define('FSC_DISTRIBUTOR_VERSION', '1.0.0');
define('FSC_DISTRIBUTOR_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FSC_DISTRIBUTOR_PLUGIN_URL', plugin_dir_url(__FILE__));

创建经销商自定义文章类型

经销商将作为自定义文章类型存储在WordPress中:

/**
 * 注册经销商自定义文章类型
 */
function fsc_register_distributor_post_type() {
    $labels = array(
        'name'               => '经销商',
        'singular_name'      => '经销商',
        'menu_name'          => '经销商管理',
        'add_new'            => '添加经销商',
        'add_new_item'       => '添加新经销商',
        'edit_item'          => '编辑经销商',
        'new_item'           => '新经销商',
        'view_item'          => '查看经销商',
        'search_items'       => '搜索经销商',
        'not_found'          => '未找到经销商',
        'not_found_in_trash' => '回收站中无经销商'
    );
    
    $args = array(
        'labels'             => $labels,
        'public'             => true,
        'publicly_queryable' => true,
        'show_ui'            => true,
        'show_in_menu'       => true,
        'query_var'          => true,
        'rewrite'            => array('slug' => 'distributor'),
        'capability_type'    => 'post',
        'has_archive'        => true,
        'hierarchical'       => false,
        'menu_position'      => 30,
        'menu_icon'          => 'dashicons-networking',
        'supports'           => array('title', 'editor', 'thumbnail', 'custom-fields'),
        'show_in_rest'       => true // 启用Gutenberg编辑器支持
    );
    
    register_post_type('distributor', $args);
}
add_action('init', 'fsc_register_distributor_post_type');

实现经销商层级关系管理

经销商之间的层级关系是系统的核心,我们将使用自定义分类法来管理:

/**
 * 注册经销商层级分类法
 */
function fsc_register_distributor_hierarchy() {
    $labels = array(
        'name'              => '经销商层级',
        'singular_name'     => '层级',
        'search_items'      => '搜索层级',
        'all_items'         => '所有层级',
        'parent_item'       => '父级层级',
        'parent_item_colon' => '父级层级:',
        'edit_item'         => '编辑层级',
        'update_item'       => '更新层级',
        'add_new_item'      => '添加新层级',
        'new_item_name'     => '新层级名称',
        'menu_name'         => '层级管理'
    );
    
    $args = array(
        'hierarchical'      => true, // 设置为true以创建层级结构
        'labels'            => $labels,
        'show_ui'           => true,
        'show_admin_column' => true,
        'query_var'         => true,
        'rewrite'           => array('slug' => 'distributor-level'),
        'show_in_rest'      => true
    );
    
    register_taxonomy('distributor_level', array('distributor'), $args);
}
add_action('init', 'fsc_register_distributor_hierarchy');

/**
 * 添加上级经销商选择字段
 */
function fsc_add_parent_distributor_meta_box() {
    add_meta_box(
        'fsc_parent_distributor',
        '上级经销商',
        'fsc_parent_distributor_meta_box_callback',
        'distributor',
        'side',
        'high'
    );
}
add_action('add_meta_boxes', 'fsc_add_parent_distributor_meta_box');

/**
 * 上级经销商选择框回调函数
 */
function fsc_parent_distributor_meta_box_callback($post) {
    // 添加安全验证
    wp_nonce_field('fsc_save_parent_distributor', 'fsc_parent_distributor_nonce');
    
    // 获取当前上级经销商ID
    $parent_id = get_post_meta($post->ID, '_fsc_parent_distributor_id', true);
    
    // 查询所有经销商(排除当前经销商)
    $args = array(
        'post_type'      => 'distributor',
        'posts_per_page' => -1,
        'post__not_in'   => array($post->ID),
        'orderby'        => 'title',
        'order'          => 'ASC'
    );
    
    $distributors = get_posts($args);
    
    echo '<select name="fsc_parent_distributor" id="fsc_parent_distributor" style="width:100%;">';
    echo '<option value="">无上级经销商(顶级)</option>';
    
    foreach ($distributors as $distributor) {
        $selected = ($parent_id == $distributor->ID) ? 'selected="selected"' : '';
        echo '<option value="' . esc_attr($distributor->ID) . '" ' . $selected . '>';
        echo esc_html($distributor->post_title);
        echo '</option>';
    }
    
    echo '</select>';
    echo '<p class="description">选择此经销商的上级经销商</p>';
}

/**
 * 保存上级经销商信息
 */
function fsc_save_parent_distributor_meta($post_id) {
    // 检查安全验证
    if (!isset($_POST['fsc_parent_distributor_nonce']) || 
        !wp_verify_nonce($_POST['fsc_parent_distributor_nonce'], 'fsc_save_parent_distributor')) {
        return;
    }
    
    // 检查自动保存
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    // 检查用户权限
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // 保存上级经销商ID
    if (isset($_POST['fsc_parent_distributor'])) {
        update_post_meta(
            $post_id, 
            '_fsc_parent_distributor_id', 
            sanitize_text_field($_POST['fsc_parent_distributor'])
        );
    }
}
add_action('save_post_distributor', 'fsc_save_parent_distributor_meta');

经销商信息管理扩展字段

除了基本信息和层级关系,我们还需要存储经销商的详细信息:

/**
 * 添加经销商详细信息元框
 */
function fsc_add_distributor_details_meta_box() {
    add_meta_box(
        'fsc_distributor_details',
        '经销商详细信息',
        'fsc_distributor_details_meta_box_callback',
        'distributor',
        'normal',
        'high'
    );
}
add_action('add_meta_boxes', 'fsc_add_distributor_details_meta_box');

/**
 * 经销商详细信息元框回调函数
 */
function fsc_distributor_details_meta_box_callback($post) {
    // 安全验证
    wp_nonce_field('fsc_save_distributor_details', 'fsc_distributor_details_nonce');
    
    // 获取现有值
    $contact_person = get_post_meta($post->ID, '_fsc_contact_person', true);
    $contact_phone = get_post_meta($post->ID, '_fsc_contact_phone', true);
    $contact_email = get_post_meta($post->ID, '_fsc_contact_email', true);
    $region = get_post_meta($post->ID, '_fsc_region', true);
    $address = get_post_meta($post->ID, '_fsc_address', true);
    $commission_rate = get_post_meta($post->ID, '_fsc_commission_rate', true);
    $credit_limit = get_post_meta($post->ID, '_fsc_credit_limit', true);
    
    // 输出表单字段
    ?>
    <table class="form-table">
        <tr>
            <th><label for="fsc_contact_person">联系人</label></th>
            <td>
                <input type="text" id="fsc_contact_person" name="fsc_contact_person" 
                       value="<?php echo esc_attr($contact_person); ?>" class="regular-text">
            </td>
        </tr>
        <tr>
            <th><label for="fsc_contact_phone">联系电话</label></th>
            <td>
                <input type="tel" id="fsc_contact_phone" name="fsc_contact_phone" 
                       value="<?php echo esc_attr($contact_phone); ?>" class="regular-text">
            </td>
        </tr>
        <tr>
            <th><label for="fsc_contact_email">联系邮箱</label></th>
            <td>
                <input type="email" id="fsc_contact_email" name="fsc_contact_email" 
                       value="<?php echo esc_attr($contact_email); ?>" class="regular-text">
            </td>
        </tr>
        <tr>
            <th><label for="fsc_region">负责区域</label></th>
            <td>
                <input type="text" id="fsc_region" name="fsc_region" 
                       value="<?php echo esc_attr($region); ?>" class="regular-text">
            </td>
        </tr>
        <tr>
            <th><label for="fsc_address">详细地址</label></th>
            <td>
                <textarea id="fsc_address" name="fsc_address" rows="3" class="large-text"><?php echo esc_textarea($address); ?></textarea>
            </td>
        </tr>
        <tr>
            <th><label for="fsc_commission_rate">佣金比例(%)</label></th>
            <td>
                <input type="number" id="fsc_commission_rate" name="fsc_commission_rate" 
                       value="<?php echo esc_attr($commission_rate); ?>" min="0" max="100" step="0.1" class="small-text">
            </td>
        </tr>
        <tr>
            <th><label for="fsc_credit_limit">信用额度</label></th>
            <td>
                <input type="number" id="fsc_credit_limit" name="fsc_credit_limit" 
                       value="<?php echo esc_attr($credit_limit); ?>" min="0" step="0.01" class="small-text">
            </td>
        </tr>
    </table>
    <?php
}

/**
 * 保存经销商详细信息
 */
function fsc_save_distributor_details_meta($post_id) {
    // 安全检查
    if (!isset($_POST['fsc_distributor_details_nonce']) || 
        !wp_verify_nonce($_POST['fsc_distributor_details_nonce'], 'fsc_save_distributor_details')) {
        return;
    }
    
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }
    
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }
    
    // 保存所有字段
    $fields = array(
        'fsc_contact_person',
        'fsc_contact_phone',
        'fsc_contact_email',
        'fsc_region',
        'fsc_address',
        'fsc_commission_rate',
        'fsc_credit_limit'
    );
    
    foreach ($fields as $field) {
        if (isset($_POST[$field])) {
            update_post_meta(
                $post_id, 
                '_' . $field, 
                sanitize_text_field($_POST[$field])
            );
        }
    }
}
add_action('save_post_distributor', 'fsc_save_distributor_details_meta');

经销商层级树形结构展示

为了直观展示经销商层级关系,我们需要创建一个树形结构展示功能:

/**
 * 获取经销商层级树
 * @param int $parent_id 父级经销商ID
 * @param int $level 当前层级深度
 * @return string 树形结构HTML
 */
function fsc_get_distributor_tree($parent_id = 0, $level = 0) {
    $args = array(
        'post_type'      => 'distributor',
        'posts_per_page' => -1,
        'meta_query'     => array(
            array(
                'key'   => '_fsc_parent_distributor_id',
                'value' => $parent_id
            )
        ),
        'orderby'        => 'title',
        'order'          => 'ASC'
    );
    
    $children = get_posts($args);
    
    if (empty($children)) {
        return '';
    }
    
    $output = '';
    
    foreach ($children as $child) {
        $indent = str_repeat('&nbsp;&nbsp;&nbsp;&nbsp;', $level);
        $output .= '<div class="distributor-tree-item" style="margin-left:' . ($level * 20) . 'px;">';
        $output .= $indent . '├─ ' . esc_html($child->post_title);
        $output .= ' <a href="' . get_edit_post_link($child->ID) . '">编辑</a>';
        $output .= '</div>';
        
        // 递归获取子级
        $output .= fsc_get_distributor_tree($child->ID, $level + 1);
    }
    
    return $output;
}

/**
 * 经销商树形结构短代码
 */
function fsc_distributor_tree_shortcode() {
    ob_start();
    ?>
    <div class="distributor-tree-container">
        <h3>经销商层级结构</h3>
        <div class="distributor-tree">
            <?php echo fsc_get_distributor_tree(); ?>
        </div>
    </div>
    <style>
        .distributor-tree-container {
            background: #f9f9f9;
            padding: 20px;
            border-radius: 5px;
            margin: 20px 0;
        }
        .distributor-tree-item {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        .distributor-tree-item:last-child {
            border-bottom: none;
        }
    </style>
    <?php
    return ob_get_clean();
}
add_shortcode('distributor_tree', 'fsc_distributor_tree_shortcode');

订单分配与佣金计算系统

订单分配和佣金计算是多级经销商管理的核心功能:

/**
 * 订单分配类
 */
class FSC_Order_Distribution {
    
    /**
     * 根据区域自动分配订单给经销商
     * @param int $order_id WooCommerce订单ID
     * @param string $region 订单区域
     * @return int|bool 经销商ID或false
     */
    public static function assign_order_to_distributor($order_id, $region) {
        // 查找负责该区域的经销商
        $args = array(
            'post_type'  => 'distributor',
            'meta_query' => array(
                array(
                    'key'     => '_fsc_region',
                    'value'   => $region,
                    'compare' => 'LIKE'
                )
            ),
            'posts_per_page' => 1
        );
        
        $distributors = get_posts($args);
        
        if (empty($distributors)) {
            // 如果没有找到特定区域的经销商,分配给顶级经销商
            $args = array(
                'post_type'  => 'distributor',
                'meta_query' => array(
                    array(
                        'key'     => '_fsc_parent_distributor_id',
                        'value'   => '',
                        'compare' => '='
                    )
                ),
                'posts_per_page' => 1,
                'orderby'        => 'rand'
            );
            
            $distributors = get_posts($args);
        }
        
        if (!empty($distributors)) {
            $distributor_id = $distributors[0]->ID;
            
            // 保存订单与经销商关联
            update_post_meta($order_id, '_fsc_assigned_distributor', $distributor_id);
            
            // 计算并分配佣金
            self::calculate_commission($order_id, $distributor_id);
            
            return $distributor_id;
        }
        
        return false;
    }
    
    /**
     * 计算经销商佣金
     * @param int $order_id 订单ID
     * @param int $distributor_id 经销商ID
     */
    private static function calculate_commission($order_id, $distributor_id) {
        $order = wc_get_order($order_id);
        $order_total = $order->get_total();
        

佣金计算与分配系统

/**
 * 计算经销商佣金(续)
 */
private static function calculate_commission($order_id, $distributor_id) {
    $order = wc_get_order($order_id);
    $order_total = $order->get_total();
    
    // 获取经销商佣金比例
    $commission_rate = get_post_meta($distributor_id, '_fsc_commission_rate', true);
    
    // 如果未设置佣金比例,使用默认值
    if (empty($commission_rate)) {
        $commission_rate = 10; // 默认10%
    }
    
    // 计算佣金金额
    $commission_amount = ($order_total * $commission_rate) / 100;
    
    // 保存佣金记录
    $commission_data = array(
        'order_id'          => $order_id,
        'distributor_id'    => $distributor_id,
        'order_total'       => $order_total,
        'commission_rate'   => $commission_rate,
        'commission_amount' => $commission_amount,
        'status'            => 'pending',
        'created_at'        => current_time('mysql')
    );
    
    // 将佣金记录保存为自定义文章类型
    $commission_id = wp_insert_post(array(
        'post_title'   => sprintf('佣金订单 #%d - 经销商 #%d', $order_id, $distributor_id),
        'post_type'    => 'fsc_commission',
        'post_status'  => 'publish',
        'post_content' => '',
        'meta_input'   => $commission_data
    ));
    
    // 计算上级经销商的佣金(多级佣金)
    self::calculate_parent_commission($order_id, $distributor_id, $order_total);
    
    return $commission_amount;
}

/**
 * 计算上级经销商佣金(多级佣金体系)
 * @param int $order_id 订单ID
 * @param int $distributor_id 当前经销商ID
 * @param float $order_total 订单总金额
 */
private static function calculate_parent_commission($order_id, $distributor_id, $order_total) {
    $parent_id = get_post_meta($distributor_id, '_fsc_parent_distributor_id', true);
    $level = 1;
    
    // 循环计算所有上级经销商的佣金
    while (!empty($parent_id) && $level <= 5) { // 最多支持5级佣金
        $parent_rate = get_post_meta($parent_id, '_fsc_parent_commission_rate', true);
        
        // 如果未设置上级佣金比例,使用递减公式
        if (empty($parent_rate)) {
            $parent_rate = max(0, 10 - ($level * 2)); // 每级递减2%
        }
        
        if ($parent_rate > 0) {
            $parent_amount = ($order_total * $parent_rate) / 100;
            
            $parent_commission_data = array(
                'order_id'          => $order_id,
                'distributor_id'    => $parent_id,
                'order_total'       => $order_total,
                'commission_rate'   => $parent_rate,
                'commission_amount' => $parent_amount,
                'level'             => $level,
                'status'            => 'pending',
                'created_at'        => current_time('mysql')
            );
            
            wp_insert_post(array(
                'post_title'   => sprintf('上级佣金 L%d - 订单 #%d', $level, $order_id),
                'post_type'    => 'fsc_commission',
                'post_status'  => 'publish',
                'meta_input'   => $parent_commission_data
            ));
        }
        
        // 获取上一级经销商
        $parent_id = get_post_meta($parent_id, '_fsc_parent_distributor_id', true);
        $level++;
    }
}

/**
 * 注册佣金记录自定义文章类型
 */
function fsc_register_commission_post_type() {
    $labels = array(
        'name'               => '佣金记录',
        'singular_name'      => '佣金记录',
        'menu_name'          => '佣金管理',
        'add_new'            => '添加佣金记录',
        'add_new_item'       => '添加新佣金记录',
        'edit_item'          => '编辑佣金记录',
        'new_item'           => '新佣金记录',
        'view_item'          => '查看佣金记录',
        'search_items'       => '搜索佣金记录'
    );
    
    $args = array(
        'labels'             => $labels,
        'public'             => false,
        'publicly_queryable' => false,
        'show_ui'            => true,
        'show_in_menu'       => 'edit.php?post_type=distributor',
        'query_var'          => true,
        'capability_type'    => 'post',
        'has_archive'        => false,
        'hierarchical'       => false,
        'menu_position'      => null,
        'supports'           => array('title'),
        'show_in_rest'       => false
    );
    
    register_post_type('fsc_commission', $args);
}
add_action('init', 'fsc_register_commission_post_type');

经销商后台管理界面

为经销商提供专门的后台管理界面:

/**
 * 创建经销商后台管理页面
 */
function fsc_create_distributor_dashboard() {
    add_menu_page(
        '经销商面板',
        '经销商面板',
        'read',
        'distributor-dashboard',
        'fsc_distributor_dashboard_content',
        'dashicons-businessperson',
        30
    );
    
    // 添加子菜单
    add_submenu_page(
        'distributor-dashboard',
        '我的业绩',
        '我的业绩',
        'read',
        'distributor-performance',
        'fsc_distributor_performance_content'
    );
    
    add_submenu_page(
        'distributor-dashboard',
        '我的团队',
        '我的团队',
        'read',
        'distributor-team',
        'fsc_distributor_team_content'
    );
    
    add_submenu_page(
        'distributor-dashboard',
        '佣金明细',
        '佣金明细',
        'read',
        'distributor-commissions',
        'fsc_distributor_commissions_content'
    );
}
add_action('admin_menu', 'fsc_create_distributor_dashboard');

/**
 * 经销商主面板内容
 */
function fsc_distributor_dashboard_content() {
    // 获取当前用户关联的经销商
    $user_id = get_current_user_id();
    $distributor_id = get_user_meta($user_id, '_fsc_distributor_id', true);
    
    if (!$distributor_id) {
        echo '<div class="notice notice-warning"><p>您尚未关联经销商账户,请联系管理员。</p></div>';
        return;
    }
    
    $distributor = get_post($distributor_id);
    ?>
    <div class="wrap">
        <h1>经销商面板 - <?php echo esc_html($distributor->post_title); ?></h1>
        
        <div class="fsc-dashboard-widgets">
            <div class="fsc-widget">
                <h3>本月销售额</h3>
                <p class="fsc-widget-value"><?php echo fsc_get_monthly_sales($distributor_id); ?></p>
            </div>
            
            <div class="fsc-widget">
                <h3>待结算佣金</h3>
                <p class="fsc-widget-value"><?php echo fsc_get_pending_commissions($distributor_id); ?></p>
            </div>
            
            <div class="fsc-widget">
                <h3>团队人数</h3>
                <p class="fsc-widget-value"><?php echo fsc_get_team_count($distributor_id); ?></p>
            </div>
            
            <div class="fsc-widget">
                <h3>信用额度</h3>
                <p class="fsc-widget-value"><?php echo get_post_meta($distributor_id, '_fsc_credit_limit', true); ?></p>
            </div>
        </div>
        
        <div class="fsc-dashboard-chart">
            <h3>销售趋势</h3>
            <canvas id="salesChart" width="400" height="200"></canvas>
        </div>
    </div>
    
    <style>
        .fsc-dashboard-widgets {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
            gap: 20px;
            margin: 20px 0;
        }
        .fsc-widget {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            text-align: center;
        }
        .fsc-widget-value {
            font-size: 24px;
            font-weight: bold;
            color: #0073aa;
            margin: 10px 0 0;
        }
        .fsc-dashboard-chart {
            background: #fff;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            margin-top: 20px;
        }
    </style>
    
    <script>
    document.addEventListener('DOMContentLoaded', function() {
        var ctx = document.getElementById('salesChart').getContext('2d');
        var salesChart = new Chart(ctx, {
            type: 'line',
            data: {
                labels: ['1月', '2月', '3月', '4月', '5月', '6月'],
                datasets: [{
                    label: '销售额',
                    data: [12000, 19000, 15000, 25000, 22000, 30000],
                    borderColor: '#0073aa',
                    backgroundColor: 'rgba(0, 115, 170, 0.1)',
                    borderWidth: 2,
                    fill: true
                }]
            },
            options: {
                responsive: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    });
    </script>
    <?php
}

/**
 * 获取经销商月度销售额
 */
function fsc_get_monthly_sales($distributor_id) {
    global $wpdb;
    
    $current_month = date('Y-m');
    
    $sales = $wpdb->get_var($wpdb->prepare(
        "SELECT SUM(meta_value) 
        FROM {$wpdb->postmeta} 
        WHERE meta_key = '_fsc_commission_amount' 
        AND post_id IN (
            SELECT ID FROM {$wpdb->posts} 
            WHERE post_type = 'fsc_commission' 
            AND post_status = 'publish'
            AND DATE(post_date) LIKE %s
            AND ID IN (
                SELECT post_id FROM {$wpdb->postmeta} 
                WHERE meta_key = 'distributor_id' 
                AND meta_value = %d
            )
        )",
        $current_month . '%',
        $distributor_id
    ));
    
    return $sales ? number_format($sales, 2) : '0.00';
}

经销商团队管理功能

/**
 * 经销商团队管理页面内容
 */
function fsc_distributor_team_content() {
    $user_id = get_current_user_id();
    $distributor_id = get_user_meta($user_id, '_fsc_distributor_id', true);
    
    if (!$distributor_id) {
        echo '<div class="notice notice-warning"><p>您尚未关联经销商账户。</p></div>';
        return;
    }
    ?>
    <div class="wrap">
        <h1>我的团队管理</h1>
        
        <div class="tablenav top">
            <div class="alignleft actions">
                <a href="<?php echo admin_url('post-new.php?post_type=distributor&parent=' . $distributor_id); ?>" 
                   class="button button-primary">添加下级经销商</a>
            </div>
        </div>
        
        <table class="wp-list-table widefat fixed striped">
            <thead>
                <tr>
                    <th>经销商名称</th>
                    <th>联系人</th>
                    <th>联系电话</th>
                    <th>负责区域</th>
                    <th>本月销售额</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php
                $sub_distributors = get_posts(array(
                    'post_type'      => 'distributor',
                    'posts_per_page' => -1,
                    'meta_query'     => array(
                        array(
                            'key'   => '_fsc_parent_distributor_id',
                            'value' => $distributor_id
                        )
                    )
                ));
                
                if ($sub_distributors) {
                    foreach ($sub_distributors as $distributor) {
                        $contact_person = get_post_meta($distributor->ID, '_fsc_contact_person', true);
                        $contact_phone = get_post_meta($distributor->ID, '_fsc_contact_phone', true);
                        $region = get_post_meta($distributor->ID, '_fsc_region', true);
                        $monthly_sales = fsc_get_monthly_sales($distributor->ID);
                        ?>
                        <tr>
                            <td><?php echo esc_html($distributor->post_title); ?></td>
                            <td><?php echo esc_html($contact_person); ?></td>
                            <td><?php echo esc_html($contact_phone); ?></td>
                            <td><?php echo esc_html($region); ?></td>
                            <td><?php echo $monthly_sales; ?></td>
                            <td>
                                <a href="<?php echo get_edit_post_link($distributor->ID); ?>" class="button button-small">编辑</a>
                                <a href="<?php echo admin_url('admin.php?page=distributor-team&view=' . $distributor->ID); ?>" 
                                   class="button button-small">查看详情</a>
                            </td>
                        </tr>
                        <?php
                    }
                } else {
                    echo '<tr><td colspan="6">暂无下级经销商</td></tr>';
                }
                ?>
            </tbody>
        </table>
    </div>
    <?php
}

/**
 * 获取团队人数
 */
function fsc_get_team_count($distributor_id) {
    $count = 0;
    
    // 直接下级经销商
    $direct_count = count(get_posts(array(
        'post_type'      => 'distributor',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'meta_query'     => array(
            array(
                'key'   => '_fsc_parent_distributor_id',
                'value' => $distributor_id
            )
        )
    )));
    
    $count += $direct_count;
    
    // 递归获取所有下级经销商
    $children = get_posts(array(
        'post_type'      => 'distributor',
        'posts_per_page' => -1,
        'fields'         => 'ids',
        'meta_query'     => array(
            array(
                'key'   => '_fsc_parent_distributor_id',
                'value' => $distributor_id
            )
        )
    ));
    
    foreach ($children as $child_id) {
        $count += fsc_get_team_count($child_id);
    }
    
    return $count;
}

数据报表与分析功能

/**
 * 经销商数据报表功能
 */
class FSC_Distributor_Reports {
    
    /**
     * 生成销售报表
     */
    public static function generate_sales_report($distributor_id, $start_date, $end_date) {
        global $wpdb;
        
        $report_data = array(
            'total_sales'      => 0,
            'total_commissions' => 0,
            'order_count'      => 0,
            'monthly_breakdown' => array(),
            'top_products'     => array()
        );
        
        // 获取总销售额和佣金
        $sales_data = $wpdb->get_row($wpdb->prepare(
            "SELECT 
                COUNT(DISTINCT order_id) as order_count,
                SUM(order_total) as total_sales,
                SUM(commission_amount) as total_commissions
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} pm1 ON p.ID = pm1.post_id
            INNER JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id
            WHERE p.post_type = 'fsc_commission'
            AND p.post_status = 'publish'
            AND pm1.meta_key = 'distributor_id'
            AND pm1.meta_value = %d
            AND pm2.meta_key = 'created_at'
            AND DATE(pm2.meta_value) BETWEEN %s AND %s",
            $distributor_id,
            $start_date,
            $end_date
        ));
        
        if ($sales_data) {
            $report_data['total_sales'] = floatval($sales_data->total_sales);
            $report_data['total_commissions'] = floatval($sales_data->total_commissions);
            $report_data['order_count'] = intval($sales_data->order_count);
        }
        
        // 获取月度细分数据
        $monthly_data = $wpdb->get_results($wpdb->prepare(
            "SELECT 
                DATE_FORMAT(pm2.meta_value, '%%Y-%%m') as month,
                SUM(pm3.meta_value) as monthly_sales
            FROM {$wpdb->posts} p
            INNER JOIN {$wpdb->postmeta} pm1 ON p.ID = pm1.post_id
            INNER JOIN {$wpdb->postmeta} pm2 ON p.ID = pm2.post_id
            INNER JOIN {$wpdb->postmeta} pm3 ON p.ID = pm3.post_id
            WHERE p.post_type = 'fsc_commission'
            AND p.post_status = 'publish'
本文来自网络投稿,不代表本站点的立场,转载请注明出处:https://www.gongxiangcang.com/6605.html

溯源库®作者

漳州柔性供应链服务有限公司 小批量订单定制化服务商( 投稿邮箱:vip@jiaochengku.com)
上一篇
下一篇

为您推荐

联系我们

联系我们

18559313275

在线咨询: QQ交谈

邮箱: vip@suyuanku.com

工作时间:周一至周五,9:00-17:30,节假日休息
关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部