文章目录[隐藏]
WordPress柔性供应链管理插件完整开发教程
引言:为什么需要柔性供应链管理插件
在当今快速变化的电商环境中,供应链的灵活性已成为企业成功的关键因素。WordPress作为全球最流行的内容管理系统,拥有庞大的电商生态系统,但大多数供应链管理解决方案要么过于复杂,要么缺乏定制性。本教程将指导您开发一个柔性供应链管理插件,帮助企业根据需求动态调整供应链策略。
柔性供应链管理插件的核心价值在于:
- 实时库存监控和预警
- 多供应商动态分配
- 需求预测和智能补货
- 供应链可视化仪表板
开发环境准备
在开始开发之前,请确保您的环境满足以下要求:
<?php
/**
* 环境检查函数
* 确保服务器满足插件运行的最低要求
*/
function check_environment() {
$errors = array();
// 检查PHP版本
if (version_compare(PHP_VERSION, '7.0.0', '<')) {
$errors[] = 'PHP版本需要7.0.0或更高,当前版本:' . PHP_VERSION;
}
// 检查WordPress版本
global $wp_version;
if (version_compare($wp_version, '5.0', '<')) {
$errors[] = 'WordPress需要5.0或更高版本,当前版本:' . $wp_version;
}
// 检查必要扩展
$required_extensions = ['mysqli', 'json', 'curl'];
foreach ($required_extensions as $ext) {
if (!extension_loaded($ext)) {
$errors[] = '缺少必要扩展:' . $ext;
}
}
// 检查WooCommerce是否安装(如果电商功能需要)
if (!class_exists('WooCommerce')) {
$errors[] = '建议安装WooCommerce以获得完整功能';
}
return $errors;
}
// 运行环境检查
$environment_errors = check_environment();
if (!empty($environment_errors)) {
foreach ($environment_errors as $error) {
error_log('柔性供应链插件环境错误:' . $error);
}
}
?>
插件基础结构
首先创建插件的主文件,这是插件的入口点:
<?php
/**
* Plugin Name: 柔性供应链管理系统
* Plugin URI: https://yourwebsite.com/flexible-supply-chain
* Description: 为WordPress网站提供柔性供应链管理功能
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
* Text Domain: flexible-supply-chain
*/
// 防止直接访问
if (!defined('ABSPATH')) {
exit;
}
// 定义插件常量
define('FSC_VERSION', '1.0.0');
define('FSC_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('FSC_PLUGIN_URL', plugin_dir_url(__FILE__));
define('FSC_PLUGIN_FILE', __FILE__);
/**
* 插件主类
*/
class FlexibleSupplyChain {
private static $instance = null;
/**
* 获取单例实例
*/
public static function get_instance() {
if (null === self::$instance) {
self::$instance = new self();
}
return self::$instance;
}
/**
* 构造函数
*/
private function __construct() {
$this->init_hooks();
$this->includes();
}
/**
* 初始化钩子
*/
private function init_hooks() {
// 激活/停用钩子
register_activation_hook(__FILE__, array($this, 'activate'));
register_deactivation_hook(__FILE__, array($this, 'deactivate'));
// 初始化钩子
add_action('init', array($this, 'init'));
// 管理界面钩子
add_action('admin_menu', array($this, 'add_admin_menu'));
// 前端资源
add_action('wp_enqueue_scripts', array($this, 'enqueue_frontend_assets'));
// 管理端资源
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_assets'));
}
/**
* 包含必要文件
*/
private function includes() {
// 核心功能文件
require_once FSC_PLUGIN_DIR . 'includes/class-supplier-manager.php';
require_once FSC_PLUGIN_DIR . 'includes/class-inventory-manager.php';
require_once FSC_PLUGIN_DIR . 'includes/class-order-distributor.php';
require_once FSC_PLUGIN_DIR . 'includes/class-analytics.php';
// 工具函数
require_once FSC_PLUGIN_DIR . 'includes/functions.php';
// 数据库操作
require_once FSC_PLUGIN_DIR . 'includes/class-database.php';
}
/**
* 插件激活时执行
*/
public function activate() {
// 创建数据库表
FSC_Database::create_tables();
// 设置默认选项
$default_options = array(
'low_stock_threshold' => 10,
'auto_reorder' => true,
'supplier_priority' => 'cost',
'notification_email' => get_option('admin_email'),
);
add_option('fsc_settings', $default_options);
// 记录激活时间
add_option('fsc_install_date', current_time('timestamp'));
}
/**
* 插件停用时执行
*/
public function deactivate() {
// 清理定时任务
wp_clear_scheduled_hook('fsc_daily_inventory_check');
}
/**
* 初始化
*/
public function init() {
// 加载文本域
load_plugin_textdomain('flexible-supply-chain', false, dirname(plugin_basename(__FILE__)) . '/languages');
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
__('供应链管理', 'flexible-supply-chain'),
__('供应链', 'flexible-supply-chain'),
'manage_options',
'fsc-dashboard',
array($this, 'render_dashboard'),
'dashicons-networking',
30
);
// 子菜单
add_submenu_page(
'fsc-dashboard',
__('供应商管理', 'flexible-supply-chain'),
__('供应商', 'flexible-supply-chain'),
'manage_options',
'fsc-suppliers',
array($this, 'render_suppliers_page')
);
add_submenu_page(
'fsc-dashboard',
__('库存管理', 'flexible-supply-chain'),
__('库存', 'flexible-supply-chain'),
'manage_options',
'fsc-inventory',
array($this, 'render_inventory_page')
);
add_submenu_page(
'fsc-dashboard',
__('设置', 'flexible-supply-chain'),
__('设置', 'flexible-supply-chain'),
'manage_options',
'fsc-settings',
array($this, 'render_settings_page')
);
}
/**
* 渲染仪表板
*/
public function render_dashboard() {
include FSC_PLUGIN_DIR . 'templates/admin/dashboard.php';
}
/**
* 加载前端资源
*/
public function enqueue_frontend_assets() {
// 前端样式
wp_enqueue_style(
'fsc-frontend',
FSC_PLUGIN_URL . 'assets/css/frontend.css',
array(),
FSC_VERSION
);
// 前端脚本
wp_enqueue_script(
'fsc-frontend',
FSC_PLUGIN_URL . 'assets/js/frontend.js',
array('jquery'),
FSC_VERSION,
true
);
// 本地化脚本
wp_localize_script('fsc-frontend', 'fsc_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('fsc_nonce')
));
}
/**
* 加载管理端资源
*/
public function enqueue_admin_assets($hook) {
// 仅在我们的插件页面加载
if (strpos($hook, 'fsc-') === false) {
return;
}
// 管理端样式
wp_enqueue_style(
'fsc-admin',
FSC_PLUGIN_URL . 'assets/css/admin.css',
array(),
FSC_VERSION
);
// Chart.js 用于数据可视化
wp_enqueue_script(
'chart-js',
'https://cdn.jsdelivr.net/npm/chart.js@3.7.0/dist/chart.min.js',
array(),
'3.7.0',
true
);
// 管理端脚本
wp_enqueue_script(
'fsc-admin',
FSC_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'chart-js'),
FSC_VERSION,
true
);
}
}
// 初始化插件
FlexibleSupplyChain::get_instance();
?>
数据库设计与实现
供应链管理需要存储供应商、库存、订单分配等数据。以下是数据库表的创建代码:
<?php
/**
* 数据库管理类
* 处理所有数据库相关操作
*/
class FSC_Database {
/**
* 创建插件所需的数据库表
*/
public static function create_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
// 供应商表
$suppliers_table = $wpdb->prefix . 'fsc_suppliers';
$suppliers_sql = "CREATE TABLE IF NOT EXISTS $suppliers_table (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(255) NOT NULL,
contact_person VARCHAR(255),
email VARCHAR(255),
phone VARCHAR(50),
address TEXT,
lead_time INT(11) DEFAULT 7 COMMENT '交货时间(天)',
reliability_score DECIMAL(3,2) DEFAULT 1.0 COMMENT '可靠性评分',
cost_factor DECIMAL(3,2) DEFAULT 1.0 COMMENT '成本系数',
min_order_quantity INT(11) DEFAULT 1,
max_order_quantity INT(11) DEFAULT 1000,
is_active TINYINT(1) DEFAULT 1,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX idx_reliability (reliability_score),
INDEX idx_cost (cost_factor)
) $charset_collate;";
// 库存表
$inventory_table = $wpdb->prefix . 'fsc_inventory';
$inventory_sql = "CREATE TABLE IF NOT EXISTS $inventory_table (
id INT(11) NOT NULL AUTO_INCREMENT,
product_id INT(11) NOT NULL COMMENT '关联产品ID',
sku VARCHAR(100),
current_stock INT(11) DEFAULT 0,
safety_stock INT(11) DEFAULT 10 COMMENT '安全库存',
reorder_point INT(11) DEFAULT 20 COMMENT '补货点',
reorder_quantity INT(11) DEFAULT 50 COMMENT '补货数量',
supplier_id INT(11) COMMENT '主要供应商',
backup_supplier_id INT(11) COMMENT '备用供应商',
last_restock_date DATE,
next_restock_date DATE,
demand_forecast INT(11) DEFAULT 0 COMMENT '需求预测',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX idx_product (product_id),
INDEX idx_supplier (supplier_id),
INDEX idx_stock (current_stock),
FOREIGN KEY (supplier_id) REFERENCES $suppliers_table(id) ON DELETE SET NULL
) $charset_collate;";
// 订单分配表
$allocations_table = $wpdb->prefix . 'fsc_allocations';
$allocations_sql = "CREATE TABLE IF NOT EXISTS $allocations_table (
id INT(11) NOT NULL AUTO_INCREMENT,
order_id INT(11) NOT NULL COMMENT 'WooCommerce订单ID',
product_id INT(11) NOT NULL,
supplier_id INT(11) NOT NULL,
quantity INT(11) NOT NULL,
allocation_date DATE NOT NULL,
estimated_delivery DATE,
actual_delivery DATE,
status ENUM('pending', 'confirmed', 'shipped', 'delivered', 'cancelled') DEFAULT 'pending',
notes TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX idx_order (order_id),
INDEX idx_supplier (supplier_id),
INDEX idx_status (status),
FOREIGN KEY (supplier_id) REFERENCES $suppliers_table(id) ON DELETE CASCADE
) $charset_collate;";
// 需求历史表
$demand_history_table = $wpdb->prefix . 'fsc_demand_history';
$demand_history_sql = "CREATE TABLE IF NOT EXISTS $demand_history_table (
id INT(11) NOT NULL AUTO_INCREMENT,
product_id INT(11) NOT NULL,
date DATE NOT NULL,
demand INT(11) NOT NULL COMMENT '当日需求',
seasonality_factor DECIMAL(4,3) DEFAULT 1.0 COMMENT '季节性因子',
promotion_flag TINYINT(1) DEFAULT 0 COMMENT '是否促销期',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
INDEX idx_product_date (product_id, date),
INDEX idx_date (date)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
// 执行SQL
dbDelta($suppliers_sql);
dbDelta($inventory_sql);
dbDelta($allocations_sql);
dbDelta($demand_history_sql);
// 记录数据库版本
add_option('fsc_db_version', '1.0.0');
}
/**
* 获取库存水平
*/
public static function get_inventory_levels($threshold = null) {
global $wpdb;
$table = $wpdb->prefix . 'fsc_inventory';
$products_table = $wpdb->prefix . 'posts';
$sql = "SELECT
i.*,
p.post_title as product_name,
(i.current_stock - i.safety_stock) as stock_buffer,
CASE
WHEN i.current_stock <= i.safety_stock THEN 'critical'
WHEN i.current_stock <= i.reorder_point THEN 'low'
ELSE 'normal'
END as stock_status
FROM $table i
LEFT JOIN $products_table p ON i.product_id = p.ID
WHERE p.post_type = 'product'";
if ($threshold !== null) {
$sql .= $wpdb->prepare(" AND i.current_stock <= %d", $threshold);
}
$sql .= " ORDER BY stock_buffer ASC";
return $wpdb->get_results($sql);
}
/**
* 获取供应商绩效数据
*/
public static function get_supplier_performance($days = 30) {
global $wpdb;
$suppliers_table = $wpdb->prefix . 'fsc_suppliers';
$allocations_table = $wpdb->prefix . 'fsc_allocations';
$sql = $wpdb->prepare(
"SELECT
s.id,
s.name,
COUNT(a.id) as total_orders,
SUM(CASE WHEN a.status = 'delivered' THEN 1 ELSE 0 END) as delivered_orders,
AVG(DATEDIFF(a.actual_delivery, a.allocation_date)) as avg_delivery_time,
SUM(CASE WHEN DATEDIFF(a.actual_delivery, a.estimated_delivery) > 0 THEN 1 ELSE 0 END) as late_deliveries
FROM $suppliers_table s
LEFT JOIN $allocations_table a ON s.id = a.supplier_id
WHERE a.allocation_date >= DATE_SUB(CURDATE(), INTERVAL %d DAY)
GROUP BY s.id
ORDER BY s.reliability_score DESC",
$days
);
return $wpdb->get_results($sql);
}
}
?>
智能订单分配算法
柔性供应链的核心是智能订单分配系统,以下是一个基于多因素决策的分配算法:
<?php
/**
* 订单分配器类
* 实现智能订单分配算法
*/
class OrderDistributor {
/**
* 分配订单给供应商
*
* @param int $product_id 产品ID
* @param int $quantity 需求数量
* @param array $constraints 约束条件
* @return array 分配结果
*/
public function allocate_order($product_id, $quantity, $constraints = array()) {
global $wpdb;
// 获取可用供应商
$suppliers = $this->get_available_suppliers($product_id, $quantity);
if (empty($suppliers)) {
return array(
'success' => false,
'message' => '没有可用的供应商满足需求'
);
}
// 计算每个供应商的得分
$scored_suppliers = array();
foreach ($suppliers as $supplier) {
$score = $this->calculate_supplier_score($supplier, $quantity, $constraints);
$scored_suppliers[] = array(
'supplier' => $supplier,
'score' => $score,
'allocation' => $this->calculate_allocation($supplier, $quantity)
);
}
// 按得分排序
usort($scored_suppliers, function($a, $b) {
return $b['score'] <=> $a['score'];
});
// 选择最佳供应商
$best_supplier = $scored_suppliers[0];
// 检查是否需要拆分订单
$allocations = $this->split_order_if_needed($scored_suppliers, $quantity);
return array(
'success' => true,
'allocations' => $allocations,
'total_cost' => $this->calculate_total_cost($allocations),
'estimated_delivery' => $this->calculate_estimated_delivery($allocations)
);
}
/**
* 获取可用供应商
*/
private function get_available_suppliers($product_id, $quantity) {
global $wpdb;
$suppliers_table = $wpdb->prefix . 'fsc_suppliers';
$inventory_table = $wpdb->prefix . 'fsc_inventory';
$sql = $wpdb->prepare(
"SELECT
s.*,
i.current_stock as supplier_stock,
i.lead_time,
i.cost_per_unit,
i.max_order_quantity
FROM $suppliers_table s
INNER JOIN $inventory_table i ON s.id = i.supplier_id
WHERE i.product_id = %d
AND s.is_active = 1
AND i.current_stock >= %d
AND i.max_order_quantity >= %d
ORDER BY s.reliability_score DESC, i.cost_per_unit ASC",
$product_id,
$quantity,
$quantity
);
return $wpdb->get_results($sql, ARRAY_A);
}
/**
* 计算供应商得分
* 基于成本、可靠性、交货时间等多因素
*/
private function calculate_supplier_score($supplier, $quantity, $constraints) {
$weights = array(
'cost' => 0.35, // 成本权重
'reliability' => 0.30, // 可靠性权重
'delivery' => 0.25, // 交货时间权重
'relationship' => 0.10 // 合作关系权重
);
// 成本得分(成本越低得分越高)
$cost_score = $this->calculate_cost_score($supplier, $quantity);
// 可靠性得分
$reliability_score = $this->calculate_reliability_score($supplier);
// 交货时间得分
$delivery_score = $this->calculate_delivery_score($supplier);
// 合作关系得分
$relationship_score = $this->calculate_relationship_score($supplier);
// 加权总分
$total_score =
($cost_score * $weights['cost']) +
($reliability_score * $weights['reliability']) +
($delivery_score * $weights['delivery']) +
($relationship_score * $weights['relationship']);
// 应用约束条件调整
if (!empty($constraints)) {
$total_score = $this->apply_constraints($total_score, $supplier, $constraints);
}
return round($total_score, 2);
}
/**
* 计算成本得分
*/
private function calculate_cost_score($supplier, $quantity) {
$base_cost = $supplier['cost_per_unit'] * $quantity;
// 考虑批量折扣
$discount = $this->calculate_volume_discount($supplier, $quantity);
$final_cost = $base_cost * (1 - $discount);
// 标准化得分(0-100)
$max_cost = $base_cost * 1.5; // 假设最高成本为基础成本的1.5倍
$cost_score = 100 * (1 - ($final_cost / $max_cost));
return max(0, min(100, $cost_score));
}
/**
* 计算批量折扣
*/
private function calculate_volume_discount($supplier, $quantity) {
$discount_tiers = array(
100 => 0.02, // 100件以上2%折扣
500 => 0.05, // 500件以上5%折扣
1000 => 0.08, // 1000件以上8%折扣
5000 => 0.12 // 5000件以上12%折扣
);
$discount = 0;
foreach ($discount_tiers as $threshold => $rate) {
if ($quantity >= $threshold && $rate > $discount) {
$discount = $rate;
}
}
return $discount;
}
/**
* 计算可靠性得分
*/
private function calculate_reliability_score($supplier) {
global $wpdb;
$allocations_table = $wpdb->prefix . 'fsc_allocations';
// 获取历史交付数据
$sql = $wpdb->prepare(
"SELECT
COUNT(*) as total_orders,
SUM(CASE WHEN status = 'delivered' AND
DATEDIFF(actual_delivery, estimated_delivery) <= 2 THEN 1 ELSE 0 END) as on_time_orders
FROM $allocations_table
WHERE supplier_id = %d
AND allocation_date >= DATE_SUB(CURDATE(), INTERVAL 90 DAY)",
$supplier['id']
);
$result = $wpdb->get_row($sql);
if ($result->total_orders > 0) {
$on_time_rate = $result->on_time_orders / $result->total_orders;
return round($on_time_rate * 100, 2);
}
// 如果没有历史数据,使用默认可靠性评分
return $supplier['reliability_score'] * 100;
}
/**
* 拆分订单(如果需要)
*/
private function split_order_if_needed($scored_suppliers, $total_quantity) {
$allocations = array();
$remaining_quantity = $total_quantity;
foreach ($scored_suppliers as $scored) {
if ($remaining_quantity <= 0) break;
$supplier = $scored['supplier'];
$max_capacity = min(
$supplier['supplier_stock'],
$supplier['max_order_quantity']
);
$allocated_quantity = min($remaining_quantity, $max_capacity);
if ($allocated_quantity > 0) {
$allocations[] = array(
'supplier_id' => $supplier['id'],
'supplier_name' => $supplier['name'],
'quantity' => $allocated_quantity,
'unit_cost' => $supplier['cost_per_unit'],
'lead_time' => $supplier['lead_time'],
'total_cost' => $allocated_quantity * $supplier['cost_per_unit']
);
$remaining_quantity -= $allocated_quantity;
}
}
// 如果仍有剩余数量,尝试调整分配
if ($remaining_quantity > 0) {
$allocations = $this->redistribute_order($allocations, $scored_suppliers, $total_quantity);
}
return $allocations;
}
/**
* 重新分配订单
*/
private function redistribute_order($current_allocations, $scored_suppliers, $total_quantity) {
// 按供应商能力重新分配
$total_capacity = 0;
foreach ($scored_suppliers as $scored) {
$supplier = $scored['supplier'];
$total_capacity += min(
$supplier['supplier_stock'],
$supplier['max_order_quantity']
);
}
// 如果总容量不足,返回当前分配
if ($total_capacity < $total_quantity) {
return $current_allocations;
}
// 按供应商得分比例重新分配
$allocations = array();
$total_score = array_sum(array_column($scored_suppliers, 'score'));
foreach ($scored_suppliers as $scored) {
$supplier = $scored['supplier'];
$score_ratio = $scored['score'] / $total_score;
$allocated_quantity = floor($total_quantity * $score_ratio);
$max_capacity = min(
$supplier['supplier_stock'],
$supplier['max_order_quantity']
);
$allocated_quantity = min($allocated_quantity, $max_capacity);
if ($allocated_quantity > 0) {
$allocations[] = array(
'supplier_id' => $supplier['id'],
'supplier_name' => $supplier['name'],
'quantity' => $allocated_quantity,
'unit_cost' => $supplier['cost_per_unit'],
'lead_time' => $supplier['lead_time'],
'total_cost' => $allocated_quantity * $supplier['cost_per_unit']
);
}
}
return $allocations;
}
}
?>
库存预测与补货系统
<?php
/**
* 库存预测与智能补货系统
*/
class InventoryForecaster {
/**
* 预测未来需求
*/
public function forecast_demand($product_id, $period_days = 30) {
global $wpdb;
$history_table = $wpdb->prefix . 'fsc_demand_history';
// 获取历史数据
$sql = $wpdb->prepare(
"SELECT date, demand, seasonality_factor
FROM $history_table
WHERE product_id = %d
AND date >= DATE_SUB(CURDATE(), INTERVAL 180 DAY)
ORDER BY date DESC",
$product_id
);
$historical_data = $wpdb->get_results($sql, ARRAY_A);
if (empty($historical_data)) {
return $this->calculate_basic_forecast($product_id);
}
// 使用移动平均法预测
$forecast = $this->calculate_moving_average($historical_data, $period_days);
// 应用季节性调整
$forecast = $this->apply_seasonality($forecast, $product_id);
// 考虑趋势因素
$forecast = $this->apply_trend($historical_data, $forecast);
return $forecast;
}
/**
* 计算移动平均预测
*/
private function calculate_moving_average($data, $period) {
$total_demand = 0;
$count = 0;
// 计算最近period天的平均需求
$recent_data = array_slice($data, 0, $period);
foreach ($recent_data as $day) {
$total_demand += $day['demand'];
$count++;
}
if ($count == 0) return 0;
$average_daily = $total_demand / $count;
return array(
'daily_average' => round($average_daily, 2),
'weekly_forecast' => round($average_daily * 7, 2),
'monthly_forecast' => round($average_daily * 30, 2),
'confidence_level' => $this->calculate_confidence($data, $average_daily)
);
}
/**
* 智能补货建议
*/
public function get_replenishment_suggestions() {
global $wpdb;
$inventory_table = $wpdb->prefix . 'fsc_inventory';
$products_table = $wpdb->prefix . 'posts';
$sql = "SELECT
i.*,
p.post_title as product_name,
i.current_stock,
i.safety_stock,
i.reorder_point,
(i.current_stock - i.safety_stock) as buffer_stock,
DATEDIFF(i.next_restock_date, CURDATE()) as days_to_restock
FROM $inventory_table i
LEFT JOIN $products_table p ON i.product_id = p.ID
WHERE p.post_type = 'product'
AND i.current_stock <= i.reorder_point
ORDER BY buffer_stock ASC";
$low_stock_items = $wpdb->get_results($sql);
$suggestions = array();
foreach ($low_stock_items as $item) {
$forecast = $this->forecast_demand($item->product_id);
$suggestion = $this->calculate_reorder_quantity($item, $forecast);
$suggestions[] = array(
'product_id' => $item->product_id,
'product_name' => $item->product_name,
'current_stock' => $item->current_stock,
'safety_stock' => $item->safety_stock,
'reorder_point' => $item->reorder_point,
'suggested_quantity' => $suggestion['quantity'],
'urgency_level' => $suggestion['urgency'],
'estimated_runout_days' => $this->calculate_runout_days($item, $forecast)
);
}
return $suggestions;
}
/**
* 计算补货数量
*/
private function calculate_reorder_quantity($item, $forecast) {
// 计算需求覆盖天数
$lead_time_demand = $forecast['daily_average'] * $item->lead_time;
// 计算安全库存
$safety_stock = $this->calculate_safety_stock($forecast, $item->lead_time);
// 计算经济订单量(EOQ)
$eoq = $this->calculate_eoq($item, $forecast);
// 确定最终补货量
$required_quantity = max(
$lead_time_demand + $safety_stock - $item->current_stock,
$item->reorder_quantity,
$eoq
);
// 确定紧急程度
$urgency = $this->determine_urgency($item, $forecast);
return array(
'quantity' => ceil($required_quantity),
'urgency' => $urgency
);
}
/**
* 计算经济订单量(EOQ)
*/
private function calculate_eoq($item, $forecast) {
// EOQ公式:√[(2 × D × S) / H]
// D: 年需求量
// S: 每次订货成本
// H: 单位持有成本
$annual_demand = $forecast['daily_average'] * 365;
$order_cost = 50; // 假设每次订货成本50元
$holding_cost_per_unit = $item->cost_per_unit * 0.2; // 假设持有成本为商品价值的20%
if ($holding_cost_per_unit <= 0) {
return $item->reorder_quantity;
}
$eoq = sqrt((2 * $annual_demand * $order_cost) / $holding_cost_per_unit);
return round($eoq);
}
}
?>
管理界面实现
<?php
/**
* 管理界面模板 - 仪表板
*/
// templates/admin/dashboard.php
?>
<div class="wrap fsc-dashboard">
<h1><?php _e('柔性供应链仪表板', 'flexible-supply-chain'); ?></h1>
<div class="fsc-stats-container">
<div class="fsc-stat-card">
<h3><?php _e('库存状态', 'flexible-supply-chain'); ?></h3>
<div class="stat-number"><?php echo $inventory_stats['total_items']; ?></div>
<div class="stat-detail">
<span class="status-normal">正常: <?php echo $inventory_stats['normal']; ?></span>
<span class="status-low">偏低: <?php echo $inventory_stats['low']; ?></span>
<span class="status-critical">紧急: <?php echo $inventory_stats['critical']; ?></span>
</div>
</div>
<div class="fsc-stat-card">
<h3><?php _e('供应商绩效', 'flexible-supply-chain'); ?></h3>
<div class="stat-number"><?php echo $supplier_stats['avg_score']; ?>%</div>
<div class="stat-detail">
活跃供应商: <?php echo $supplier_stats['active_count']; ?>
</div>
</div>
<div class="fsc-stat-card">
<h3><?php _e('订单分配', 'flexible-supply-chain'); ?></h3>
<div class="stat-number"><?php echo $order_stats['today_orders']; ?></div>
<div class="stat-detail">
今日完成: <?php echo $order_stats['completed_today']; ?>
</div>
</div>
</div>
<div class="fsc-charts-container">
<div class="fsc-chart-card">
<h3><?php _e('库存趋势', 'flexible-supply-chain'); ?></h3>
<canvas id="inventoryTrendChart" width="400" height="200"></canvas>
</div>
<div class="fsc-chart-card">
<h3><?php _e('供应商分布', 'flexible-supply-chain'); ?></h3>
<canvas id="supplierDistributionChart" width="400" height="200"></canvas>
</div>
</div>
<div class="fsc-alerts-container">
<h3><?php _e('待处理事项', 'flexible-supply-chain'); ?></h3>
<?php if (!empty($alerts)): ?>
<ul class="fsc-alerts-list">
<?php foreach ($alerts as $alert): ?>
<li class="alert-<?php echo $alert['level']; ?>">
<span class="alert-icon">⚠️</span>
<span class="alert-message"><?php echo $alert['message']; ?></span>
<span class="alert-time"><?php echo $alert['time']; ?></span>
</li>
<?php endforeach; ?>
</ul>
<?php else: ?>
