文章目录[隐藏]
WordPress柔性供应链中的数字孪生应用开发入门教程
引言:当WordPress遇见数字孪生
在当今快速变化的商业环境中,柔性供应链已成为企业保持竞争力的关键。而数字孪生技术——通过创建物理实体的虚拟副本来实现实时监控、分析和优化——正在彻底改变供应链管理方式。本教程将指导您如何在WordPress平台中开发一个基础的供应链数字孪生应用,即使您是初学者也能跟随学习。
环境准备与基础配置
WordPress环境搭建
首先,确保您有一个运行中的WordPress网站。如果您是本地开发,可以使用XAMPP、MAMP或Local by Flywheel等工具快速搭建环境。对于生产环境,建议选择支持PHP 7.4+和MySQL 5.7+的主机服务。
必要插件安装
为了开发数字孪生应用,我们需要几个关键插件:
- Advanced Custom Fields (ACF) - 用于创建自定义数据字段
- Custom Post Type UI - 创建自定义内容类型
- WP REST API - 确保WordPress REST API功能完整
创建供应链数据模型
定义自定义内容类型
我们将创建三个核心内容类型:供应商、产品和库存节点。在主题的functions.php文件中添加以下代码:
/**
* 注册供应链相关自定义内容类型
*/
function register_supply_chain_post_types() {
// 注册供应商内容类型
$supplier_labels = array(
'name' => '供应商',
'singular_name' => '供应商',
'add_new' => '添加新供应商',
'add_new_item' => '添加新供应商',
'edit_item' => '编辑供应商',
'new_item' => '新供应商',
'view_item' => '查看供应商',
'search_items' => '搜索供应商',
'not_found' => '未找到供应商',
'not_found_in_trash' => '回收站中无供应商'
);
$supplier_args = array(
'labels' => $supplier_labels,
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-building',
'supports' => array('title', 'editor', 'thumbnail'),
'show_in_rest' => true, // 启用REST API支持
'rest_base' => 'suppliers'
);
register_post_type('supplier', $supplier_args);
// 注册产品内容类型
$product_labels = array(
'name' => '供应链产品',
'singular_name' => '产品',
'add_new' => '添加新产品',
'add_new_item' => '添加新产品',
'edit_item' => '编辑产品',
'new_item' => '新产品',
'view_item' => '查看产品',
'search_items' => '搜索产品',
'not_found' => '未找到产品',
'not_fash_found_in_trash' => '回收站中无产品'
);
$product_args = array(
'labels' => $product_labels,
'public' => true,
'has_archive' => true,
'menu_icon' => 'dashicons-products',
'supports' => array('title', 'editor', 'thumbnail'),
'show_in_rest' => true,
'rest_base' => 'supply-products'
);
register_post_type('supply_product', $product_args);
}
add_action('init', 'register_supply_chain_post_types');
使用ACF创建自定义字段
通过ACF插件为供应商和产品添加元数据字段。以下是关键字段示例:
- 供应商字段:地理位置、产能评级、响应时间
- 产品字段:SKU、当前库存、最小库存阈值、供应商关联
- 库存节点字段:位置坐标、容量、当前库存水平
构建数字孪生数据层
实时数据集成
数字孪生的核心是实时数据。我们将创建一个数据收集类,模拟从各种源获取数据:
/**
* 供应链数据收集器类
* 模拟从传感器、ERP系统等获取实时数据
*/
class SupplyChainDataCollector {
private $data_sources;
public function __construct() {
$this->data_sources = array(
'inventory_sensors' => 'https://api.example.com/inventory-sensors',
'shipping_trackers' => 'https://api.example.com/shipping-data',
'supplier_feeds' => 'https://api.example.com/supplier-updates'
);
}
/**
* 获取库存水平数据
* @param int $product_id 产品ID
* @return array 库存数据
*/
public function get_inventory_level($product_id) {
// 模拟从传感器获取数据
// 实际应用中,这里会调用API或读取数据库
$mock_data = array(
'product_id' => $product_id,
'current_stock' => rand(50, 200), // 模拟随机库存
'timestamp' => current_time('mysql'),
'location' => 'Warehouse-A',
'status' => $this->get_stock_status($product_id)
);
// 实际API调用示例(注释状态)
/*
$response = wp_remote_get($this->data_sources['inventory_sensors'] . '?product=' . $product_id);
if (!is_wp_error($response)) {
$data = json_decode(wp_remote_retrieve_body($response), true);
return $data;
}
*/
return $mock_data;
}
/**
* 根据库存水平确定状态
* @param int $product_id 产品ID
* @return string 库存状态
*/
private function get_stock_status($product_id) {
// 获取产品的最小库存阈值
$min_threshold = get_field('min_inventory_threshold', $product_id);
$current_stock = get_field('current_inventory', $product_id);
if ($current_stock <= $min_threshold * 0.2) {
return 'critical';
} elseif ($current_stock <= $min_threshold) {
return 'low';
} else {
return 'normal';
}
}
/**
* 获取供应链整体健康度
* @return array 健康度指标
*/
public function get_supply_chain_health() {
$indicators = array(
'on_time_delivery' => rand(85, 99), // 准时交付率
'inventory_turnover' => rand(4, 12), // 库存周转率
'supplier_reliability' => rand(75, 98), // 供应商可靠性
'order_accuracy' => rand(95, 100) // 订单准确率
);
// 计算整体健康分数
$total_score = array_sum($indicators) / count($indicators);
$indicators['overall_score'] = round($total_score, 2);
return $indicators;
}
}
可视化界面开发
创建数字孪生仪表板
使用WordPress短代码功能创建一个可视化仪表板:
/**
* 数字孪生仪表板短代码
* 用法:[digital_twin_dashboard]
*/
function digital_twin_dashboard_shortcode($atts) {
// 提取短代码属性
$atts = shortcode_atts(array(
'width' => '100%',
'height' => '600px'
), $atts);
// 初始化数据收集器
$data_collector = new SupplyChainDataCollector();
// 获取供应链健康数据
$health_data = $data_collector->get_supply_chain_health();
// 构建仪表板HTML
$output = '<div class="digital-twin-dashboard" style="width: ' . esc_attr($atts['width']) . '; height: ' . esc_attr($atts['height']) . ';">';
$output .= '<div class="dashboard-header">';
$output .= '<h2>供应链数字孪生仪表板</h2>';
$output .= '<div class="health-score">整体健康度: <span class="score">' . $health_data['overall_score'] . '</span>/100</div>';
$output .= '</div>';
$output .= '<div class="dashboard-grid">';
// 健康指标卡片
$output .= '<div class="dashboard-card health-metrics">';
$output .= '<h3>关键绩效指标</h3>';
$output .= '<div class="metrics-grid">';
foreach ($health_data as $metric => $value) {
if ($metric !== 'overall_score') {
$output .= '<div class="metric-item">';
$output .= '<div class="metric-label">' . $this->get_metric_label($metric) . '</div>';
$output .= '<div class="metric-value">' . $value . '%</div>';
$output .= '</div>';
}
}
$output .= '</div></div>';
// 库存状态卡片
$output .= '<div class="dashboard-card inventory-status">';
$output .= '<h3>实时库存状态</h3>';
// 获取产品列表
$products = get_posts(array(
'post_type' => 'supply_product',
'posts_per_page' => 5
));
if ($products) {
$output .= '<table class="inventory-table">';
$output .= '<thead><tr><th>产品</th><th>当前库存</th><th>状态</th><th>更新时间</th></tr></thead>';
$output .= '<tbody>';
foreach ($products as $product) {
$inventory_data = $data_collector->get_inventory_level($product->ID);
$status_class = 'status-' . $inventory_data['status'];
$output .= '<tr>';
$output .= '<td>' . esc_html($product->post_title) . '</td>';
$output .= '<td>' . $inventory_data['current_stock'] . '</td>';
$output .= '<td><span class="status-indicator ' . $status_class . '">' . $this->get_status_text($inventory_data['status']) . '</span></td>';
$output .= '<td>' . $inventory_data['timestamp'] . '</td>';
$output .= '</tr>';
}
$output .= '</tbody></table>';
}
$output .= '</div></div></div>';
// 添加CSS样式
$output .= '<style>
.digital-twin-dashboard {
font-family: Arial, sans-serif;
background: #f5f7fa;
border-radius: 10px;
padding: 20px;
box-shadow: 0 4px 6px rgba(0,0,0,0.1);
}
.dashboard-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 30px;
}
.health-score .score {
font-size: 24px;
font-weight: bold;
color: #4CAF50;
}
.dashboard-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.dashboard-card {
background: white;
border-radius: 8px;
padding: 20px;
box-shadow: 0 2px 4px rgba(0,0,0,0.05);
}
.metrics-grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 15px;
margin-top: 15px;
}
.metric-item {
text-align: center;
padding: 10px;
background: #f8f9fa;
border-radius: 5px;
}
.status-indicator {
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
font-weight: bold;
}
.status-critical { background: #ffebee; color: #c62828; }
.status-low { background: #fff3e0; color: #ef6c00; }
.status-normal { background: #e8f5e9; color: #2e7d32; }
.inventory-table {
width: 100%;
border-collapse: collapse;
margin-top: 15px;
}
.inventory-table th, .inventory-table td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #eee;
}
</style>';
return $output;
}
/**
* 辅助函数:获取指标标签
*/
private function get_metric_label($metric_key) {
$labels = array(
'on_time_delivery' => '准时交付率',
'inventory_turnover' => '库存周转率',
'supplier_reliability' => '供应商可靠性',
'order_accuracy' => '订单准确率'
);
return isset($labels[$metric_key]) ? $labels[$metric_key] : $metric_key;
}
/**
* 辅助函数:获取状态文本
*/
private function get_status_text($status_key) {
$statuses = array(
'critical' => '严重不足',
'low' => '库存偏低',
'normal' => '正常'
);
return isset($statuses[$status_key]) ? $statuses[$status_key] : $status_key;
}
// 注册短代码
add_shortcode('digital_twin_dashboard', 'digital_twin_dashboard_shortcode');
实现实时数据更新
使用AJAX保持数据同步
为了使数字孪生仪表板能够实时更新,我们需要添加AJAX功能:
/**
* 处理AJAX请求,获取实时库存数据
*/
function get_realtime_inventory_data() {
// 安全检查
if (!check_ajax_referer('digital_twin_nonce', 'security', false)) {
wp_die('权限验证失败');
}
$product_id = isset($_POST['product_id']) ? intval($_POST['product_id']) : 0;
if ($product_id <= 0) {
wp_send_json_error('无效的产品ID');
}
$data_collector = new SupplyChainDataCollector();
$inventory_data = $data_collector->get_inventory_level($product_id);
wp_send_json_success($inventory_data);
}
// 为登录用户和非登录用户分别注册AJAX处理函数
add_action('wp_ajax_get_inventory_data', 'get_realtime_inventory_data');
add_action('wp_ajax_nopriv_get_inventory_data', 'get_realtime_inventory_data');
/**
* 在前端添加AJAX脚本
*/
function enqueue_digital_twin_scripts() {
wp_enqueue_script(
'digital-twin-ajax',
get_template_directory_uri() . '/js/digital-twin.js',
array('jquery'),
'1.0.0',
true
);
// 传递AJAX URL和非ce到前端
wp_localize_script('digital-twin-ajax', 'digitalTwinAjax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('digital_twin_nonce')
));
}
add_action('wp_enqueue_scripts', 'enqueue_digital_twin_scripts');
创建对应的JavaScript文件 (/js/digital-twin.js):
/**
* 数字孪生实时数据更新
*/
jQuery(document).ready(function($) {
// 如果页面上有数字孪生仪表板
if ($('.digital-twin-dashboard').length > 0) {
// 实时更新库存数据(每30秒)
function updateInventoryData() {
$('.inventory-table tbody tr').each(function() {
var productId = $(this).data('product-id');
if (productId) {
$.ajax({
url: digitalTwinAjax.ajax_url,
type: 'POST',
data: {
action: 'get_inventory_data',
product_id: productId,
security: digitalTwinAjax.nonce
},
success: function(response) {
if (response.success) {
var data = response.data;
var row = $('tr[data-product-id="' + productId + '"]');
// 更新库存数量
row.find('.inventory-count').text(data.current_stock);
// 更新状态
var statusText = getStatusText(data.status);
var statusClass = 'status-' + data.status;
row.find('.status-indicator')
.text(statusText)
.removeClass()
.addClass('status-indicator ' + statusClass);
// 更新时间戳
row.find('.update-time').text(data.timestamp);
}
},
error: function() {
console.log('获取库存数据失败');
}
});
}
});
}
// 辅助函数:获取状态文本
function getStatusText(statusKey) {
var statusMap = {
'critical': '严重不足',
'low': '库存偏低',
'normal': '正常'
};
return statusMap[statusKey] || statusKey;
}
// 初始加载后立即更新一次
setTimeout(updateInventoryData, 1000);
// 设置定期更新
setInterval(updateInventoryData, 30000); // 每30秒更新一次
// 添加手动刷新按钮功能
$('.refresh-inventory').on('click', function(e) {
e.preventDefault();
updateInventoryData();
$(this).text('刷新中...').prop('disabled', true);
setTimeout(function() {
$('.refresh-inventory').text('手动刷新').prop('disabled', false);
}, 2000);
});
}
});
部署与优化建议
性能优化策略
- 数据缓存:对不常变化的数据实施缓存策略
部署与优化建议(续)
性能优化策略
- 数据缓存:对不常变化的数据实施缓存策略
- 异步处理:将耗时的数据同步操作转为后台任务
- 数据库索引:为频繁查询的字段添加索引
/**
* 数据缓存管理器
* 减少对实时数据源的频繁请求
*/
class SupplyChainCacheManager {
private $cache_group = 'supply_chain';
private $cache_expiration = 300; // 5分钟
/**
* 获取缓存数据
*/
public function get_cached_data($key) {
$data = wp_cache_get($key, $this->cache_group);
if ($data === false) {
// 缓存未命中,从数据源获取
$data = $this->fetch_from_source($key);
if ($data) {
wp_cache_set($key, $data, $this->cache_group, $this->cache_expiration);
}
}
return $data;
}
/**
* 更新缓存数据
*/
public function update_cache($key, $data) {
return wp_cache_set($key, $data, $this->cache_group, $this->cache_expiration);
}
/**
* 清除特定缓存
*/
public function clear_cache($key = '') {
if ($key) {
wp_cache_delete($key, $this->cache_group);
} else {
wp_cache_flush();
}
}
/**
* 从数据源获取数据
*/
private function fetch_from_source($key) {
// 根据key从不同数据源获取数据
$data_collector = new SupplyChainDataCollector();
if (strpos($key, 'inventory_') === 0) {
$product_id = str_replace('inventory_', '', $key);
return $data_collector->get_inventory_level($product_id);
} elseif (strpos($key, 'health_metrics') !== false) {
return $data_collector->get_supply_chain_health();
}
return null;
}
}
安全加固措施
/**
* 供应链数据安全验证器
*/
class SupplyChainSecurity {
/**
* 验证数据访问权限
*/
public static function check_access_permission($user_id, $data_type) {
$user = get_userdata($user_id);
if (!in_array('supply_chain_manager', $user->roles)) {
return false;
}
// 检查特定数据类型的访问权限
$allowed_data_types = get_user_meta($user_id, 'allowed_supply_data', true);
if (is_array($allowed_data_types) && !in_array($data_type, $allowed_data_types)) {
return false;
}
return true;
}
/**
* 数据输入验证
*/
public static function validate_input_data($data, $data_type) {
$validation_rules = [
'inventory_update' => [
'product_id' => 'is_numeric',
'quantity' => 'is_numeric|min:0',
'location' => 'sanitize_text_field|max:100'
],
'supplier_data' => [
'name' => 'sanitize_text_field|required',
'capacity' => 'is_numeric|min:0',
'lead_time' => 'is_numeric|min:1'
]
];
if (!isset($validation_rules[$data_type])) {
return false;
}
foreach ($validation_rules[$data_type] as $field => $rules) {
if (!isset($data[$field])) {
return false;
}
// 应用验证规则
if (!$this->apply_validation_rules($data[$field], $rules)) {
return false;
}
}
return true;
}
/**
* 应用验证规则
*/
private function apply_validation_rules($value, $rules) {
$rule_list = explode('|', $rules);
foreach ($rule_list as $rule) {
if ($rule === 'required' && empty($value)) {
return false;
}
if ($rule === 'is_numeric' && !is_numeric($value)) {
return false;
}
if (strpos($rule, 'min:') === 0) {
$min_value = str_replace('min:', '', $rule);
if ($value < $min_value) {
return false;
}
}
if (strpos($rule, 'max:') === 0) {
$max_value = str_replace('max:', '', $rule);
if (strlen($value) > $max_value) {
return false;
}
}
}
return true;
}
}
高级功能扩展
预测分析模块
/**
* 供应链预测分析引擎
* 使用历史数据进行趋势预测
*/
class SupplyChainPredictiveAnalytics {
private $historical_data_days = 90;
/**
* 预测库存需求
*/
public function predict_inventory_demand($product_id, $days_ahead = 7) {
// 获取历史销售数据
$historical_data = $this->get_historical_sales_data($product_id);
if (empty($historical_data)) {
return $this->get_default_prediction($product_id);
}
// 应用简单移动平均算法
$prediction = $this->calculate_moving_average($historical_data, $days_ahead);
// 考虑季节性因素
$seasonal_adjustment = $this->calculate_seasonal_adjustment();
$prediction = $prediction * $seasonal_adjustment;
return [
'product_id' => $product_id,
'predicted_demand' => round($prediction),
'confidence_level' => $this->calculate_confidence_level($historical_data),
'forecast_period' => $days_ahead,
'calculation_date' => current_time('mysql')
];
}
/**
* 获取历史销售数据
*/
private function get_historical_sales_data($product_id) {
global $wpdb;
$query = $wpdb->prepare(
"SELECT DATE(date) as sale_date, SUM(quantity) as daily_sales
FROM {$wpdb->prefix}supply_chain_sales
WHERE product_id = %d
AND date >= DATE_SUB(NOW(), INTERVAL %d DAY)
GROUP BY DATE(date)
ORDER BY sale_date",
$product_id,
$this->historical_data_days
);
return $wpdb->get_results($query, ARRAY_A);
}
/**
* 计算移动平均
*/
private function calculate_moving_average($data, $period) {
$sales = array_column($data, 'daily_sales');
if (count($sales) < 7) {
return array_sum($sales) / max(count($sales), 1);
}
// 使用最近7天的移动平均
$recent_sales = array_slice($sales, -7);
$average = array_sum($recent_sales) / 7;
// 应用趋势因子
$trend = $this->calculate_trend($sales);
return $average * (1 + $trend * $period / 30);
}
/**
* 计算销售趋势
*/
private function calculate_trend($sales_data) {
if (count($sales_data) < 14) {
return 0;
}
$first_half = array_slice($sales_data, 0, floor(count($sales_data) / 2));
$second_half = array_slice($sales_data, floor(count($sales_data) / 2));
$avg_first = array_sum($first_half) / count($first_half);
$avg_second = array_sum($second_half) / count($second_half);
if ($avg_first == 0) {
return 0;
}
return ($avg_second - $avg_first) / $avg_first;
}
/**
* 计算季节性调整因子
*/
private function calculate_seasonal_adjustment() {
$month = date('n');
// 简单的月度调整因子(示例数据)
$monthly_factors = [
1 => 0.9, // 1月
2 => 0.95, // 2月
3 => 1.0, // 3月
4 => 1.1, // 4月
5 => 1.15, // 5月
6 => 1.2, // 6月
7 => 1.1, // 7月
8 => 1.05, // 8月
9 => 1.0, // 9月
10 => 0.95, // 10月
11 => 1.1, // 11月
12 => 1.3 // 12月
];
return $monthly_factors[$month] ?? 1.0;
}
/**
* 计算预测置信度
*/
private function calculate_confidence_level($historical_data) {
$data_points = count($historical_data);
if ($data_points < 7) {
return '低';
} elseif ($data_points < 30) {
return '中';
} else {
return '高';
}
}
/**
* 默认预测(当数据不足时)
*/
private function get_default_prediction($product_id) {
// 基于产品类型和平均销售量的简单预测
$product_type = get_field('product_type', $product_id);
$default_predictions = [
'fast_moving' => 100,
'slow_moving' => 20,
'seasonal' => 50
];
return [
'product_id' => $product_id,
'predicted_demand' => $default_predictions[$product_type] ?? 30,
'confidence_level' => '低',
'forecast_period' => 7,
'calculation_date' => current_time('mysql')
];
}
}
自动化决策支持
/**
* 自动化决策引擎
* 基于规则和机器学习提供决策建议
*/
class AutomatedDecisionEngine {
/**
* 库存补货建议
*/
public function get_replenishment_suggestion($product_id) {
$current_inventory = get_field('current_inventory', $product_id);
$min_threshold = get_field('min_inventory_threshold', $product_id);
$lead_time = get_field('supplier_lead_time', $product_id);
// 获取预测需求
$predictive_engine = new SupplyChainPredictiveAnalytics();
$demand_prediction = $predictive_engine->predict_inventory_demand($product_id, $lead_time + 7);
$predicted_demand = $demand_prediction['predicted_demand'];
// 计算建议补货量
$safety_stock = $min_threshold * 1.5;
$required_inventory = $predicted_demand + $safety_stock;
$suggested_order = max(0, $required_inventory - $current_inventory);
// 确定紧急程度
$urgency = $this->calculate_urgency_level($current_inventory, $min_threshold, $predicted_demand);
return [
'product_id' => $product_id,
'current_inventory' => $current_inventory,
'predicted_demand' => $predicted_demand,
'suggested_order_quantity' => round($suggested_order),
'urgency_level' => $urgency,
'recommended_action' => $this->get_recommended_action($urgency, $suggested_order),
'calculation_date' => current_time('mysql')
];
}
/**
* 计算紧急程度
*/
private function calculate_urgency_level($current, $threshold, $predicted) {
$days_of_supply = $current / max($predicted / 30, 0.1); // 转换为天数
if ($current <= $threshold * 0.5) {
return 'critical';
} elseif ($days_of_supply <= 7) {
return 'high';
} elseif ($days_of_supply <= 14) {
return 'medium';
} else {
return 'low';
}
}
/**
* 获取推荐行动
*/
private function get_recommended_action($urgency, $quantity) {
$actions = [
'critical' => [
'action' => '立即补货',
'priority' => 1,
'timeframe' => '24小时内',
'method' => '加急订单'
],
'high' => [
'action' => '计划补货',
'priority' => 2,
'timeframe' => '3天内',
'method' => '常规订单'
],
'medium' => [
'action' => '监控库存',
'priority' => 3,
'timeframe' => '1周内',
'method' => '计划订单'
],
'low' => [
'action' => '维持现状',
'priority' => 4,
'timeframe' => '2周后复查',
'method' => '无需行动'
]
];
$action = $actions[$urgency] ?? $actions['low'];
$action['order_quantity'] = $quantity;
return $action;
}
/**
* 供应商选择建议
*/
public function suggest_supplier($product_id, $required_quantity) {
$suppliers = get_posts([
'post_type' => 'supplier',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => 'supplied_products',
'value' => '"' . $product_id . '"',
'compare' => 'LIKE'
]
]
]);
$scored_suppliers = [];
foreach ($suppliers as $supplier) {
$score = $this->calculate_supplier_score($supplier->ID, $product_id, $required_quantity);
$scored_suppliers[] = [
'supplier_id' => $supplier->ID,
'supplier_name' => $supplier->post_title,
'score' => $score,
'lead_time' => get_field('lead_time', $supplier->ID),
'unit_cost' => get_field('unit_cost', $supplier->ID),
'reliability' => get_field('reliability_rating', $supplier->ID)
];
}
// 按分数排序
usort($scored_suppliers, function($a, $b) {
return $b['score'] <=> $a['score'];
});
return array_slice($scored_suppliers, 0, 3); // 返回前三名
}
/**
* 计算供应商评分
*/
private function calculate_supplier_score($supplier_id, $product_id, $quantity) {
$base_score = 0;
// 价格因素(40%权重)
$unit_cost = get_field('unit_cost', $supplier_id);
$base_score += (100 - min($unit_cost, 100)) * 0.4;
// 交货时间(30%权重)
$lead_time = get_field('lead_time', $supplier_id);
$base_score += (100 - min($lead_time, 30)) * 3.33 * 0.3;
// 可靠性(20%权重)
$reliability = get_field('reliability_rating', $supplier_id);
$base_score += $reliability * 0.2;
// 产能匹配(10%权重)
$capacity = get_field('production_capacity', $supplier_id);
if ($capacity >= $quantity) {
$base_score += 10;
} else {
$base_score += ($capacity / $quantity) * 10;
}
return round($base_score, 2);
}
}
集成与API开发
REST API端点
/**
* 供应链数字孪生REST API
*/
class SupplyChainDigitalTwinAPI {
public function __construct() {
add_action('rest_api_init', [$this, 'register_routes']);
}
/**
* 注册API路由
*/
public function register_routes() {
// 库存数据端点
register_rest_route('digital-twin/v1', '/inventory/(?P<id>d+)', [
[
'methods' => 'GET',
'callback' => [$this, 'get_inventory_data'],
'permission_callback' => [$this, 'check_api_permission'],
'args' => [
'id' => [
'validate_callback' => 'is_numeric'
]
]
]
]);
// 预测分析端点
register_rest_route('digital-twin/v1', '/predict/(?P<product_id>d+)', [
[
'methods' => 'GET',
'callback' => [$this, 'get_prediction'],
'permission_callback' => [$this, 'check_api_permission'],
'args' => [
'product_id' => [
'validate_callback' => 'is_numeric'
],
'days_ahead' => [
'required' => false,
'default' => 7,
'validate_callback' => 'is_numeric'
]
]
]
]);
// 决策建议端点
register_rest_route('digital-twin/v1', '/recommendations/(?P<product_id>d+)', [
[
'methods' => 'GET',
