文章目录
-
- 在当今快速变化的电商环境中,企业面临着供应链管理的巨大挑战。库存积压、物流延迟、供应商变动等问题时常困扰着电商运营者。WordPress作为全球最流行的内容管理系统,通过插件集成柔性供应链解决方案,可以帮助企业实现库存优化、供应商管理和物流协调的一体化运营。 本教程将详细介绍如何在WordPress中集成柔性供应链解决方案,包括插件选择、代码集成和实际应用示例。
- 在开始集成之前,请确保您的WordPress环境满足以下要求: WordPress 5.0或更高版本 PHP 7.4或更高版本 MySQL 5.6或更高版本 已安装WooCommerce插件(如果涉及电商功能)
- 下面我们将创建一个自定义插件,实现柔性供应链的核心功能。 <?php /** * Plugin Name: 柔性供应链管理系统 * Plugin URI: https://yourwebsite.com/ * Description: WordPress柔性供应链解决方案核心插件 * Version: 1.0.0 * Author: 您的名称 * License: GPL v2 or later */ // 防止直接访问 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__)); /** * 供应链管理主类 */ class Flexible_Supply_Chain { 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(); } /** * 初始化钩子和动作 */ private function init_hooks() { // 后台管理菜单 add_action('admin_menu', array($this, 'add_admin_menu')); // 初始化数据库表 register_activation_hook(__FILE__, array($this, 'create_database_tables')); // 加载脚本和样式 add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts')); // 集成WooCommerce钩子 if (class_exists('WooCommerce')) { add_action('woocommerce_order_status_changed', array($this, 'handle_order_status_change'), 10, 4); } } /** * 创建数据库表 */ public function create_database_tables() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name_suppliers = $wpdb->prefix . 'fsc_suppliers'; $table_name_inventory = $wpdb->prefix . 'fsc_inventory_log'; // 供应商表 $sql_suppliers = "CREATE TABLE IF NOT EXISTS $table_name_suppliers ( id mediumint(9) NOT NULL AUTO_INCREMENT, name varchar(100) NOT NULL, contact_person varchar(100), email varchar(100), phone varchar(30), lead_time_days int(11) DEFAULT 7, reliability_score decimal(3,2) DEFAULT 1.00, is_active tinyint(1) DEFAULT 1, created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id) ) $charset_collate;"; // 库存日志表 $sql_inventory = "CREATE TABLE IF NOT EXISTS $table_name_inventory ( id mediumint(9) NOT NULL AUTO_INCREMENT, product_id bigint(20) NOT NULL, supplier_id mediumint(9), change_type varchar(50) NOT NULL, quantity_change int(11) NOT NULL, current_stock int(11) NOT NULL, note text, created_by bigint(20), created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY product_id (product_id), KEY supplier_id (supplier_id) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql_suppliers); dbDelta($sql_inventory); } /** * 添加管理菜单 */ public function add_admin_menu() { add_menu_page( '柔性供应链管理', '供应链管理', 'manage_options', 'flexible-supply-chain', array($this, 'render_dashboard'), 'dashicons-networking', 30 ); add_submenu_page( 'flexible-supply-chain', '供应商管理', '供应商', 'manage_options', 'fsc-suppliers', array($this, 'render_suppliers_page') ); add_submenu_page( 'flexible-supply-chain', '库存优化', '库存优化', 'manage_options', 'fsc-inventory', array($this, 'render_inventory_page') ); } /** * 处理订单状态变化 */ public function handle_order_status_change($order_id, $old_status, $new_status, $order) { // 当订单状态变为处理中时,更新库存 if ($new_status === 'processing') { $this->update_inventory_for_order($order); } // 记录供应链事件 $this->log_supply_chain_event($order_id, 'status_change', "订单状态从 $old_status 变为 $new_status"); } /** * 根据订单更新库存 */ private function update_inventory_for_order($order) { global $wpdb; foreach ($order->get_items() as $item) { $product_id = $item->get_product_id(); $quantity = $item->get_quantity(); // 获取当前库存 $current_stock = get_post_meta($product_id, '_stock', true); $new_stock = $current_stock - $quantity; // 更新库存 update_post_meta($product_id, '_stock', $new_stock); // 记录库存变化 $table_name = $wpdb->prefix . 'fsc_inventory_log'; $wpdb->insert( $table_name, array( 'product_id' => $product_id, 'change_type' => 'order_fulfillment', 'quantity_change' => -$quantity, 'current_stock' => $new_stock, 'note' => "订单 #{$order->get_id()} 发货", 'created_by' => get_current_user_id() ) ); // 检查库存水平,触发补货警报 $this->check_reorder_level($product_id, $new_stock); } } /** * 检查补货水平 */ private function check_reorder_level($product_id, $current_stock) { $reorder_level = get_post_meta($product_id, '_reorder_level', true); if (!$reorder_level) { // 默认重新订购点为10 $reorder_level = 10; } if ($current_stock <= $reorder_level) { // 触发补货通知 $this->send_reorder_alert($product_id, $current_stock); } } /** * 发送补货警报 */ private function send_reorder_alert($product_id, $current_stock) { $product = wc_get_product($product_id); $product_name = $product->get_name(); // 获取管理员邮箱 $admin_email = get_option('admin_email'); $subject = "库存警报: {$product_name} 需要补货"; $message = "产品: {$product_name}n"; $message .= "当前库存: {$current_stock}n"; $message .= "产品ID: {$product_id}n"; $message .= "请及时联系供应商补货。nn"; $message .= "此邮件由柔性供应链系统自动发送"; wp_mail($admin_email, $subject, $message); // 记录警报事件 $this->log_supply_chain_event($product_id, 'reorder_alert', "产品库存低于重新订购点"); } /** * 记录供应链事件 */ private function log_supply_chain_event($entity_id, $event_type, $description) { global $wpdb; $table_name = $wpdb->prefix . 'fsc_events_log'; // 确保事件日志表存在 if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) { $this->create_events_table(); } $wpdb->insert( $table_name, array( 'entity_id' => $entity_id, 'event_type' => $event_type, 'description' => $description, 'created_by' => get_current_user_id(), 'ip_address' => $_SERVER['REMOTE_ADDR'] ) ); } /** * 创建事件日志表 */ private function create_events_table() { global $wpdb; $charset_collate = $wpdb->get_charset_collate(); $table_name = $wpdb->prefix . 'fsc_events_log'; $sql = "CREATE TABLE IF NOT EXISTS $table_name ( id mediumint(9) NOT NULL AUTO_INCREMENT, entity_id bigint(20) NOT NULL, event_type varchar(50) NOT NULL, description text, created_by bigint(20), ip_address varchar(45), created_at datetime DEFAULT CURRENT_TIMESTAMP, PRIMARY KEY (id), KEY entity_id (entity_id), KEY event_type (event_type) ) $charset_collate;"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } /** * 加载管理端脚本和样式 */ public function enqueue_admin_scripts($hook) { if (strpos($hook, 'flexible-supply-chain') === false) { return; } wp_enqueue_style( 'fsc-admin-style', FSC_PLUGIN_URL . 'assets/css/admin.css', array(), FSC_VERSION ); wp_enqueue_script( 'fsc-admin-script', FSC_PLUGIN_URL . 'assets/js/admin.js', array('jquery', 'jquery-ui-sortable'), FSC_VERSION, true ); // 本地化脚本,传递数据到JavaScript wp_localize_script('fsc-admin-script', 'fsc_ajax', array( 'ajax_url' => admin_url('admin-ajax.php'), 'nonce' => wp_create_nonce('fsc_ajax_nonce') )); } /** * 渲染仪表板页面 */ public function render_dashboard() { include FSC_PLUGIN_DIR . 'templates/dashboard.php'; } /** * 渲染供应商页面 */ public function render_suppliers_page() { include FSC_PLUGIN_DIR . 'templates/suppliers.php'; } /** * 渲染库存页面 */ public function render_inventory_page() { include FSC_PLUGIN_DIR . 'templates/inventory.php'; } } // 初始化插件 add_action('plugins_loaded', function() { Flexible_Supply_Chain::get_instance(); }); /** * AJAX处理:获取库存数据 */ add_action('wp_ajax_fsc_get_inventory_data', 'fsc_ajax_get_inventory_data'); function fsc_ajax_get_inventory_data() { // 验证nonce check_ajax_referer('fsc_ajax_nonce', 'nonce'); global $wpdb; $table_name = $wpdb->prefix . 'fsc_inventory_log'; // 获取最近30天的库存变化 $results = $wpdb->get_results( $wpdb->prepare( "SELECT DATE(created_at) as date, SUM(CASE WHEN change_type = 'restock' THEN quantity_change ELSE 0 END) as restocked, SUM(CASE WHEN change_type = 'order_fulfillment' THEN quantity_change ELSE 0 END) as sold FROM $table_name WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY DATE(created_at) ORDER BY date DESC" ) ); wp_send_json_success($results); } ?>
- 以下代码展示了如何扩展供应商管理功能: <?php /** * 供应商管理类 */ class FSC_Supplier_Manager { /** * 添加新供应商 */ public static function add_supplier($data) { global $wpdb; $table_name = $wpdb->prefix . 'fsc_suppliers'; $result = $wpdb->insert( $table_name, array( 'name' => sanitize_text_field($data['name']), 'contact_person' => sanitize_text_field($data['contact_person']), 'email' => sanitize_email($data['email']), 'phone' => sanitize_text_field($data['phone']), 'lead_time_days' => intval($data['lead_time_days']), 'reliability_score' => floatval($data['reliability_score']) ), array('%s', '%s', '%s', '%s', '%d', '%f') ); return $result ? $wpdb->insert_id : false; } /** * 获取所有供应商 */ public static function get_all_suppliers($active_only = true) { global $wpdb; $table_name = $wpdb->prefix . 'fsc_suppliers'; $where = $active_only ? "WHERE is_active = 1" : ""; return $wpdb->get_results( "SELECT * FROM $table_name $where ORDER BY name ASC" ); } /** * 根据产品需求智能推荐供应商 */ public static function recommend_supplier($product_id, $required_quantity, $urgency_level = 'normal') { $suppliers = self::get_all_suppliers(); $recommendations = array(); foreach ($suppliers as $supplier) { $score = self::calculate_supplier_score($supplier, $product_id, $required_quantity, $urgency_level); $recommendations[] = array( 'supplier' => $supplier, 'score' => $score ); } // 按分数排序 usort($recommendations, function($a, $b) { return $b['score'] <=> $a['score']; }); return $recommendations; } /** * 计算供应商得分 */ private static function calculate_supplier_score($supplier, $product_id, $quantity, $urgency) { $score = 0; // 基础可靠性得分 (0-40分) $score += $supplier->reliability_score * 40; // 根据紧急程度调整交货时间得分 $lead_time_score = self::calculate_lead_time_score($supplier->lead_time_days, $urgency); $score += $lead_time_score; // 历史合作记录加分 (如果有) $history_score = self::calculate_history_score($supplier->id, $product_id); $score += $history_score; return $score; } /** * 计算交货时间得分 */ private static function calculate_lead_time_score($lead_time_days, $urgency) { $urgency_multipliers = array( 'high' => 1.5, 'normal' => 1.0, 'low' => 0.7 ); $multiplier = $urgency_multipliers[$urgency] ?? 1.0; // 交货时间越短,得分越高 $base_score = max(0, 30 - ($lead_time_days * 2)); return $base_score * $multiplier; } } ?>
- <?php /** * 库存优化管理类 */ class FSC_Inventory_Optimizer { /** * 计算经济订单量 (EOQ) * EOQ = √((2 × D × S) / H) * D: 年需求量, S: 每次订购成本, H: 单位持有成本 */ public static function calculate_eoq($annual_demand, $order_cost, $holding_cost_per_unit) { if ($holding_cost_per_unit <= 0) { return 0; } $eoq = sqrt((2 * $annual_demand * $order_cost) / $holding_cost_per_unit); return ceil($eoq); // 向上取整 } /** * 计算安全库存 * 安全库存 = Z × σ × √L * Z: 服务水平系数, σ: 需求标准差, L: 提前期 */ public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) { // Z值对应表 (服务水平 -> Z值) $z_values = array( 0.80 => 0.84, 0.85 => 1.04, 0.90 => 1.28, 0.95 => 1.65, 0.99 => 2.33 ); <?php /** * 库存优化管理类 - 续 */ class FSC_Inventory_Optimizer { /** * 计算安全库存 * 安全库存 = Z × σ × √L * Z: 服务水平系数, σ: 需求标准差, L: 提前期 */ public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) { // Z值对应表 (服务水平 -> Z值) $z_values = array( 0.80 => 0.84, 0.85 => 1.04, 0.90 => 1.28, 0.95 => 1.65, 0.99 => 2.33 ); $z = $z_values[$service_level] ?? 1.65; // 默认95%服务水平 $safety_stock = $z * $demand_stddev * sqrt($lead_time); return ceil($safety_stock); } /** * 计算重新订购点 (ROP) * ROP = (平均日需求 × 提前期) + 安全库存 */ public static function calculate_reorder_point($avg_daily_demand, $lead_time_days, $safety_stock) { $rop = ($avg_daily_demand * $lead_time_days) + $safety_stock; return ceil($rop); } /** * 智能库存分配算法 * 根据多个仓库的库存和需求进行优化分配 */ public static function optimize_inventory_allocation($warehouses, $total_demand) { $allocation = array(); $remaining_demand = $total_demand; // 按库存成本排序(成本低的优先分配) usort($warehouses, function($a, $b) { return $a['holding_cost'] <=> $b['holding_cost']; }); foreach ($warehouses as $warehouse) { if ($remaining_demand <= 0) break; $warehouse_id = $warehouse['id']; $available_stock = $warehouse['current_stock']; $max_allocation = min($available_stock, $remaining_demand); // 考虑运输成本,如果成本过高则减少分配量 $transport_cost_factor = $warehouse['transport_cost'] / 100; // 假设成本以百分比表示 $adjusted_allocation = $max_allocation * (1 - $transport_cost_factor); $allocation[$warehouse_id] = floor($adjusted_allocation); $remaining_demand -= $allocation[$warehouse_id]; } // 如果仍有需求未满足,记录短缺 if ($remaining_demand > 0) { $allocation['shortage'] = $remaining_demand; $allocation['needs_replenishment'] = true; } return $allocation; } /** * 预测未来需求(简单移动平均法) */ public static function forecast_demand($historical_data, $periods = 30) { if (count($historical_data) < $periods) { return 0; } // 取最近$periods个数据点 $recent_data = array_slice($historical_data, -$periods); $sum = array_sum($recent_data); return $sum / $periods; } } ?>
- <?php /** * 物流集成管理类 */ class FSC_Logistics_Integration { private $api_keys = array(); public function __construct() { $this->api_keys = get_option('fsc_logistics_api_keys', array()); } /** * 集成主流物流API */ public function integrate_shipping_apis($order_id, $shipping_method) { $order = wc_get_order($order_id); $shipping_address = $order->get_shipping_address_1(); $shipping_city = $order->get_shipping_city(); switch ($shipping_method) { case 'fedex': return $this->fedex_integration($order); case 'dhl': return $this->dhl_integration($order); case 'ups': return $this->ups_integration($order); case 'custom': return $this->custom_carrier_integration($order); default: return $this->standard_shipping($order); } } /** * FedEx API集成示例 */ private function fedex_integration($order) { $api_key = $this->api_keys['fedex'] ?? ''; if (empty($api_key)) { return array( 'success' => false, 'error' => 'FedEx API密钥未配置' ); } // 构建FedEx API请求 $request_data = array( 'request' => array( 'webAuthenticationDetail' => array( 'userCredential' => array( 'key' => $api_key, 'password' => $this->api_keys['fedex_password'] ) ), 'clientDetail' => array( 'accountNumber' => $this->api_keys['fedex_account'], 'meterNumber' => $this->api_keys['fedex_meter'] ), 'transactionDetail' => array( 'customerTransactionId' => 'Order_' . $order->get_id() ), 'version' => array( 'serviceId' => 'ship', 'major' => '26', 'intermediate' => '0', 'minor' => '0' ), 'requestedShipment' => array( 'dropoffType' => 'REGULAR_PICKUP', 'serviceType' => 'FEDEX_GROUND', 'packagingType' => 'YOUR_PACKAGING', 'shipper' => $this->get_shipper_address(), 'recipient' => $this->get_recipient_address($order), 'shippingChargesPayment' => array( 'paymentType' => 'SENDER', 'payor' => array( 'responsibleParty' => array( 'accountNumber' => $this->api_keys['fedex_account'] ) ) ), 'labelSpecification' => array( 'labelFormatType' => 'COMMON2D', 'imageType' => 'PDF', 'labelStockType' => 'PAPER_85X11_TOP_HALF_LABEL' ), 'rateRequestTypes' => array('LIST'), 'packageCount' => '1', 'requestedPackageLineItems' => array( '0' => array( 'weight' => array( 'value' => $this->calculate_order_weight($order), 'units' => 'LB' ), 'dimensions' => array( 'length' => 10, 'width' => 10, 'height' => 10, 'units' => 'IN' ) ) ) ) ) ); // 发送API请求 $response = $this->send_api_request( 'https://apis.fedex.com/ship/v1/shipments', $request_data, $api_key ); return $this->process_fedex_response($response); } /** * 多物流商比价 */ public function compare_shipping_rates($order) { $rates = array(); // 获取各物流商报价 $rates['fedex'] = $this->get_fedex_rate($order); $rates['dhl'] = $this->get_dhl_rate($order); $rates['ups'] = $this->get_ups_rate($order); $rates['local'] = $this->get_local_carrier_rate($order); // 按价格排序 uasort($rates, function($a, $b) { return $a['cost'] <=> $b['cost']; }); // 考虑交货时间和可靠性 foreach ($rates as &$rate) { $rate['score'] = $this->calculate_shipping_score( $rate['cost'], $rate['estimated_days'], $rate['reliability'] ); } return $rates; } /** * 计算物流得分 */ private function calculate_shipping_score($cost, $delivery_days, $reliability) { $cost_score = max(0, 100 - ($cost * 10)); // 成本越低得分越高 $speed_score = max(0, 100 - ($delivery_days * 20)); // 越快得分越高 $reliability_score = $reliability * 100; // 可靠性得分 // 加权计算总分 $total_score = ($cost_score * 0.4) + ($speed_score * 0.3) + ($reliability_score * 0.3); return $total_score; } /** * 实时物流跟踪 */ public function track_shipment($tracking_number, $carrier) { $tracking_urls = array( 'fedex' => 'https://www.fedex.com/fedextrack/?trknbr=', 'dhl' => 'https://www.dhl.com/en/express/tracking.html?AWB=', 'ups' => 'https://www.ups.com/track?tracknum=', 'usps' => 'https://tools.usps.com/go/TrackConfirmAction?tLabels=' ); $url = $tracking_urls[$carrier] ?? ''; if ($url) { return $url . $tracking_number; } // 如果未找到预设URL,尝试通用查询 return $this->universal_tracking_query($tracking_number, $carrier); } } ?>
- <?php /** * 前端供应链状态展示 */ class FSC_Frontend_Display { /** * 在产品页面显示供应链信息 */ public static function display_product_supply_info($product_id) { $stock_level = get_post_meta($product_id, '_stock', true); $lead_time = get_post_meta($product_id, '_lead_time', true); $supplier_name = get_post_meta($product_id, '_supplier_name', true); if (empty($stock_level) && empty($lead_time)) { return; } ob_start(); ?> <div class="fsc-supply-info"> <h3>供应链信息</h3> <div class="fsc-info-grid"> <?php if ($stock_level !== '') : ?> <div class="fsc-info-item"> <span class="fsc-label">库存状态:</span> <span class="fsc-value stock-<?php echo ($stock_level > 10) ? 'high' : (($stock_level > 0) ? 'low' : 'out'); ?>"> <?php if ($stock_level > 10) { echo '充足 (' . $stock_level . '件)'; } elseif ($stock_level > 0) { echo '紧张 (' . $stock_level . '件)'; } else { echo '缺货'; } ?> </span> </div> <?php endif; ?> <?php if ($lead_time) : ?> <div class="fsc-info-item"> <span class="fsc-label">预计补货时间:</span> <span class="fsc-value"><?php echo $lead_time; ?> 天</span> </div> <?php endif; ?> <?php if ($supplier_name) : ?> <div class="fsc-info-item"> <span class="fsc-label">供应商:</span> <span class="fsc-value"><?php echo esc_html($supplier_name); ?></span> </div> <?php endif; ?> </div> <?php // 显示库存预测图表 if (current_user_can('manage_options')) { self::display_inventory_chart($product_id); } ?> </div> <style> .fsc-supply-info { margin: 20px 0; padding: 15px; border: 1px solid #e0e0e0; border-radius: 5px; background: #f9f9f9; } .fsc-info-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 10px; margin-top: 10px; } .fsc-info-item { display: flex; justify-content: space-between; padding: 8px; background: white; border-radius: 3px; } .fsc-label { font-weight: bold; color: #555; } .stock-high { color: #2ecc71; } .stock-low { color: #f39c12; } .stock-out { color: #e74c3c; } </style> <?php echo ob_get_clean(); } /** * 显示库存预测图表 */ private static function display_inventory_chart($product_id) { global $wpdb; $table_name = $wpdb->prefix . 'fsc_inventory_log'; $data = $wpdb->get_results($wpdb->prepare( "SELECT DATE(created_at) as date, SUM(quantity_change) as daily_change, AVG(current_stock) as avg_stock FROM $table_name WHERE product_id = %d AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY) GROUP BY DATE(created_at) ORDER BY date ASC", $product_id )); if (empty($data)) return; $dates = array(); $stocks = array(); foreach ($data as $row) { $dates[] = $row->date; $stocks[] = $row->avg_stock; } ?> <div class="fsc-inventory-chart"> <h4>库存趋势 (最近30天)</h4> <canvas id="inventoryChart-<?php echo $product_id; ?>" width="400" height="200"></canvas> <script> document.addEventListener('DOMContentLoaded', function() { var ctx = document.getElementById('inventoryChart-<?php echo $product_id; ?>').getContext('2d'); var chart = new Chart(ctx, { type: 'line', data: { labels: <?php echo json_encode($dates); ?>, datasets: [{ label: '库存水平', data: <?php echo json_encode($stocks); ?>, borderColor: '#3498db', backgroundColor: 'rgba(52, 152, 219, 0.1)', fill: true, tension: 0.4 }] }, options: { responsive: true, plugins: { legend: { display: false } }, scales: { y: { beginAtZero: true, title: { display: true, text: '库存数量' } }, x: { title: { display: true, text: '日期' } } } } }); }); </script> </div> <?php } /** * 在订单页面显示供应链状态 */ public static function display_order_supply_status($order_id) { $supply_status = get_post_meta($order_id, '_fsc_supply_status', true); $estimated_delivery = get_post_meta($order_id, '_fsc_estimated_delivery', true); if (!$supply_status) return; $status_labels = array( 'supplier_confirmed' => '供应商已确认', 'production_started' => '生产中', 'quality_check' => '质量检测', 'ready_to_ship' => '准备发货', 'shipped' => '已发货', 'delivered' => '已送达' ); $current_status = $status_labels[$supply_status] ?? $supply_status; ob_start(); ?> <div class="fsc-order-status"> <h3>供应链状态跟踪</h3> <div class="status-timeline"> <?php $statuses = array_keys($status_labels); $current_index = array_search($supply_status, $statuses); foreach ($statuses as $index => $status) { $is_completed = $index <= $current_index; $is_current = $index === $current_index; ?> <div class="status-step <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_current ? 'current' : ''; ?>"> <div class="step-icon"> <?php if ($is_completed) : ?> <span class="dashicons dashicons-yes"></span> <?php else : ?> <span class="step-number"><?php echo $index + 1; ?></span> <?php endif; ?> </div> <div class="step-label"><?php echo $status_labels[$status]; ?></div> </div> <?php if ($index < count($statuses) - 1) : ?> <div class="step-connector"></div> <?php endif; } ?> </div> <?php if ($estimated_delivery) : ?> <div class="estimated-delivery"> <strong>预计送达时间:</strong> <?php echo date('Y年m月d日', strtotime($estimated_delivery)); ?> </div> <?php endif; ?> </div> <style> .fsc-order-status { margin: 20px 0; padding: 20px;
在当今快速变化的电商环境中,企业面临着供应链管理的巨大挑战。库存积压、物流延迟、供应商变动等问题时常困扰着电商运营者。WordPress作为全球最流行的内容管理系统,通过插件集成柔性供应链解决方案,可以帮助企业实现库存优化、供应商管理和物流协调的一体化运营。
本教程将详细介绍如何在WordPress中集成柔性供应链解决方案,包括插件选择、代码集成和实际应用示例。
在开始集成之前,请确保您的WordPress环境满足以下要求:
- WordPress 5.0或更高版本
- PHP 7.4或更高版本
- MySQL 5.6或更高版本
- 已安装WooCommerce插件(如果涉及电商功能)
- WooCommerce Stock Manager - 库存管理
- Supplier Management for WooCommerce - 供应商管理
- Advanced Shipment Tracking - 物流跟踪
- Flexible Supply Chain Framework - 自定义开发基础
下面我们将创建一个自定义插件,实现柔性供应链的核心功能。
<?php
/**
* Plugin Name: 柔性供应链管理系统
* Plugin URI: https://yourwebsite.com/
* Description: WordPress柔性供应链解决方案核心插件
* Version: 1.0.0
* Author: 您的名称
* License: GPL v2 or later
*/
// 防止直接访问
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__));
/**
* 供应链管理主类
*/
class Flexible_Supply_Chain {
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();
}
/**
* 初始化钩子和动作
*/
private function init_hooks() {
// 后台管理菜单
add_action('admin_menu', array($this, 'add_admin_menu'));
// 初始化数据库表
register_activation_hook(__FILE__, array($this, 'create_database_tables'));
// 加载脚本和样式
add_action('admin_enqueue_scripts', array($this, 'enqueue_admin_scripts'));
// 集成WooCommerce钩子
if (class_exists('WooCommerce')) {
add_action('woocommerce_order_status_changed', array($this, 'handle_order_status_change'), 10, 4);
}
}
/**
* 创建数据库表
*/
public function create_database_tables() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name_suppliers = $wpdb->prefix . 'fsc_suppliers';
$table_name_inventory = $wpdb->prefix . 'fsc_inventory_log';
// 供应商表
$sql_suppliers = "CREATE TABLE IF NOT EXISTS $table_name_suppliers (
id mediumint(9) NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
contact_person varchar(100),
email varchar(100),
phone varchar(30),
lead_time_days int(11) DEFAULT 7,
reliability_score decimal(3,2) DEFAULT 1.00,
is_active tinyint(1) DEFAULT 1,
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id)
) $charset_collate;";
// 库存日志表
$sql_inventory = "CREATE TABLE IF NOT EXISTS $table_name_inventory (
id mediumint(9) NOT NULL AUTO_INCREMENT,
product_id bigint(20) NOT NULL,
supplier_id mediumint(9),
change_type varchar(50) NOT NULL,
quantity_change int(11) NOT NULL,
current_stock int(11) NOT NULL,
note text,
created_by bigint(20),
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY product_id (product_id),
KEY supplier_id (supplier_id)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql_suppliers);
dbDelta($sql_inventory);
}
/**
* 添加管理菜单
*/
public function add_admin_menu() {
add_menu_page(
'柔性供应链管理',
'供应链管理',
'manage_options',
'flexible-supply-chain',
array($this, 'render_dashboard'),
'dashicons-networking',
30
);
add_submenu_page(
'flexible-supply-chain',
'供应商管理',
'供应商',
'manage_options',
'fsc-suppliers',
array($this, 'render_suppliers_page')
);
add_submenu_page(
'flexible-supply-chain',
'库存优化',
'库存优化',
'manage_options',
'fsc-inventory',
array($this, 'render_inventory_page')
);
}
/**
* 处理订单状态变化
*/
public function handle_order_status_change($order_id, $old_status, $new_status, $order) {
// 当订单状态变为处理中时,更新库存
if ($new_status === 'processing') {
$this->update_inventory_for_order($order);
}
// 记录供应链事件
$this->log_supply_chain_event($order_id, 'status_change', "订单状态从 $old_status 变为 $new_status");
}
/**
* 根据订单更新库存
*/
private function update_inventory_for_order($order) {
global $wpdb;
foreach ($order->get_items() as $item) {
$product_id = $item->get_product_id();
$quantity = $item->get_quantity();
// 获取当前库存
$current_stock = get_post_meta($product_id, '_stock', true);
$new_stock = $current_stock - $quantity;
// 更新库存
update_post_meta($product_id, '_stock', $new_stock);
// 记录库存变化
$table_name = $wpdb->prefix . 'fsc_inventory_log';
$wpdb->insert(
$table_name,
array(
'product_id' => $product_id,
'change_type' => 'order_fulfillment',
'quantity_change' => -$quantity,
'current_stock' => $new_stock,
'note' => "订单 #{$order->get_id()} 发货",
'created_by' => get_current_user_id()
)
);
// 检查库存水平,触发补货警报
$this->check_reorder_level($product_id, $new_stock);
}
}
/**
* 检查补货水平
*/
private function check_reorder_level($product_id, $current_stock) {
$reorder_level = get_post_meta($product_id, '_reorder_level', true);
if (!$reorder_level) {
// 默认重新订购点为10
$reorder_level = 10;
}
if ($current_stock <= $reorder_level) {
// 触发补货通知
$this->send_reorder_alert($product_id, $current_stock);
}
}
/**
* 发送补货警报
*/
private function send_reorder_alert($product_id, $current_stock) {
$product = wc_get_product($product_id);
$product_name = $product->get_name();
// 获取管理员邮箱
$admin_email = get_option('admin_email');
$subject = "库存警报: {$product_name} 需要补货";
$message = "产品: {$product_name}n";
$message .= "当前库存: {$current_stock}n";
$message .= "产品ID: {$product_id}n";
$message .= "请及时联系供应商补货。nn";
$message .= "此邮件由柔性供应链系统自动发送";
wp_mail($admin_email, $subject, $message);
// 记录警报事件
$this->log_supply_chain_event($product_id, 'reorder_alert', "产品库存低于重新订购点");
}
/**
* 记录供应链事件
*/
private function log_supply_chain_event($entity_id, $event_type, $description) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_events_log';
// 确保事件日志表存在
if ($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {
$this->create_events_table();
}
$wpdb->insert(
$table_name,
array(
'entity_id' => $entity_id,
'event_type' => $event_type,
'description' => $description,
'created_by' => get_current_user_id(),
'ip_address' => $_SERVER['REMOTE_ADDR']
)
);
}
/**
* 创建事件日志表
*/
private function create_events_table() {
global $wpdb;
$charset_collate = $wpdb->get_charset_collate();
$table_name = $wpdb->prefix . 'fsc_events_log';
$sql = "CREATE TABLE IF NOT EXISTS $table_name (
id mediumint(9) NOT NULL AUTO_INCREMENT,
entity_id bigint(20) NOT NULL,
event_type varchar(50) NOT NULL,
description text,
created_by bigint(20),
ip_address varchar(45),
created_at datetime DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (id),
KEY entity_id (entity_id),
KEY event_type (event_type)
) $charset_collate;";
require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
dbDelta($sql);
}
/**
* 加载管理端脚本和样式
*/
public function enqueue_admin_scripts($hook) {
if (strpos($hook, 'flexible-supply-chain') === false) {
return;
}
wp_enqueue_style(
'fsc-admin-style',
FSC_PLUGIN_URL . 'assets/css/admin.css',
array(),
FSC_VERSION
);
wp_enqueue_script(
'fsc-admin-script',
FSC_PLUGIN_URL . 'assets/js/admin.js',
array('jquery', 'jquery-ui-sortable'),
FSC_VERSION,
true
);
// 本地化脚本,传递数据到JavaScript
wp_localize_script('fsc-admin-script', 'fsc_ajax', array(
'ajax_url' => admin_url('admin-ajax.php'),
'nonce' => wp_create_nonce('fsc_ajax_nonce')
));
}
/**
* 渲染仪表板页面
*/
public function render_dashboard() {
include FSC_PLUGIN_DIR . 'templates/dashboard.php';
}
/**
* 渲染供应商页面
*/
public function render_suppliers_page() {
include FSC_PLUGIN_DIR . 'templates/suppliers.php';
}
/**
* 渲染库存页面
*/
public function render_inventory_page() {
include FSC_PLUGIN_DIR . 'templates/inventory.php';
}
}
// 初始化插件
add_action('plugins_loaded', function() {
Flexible_Supply_Chain::get_instance();
});
/**
* AJAX处理:获取库存数据
*/
add_action('wp_ajax_fsc_get_inventory_data', 'fsc_ajax_get_inventory_data');
function fsc_ajax_get_inventory_data() {
// 验证nonce
check_ajax_referer('fsc_ajax_nonce', 'nonce');
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_inventory_log';
// 获取最近30天的库存变化
$results = $wpdb->get_results(
$wpdb->prepare(
"SELECT DATE(created_at) as date,
SUM(CASE WHEN change_type = 'restock' THEN quantity_change ELSE 0 END) as restocked,
SUM(CASE WHEN change_type = 'order_fulfillment' THEN quantity_change ELSE 0 END) as sold
FROM $table_name
WHERE created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY DATE(created_at)
ORDER BY date DESC"
)
);
wp_send_json_success($results);
}
?>
以下代码展示了如何扩展供应商管理功能:
<?php
/**
* 供应商管理类
*/
class FSC_Supplier_Manager {
/**
* 添加新供应商
*/
public static function add_supplier($data) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_suppliers';
$result = $wpdb->insert(
$table_name,
array(
'name' => sanitize_text_field($data['name']),
'contact_person' => sanitize_text_field($data['contact_person']),
'email' => sanitize_email($data['email']),
'phone' => sanitize_text_field($data['phone']),
'lead_time_days' => intval($data['lead_time_days']),
'reliability_score' => floatval($data['reliability_score'])
),
array('%s', '%s', '%s', '%s', '%d', '%f')
);
return $result ? $wpdb->insert_id : false;
}
/**
* 获取所有供应商
*/
public static function get_all_suppliers($active_only = true) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_suppliers';
$where = $active_only ? "WHERE is_active = 1" : "";
return $wpdb->get_results(
"SELECT * FROM $table_name $where ORDER BY name ASC"
);
}
/**
* 根据产品需求智能推荐供应商
*/
public static function recommend_supplier($product_id, $required_quantity, $urgency_level = 'normal') {
$suppliers = self::get_all_suppliers();
$recommendations = array();
foreach ($suppliers as $supplier) {
$score = self::calculate_supplier_score($supplier, $product_id, $required_quantity, $urgency_level);
$recommendations[] = array(
'supplier' => $supplier,
'score' => $score
);
}
// 按分数排序
usort($recommendations, function($a, $b) {
return $b['score'] <=> $a['score'];
});
return $recommendations;
}
/**
* 计算供应商得分
*/
private static function calculate_supplier_score($supplier, $product_id, $quantity, $urgency) {
$score = 0;
// 基础可靠性得分 (0-40分)
$score += $supplier->reliability_score * 40;
// 根据紧急程度调整交货时间得分
$lead_time_score = self::calculate_lead_time_score($supplier->lead_time_days, $urgency);
$score += $lead_time_score;
// 历史合作记录加分 (如果有)
$history_score = self::calculate_history_score($supplier->id, $product_id);
$score += $history_score;
return $score;
}
/**
* 计算交货时间得分
*/
private static function calculate_lead_time_score($lead_time_days, $urgency) {
$urgency_multipliers = array(
'high' => 1.5,
'normal' => 1.0,
'low' => 0.7
);
$multiplier = $urgency_multipliers[$urgency] ?? 1.0;
// 交货时间越短,得分越高
$base_score = max(0, 30 - ($lead_time_days * 2));
return $base_score * $multiplier;
}
}
?>
<?php
/**
* 库存优化管理类
*/
class FSC_Inventory_Optimizer {
/**
* 计算经济订单量 (EOQ)
* EOQ = √((2 × D × S) / H)
* D: 年需求量, S: 每次订购成本, H: 单位持有成本
*/
public static function calculate_eoq($annual_demand, $order_cost, $holding_cost_per_unit) {
if ($holding_cost_per_unit <= 0) {
return 0;
}
$eoq = sqrt((2 * $annual_demand * $order_cost) / $holding_cost_per_unit);
return ceil($eoq); // 向上取整
}
/**
* 计算安全库存
* 安全库存 = Z × σ × √L
* Z: 服务水平系数, σ: 需求标准差, L: 提前期
*/
public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) {
// Z值对应表 (服务水平 -> Z值)
$z_values = array(
0.80 => 0.84,
0.85 => 1.04,
0.90 => 1.28,
0.95 => 1.65,
0.99 => 2.33
);
<?php
/**
* 库存优化管理类 - 续
*/
class FSC_Inventory_Optimizer {
/**
* 计算安全库存
* 安全库存 = Z × σ × √L
* Z: 服务水平系数, σ: 需求标准差, L: 提前期
*/
public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) {
// Z值对应表 (服务水平 -> Z值)
$z_values = array(
0.80 => 0.84,
0.85 => 1.04,
0.90 => 1.28,
0.95 => 1.65,
0.99 => 2.33
);
$z = $z_values[$service_level] ?? 1.65; // 默认95%服务水平
$safety_stock = $z * $demand_stddev * sqrt($lead_time);
return ceil($safety_stock);
}
/**
* 计算重新订购点 (ROP)
* ROP = (平均日需求 × 提前期) + 安全库存
*/
public static function calculate_reorder_point($avg_daily_demand, $lead_time_days, $safety_stock) {
$rop = ($avg_daily_demand * $lead_time_days) + $safety_stock;
return ceil($rop);
}
/**
* 智能库存分配算法
* 根据多个仓库的库存和需求进行优化分配
*/
public static function optimize_inventory_allocation($warehouses, $total_demand) {
$allocation = array();
$remaining_demand = $total_demand;
// 按库存成本排序(成本低的优先分配)
usort($warehouses, function($a, $b) {
return $a['holding_cost'] <=> $b['holding_cost'];
});
foreach ($warehouses as $warehouse) {
if ($remaining_demand <= 0) break;
$warehouse_id = $warehouse['id'];
$available_stock = $warehouse['current_stock'];
$max_allocation = min($available_stock, $remaining_demand);
// 考虑运输成本,如果成本过高则减少分配量
$transport_cost_factor = $warehouse['transport_cost'] / 100; // 假设成本以百分比表示
$adjusted_allocation = $max_allocation * (1 - $transport_cost_factor);
$allocation[$warehouse_id] = floor($adjusted_allocation);
$remaining_demand -= $allocation[$warehouse_id];
}
// 如果仍有需求未满足,记录短缺
if ($remaining_demand > 0) {
$allocation['shortage'] = $remaining_demand;
$allocation['needs_replenishment'] = true;
}
return $allocation;
}
/**
* 预测未来需求(简单移动平均法)
*/
public static function forecast_demand($historical_data, $periods = 30) {
if (count($historical_data) < $periods) {
return 0;
}
// 取最近$periods个数据点
$recent_data = array_slice($historical_data, -$periods);
$sum = array_sum($recent_data);
return $sum / $periods;
}
}
?>
<?php
/**
* 库存优化管理类
*/
class FSC_Inventory_Optimizer {
/**
* 计算经济订单量 (EOQ)
* EOQ = √((2 × D × S) / H)
* D: 年需求量, S: 每次订购成本, H: 单位持有成本
*/
public static function calculate_eoq($annual_demand, $order_cost, $holding_cost_per_unit) {
if ($holding_cost_per_unit <= 0) {
return 0;
}
$eoq = sqrt((2 * $annual_demand * $order_cost) / $holding_cost_per_unit);
return ceil($eoq); // 向上取整
}
/**
* 计算安全库存
* 安全库存 = Z × σ × √L
* Z: 服务水平系数, σ: 需求标准差, L: 提前期
*/
public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) {
// Z值对应表 (服务水平 -> Z值)
$z_values = array(
0.80 => 0.84,
0.85 => 1.04,
0.90 => 1.28,
0.95 => 1.65,
0.99 => 2.33
);
<?php
/**
* 库存优化管理类 - 续
*/
class FSC_Inventory_Optimizer {
/**
* 计算安全库存
* 安全库存 = Z × σ × √L
* Z: 服务水平系数, σ: 需求标准差, L: 提前期
*/
public static function calculate_safety_stock($service_level, $demand_stddev, $lead_time) {
// Z值对应表 (服务水平 -> Z值)
$z_values = array(
0.80 => 0.84,
0.85 => 1.04,
0.90 => 1.28,
0.95 => 1.65,
0.99 => 2.33
);
$z = $z_values[$service_level] ?? 1.65; // 默认95%服务水平
$safety_stock = $z * $demand_stddev * sqrt($lead_time);
return ceil($safety_stock);
}
/**
* 计算重新订购点 (ROP)
* ROP = (平均日需求 × 提前期) + 安全库存
*/
public static function calculate_reorder_point($avg_daily_demand, $lead_time_days, $safety_stock) {
$rop = ($avg_daily_demand * $lead_time_days) + $safety_stock;
return ceil($rop);
}
/**
* 智能库存分配算法
* 根据多个仓库的库存和需求进行优化分配
*/
public static function optimize_inventory_allocation($warehouses, $total_demand) {
$allocation = array();
$remaining_demand = $total_demand;
// 按库存成本排序(成本低的优先分配)
usort($warehouses, function($a, $b) {
return $a['holding_cost'] <=> $b['holding_cost'];
});
foreach ($warehouses as $warehouse) {
if ($remaining_demand <= 0) break;
$warehouse_id = $warehouse['id'];
$available_stock = $warehouse['current_stock'];
$max_allocation = min($available_stock, $remaining_demand);
// 考虑运输成本,如果成本过高则减少分配量
$transport_cost_factor = $warehouse['transport_cost'] / 100; // 假设成本以百分比表示
$adjusted_allocation = $max_allocation * (1 - $transport_cost_factor);
$allocation[$warehouse_id] = floor($adjusted_allocation);
$remaining_demand -= $allocation[$warehouse_id];
}
// 如果仍有需求未满足,记录短缺
if ($remaining_demand > 0) {
$allocation['shortage'] = $remaining_demand;
$allocation['needs_replenishment'] = true;
}
return $allocation;
}
/**
* 预测未来需求(简单移动平均法)
*/
public static function forecast_demand($historical_data, $periods = 30) {
if (count($historical_data) < $periods) {
return 0;
}
// 取最近$periods个数据点
$recent_data = array_slice($historical_data, -$periods);
$sum = array_sum($recent_data);
return $sum / $periods;
}
}
?>
<?php
/**
* 物流集成管理类
*/
class FSC_Logistics_Integration {
private $api_keys = array();
public function __construct() {
$this->api_keys = get_option('fsc_logistics_api_keys', array());
}
/**
* 集成主流物流API
*/
public function integrate_shipping_apis($order_id, $shipping_method) {
$order = wc_get_order($order_id);
$shipping_address = $order->get_shipping_address_1();
$shipping_city = $order->get_shipping_city();
switch ($shipping_method) {
case 'fedex':
return $this->fedex_integration($order);
case 'dhl':
return $this->dhl_integration($order);
case 'ups':
return $this->ups_integration($order);
case 'custom':
return $this->custom_carrier_integration($order);
default:
return $this->standard_shipping($order);
}
}
/**
* FedEx API集成示例
*/
private function fedex_integration($order) {
$api_key = $this->api_keys['fedex'] ?? '';
if (empty($api_key)) {
return array(
'success' => false,
'error' => 'FedEx API密钥未配置'
);
}
// 构建FedEx API请求
$request_data = array(
'request' => array(
'webAuthenticationDetail' => array(
'userCredential' => array(
'key' => $api_key,
'password' => $this->api_keys['fedex_password']
)
),
'clientDetail' => array(
'accountNumber' => $this->api_keys['fedex_account'],
'meterNumber' => $this->api_keys['fedex_meter']
),
'transactionDetail' => array(
'customerTransactionId' => 'Order_' . $order->get_id()
),
'version' => array(
'serviceId' => 'ship',
'major' => '26',
'intermediate' => '0',
'minor' => '0'
),
'requestedShipment' => array(
'dropoffType' => 'REGULAR_PICKUP',
'serviceType' => 'FEDEX_GROUND',
'packagingType' => 'YOUR_PACKAGING',
'shipper' => $this->get_shipper_address(),
'recipient' => $this->get_recipient_address($order),
'shippingChargesPayment' => array(
'paymentType' => 'SENDER',
'payor' => array(
'responsibleParty' => array(
'accountNumber' => $this->api_keys['fedex_account']
)
)
),
'labelSpecification' => array(
'labelFormatType' => 'COMMON2D',
'imageType' => 'PDF',
'labelStockType' => 'PAPER_85X11_TOP_HALF_LABEL'
),
'rateRequestTypes' => array('LIST'),
'packageCount' => '1',
'requestedPackageLineItems' => array(
'0' => array(
'weight' => array(
'value' => $this->calculate_order_weight($order),
'units' => 'LB'
),
'dimensions' => array(
'length' => 10,
'width' => 10,
'height' => 10,
'units' => 'IN'
)
)
)
)
)
);
// 发送API请求
$response = $this->send_api_request(
'https://apis.fedex.com/ship/v1/shipments',
$request_data,
$api_key
);
return $this->process_fedex_response($response);
}
/**
* 多物流商比价
*/
public function compare_shipping_rates($order) {
$rates = array();
// 获取各物流商报价
$rates['fedex'] = $this->get_fedex_rate($order);
$rates['dhl'] = $this->get_dhl_rate($order);
$rates['ups'] = $this->get_ups_rate($order);
$rates['local'] = $this->get_local_carrier_rate($order);
// 按价格排序
uasort($rates, function($a, $b) {
return $a['cost'] <=> $b['cost'];
});
// 考虑交货时间和可靠性
foreach ($rates as &$rate) {
$rate['score'] = $this->calculate_shipping_score(
$rate['cost'],
$rate['estimated_days'],
$rate['reliability']
);
}
return $rates;
}
/**
* 计算物流得分
*/
private function calculate_shipping_score($cost, $delivery_days, $reliability) {
$cost_score = max(0, 100 - ($cost * 10)); // 成本越低得分越高
$speed_score = max(0, 100 - ($delivery_days * 20)); // 越快得分越高
$reliability_score = $reliability * 100; // 可靠性得分
// 加权计算总分
$total_score = ($cost_score * 0.4) + ($speed_score * 0.3) + ($reliability_score * 0.3);
return $total_score;
}
/**
* 实时物流跟踪
*/
public function track_shipment($tracking_number, $carrier) {
$tracking_urls = array(
'fedex' => 'https://www.fedex.com/fedextrack/?trknbr=',
'dhl' => 'https://www.dhl.com/en/express/tracking.html?AWB=',
'ups' => 'https://www.ups.com/track?tracknum=',
'usps' => 'https://tools.usps.com/go/TrackConfirmAction?tLabels='
);
$url = $tracking_urls[$carrier] ?? '';
if ($url) {
return $url . $tracking_number;
}
// 如果未找到预设URL,尝试通用查询
return $this->universal_tracking_query($tracking_number, $carrier);
}
}
?>
<?php
/**
* 物流集成管理类
*/
class FSC_Logistics_Integration {
private $api_keys = array();
public function __construct() {
$this->api_keys = get_option('fsc_logistics_api_keys', array());
}
/**
* 集成主流物流API
*/
public function integrate_shipping_apis($order_id, $shipping_method) {
$order = wc_get_order($order_id);
$shipping_address = $order->get_shipping_address_1();
$shipping_city = $order->get_shipping_city();
switch ($shipping_method) {
case 'fedex':
return $this->fedex_integration($order);
case 'dhl':
return $this->dhl_integration($order);
case 'ups':
return $this->ups_integration($order);
case 'custom':
return $this->custom_carrier_integration($order);
default:
return $this->standard_shipping($order);
}
}
/**
* FedEx API集成示例
*/
private function fedex_integration($order) {
$api_key = $this->api_keys['fedex'] ?? '';
if (empty($api_key)) {
return array(
'success' => false,
'error' => 'FedEx API密钥未配置'
);
}
// 构建FedEx API请求
$request_data = array(
'request' => array(
'webAuthenticationDetail' => array(
'userCredential' => array(
'key' => $api_key,
'password' => $this->api_keys['fedex_password']
)
),
'clientDetail' => array(
'accountNumber' => $this->api_keys['fedex_account'],
'meterNumber' => $this->api_keys['fedex_meter']
),
'transactionDetail' => array(
'customerTransactionId' => 'Order_' . $order->get_id()
),
'version' => array(
'serviceId' => 'ship',
'major' => '26',
'intermediate' => '0',
'minor' => '0'
),
'requestedShipment' => array(
'dropoffType' => 'REGULAR_PICKUP',
'serviceType' => 'FEDEX_GROUND',
'packagingType' => 'YOUR_PACKAGING',
'shipper' => $this->get_shipper_address(),
'recipient' => $this->get_recipient_address($order),
'shippingChargesPayment' => array(
'paymentType' => 'SENDER',
'payor' => array(
'responsibleParty' => array(
'accountNumber' => $this->api_keys['fedex_account']
)
)
),
'labelSpecification' => array(
'labelFormatType' => 'COMMON2D',
'imageType' => 'PDF',
'labelStockType' => 'PAPER_85X11_TOP_HALF_LABEL'
),
'rateRequestTypes' => array('LIST'),
'packageCount' => '1',
'requestedPackageLineItems' => array(
'0' => array(
'weight' => array(
'value' => $this->calculate_order_weight($order),
'units' => 'LB'
),
'dimensions' => array(
'length' => 10,
'width' => 10,
'height' => 10,
'units' => 'IN'
)
)
)
)
)
);
// 发送API请求
$response = $this->send_api_request(
'https://apis.fedex.com/ship/v1/shipments',
$request_data,
$api_key
);
return $this->process_fedex_response($response);
}
/**
* 多物流商比价
*/
public function compare_shipping_rates($order) {
$rates = array();
// 获取各物流商报价
$rates['fedex'] = $this->get_fedex_rate($order);
$rates['dhl'] = $this->get_dhl_rate($order);
$rates['ups'] = $this->get_ups_rate($order);
$rates['local'] = $this->get_local_carrier_rate($order);
// 按价格排序
uasort($rates, function($a, $b) {
return $a['cost'] <=> $b['cost'];
});
// 考虑交货时间和可靠性
foreach ($rates as &$rate) {
$rate['score'] = $this->calculate_shipping_score(
$rate['cost'],
$rate['estimated_days'],
$rate['reliability']
);
}
return $rates;
}
/**
* 计算物流得分
*/
private function calculate_shipping_score($cost, $delivery_days, $reliability) {
$cost_score = max(0, 100 - ($cost * 10)); // 成本越低得分越高
$speed_score = max(0, 100 - ($delivery_days * 20)); // 越快得分越高
$reliability_score = $reliability * 100; // 可靠性得分
// 加权计算总分
$total_score = ($cost_score * 0.4) + ($speed_score * 0.3) + ($reliability_score * 0.3);
return $total_score;
}
/**
* 实时物流跟踪
*/
public function track_shipment($tracking_number, $carrier) {
$tracking_urls = array(
'fedex' => 'https://www.fedex.com/fedextrack/?trknbr=',
'dhl' => 'https://www.dhl.com/en/express/tracking.html?AWB=',
'ups' => 'https://www.ups.com/track?tracknum=',
'usps' => 'https://tools.usps.com/go/TrackConfirmAction?tLabels='
);
$url = $tracking_urls[$carrier] ?? '';
if ($url) {
return $url . $tracking_number;
}
// 如果未找到预设URL,尝试通用查询
return $this->universal_tracking_query($tracking_number, $carrier);
}
}
?>
<?php
/**
* 前端供应链状态展示
*/
class FSC_Frontend_Display {
/**
* 在产品页面显示供应链信息
*/
public static function display_product_supply_info($product_id) {
$stock_level = get_post_meta($product_id, '_stock', true);
$lead_time = get_post_meta($product_id, '_lead_time', true);
$supplier_name = get_post_meta($product_id, '_supplier_name', true);
if (empty($stock_level) && empty($lead_time)) {
return;
}
ob_start();
?>
<div class="fsc-supply-info">
<h3>供应链信息</h3>
<div class="fsc-info-grid">
<?php if ($stock_level !== '') : ?>
<div class="fsc-info-item">
<span class="fsc-label">库存状态:</span>
<span class="fsc-value stock-<?php echo ($stock_level > 10) ? 'high' : (($stock_level > 0) ? 'low' : 'out'); ?>">
<?php
if ($stock_level > 10) {
echo '充足 (' . $stock_level . '件)';
} elseif ($stock_level > 0) {
echo '紧张 (' . $stock_level . '件)';
} else {
echo '缺货';
}
?>
</span>
</div>
<?php endif; ?>
<?php if ($lead_time) : ?>
<div class="fsc-info-item">
<span class="fsc-label">预计补货时间:</span>
<span class="fsc-value"><?php echo $lead_time; ?> 天</span>
</div>
<?php endif; ?>
<?php if ($supplier_name) : ?>
<div class="fsc-info-item">
<span class="fsc-label">供应商:</span>
<span class="fsc-value"><?php echo esc_html($supplier_name); ?></span>
</div>
<?php endif; ?>
</div>
<?php
// 显示库存预测图表
if (current_user_can('manage_options')) {
self::display_inventory_chart($product_id);
}
?>
</div>
<style>
.fsc-supply-info {
margin: 20px 0;
padding: 15px;
border: 1px solid #e0e0e0;
border-radius: 5px;
background: #f9f9f9;
}
.fsc-info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin-top: 10px;
}
.fsc-info-item {
display: flex;
justify-content: space-between;
padding: 8px;
background: white;
border-radius: 3px;
}
.fsc-label {
font-weight: bold;
color: #555;
}
.stock-high { color: #2ecc71; }
.stock-low { color: #f39c12; }
.stock-out { color: #e74c3c; }
</style>
<?php
echo ob_get_clean();
}
/**
* 显示库存预测图表
*/
private static function display_inventory_chart($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_inventory_log';
$data = $wpdb->get_results($wpdb->prepare(
"SELECT DATE(created_at) as date,
SUM(quantity_change) as daily_change,
AVG(current_stock) as avg_stock
FROM $table_name
WHERE product_id = %d
AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY DATE(created_at)
ORDER BY date ASC",
$product_id
));
if (empty($data)) return;
$dates = array();
$stocks = array();
foreach ($data as $row) {
$dates[] = $row->date;
$stocks[] = $row->avg_stock;
}
?>
<div class="fsc-inventory-chart">
<h4>库存趋势 (最近30天)</h4>
<canvas id="inventoryChart-<?php echo $product_id; ?>" width="400" height="200"></canvas>
<script>
document.addEventListener('DOMContentLoaded', function() {
var ctx = document.getElementById('inventoryChart-<?php echo $product_id; ?>').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($dates); ?>,
datasets: [{
label: '库存水平',
data: <?php echo json_encode($stocks); ?>,
borderColor: '#3498db',
backgroundColor: 'rgba(52, 152, 219, 0.1)',
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
}
},
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '库存数量'
}
},
x: {
title: {
display: true,
text: '日期'
}
}
}
}
});
});
</script>
</div>
<?php
}
/**
* 在订单页面显示供应链状态
*/
public static function display_order_supply_status($order_id) {
$supply_status = get_post_meta($order_id, '_fsc_supply_status', true);
$estimated_delivery = get_post_meta($order_id, '_fsc_estimated_delivery', true);
if (!$supply_status) return;
$status_labels = array(
'supplier_confirmed' => '供应商已确认',
'production_started' => '生产中',
'quality_check' => '质量检测',
'ready_to_ship' => '准备发货',
'shipped' => '已发货',
'delivered' => '已送达'
);
$current_status = $status_labels[$supply_status] ?? $supply_status;
ob_start();
?>
<div class="fsc-order-status">
<h3>供应链状态跟踪</h3>
<div class="status-timeline">
<?php
$statuses = array_keys($status_labels);
$current_index = array_search($supply_status, $statuses);
foreach ($statuses as $index => $status) {
$is_completed = $index <= $current_index;
$is_current = $index === $current_index;
?>
<div class="status-step <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_current ? 'current' : ''; ?>">
<div class="step-icon">
<?php if ($is_completed) : ?>
<span class="dashicons dashicons-yes"></span>
<?php else : ?>
<span class="step-number"><?php echo $index + 1; ?></span>
<?php endif; ?>
</div>
<div class="step-label"><?php echo $status_labels[$status]; ?></div>
</div>
<?php if ($index < count($statuses) - 1) : ?>
<div class="step-connector"></div>
<?php endif;
}
?>
</div>
<?php if ($estimated_delivery) : ?>
<div class="estimated-delivery">
<strong>预计送达时间:</strong> <?php echo date('Y年m月d日', strtotime($estimated_delivery)); ?>
</div>
<?php endif; ?>
</div>
<style>
.fsc-order-status {
margin: 20px 0;
padding: 20px;
<?php
/**
* 前端供应链状态展示
*/
class FSC_Frontend_Display {
/**
* 在产品页面显示供应链信息
*/
public static function display_product_supply_info($product_id) {
$stock_level = get_post_meta($product_id, '_stock', true);
$lead_time = get_post_meta($product_id, '_lead_time', true);
$supplier_name = get_post_meta($product_id, '_supplier_name', true);
if (empty($stock_level) && empty($lead_time)) {
return;
}
ob_start();
?>
<div class="fsc-supply-info">
<h3>供应链信息</h3>
<div class="fsc-info-grid">
<?php if ($stock_level !== '') : ?>
<div class="fsc-info-item">
<span class="fsc-label">库存状态:</span>
<span class="fsc-value stock-<?php echo ($stock_level > 10) ? 'high' : (($stock_level > 0) ? 'low' : 'out'); ?>">
<?php
if ($stock_level > 10) {
echo '充足 (' . $stock_level . '件)';
} elseif ($stock_level > 0) {
echo '紧张 (' . $stock_level . '件)';
} else {
echo '缺货';
}
?>
</span>
</div>
<?php endif; ?>
<?php if ($lead_time) : ?>
<div class="fsc-info-item">
<span class="fsc-label">预计补货时间:</span>
<span class="fsc-value"><?php echo $lead_time; ?> 天</span>
</div>
<?php endif; ?>
<?php if ($supplier_name) : ?>
<div class="fsc-info-item">
<span class="fsc-label">供应商:</span>
<span class="fsc-value"><?php echo esc_html($supplier_name); ?></span>
</div>
<?php endif; ?>
</div>
<?php
// 显示库存预测图表
if (current_user_can('manage_options')) {
self::display_inventory_chart($product_id);
}
?>
</div>
<style>
.fsc-supply-info {
margin: 20px 0;
padding: 15px;
border: 1px solid #e0e0e0;
border-radius: 5px;
background: #f9f9f9;
}
.fsc-info-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 10px;
margin-top: 10px;
}
.fsc-info-item {
display: flex;
justify-content: space-between;
padding: 8px;
background: white;
border-radius: 3px;
}
.fsc-label {
font-weight: bold;
color: #555;
}
.stock-high { color: #2ecc71; }
.stock-low { color: #f39c12; }
.stock-out { color: #e74c3c; }
</style>
<?php
echo ob_get_clean();
}
/**
* 显示库存预测图表
*/
private static function display_inventory_chart($product_id) {
global $wpdb;
$table_name = $wpdb->prefix . 'fsc_inventory_log';
$data = $wpdb->get_results($wpdb->prepare(
"SELECT DATE(created_at) as date,
SUM(quantity_change) as daily_change,
AVG(current_stock) as avg_stock
FROM $table_name
WHERE product_id = %d
AND created_at >= DATE_SUB(NOW(), INTERVAL 30 DAY)
GROUP BY DATE(created_at)
ORDER BY date ASC",
$product_id
));
if (empty($data)) return;
$dates = array();
$stocks = array();
foreach ($data as $row) {
$dates[] = $row->date;
$stocks[] = $row->avg_stock;
}
?>
<div class="fsc-inventory-chart">
<h4>库存趋势 (最近30天)</h4>
<canvas id="inventoryChart-<?php echo $product_id; ?>" width="400" height="200"></canvas>
<script>
document.addEventListener('DOMContentLoaded', function() {
var ctx = document.getElementById('inventoryChart-<?php echo $product_id; ?>').getContext('2d');
var chart = new Chart(ctx, {
type: 'line',
data: {
labels: <?php echo json_encode($dates); ?>,
datasets: [{
label: '库存水平',
data: <?php echo json_encode($stocks); ?>,
borderColor: '#3498db',
backgroundColor: 'rgba(52, 152, 219, 0.1)',
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
plugins: {
legend: {
display: false
}
},
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '库存数量'
}
},
x: {
title: {
display: true,
text: '日期'
}
}
}
}
});
});
</script>
</div>
<?php
}
/**
* 在订单页面显示供应链状态
*/
public static function display_order_supply_status($order_id) {
$supply_status = get_post_meta($order_id, '_fsc_supply_status', true);
$estimated_delivery = get_post_meta($order_id, '_fsc_estimated_delivery', true);
if (!$supply_status) return;
$status_labels = array(
'supplier_confirmed' => '供应商已确认',
'production_started' => '生产中',
'quality_check' => '质量检测',
'ready_to_ship' => '准备发货',
'shipped' => '已发货',
'delivered' => '已送达'
);
$current_status = $status_labels[$supply_status] ?? $supply_status;
ob_start();
?>
<div class="fsc-order-status">
<h3>供应链状态跟踪</h3>
<div class="status-timeline">
<?php
$statuses = array_keys($status_labels);
$current_index = array_search($supply_status, $statuses);
foreach ($statuses as $index => $status) {
$is_completed = $index <= $current_index;
$is_current = $index === $current_index;
?>
<div class="status-step <?php echo $is_completed ? 'completed' : ''; ?> <?php echo $is_current ? 'current' : ''; ?>">
<div class="step-icon">
<?php if ($is_completed) : ?>
<span class="dashicons dashicons-yes"></span>
<?php else : ?>
<span class="step-number"><?php echo $index + 1; ?></span>
<?php endif; ?>
</div>
<div class="step-label"><?php echo $status_labels[$status]; ?></div>
</div>
<?php if ($index < count($statuses) - 1) : ?>
<div class="step-connector"></div>
<?php endif;
}
?>
</div>
<?php if ($estimated_delivery) : ?>
<div class="estimated-delivery">
<strong>预计送达时间:</strong> <?php echo date('Y年m月d日', strtotime($estimated_delivery)); ?>
</div>
<?php endif; ?>
</div>
<style>
.fsc-order-status {
margin: 20px 0;
padding: 20px;


